// Package apis for http package apis import ( "context" "net/http" "path/filepath" "strings" "github.com/go-chi/chi/v5/middleware" "github.com/google/uuid" "git.ifooth.com/common/pkg/components" ) // RequestIdGenerator request_id func RequestIdGenerator() string { uid := uuid.New().String() requestId := strings.Replace(uid, "-", "", -1) return requestId } // RequestID reuqest_id func RequestID(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() requestID := r.Header.Get(components.RequestIDHeaderKey) if requestID == "" { requestID = RequestIdGenerator() } ctx = components.WithRequestIDValue(ctx, requestID) ctx = context.WithValue(ctx, middleware.RequestIDKey, requestID) w.Header().Set(components.RequestIDHeaderKey, requestID) next.ServeHTTP(w, r.WithContext(ctx)) } return http.HandlerFunc(fn) } // AuthRequired API类型, 兼容多种鉴权模式 func AuthRequired(next http.Handler) http.Handler { ignoreExtMap := map[string]struct{}{ ".js": {}, ".css": {}, ".map": {}, ".png": {}, } fn := func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodOptions { next.ServeHTTP(w, r) return } // 静态资源过滤, 注意不会带鉴权信息 fileExt := filepath.Ext(r.URL.Path) if _, ok := ignoreExtMap[fileExt]; ok { next.ServeHTTP(w, r) return } // switch { // default: // render.Render(w, r, rest.AbortWithUnauthorizedError(rest.UnauthorizedError)) // return // } next.ServeHTTP(w, r) } return http.HandlerFunc(fn) }