获取请求携带的quetystring参数
http://127.0.0.1:8080/web?query=jibu
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// gin.Context,封装了request和response
func main() {
r := gin.Default()
r.GET("/web", func(c *gin.Context) {
// 获取请求携带的quetystring参数
// 取不到使用默认值
name := c.DefaultQuery("query","morenzhi")
// 返回两个参数,这里的ok是布尔值
name,ok := c.GetQuery("query")
name := c.Query("query")
if !ok{
name="没取到"
}
c.JSON(http.StatusOK,gin.H{
"name":name,
})
})
r.Run()
}
补充一个命令
查一下项目中依赖的包有没有都存在
go mod tidy
form参数
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// gin.Context,封装了request和response
func main() {
r := gin.Default()
r.LoadHTMLFiles("./login.html")
// 发送get请求获取登录页面
r.GET("/login",func(c *gin.Context){
c.HTML(http.StatusOK,"login.html",nil)
})
//点击登录
r.POST("/login", func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
//username := c.DefaultPostForm("username")
//password := c.DefaultPostForm("password")
//
//username,ok := c.GetPostForm("username")
//if !ok{
// username = "sb"
//}
c.HTML(http.StatusOK,"index.html",gin.H{
"Name":username,
"Password":password,
})
})
r.Run()
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login" method="post" novalidate autocomplete="off">
<div>
<label for="username">username:</label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="">password:</label>
<input type="password" name="password" id="password">
</div>
<input type="button" value="登录">
</form>
</body>
</html>
路径穿参
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// gin.Context,封装了request和response
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.Run()
}
注意:URL路径不要冲突