pkg/apis/middleware.go

73 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-06-02 09:19:01 +00:00
// Package apis for http
2023-04-09 15:04:57 +00:00
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
}
2023-04-09 15:44:24 +00:00
// switch {
// default:
// render.Render(w, r, rest.AbortWithUnauthorizedError(rest.UnauthorizedError))
// return
// }
2023-04-09 15:04:57 +00:00
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}