github.com/qiniu/go-sdk/v7@v7.27.0/internal/clientv2/interceptor.go (about) 1 package clientv2 2 3 import ( 4 "net/http" 5 ) 6 7 const ( 8 InterceptorPriorityDefault InterceptorPriority = 100 9 InterceptorPriorityRetryHosts InterceptorPriority = 200 10 InterceptorPriorityRetrySimple InterceptorPriority = 300 11 InterceptorPriorityUplog InterceptorPriority = 310 12 InterceptorPriorityBufferResponse InterceptorPriority = 320 13 InterceptorPrioritySetHeader InterceptorPriority = 400 14 InterceptorPriorityNormal InterceptorPriority = 500 15 InterceptorPriorityAuth InterceptorPriority = 600 16 InterceptorPriorityAntiHijacking InterceptorPriority = 700 17 InterceptorPriorityDebug InterceptorPriority = 800 18 ) 19 20 type InterceptorPriority int 21 22 type Interceptor interface { 23 // Priority 数字越小优先级越高 24 Priority() InterceptorPriority 25 26 // Intercept 拦截处理函数 27 Intercept(req *http.Request, handler Handler) (*http.Response, error) 28 } 29 30 type interceptorList []Interceptor 31 32 func (l interceptorList) Less(i, j int) bool { 33 return l[i].Priority() >= l[j].Priority() 34 } 35 36 func (l interceptorList) Swap(i, j int) { 37 l[i], l[j] = l[j], l[i] 38 } 39 40 func (l interceptorList) Len() int { 41 return len(l) 42 } 43 44 type simpleInterceptor struct { 45 priority InterceptorPriority 46 handler func(req *http.Request, handler Handler) (*http.Response, error) 47 } 48 49 func NewSimpleInterceptor(interceptorHandler func(req *http.Request, handler Handler) (*http.Response, error)) Interceptor { 50 return NewSimpleInterceptorWithPriority(InterceptorPriorityNormal, interceptorHandler) 51 } 52 53 func NewSimpleInterceptorWithPriority(priority InterceptorPriority, interceptorHandler func(req *http.Request, handler Handler) (*http.Response, error)) Interceptor { 54 if priority <= 0 { 55 priority = InterceptorPriorityNormal 56 } 57 58 return &simpleInterceptor{ 59 priority: priority, 60 handler: interceptorHandler, 61 } 62 } 63 64 func (interceptor *simpleInterceptor) Priority() InterceptorPriority { 65 return interceptor.priority 66 } 67 68 func (interceptor *simpleInterceptor) Intercept(req *http.Request, handler Handler) (*http.Response, error) { 69 if interceptor == nil || interceptor.handler == nil { 70 return handler(req) 71 } 72 return interceptor.handler(req, handler) 73 }