controller绑定参数常用如下方法
1、 获取path中的参数
// this one will match /user/john/ and also /user/john/send// If no other routers match /user/john, it will redirect to /user/john/router.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") message := name + " is " + action c.String(http.StatusOK, message)})
2、 获取query string中的参数
// Query string parameters are parsed using the existing underlying request object.// The request responds to a url matching: /welcome?firstname=Jane&lastname=Doerouter.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname", "Guest")
lastname := c.Query("lastname")
// shortcut for c.Request.URL.Query().Get("lastname")
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
3、 处理表单数据
// Query string parameters are parsed using the existing underlying router.POST("/form_post", func(c *gin.Context) { message := c.PostForm("message") nick := c.DefaultPostForm("nick", "anonymous") c.JSON(200, gin.H{ "status": "posted", "message": message, "nick": nick, })})
4、 处理单文件上传
//curl -X POST http://localhost:8080/upload -F "file=@/Users/appleboy/test.zip" -H "Content-Type: multipart/form-data"
router.POST("/upload", func(c *gin.Context) { // single file file, _ := c.FormFile("file") log.Println(file.Filename) // Upload the file to specific dst. // c.SaveUploadedFile(file, dst) c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))})
5、 处理多文件上传
// curl -X POST http://localhost:8080/upload \ -F "upload[]=@/Users/appleboy/test1.zip" \ -F "upload[]=@/Users/appleboy/test2.zip" \ -H "Content-Type: multipart/form-data" router := gin.Default() // Set a lower memory limit for multipart forms (default is 32 MiB) // router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // Multipart form form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { log.Println(file.Filename) // Upload the file to specific dst. // c.SaveUploadedFile(file, dst) } c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) })本文源代码源代码获取地址 https://github.com/winlion/restgo
10.2 天天任务清单小程序
https://github.com/winlion/dailytask
10.3 工业大数据采集
10.4 restgo cms
10.5 restgo 千人大群
作者简介:胡文林,持续创业者,长期从事技术开源工作。微信号jiepool-winlion
