栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

go利用gin框架提供接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go利用gin框架提供接口

在go中有两种web框架,其中一个是 Martini 和 Gin,gin用的更方便,下面就介绍利用gin提供简单的接口

安装gin

在terminal中输入
go get -u github.com/gin-gonic/gin

导入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()
}

运行请求接口


get请求获取请求参数

通过: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)
})
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/709419.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号