func MyMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() ctx = context.WithValue(ctx, "foo", "bar") next.ServeHTTP(w, r.WithContext(ctx)) }) } func MyHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() if value, ok := ctx.Value("foo").(string); ok { fmt.Fprintf(w, "Value of foo is %s", value) } else { fmt.Fprintf(w, "Couldn't find value for foo") } } func main() { handler := http.HandlerFunc(MyHandler) http.ListenAndServe(":8080", MyMiddleware(handler)) }
type MyParam struct { Foo string Bar int } func MyMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() myParam := MyParam{ Foo: "baz", Bar: 42, } ctx = context.WithValue(ctx, "myParam", myParam) next.ServeHTTP(w, r.WithContext(ctx)) }) } func MyHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() if myParam, ok := ctx.Value("myParam").(MyParam); ok { fmt.Fprintf(w, "Value of foo is %s, value of bar is %d", myParam.Foo, myParam.Bar) } else { fmt.Fprintf(w, "Couldn't find MyParam object in context") } } func main() { handler := http.HandlerFunc(MyHandler) http.ListenAndServe(":8080", MyMiddleware(handler)) }In this example, we define a custom `MyParam` struct that contains two fields, `Foo` and `Bar`. We create a middleware function called `MyMiddleware` that adds an instance of this struct to the context object. We then define a handler function called `MyHandler` that retrieves this value from the context and writes its fields to the response. Finally, we create a server that uses `MyMiddleware` to wrap `MyHandler`. Overall, the go github.com/go-gitea/gitea/modules/middleware package provides useful middleware functionality for developers using the Gitea web application framework.