gin框架路由传参与响应返回
1.路由传参
1.1 无参路由
请求地址:127.0.0.1:8000/hello
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/hello", GetDemoHandler)
r.Run(":8000")
}
func GetDemoHandler(c *gin.Context) {
c.String(http.StatusOK, "hello,word")
}
执行结果
1.2. url参数路由(Query,DefaultQuery)
请求地址:127.0.0.1:8000/login?name=li&age=28
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/login", GetLoginHandler)
r.Run(":8000")
}
func GetLoginHandler(c *gin.Context) {
//方式一:c.DefaultQuery获取值,如果没有使用默认值
//127.0.0.1:8000/login?name=li&age=108
/*
name := c.DefaultQuery("name", "moren")
age := c.DefaultQuery("age", "25")
c.String(http.StatusOK, fmt.Sprintf("name=%v,age=%v",name, age)) //li 108
*/
//方式二:c.Query获取请求参数的值,没有默认值,如果没有为 nil
name := c.Query("name")
age := c.Query("age")
c.String(http.StatusOK, fmt.Sprintf("name=%v,age=%v", name, age))
}
1.3. api参数路由(Param)
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/book/:id", GetBookHandler) //使用 id来获取
r.Run(":8000")
}
func GetBookHandler(c *gin.Context) {
id := c.Param("id") //通过Context的Param方法来获取API参数,id需要跟路由中定义的id名一致
c.String(http.StatusOK, fmt.Sprintf("第%v页", id))
}
1.4. 传值绑定到结构体(ShouldBind)
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.POST("/user", GetUserHandler)
r.Run(":8000")
}
type User struct {
//binding:"required" 要求username字段不能为空
Username string `from:"username" json:"username" binding:"required"`
Password string `from:"password" json:"password" binding:"required"`
}
func GetUserHandler(c *gin.Context) {
var User User //定义一个结构体对象
err := c.ShouldBind(&User) //必须要传入一个结构体对象
if err != nil {
c.String(http.StatusOK, fmt.Sprintln("err:", err)) //页面返回错误信息
}
c.String(http.StatusOK, fmt.Sprintf("username=%v,password=%v", User.Username, User.Password))
}
2. 响应和返回
2.1.响应字符串
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/string", GetStringHandler)
r.Run(":8000")
}
func GetStringHandler(c *gin.Context) {
c.String(http.StatusOK, "返回字符串")
}
2.2.响应json
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/json", GetJsonHandler)
r.Run(":8000")
}
func GetJsonHandler(c *gin.Context) {
/*
//方式一:
type Data struct {
Msg string `json:"msg"`
Code int `json:"code"`
}
d := Data{
Msg: "success",
Code: 10011,
}
c.JSON(http.StatusOK, d)
*/
//方式二:
c.JSON(http.StatusOK, gin.H{
"Msg": "success",
"Code": 10011,
})
}
2.3.路由重定向
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/redirect", GetRedirectHandler)
r.Run(":8000")
}
func GetRedirectHandler(c *gin.Context) {
//http.StatusMovedPermanently为状态码301
//第二个参数为重定向之后的路径
c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
}