1
0
Fork 0
mirror of https://github.com/ossrs/srs.git synced 2025-02-15 04:42:04 +00:00
srs/proxy/logger/context.go
ChenGH 13597d1b7f
update copyright to 2025. v5.0.218 v6.0.159 v7.0.21 (#4271)
update copyright to 2025

---------

Co-authored-by: john <hondaxiao@tencent.com>
Co-authored-by: winlin <winlinvip@gmail.com>
2025-01-14 17:35:18 +08:00

43 lines
1 KiB
Go

// Copyright (c) 2025 Winlin
//
// SPDX-License-Identifier: MIT
package logger
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
)
type key string
var cidKey key = "cid.proxy.ossrs.org"
// generateContextID generates a random context id in string.
func GenerateContextID() string {
randomBytes := make([]byte, 32)
_, _ = rand.Read(randomBytes)
hash := sha256.Sum256(randomBytes)
hashString := hex.EncodeToString(hash[:])
cid := hashString[:7]
return cid
}
// WithContext creates a new context with cid, which will be used for log.
func WithContext(ctx context.Context) context.Context {
return WithContextID(ctx, GenerateContextID())
}
// WithContextID creates a new context with cid, which will be used for log.
func WithContextID(ctx context.Context, cid string) context.Context {
return context.WithValue(ctx, cidKey, cid)
}
// ContextID returns the cid in context, or empty string if not set.
func ContextID(ctx context.Context) string {
if cid, ok := ctx.Value(cidKey).(string); ok {
return cid
}
return ""
}