package main import ( "github.com/gogits/gogs/modules/context" "net/http" ) func Middleware1(ctx *context.Context) { // do something... ctx.Data["key"] = "value" } func Middleware2(ctx *context.Context) { // retrieve data from context key := ctx.Data["key"] // do something... } func main() { mux := http.NewServeMux() // add middleware functions to mux mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { ctx := context.NewContext(w, r) Middleware1(ctx) Middleware2(ctx) }) // start web server http.ListenAndServe(":8000", mux) }
package main import ( "context" "fmt" "github.com/gogits/gogs/modules/context" "net/http" "time" ) func Middleware(ctx *context.Context) { // create new context with cancellation ctx, cancel := context.WithTimeout(ctx.Context, 5*time.Second) defer cancel() // do something... select { case <-time.After(10 * time.Second): fmt.Println("Middleware timed out") case <-ctx.Done(): fmt.Println("Middleware canceled") } } func main() { mux := http.NewServeMux() // add middleware function to mux mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { ctx := context.NewContext(w, r) Middleware(ctx) }) // start web server http.ListenAndServe(":8000", mux) }In the above code examples, the context handle library is used to pass data between two different middleware functions and to handle a cancellation in one of the middleware functions. The package library used is `github.com/gogits/gogs/modules/context`.