mirror of
https://github.com/kataras/iris.git
synced 2025-12-22 04:17:03 +00:00
add HashGenerator on requestid middleware
Former-commit-id: 8f59a46a3fecc538d6d3e624fc36f2c314c20bb6
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
package requestid
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"net/http/httputil"
|
||||
|
||||
"github.com/kataras/iris/v12/context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -10,7 +14,7 @@ func init() {
|
||||
context.SetHandlerName("iris/middleware/requestid.*", "iris.request.id")
|
||||
}
|
||||
|
||||
const xRequestIDHeaderValue = "X-Request-Id"
|
||||
const xRequestIDHeaderKey = "X-Request-Id"
|
||||
|
||||
// Generator defines the function which should extract or generate
|
||||
// a Request ID. See `DefaultGenerator` and `New` package-level functions.
|
||||
@@ -23,8 +27,12 @@ type Generator func(ctx *context.Context) string
|
||||
//
|
||||
// See `Get` package-level function too.
|
||||
var DefaultGenerator Generator = func(ctx *context.Context) string {
|
||||
id := ctx.GetHeader(xRequestIDHeaderValue)
|
||||
id := ctx.ResponseWriter().Header().Get(xRequestIDHeaderKey)
|
||||
if id != "" {
|
||||
return id
|
||||
}
|
||||
|
||||
id = ctx.GetHeader(xRequestIDHeaderKey)
|
||||
if id == "" {
|
||||
uid, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
@@ -33,12 +41,21 @@ var DefaultGenerator Generator = func(ctx *context.Context) string {
|
||||
}
|
||||
|
||||
id = uid.String()
|
||||
ctx.Header(xRequestIDHeaderValue, id)
|
||||
}
|
||||
|
||||
ctx.Header(xRequestIDHeaderKey, id)
|
||||
return id
|
||||
}
|
||||
|
||||
// HashGenerator uses the request's hash to generate a fixed-length Request ID.
|
||||
// Note that one or many requests may contain the same ID, so it's not unique.
|
||||
func HashGenerator(includeBody bool) Generator {
|
||||
return func(ctx *context.Context) string {
|
||||
ctx.Header(xRequestIDHeaderKey, Hash(ctx, includeBody))
|
||||
return DefaultGenerator(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// New returns a new request id middleware.
|
||||
// It optionally accepts an ID Generator.
|
||||
// The Generator can stop the handlers chain with an error or
|
||||
@@ -81,3 +98,15 @@ func Get(ctx *context.Context) string {
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Hash returns the sha1 hash of the request.
|
||||
// It does not capture error, instead it returns an empty string.
|
||||
func Hash(ctx *context.Context, includeBody bool) string {
|
||||
h := sha1.New()
|
||||
b, err := httputil.DumpRequest(ctx.Request(), includeBody)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
h.Write(b)
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user