接受get请求的传值

例如http://localhost:8080?username=xxx&age=xxx

route.GET("/",func(context *gin.Context){
var useinfo=map[string]string{
"username":context.Query("username"),
"age":context.Query("age"),
"name":context.Query("name"),
"page":context.DefaultQuery("query","1"),
}
context.JSON(200,userinfo)
})

这里我们很明显定义了一个map来接收数据,DefaultQuery表示如果没有查询到该值,则在这里1便是它的默认值

接受post的请求的传值

很简单的例子就是创建一个html表单进行传值,这个html只做展示不一定和go对得上

<form action="/doAddUser" method="post">
<label>
username:<input type="text" name="username">
</label>
<br>
<label>
password:<input type="password" name="password">
</label>
<input type="submit" value="提交">
</form>

然后我们在后端接受,但当然我们得先渲染一下刚定义的form.html

route.GET("/user",func(context *gin.Context){
context.HTML(200,"default/user.html",gin.H{})
})

route.POST("/doAddUser",func(context *gin.Context){
var userinfo=map[string]string{
"username":context.PostForm("username"),
"age":context.PostForm("age"),
"sex":context.PostForm("username"),
"page":context.DefaultPostForm("page","1"),
}
context.JSON(200,userinfo)
})

get和post只是我们调用的函数不一样罢了
在此提醒加载html文件时,以templates/default/index.html为例

  • 在文件最顶部加上define “default/index.html
    {{define "default/index.html}}
  • 尾部加上
    {{end}}
  • 然后再创建route后,加上
    route.LoadHTMLGlob("templates/**/*")

    前两条的“ ”是不用加的,但用于渲染器的毛病不加要报错

进阶版

我们发现上面的方法都要一个一个的赋值很麻烦,然后就有新的方法context.ShouldBind()可以将值与结构体绑定,当然值得对应上

首先我们在主函数外创建一个结构体

type User struct{
Username string `form:"username" json:"username"`
Passwoed string `form:"password" json:"password"`
}

get版

route.GET("/",func (context *gin.Context){
user:=&User{}
_:=context.ShouldBind(&user)
context.json(200,user)
})

结果如下
image

post版

两者几乎一样,只不过post版得建一个form表单而已

route.GET("/user1", func(context *gin.Context) {
context.HTML(http.StatusOK, "default/user1.html", gin.H{})
})
route.POST("/doAddUser1", func(context *gin.Context) {
user := &UserInfo{}
err := context.ShouldBind(&user)
if err != nil {
return
}
context.JSON(200, user)
})

结果也与上面相同

拓展发送xml请求

在这里我们尝试用postman发送请求,结果也在图上
image

定义了一个articile的结构体

type Article struct {
Title string `xml:"title" json:"title"`
Content string `xml:"content" json:"content"`
}

xml的代码

<?xml version="1.0" encoding="UTF-8" ?>
<article>
<content type="string">我是张三</content>
<title type="string">张三</title>
</article>

xml的解析就比上面复杂一点

route.POST("/xml",func(context *gin.Context){
data,_:=context.GetRawData()//byte类型
article=&Article{}
_=xml.Unmarshal(data,&article)
context.JSON(200, article)
})

结果在上图的下面

`