package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
//获取请求的path(URL)参数 ,返回的都是字符串类型
func main() {
r := gin.Default()
r.GET("/:name/:age", func(c *gin.Context) {
//获取路径参数
name := c.Param("name")
age := c.Param("age")
c.JSON(http.StatusOK, gin.H{
"name": name,
"age": age,
})
})
r.GET("/blog/:year/:month", func(c *gin.Context) {
year := c.Param("year")
month := c.Param("month")
c.JSON(http.StatusOK, gin.H{
"year": year,
"month": month,
})
})
r.Run(":9090")
}
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type UserInfo struct {
Username string `form:"username"`
Password string `form:"password"`
}
func main() {
r := gin.Default()
r.LoadHTMLFiles("./index.html")
r.GET("/user", func(c *gin.Context) {
var u UserInfo //声明一个UserInfo类型的变量
err := c.ShouldBind(&u)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
} else {
fmt.Printf("%#v\n", u)
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"name": u.Username,
"pass": u.Password,
})
}
})
r.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil) //渲染一个页面
})
r.POST("/form", func(c *gin.Context) {
var u UserInfo //声明一个UserInfo类型的变量
err := c.ShouldBind(&u)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
} else {
fmt.Printf("%#v\n", u)
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"name": u.Username,
"pass": u.Password,
})
}
})
r.Run(":9090")
}
ShouldBind用于获取请求中携带的参数
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<form action="/form" method="post">
用户名:
<input type="text" name="username">
密码:
<input type="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>