55 lines
941 B
Go
55 lines
941 B
Go
|
package rest
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"net/http"
|
||
|
|
||
|
"github.com/google/uuid"
|
||
|
)
|
||
|
|
||
|
type contextKey struct {
|
||
|
name string
|
||
|
}
|
||
|
|
||
|
var (
|
||
|
reqCtxKey = &contextKey{"HTTPRequest"}
|
||
|
)
|
||
|
|
||
|
type ctxKey int
|
||
|
|
||
|
const (
|
||
|
requestIDCtxKey = ctxKey(1)
|
||
|
requestIDHeaderKey = "X-Request-Id"
|
||
|
)
|
||
|
|
||
|
// HTTPRequest return svr's request
|
||
|
func HTTPRequest(ctx context.Context) *http.Request { // nolint
|
||
|
val, ok := ctx.Value(reqCtxKey).(*http.Request)
|
||
|
if !ok {
|
||
|
panic("missing request in context")
|
||
|
}
|
||
|
return val
|
||
|
}
|
||
|
|
||
|
// GenRequestID 生产 request_id
|
||
|
func GenRequestID() string {
|
||
|
id, _ := uuid.NewRandom()
|
||
|
return id.String()
|
||
|
}
|
||
|
|
||
|
// RequestIDValue 获取 RequestId 值
|
||
|
func RequestIDValue(ctx context.Context) string {
|
||
|
v, ok := ctx.Value(requestIDCtxKey).(string)
|
||
|
if !ok {
|
||
|
return ""
|
||
|
}
|
||
|
|
||
|
return v
|
||
|
}
|
||
|
|
||
|
// WithRequestID 设置 request_id
|
||
|
func WithRequestID(ctx context.Context, id string) context.Context {
|
||
|
newCtx := context.WithValue(ctx, requestIDCtxKey, id)
|
||
|
return newCtx
|
||
|
}
|