您的位置:首页 > 其它

Gin框架初识

2017-10-04 17:35 232 查看
关于Gin的具体说明与源码:https://github.com/gin-gonic/gin

一.安装

命令行输入:
go get github.com/gin-gonic/gin


安装位置:go的环境变量中配置的全局的lib目录

二:基本应用

1. GET

1)gin.Context中的Query方法:get的URL传参

func getQuery(context *gin.Context){

userid := context.Query("userid")
username := context.Query("username")

context.String(http.StatusOK,userid+" "+username)
}
func main(){
// 注册一个默认路由器
router := gin.Default()

//注册GET处理
router.GET("/user", getQuery)

//默认8080端口
router.Run(":8088")
}


测试:URL:http://localhost:8088/user?userid=1&username=tyming

浏览器输出:1 tyming

2)gin.Context中的Param方法:RESRful风格URL传参

func getParam(context *gin.Context){

userid := context.Param("userid")
username := context.Param("username")

context.String(http.StatusOK,userid+" "+username)
}
func main(){
// 注册一个默认路由器
router := gin.Default()

//注册GET处理
//router.GET("/user", getQuery)
router.GET("/user/:userid/:username",getParam)
//默认8080端口
router.Run(":8088")
}


补充:/:varname必须匹配对应的,/*varname匹配后面的所有,同时不能用多个,否则编译报错

测试:URL:http://localhost:8088/user/1/tyming

页面输出:1 tyming

2. POST

*1)gin.Context中的PostForm方法:POST表单提交*


func post(context *gin.Context){

username := context.PostForm("username")
//设置默认值,没有值返回默认值
password := context.DefaultPostForm("password","1234567890")

context.JSON(200, gin.H{
"status":  "posted",
"username": username,
"password": password,
})
}
func main(){
// 注册一个默认路由器
router := gin.Default()

//注册POST处理
router.POST("/user",post)
//默认8080端口
router.Run(":8088")
}


测试:模拟post



2)参数绑定

type User struct {
UserName string `form:"username"`
PassWord string `form:"password"`
}
func bind(context *gin.Context){
var user User

if context.Bind(&user) == nil{

context.JSON(http.StatusOK,gin.H{"username":user.UserName,"password":user.PassWord})
}
}

func main(){
// 注册一个默认路由器
router := gin.Default()

//注册POST处理器
router.POST("/bind",bind)
//默认8080端口
router.Run(":8088")
}


测试:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: