\
包含不同请求类型的处理,response返回类型,类型绑定,和html模板和静态文件处理。
Request | Response |
---|---|
curl -L ‘http://localhost:8080/ping?name=xwp’ | |
curl -L --header ‘Content-Type: application/x-www-form-urlencoded’ --data-urlencode ‘usern=xwp’ --data-urlencode ‘password=xwp123’ http://localhost:8080/login | |
curl -L --request DELETE ‘http://localhost:8080/user/3’ | |
curl -L ‘http://localhost:8080/hello?id=27&username=xwp’ | |
curl -L ‘http://localhost:8080/register’ --header ‘Content-Type: application/x-www-form-urlencoded’ --data-urlencode ‘name=xwp’ --data-urlencode ‘password=xwp123’ --data-urlencode ‘phone=8772463’ | |
curl -L ‘http://localhost:8080/addstudent’ --header ‘Content-Type: application/json’ --data ‘{“id”: 100,“username”: “yjj”}’ | |
curl -L http://localhost:8080/jsonstruct | |
http://localhost:8080/testhtml |
package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
engine := gin.Default()
// curl -L 'http://localhost:8080/ping?name=xwp'
engine.GET("/ping", func(c *gin.Context) {
// c.Writer.Write([]byte("Hello, gin!\n"))
query_res := c.DefaultQuery("name", "unknow")
fmt.Printf("query_res: %v\n", query_res)
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"fullPath": c.FullPath(),
})
})
// curl -L --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'usern=xwp' --data-urlencode 'password=xwp123' http://localhost:8080/login
engine.POST("/login", func(c *gin.Context) {
var user, password string
user, b := c.GetPostForm("user")
if !b {
c.Writer.Write([]byte("username is empty, please try again!\n"))
return
}
password = c.PostForm("password")
fmt.Printf("username: %v password: %v\n", user, password)
c.Writer.Write([]byte(fmt.Sprintf("%v login successfully!", user)))
})
// curl -L --request DELETE 'http://localhost:8080/user/3'
engine.DELETE("/user/:id", func(c *gin.Context) {
id := c.Param("id")
fmt.Printf("User id: %v\n", id)
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("user %v has been deleted", id),
})
})
// GET提交表单:curl -L 'http://localhost:8080/hello?id=27&username=xwp'
engine.GET("/hello", func(c *gin.Context) {
var s Student
if err := c.ShouldBindQuery(&s); err != nil {
log.Fatal(err)
return
}
fmt.Printf("Id: %v\n", s.Id)
fmt.Printf("Username: %v\n", s.Username)
c.Writer.Write([]byte(fmt.Sprintf("hello %v\n", s.Username)))
})
// POST提交表单: curl -L 'http://localhost:8080/register' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'name=xwp' --data-urlencode 'password=xwp123' --data-urlencode 'phone=8772463'
engine.POST("/register", func(c *gin.Context) {
var register Register
if err := c.ShouldBind(®ister); err != nil {
log.Fatal(err)
return
}
fmt.Printf("Name: %v\n", register.Name)
fmt.Printf("Password: %v\n", register.Password)
fmt.Printf("Phone: %v\n", register.Phone)
c.Writer.Write([]byte(register.Name + " registe successfully!"))
})
// POST提交json数据表单: curl -L 'http://localhost:8080/addstudent' --header 'Content-Type: application/json' --data '{"id": 100,"username": "yjj"}'
engine.POST("/addstudent", func(c *gin.Context) {
var student Student
if err := c.BindJSON(&student); err != nil {
log.Fatal(err)
return
}
fmt.Printf("student.Id: %v\n", student.Id)
c.Writer.Write([]byte(fmt.Sprintf("%v add successfully!\n", student.Username)))
})
// resopnse以json格式返回一个结构体对象 curl -L http://localhost:8080/jsonstruct
engine.GET("/jsonstruct", func(c *gin.Context) {
stu1 := Student{Id: 5378, Username: "Lenyu"}
c.JSON(http.StatusOK, &stu1)
})
// 返回一个html curl -L http://localhost:8080/testhtml
engine.LoadHTMLGlob("./html/*")
engine.Static("static", "static")
engine.GET("testhtml", func(c *gin.Context) {
fullPath := c.FullPath()
c.HTML(http.StatusOK, "index.html", gin.H{
"fullPath": fullPath,
"title": "gin教程",
})
})
engine.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
type Student struct {
Id int `form:"id"`
Username string `form:"username"`
}
type Register struct {
Name string `form:"name"`
Phone string `form:"phone"`
Password string `form:"password"`
}
定义RouterGroup,定义中间件FullPathAndMethod(),打印请求路径和请求方法并返回响应状态码。
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
// 模块化开发
// 用户注册: /user/register
// 用户登录: /user/login
// 用户信息: /user/info
// 用户删除: /user/id
engine := gin.Default()
rg := engine.Group("/user")
rg.POST("/register", FullPathAndMethod(), registerHandler)
rg.POST("/login", loginHandler)
rg.DELETE("/:id", FullPathAndMethod(), deleteHandler)
rg.GET("/info", FullPathAndMethod(), infoHandler)
engine.Run()
}
func registerHandler(c *gin.Context) {
fullPath := c.FullPath()
if _, err := c.Writer.WriteString("FullPath: " + fullPath); err != nil {
fmt.Printf("Write err: %v", err)
return
}
fmt.Println("registerHandler handler")
}
func loginHandler(c *gin.Context) {
fullPath := c.FullPath()
if _, err := c.Writer.WriteString("FullPath: " + fullPath); err != nil {
fmt.Printf("Write err: %v", err)
return
}
}
func deleteHandler(c *gin.Context) {
fullPath := c.FullPath()
id := c.Param("id")
if _, err := c.Writer.WriteString("FullPath: " + fullPath + "\nDelete user id: " + id); err != nil {
fmt.Printf("Write err: %v", err)
return
}
}
func infoHandler(c *gin.Context) {
fullPath := c.FullPath()
if _, err := c.Writer.WriteString("FullPath: " + fullPath); err != nil {
fmt.Printf("Write err: %v", err)
return
}
}
// write an middleware to print request url fullpath and request method.
func FullPathAndMethod() gin.HandlerFunc {
return func(c *gin.Context) {
fullPath := c.FullPath()
method := c.Request.Method
fmt.Printf("fullPath: %v\n", fullPath)
fmt.Printf("method: %v\n", method)
c.Next()
// 打印处理响应完成后的状态码
httpCode := c.Writer.Status()
fmt.Printf("响应状态码: %v\n", httpCode)
}
}