github.com/qiniu/go-sdk/v7@v7.27.0/internal/clientv2/interceptor_auth.go (about) 1 package clientv2 2 3 import ( 4 "net/http" 5 6 "github.com/qiniu/go-sdk/v7/auth" 7 "github.com/qiniu/go-sdk/v7/storagev2/credentials" 8 ) 9 10 type AuthConfig struct { 11 // 鉴权参数 12 Credentials credentials.CredentialsProvider 13 // 鉴权类型,不包含上传 14 TokenType auth.TokenType 15 // 签名前回调函数 16 BeforeSign func(*http.Request) 17 // 签名后回调函数 18 AfterSign func(*http.Request) 19 // 签名失败回调函数 20 SignError func(*http.Request, error) 21 } 22 23 type authInterceptor struct { 24 config AuthConfig 25 } 26 27 func NewAuthInterceptor(config AuthConfig) Interceptor { 28 return &authInterceptor{ 29 config: config, 30 } 31 } 32 33 func (interceptor *authInterceptor) Priority() InterceptorPriority { 34 return InterceptorPriorityAuth 35 } 36 37 func (interceptor *authInterceptor) Intercept(req *http.Request, handler Handler) (*http.Response, error) { 38 if interceptor == nil || req == nil { 39 return handler(req) 40 } 41 42 if credentials := interceptor.config.Credentials; credentials != nil { 43 creds, err := credentials.Get(req.Context()) 44 if err != nil { 45 return nil, err 46 } 47 if interceptor.config.BeforeSign != nil { 48 interceptor.config.BeforeSign(req) 49 } 50 if err := creds.AddToken(interceptor.config.TokenType, req); err != nil { 51 if interceptor.config.SignError != nil { 52 interceptor.config.SignError(req, err) 53 } 54 return nil, err 55 } else if interceptor.config.AfterSign != nil { 56 interceptor.config.AfterSign(req) 57 } 58 } 59 60 return handler(req) 61 }