MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+50
@@ -0,0 +1,50 @@
|
||||
# Package `requestid`
|
||||
|
||||
Пакет `requestid` предоставляет утилиты для генерации и хранения уникального идентификатора запроса (`request-id`) в контексте.
|
||||
|
||||
## Constants
|
||||
|
||||
### `Header`
|
||||
|
||||
Константа `Header` содержит строку `"x-request-id"`, которая представляет собой стандартное имя HTTP-заголовка, используемого для передачи идентификатора запроса.
|
||||
|
||||
### `LogKey`
|
||||
|
||||
Константа `LogKey` содержит строку `"requestId"` — ключ, под которым `request-id` может сохраняться в логах.
|
||||
|
||||
## Types
|
||||
|
||||
Данный пакет не экспортирует пользовательских типов.
|
||||
|
||||
## Functions
|
||||
|
||||
### `ToContext(ctx context.Context, value string) context.Context`
|
||||
|
||||
Сохраняет `request-id` в переданном контексте и возвращает новый контекст с сохранённым значением.
|
||||
|
||||
### `FromContext(ctx context.Context) string`
|
||||
|
||||
Извлекает `request-id` из контекста. Если значение отсутствует, возвращается пустая строка.
|
||||
|
||||
### `Next() string`
|
||||
|
||||
Генерирует новый случайный `request-id` длиной 16 байт (в hex-представлении — 32 символа).
|
||||
Использует криптографически безопасный генератор случайных чисел. В случае ошибки вызывает `panic`.
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
import (
|
||||
"net/http"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get(requestid.Header)
|
||||
if id == "" {
|
||||
id = requestid.Next()
|
||||
}
|
||||
r = r.WithContext(requestid.ToContext(r.Context(), id))
|
||||
// теперь можно использовать FromContext(r.Context()) в любом месте
|
||||
}
|
||||
```
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// Package requestid provides utilities for managing request IDs in Go applications.
|
||||
// It supports storing and retrieving request IDs from context, along with constants
|
||||
// for common usage patterns like HTTP headers and log keys.
|
||||
package requestid
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const (
|
||||
// Header is the standard HTTP header key for request IDs.
|
||||
Header = "x-request-id"
|
||||
// LogKey is the key used for request IDs in structured logging.
|
||||
LogKey = "requestId"
|
||||
)
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
contextKeyValue = contextKey{}
|
||||
)
|
||||
|
||||
// ToContext stores the request ID in the context and returns the derived context.
|
||||
// The request ID can be retrieved later using FromContext.
|
||||
func ToContext(ctx context.Context, value string) context.Context {
|
||||
return context.WithValue(ctx, contextKeyValue, value)
|
||||
}
|
||||
|
||||
// FromContext extracts the request ID from the context.
|
||||
// Returns an empty string if no request ID is set in the context.
|
||||
func FromContext(ctx context.Context) string {
|
||||
value, _ := ctx.Value(contextKeyValue).(string)
|
||||
return value
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package requestid
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
const (
|
||||
requestIdLength = 16
|
||||
)
|
||||
|
||||
// Next generates a new cryptographically secure random request ID.
|
||||
// The returned ID is a 32-character hexadecimal string.
|
||||
// Panics if a secure random value cannot be generated.
|
||||
func Next() string {
|
||||
value := make([]byte, requestIdLength)
|
||||
_, err := rand.Read(value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(value)
|
||||
}
|
||||
Reference in new issue
Block a user