github.com/cloudwego/kitex@v0.9.0/server/middlewares.go (about) 1 /* 2 * Copyright 2024 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package server 18 19 import ( 20 "context" 21 22 "github.com/cloudwego/kitex/pkg/endpoint" 23 "github.com/cloudwego/kitex/pkg/rpcinfo" 24 ) 25 26 func serverTimeoutMW(initCtx context.Context) endpoint.Middleware { 27 return func(next endpoint.Endpoint) endpoint.Endpoint { 28 return func(ctx context.Context, request, response interface{}) (err error) { 29 // Regardless of the underlying protocol, only by checking the RPCTimeout 30 // For TTHeader, it will be set by transmeta.ServerTTHeaderHandler (not added by default though) 31 // For GRPC/HTTP2, the timeout deadline is already set in the context, so no need to check it 32 ri := rpcinfo.GetRPCInfo(ctx) 33 timeout := ri.Config().RPCTimeout() 34 if timeout <= 0 { 35 return next(ctx, request, response) 36 } 37 38 ctx, cancel := context.WithTimeout(ctx, timeout) 39 defer func() { 40 if err != nil { 41 cancel() 42 } 43 }() 44 return next(ctx, request, response) 45 } 46 } 47 }