1.获取GET参数
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func getpage(c *gin.Context) {
id1 := c.DefaultQuery("id1", "1")
id2 := c.Query("id2")
fmt.Println(id1)
c.JSON(http.StatusOK, gin.H{
"id1": id1,
"id2": id2,
})
}
func main() {
router := gin.Default()
router.GET("/page", getpage)
router.Run()
}
2.获取POST参数
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func login(c *gin.Context) {
username := c.DefaultPostForm("username", "admin")
password := c.PostForm("password")
if username == "admin" && password == "123" {
c.JSON(http.StatusOK, gin.H{"message": "登录成功"})
} else {
c.JSON(404, gin.H{"message": "登录失败"})
}
}
func main() {
router := gin.Default()
router.POST("", login)
router.Run()
}
3.同时获取GET与POST参数
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
message := c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")
}