context

package
v1.7.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2025 License: MIT, Apache-2.0, MIT Imports: 11 Imported by: 0

README

context

一个轻量却强大的上下文管理器,一个请求会生成一个context,贯穿整个请求,context记录原始请求上下文,请求时间,客户端信息,权限校验信息,及负责判断是否内部调用, 及附带唯一traceId的日志记录器

支持http及fasthttp,并支持自定义的请求类型 context

usage

Basic

new
import (
	stdcontext "context"
	"github.com/hopeio/context"
)

 ctx:= context.NewContext(stdcontext.Background())
wrap and unwrap
stdctx = ctx.Wrapper()
ctxi,_ = context.FromContext(stdctx)

request context

new
import (
    "github.com/hopeio/context/httpctx"
)
func Handle(w http.ResponseWriter, r *http.Request) {
 ctx:= httpctx.FromRequest(httpctx.RequestCtx{r,w})
}

wrap and unwrap
func Middleware(w http.ResponseWriter, r *http.Request) {
    ctx:= httpctx.FromRequest(httpctx.RequestCtx{r,w})
    r.WithContext(ctx.Wrapper())
}
func Handle(w http.ResponseWriter, r *http.Request) {
    reqctx, ok := httpctx.FromContext(r.Context())
}

auth 示例

import (
  "errors"
  "encoding/json"
  "strings"
  "github.com/golang-jwt/jwt/v5"
  "github.com/hopeio/context/httpctx"
)
var tokenSecret = []byte("xxx")
type AuthInfo struct {
	Id uint64 `json:"id"`
}

type Authorization struct {
    *AuthInfo `json:"auth"`
    jwt.RegisteredClaims
    AuthInfoRaw string `json:"-"`
}

func (x *Authorization) Validate() error {
    return nil
}

func (x *Authorization) GenerateToken(secret []byte) (string, error) {
    tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, x)
    token, err := tokenClaims.SignedString(secret)
    return token, err
}

func (x *Authorization) ParseToken(token string, secret []byte) error {
    _, err := jwti.ParseToken(x, token, secret)
    if err != nil {
        return err
    }
    x.ID = x.AuthInfo.IdStr()
    authBytes, _ := json.Marshal(x.AuthInfo)
    x.AuthInfoRaw = string(authBytes)
    return nil
}

func GetAuth(ctx *httpctx.Context) (*AuthInfo, error) {
    signature := ctx.Token[strings.LastIndexByte(ctx.Token, '.')+1:]
	
    authorization := Authorization{AuthInfo: &AuthInfo{}}
    if err := authorization.ParseToken(ctx.Token, tokenSecret); err != nil {
        return nil, err
    }
    authInfo := authorization.AuthInfo
    ctx.AuthID = authInfo.IdStr()
    ctx.AuthInfo = authInfo
    ctx.AuthInfoRaw = authorization.AuthInfoRaw
	
    return authInfo, nil
}

Documentation

Index

Constants

View Source
const (
	KindKey = attribute.Key("context.key")
)

Variables

View Source
var (
	Tracer = otel.Tracer("context")
	Meter  = otel.Meter("context")
)

Functions

func StartSpan

func StartSpan(ctx context.Context, name string, o ...trace.SpanStartOption) (context.Context, trace.Span)

func WrapperKey

func WrapperKey() ctxKey

Types

type Context

type Context struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func FromContext

func FromContext(ctx context.Context) (*Context, bool)

func New

func New(ctx context.Context) *Context

func (*Context) Base

func (c *Context) Base() context.Context

func (*Context) ErrorLog

func (c *Context) ErrorLog(err error, fields ...zap.Field)

func (*Context) Log

func (c *Context) Log(lvl zapcore.Level, msg string, fields ...zap.Field)

func (*Context) RespErrorLog

func (c *Context) RespErrorLog(respErr, originErr error, flag string, fields ...zap.Field) error

func (*Context) RootSpan

func (c *Context) RootSpan() trace.Span

func (*Context) Set added in v1.7.2

func (c *Context) Set(k, v any)

func (*Context) SetBase

func (c *Context) SetBase(ctx context.Context)

func (*Context) StartSpan

func (c *Context) StartSpan(name string, o ...trace.SpanStartOption) trace.Span

func (*Context) StartSpanEnd

func (c *Context) StartSpanEnd(name string, o ...trace.SpanStartOption) func(options ...trace.SpanEndOption)

func (*Context) TraceID

func (c *Context) TraceID() string

func (*Context) Value added in v1.7.2

func (c *Context) Value(k any) any

func (*Context) WithCancel

func (c *Context) WithCancel() context.CancelFunc

func (*Context) WithCancelCause

func (c *Context) WithCancelCause() context.CancelCauseFunc

func (*Context) WithDeadline

func (c *Context) WithDeadline(d time.Time) context.CancelFunc

func (*Context) WithDeadlineCause

func (c *Context) WithDeadlineCause(d time.Time, cause error) context.CancelFunc

func (*Context) WithTimeout

func (c *Context) WithTimeout(timeout time.Duration) context.CancelFunc

func (*Context) WithTimeoutCause

func (c *Context) WithTimeoutCause(timeout time.Duration, cause error) context.CancelFunc

func (*Context) WithValue

func (c *Context) WithValue(key, val any)

func (*Context) WithoutCancel

func (c *Context) WithoutCancel()

func (*Context) Wrapper

func (c *Context) Wrapper() context.Context

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL