func myHandler(ctx *middleware.Context) { // do something ctx.Status(200) } // in main function r := gin.New() r.Use(middleware.ContextStatus()) r.GET("/", myHandler)
func myMiddleware() gin.HandlerFunc { return func(ctx *gin.Context) { // do something ctx.Set("my_key", "my_value") ctx.Next() status := ctx.Writer.Status() if status == 0 { ctx.Status(500) } } } // in main function r := gin.New() r.Use(middleware.ContextStatus()) r.Use(myMiddleware()) r.GET("/", func(ctx *gin.Context) { value, ok := ctx.Get("my_key") if !ok { ctx.Status(404) return } // use the value ctx.JSON(200, gin.H{"my_key": value}) })In this example, we define a middleware function called `myMiddleware` that takes a `gin.Context` object and does some processing. We set a value in the context object with the key "my_key" and then call `Next()` to allow the rest of the middleware stack and the main handler to execute. We check the HTTP status code set by previous middleware or the main handler using `ctx.Writer.Status()` and if it is still set to 0 (meaning it was not set by previous middleware or the main handler), we set the HTTP status code to 500. We then create a `gin` router object and use the `ContextStatus` middleware before our middleware function and before our handler function for the root route. In the handler function, we retrieve the value stored in the context object with the key "my_key" and return it in a JSON response. If the value is not found, we set the HTTP status code to 404.