Open awkj opened 5 years ago
Try
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.POST("/status", wrapper(handler))
r.Run(":8080")
}
func wrapper(f func(c *gin.Context) (string, error)) gin.HandlerFunc {
return func(c *gin.Context) {
_, err := f(c)
if err != nil {
c.JSON(503, gin.H{"status": err})
return
}
c.JSON(200, gin.H{"status": "OK"})
}
}
func handler(c *gin.Context) (string, error) {
var status string
if err := c.ShouldBindJSON(&status); err != nil {
return "failed", err
}
return status, nil
}
With issues:
go version: go 1.12.4
gin version (or commit ref): 1.3.0
operating system: Mac/Linux
Description
My work function alway is signature
I wish to add a wrap function to wrap it, when err is nil I return
other return
and , if gin must implement `func (c *gin.Context) to add router I try to write as
but I must add this repeat code when I add a function, have better solution to write it ?
Screenshots