1、使用通用的Handle方法
r := gin.Default()
r.Handle("GET", "/hello", func(context *gin.Context) {
name := context.DefaultQuery("name", "默认值")
fmt.Println(name)
context.Writer.Write([]byte("hello," + name))
})
r.Run()
第一个参数是请求方法,如GET、POST,第二个参数是请求的地址,第三个参数是处理请求的方法。
使用http://localhost:8080/hello
输出hello,默认值。使用context.DefaultQuery("name", "默认值")获取name参数,如果没有传递name,那就使用第二个参数当做默认值,如果传递就使用传递的值
使用http://localhost:8080/hello?name=fq,输出hello,fq。
再举个POST请求的例子
r := gin.Default()
r.Handle("POST", "/hello", func(context *gin.Context) {
name := context.PostForm("name")
fmt.Println(name)
context.Writer.Write([]byte("hello," + name))
})
r.Run()
这里使用context.PostForm("name")来获取参数。
使用http://localhost:8080/hello,在post传递name值fq
输出hello,fq。
2、使用分类方法
r.Handle("GET", "/hello", func(context *gin.Context) {})
对应的就是第一个参数当做方法名,只有第二和第三是参数。
r.GET("/hello", func(context *gin.Context) {})