Gin series of lectures: Saas system, Gin+Jwt+ Casbin RestFul Api backend battle to the end

1: Gin Context details

The standard Context

Context is officially available in Golang 1.7, especially in Gin where points can be chained to pass shared variables. We only talk about Context first so that you can understand how to combine JWT token ID and user ID in Gin. Save to a custom context. Or TraceID. This is shared in later goroutines, and another important point is that these are all implemented based on GIN middleware. This is very convenient in engineering.

Custom extension Context


import (
	"context") // Define keys in the global contexttypeFunc NewTrans(CTX context.context, transCtx struct{} userIDCtx struct{} traceIDCtx struct{}) trans interface{}) context.Context {returnContext.withvalue (CTX, transCtx{}, trans)} // FromTrans obtains transactions from context func FromTrans(CTX context.context) (interface{}, bool) { v := ctx.Value(transCtx{})returnv, v ! Func NewUserID(CTX context.context, userID string) context.context {returnContext. WithValue(CTX, userIDCtx{}, userID)} // FromUserID obtains the userID from the context func FromUserID(CTX context.context) (string, bool) { v := ctx.Value(userIDCtx{})ifv ! = nil {if s, ok := v.(string); ok {
			returns, s ! =""}}return "".false} // NewTraceID creates a context for tracing the ID func NewTraceID(CTX context.context, traceID string) context.context {returncontext.WithValue(ctx, traceIDCtx{}, Func FromTraceID(CTX context.context) (string, bool) { v := ctx.Value(traceIDCtx{})ifv ! = nil {if s, ok := v.(string); ok {
			returns, s ! =""}}return "".false
}
Copy the code

NewUserID

Create a new Context based on the userID you entered, userIDCtx for key, userID for value, save it in the Context and give it to you and return the Context return

Use custom context in Gin Contxt.

func NewContext(c *gin.Context) context.Context {
	parent := context.Background()

	ifv := GetTraceID(c); v ! ="" {
		parent = icontext.NewTraceID(parent, v)
		parent = logger.NewTraceIDContext(parent, GetTraceID(c))
	}

	ifv := GetUserID(c); v ! ="" {
		parent = icontext.NewUserID(parent, v)
		parent = logger.NewUserIDContext(parent, v)
	}

	return parent
}

Copy the code

The icontext above is our custom context.

Understanding this will allow us to associate our custom context with GIN.

Gin middleware uses custom context

return func(c *gin.Context) {
		var userID string
		ift := xxx.GetToken(c); t ! ="" {
			id, err
Copy the code

Understand middleware.

A lot of people feel like middleware is superior, but it’s really just a next -> Next recursive callback. Return func*(c *ginContext) return type gin.HandlerFunc. Generally, it is middleware, which simply means that after performing an action, a step is added in the middle, just like plucking an onion