在go中有两种web框架,其中一个是 Martini 和 Gin,gin用的更方便,下面就介绍利用gin提供简单的接口
安装gin在terminal中输入
go get -u github.com/gin-gonic/gin
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/test", func(c *gin.Context) {
c.JSON(200,gin.H{
"message":"返回成功",
})
})
r.Run()
}
运行请求接口
通过:name获取请求参数,name可以随便定义
r.GET("/test/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
通过请求连接携带参数获取值
// http://127.0.0.1:8080/test?name=xxx&password=xxx,password可填可不填,默认123456
r.GET("/test", func(c *gin.Context) {
name := c.Query("name")
password := c.DefaultQuery("password", "123456")
c.String(http.StatusOK, "%s is a %s", name, password)
})
post请求获取请求参数
通过form-date格式获取参数
//post请求,获取传递的参数,password可选,默认123456
r.POST("/test", func(c *gin.Context) {
username := c.PostForm("username")
password := c.DefaultPostForm("password", "123456")
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
通过application/json格式获取参数
r.POST("/test", func(c *gin.Context) {
names := c.PostFormMap("user")
c.JSON(http.StatusOK, gin.H{
"user": user,
})
})
get和post综合使用
http://127.0.0.1:8080/test?age=xxx
通过get方式传值,还能通过post方式传值
r.POST("/test", func(c *gin.Context) {
age := c.Query("age")
sex := c.DefaultQuery("sex", "男")
username := c.PostForm("username")
password := c.DefaultPostForm("password", "123456")
c.JSON(http.StatusOK, gin.H{
"age": age,
"sex": sex,
"username": username,
"password": password,
})
})
上传文件
r.POST("/upload", func(c *gin.Context) {
//上传一个文件
file, _ := c.FormFile("file")
//上传多个文件
//form, _ := c.MultipartForm()
//files := form.File["upload[]"]
c.String(http.StatusOK, "%s uploaded!", file.Filename)
})



