Gin微框架入门——路由天下
Gin的基本入门案例:package mainimport ("github.com/gin-gonic/gin""net/http")func main() {router := gin.Default()////http://127.0.0.1:8080/params?firstname=lcd&lastname=dongrouter...
·
Gin的基本入门案例:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
//
//http://127.0.0.1:8080/params?firstname=lcd&lastname=dong
router.GET("/params", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname","defaultName")
lastname := c.Query("lastname")
c.JSON(http.StatusOK, gin.H{
"firstName":firstname,
"lastName":lastname,
})
})
//
//http://127.0.0.1:8080/user/lcd
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.JSON(http.StatusOK, gin.H{
"name": name,
})
})
//
//http://127.0.0.1:8080/form_post
router.POST("/form_post", func(c *gin.Context) {
name := c.PostForm("name")
nick := c.DefaultPostForm("age", "90")
c.JSON(200, gin.H{
"name": name,
"age": nick,
})
})
//
//http://127.0.0.1:8080/json_post
router.POST("/json_post", func(c *gin.Context) {
type User struct {
Username string `form:"username" json:"username"`
Password string `form:"passwd" json:"passwd"`
Age int `form:"age" json:"age"`
}
//
var user User
c.BindJSON(&user)
c.JSON(200, gin.H{
"data": user,
})
})
//
router.Run("0.0.0.0:8080")
}
编译运行:
go run main.go
go build main.go
参考:
https://segmentfault.com/a/1190000019972283?utm_source=tag-newest
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)