第十五章 Go语言如何编写请求Api
GO 语言框架gin
HelloWorld
1.首先下载框架到本地
go get -u github.com/gin-gonic/gin
2.导入包
import "github.com/gin-gonic/gin"
func main (){
//编写一个helloworld
//1 创建一个路由
engine := gin.Default()
//2 绑定路由规则,执行的函数
//gin.Context 相当于把Request 和Response 封装起来了
engine.GET("/", func(context *gin.Context) {
//如果是200 就返回 hello World
context.String(http.StatusOK,"hello World!")
})
//3 监听端口 默认是8080
engine.Run(":8001")
}
使用api参数
engine.GET("/get/:name", func(context *gin.Context) {
//如果是200 就返回 hello World
var name = context.Param("name")
context.String(http.StatusOK,"hello World!"+name)
})
使用url参数
engine.GET("/get", func(context *gin.Context) {
//如果是200 就返回 hello World
name := context.Query("name")
age := context.DefaultQuery("age", "18")
context.String(http.StatusOK,age+" hello World! "+name)
})
使用表单提交
engine.GET("/get", func(context *gin.Context) {
//如果是200 就返回 hello World
name, _ := context.GetPostForm("name")
age, _ := context.GetPostForm("age")
context.String(http.StatusOK,age+" hello World! "+name)
})
表单上传文件:
前端
<form name="上传文件" method="post" enctype="multipart/form-data" action="http://127.0.0.1:8001/file">
<input type="file" name="image_1" >
<input type="submit" value="提交post">
</form>
后端:
engine.POST("/file", func(context *gin.Context) {
//如果是200 就返回 hello World
file, _ := context.FormFile("image_1")
//打印文件名称
log.Println(file.Filename)
//上传文件并且保存在项目根路径 第一个是文件 第二个是 文件名称
context.SaveUploadedFile(file,file.Filename)
//打印信息
context.String(http.StatusOK,"上传成功")
})
请求json 数据
engine.POST("/json", func(context *gin.Context) {
var user1 User1
err := context.ShouldBind(&user1)
if err !=nil {
context.JSON(http.StatusBadRequest,gin.H{"status":"304"})
return
}
fmt.Println("打印 "+user1.Id+" " +user1.Name )
//打印信息
context.String(http.StatusOK,"{\"code\":\"json参数成功\"}")
})
type User1 struct {
Id string `json:"id"`
Name string `json:"name"`
}
请求JSON数组数据
engine.POST("/json", func(context *gin.Context) {
//var user1 User1
var cards []Cards
err := context.ShouldBind(&cards)
if err !=nil {
context.JSON(http.StatusBadRequest,gin.H{"status":"304"})
return
}
if cards !=nil{
//遍历数据
for index,value :=range cards{
fmt.Printf("数组cards[%d] = %v \n",index,value)
}
}
//打印信息
context.String(http.StatusOK,"{\"code\":\"json参数成功\"}")
})
请求JSON对象携带JSON数组
engine.POST("/jsonObj", func(context *gin.Context) {
var user1 User1
err := context.ShouldBind(&user1)
if err !=nil {
context.JSON(http.StatusBadRequest,gin.H{"status":"304"})
return
}
fmt.Println(user1.Id+" "+user1.Name)
//遍历数据
for index,value :=range user1.Card{
fmt.Printf("数组cards[%d] = %v \n",index,value)
}
//打印信息
context.String(http.StatusOK,"{\"code\":\"json参数成功\"}")
})

浙公网安备 33010602011771号