Middleware return func(c *gin.Context) cCp := c.Copy()


func Middleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var json Data
		fmt.Println(c)
		fmt.Println("Action", json.Action)
		buf := make([]byte, 1024)
		n, _ := c.Request.Body.Read(buf)
		fmt.Println(string(buf[0:n]))
		cCp := c.Copy()
		if err := c.ShouldBindJSON(&json); err == nil {
			switch json.Action {
			case "goto":
				fmt.Println(json.Action)
				TOGO(cCp)
			}
		} else {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		}

		c.Next()

	}
}

func main() {
	router := gin.Default()

	//router.POST("/", gin.WrapF(test))
	router.POST("/", Middleware())
	router.Run(":8090")
}

func TOGO(c *gin.Context) {
	fmt.Println("dsdsdsd")
	fmt.Println(c)
	var json Infos
	fmt.Println(json.Instance_id)
	buf := make([]byte, 1024)
	n, _ := c.Request.Body.Read(buf)
	fmt.Println(string(buf[0:n]))
	if err := c.BindJSON(&json); err == nil {
		fmt.Println("Action", json.Instance_id)
	}
	c.JSON(200, gin.H{
		"status":  "posted",
		"message": json.Instance_id,
	})

}

outconsole

&{{0xc42023c0e0 -1 200} 0xc42024a000 0xc420250000 [] [0x1508b60 0x1509920 0x150ba30] 2 0xc42023e000 map[]  []}

Action goto
&{{0xc42023c0e0 -1 200} 0xc42024a000 0xc420250000 [] [0x1508b60 0x1509920 0x150ba30] 2 0xc42023e000 map[]  []}
[GIN] 2018/08/05 - 17:17:49 | 200 |     332.399µs |       127.0.0.1 | POST     /

Why don’t you get Jie g at the address json action ?

go version

~ » go env                                                                                                                                                                                                     liberxue@liberxuedeMacBook-Pro
GOARCH="amd64"
GOBIN="/Users/liberxue/golang/bin"
GOCACHE="/Users/liberxue/Library/Caches/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/liberxue/golang"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.10.3/libexec"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.10.3/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/1f/1b5_xh8x2sq5q_lfs0p86x640000gn/T/go-build428959401=/tmp/go-build -gno-record-gcc-switches -fno-common"

1 possible answer(s) on “Middleware return func(c *gin.Context) cCp := c.Copy()