人生如梦 一樽还酹江月
gin:一款高性能的go web框架
目录
项目结构
main.go(多组路由)
分两组路由,验证路由分组功能
package main
import (
"gin-coms/config"
"gin-coms/routers"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// 第一组路由:以/api开头
apiGroup := router.Group("/api")
{
routers.CusRoute(apiGroup)
routers.OrderRoute(apiGroup)
}
// 第二组路由:以/other开头
otherGroup := router.Group("/other")
{
routers.OtherRoute(otherGroup)
}
//config.InitMysql()
router.Run(config.ComsAddress + ":" + config.ComsPort)
}
以order.go测试GET各请求
package routers
import (
"fmt"
"gin-coms/model"
"github.com/gin-gonic/gin"
"net/http"
)
func OrderRoute(group *gin.RouterGroup) {
group.GET("/order", OrderList)
group.GET("/order/:ID", OrderDetail)
// URL的问号会带参数name
// http://localhost:8000/api/orderByName?name=无名
group.GET("/orderByName", OrderByName)
}
func OrderByName(c *gin.Context) {
name := c.Query("name") //获取URL路径参数
fmt.Println("您要查询的订单名称是:", name)
c.JSON(http.StatusOK, "hello 这里是/api/orderByName路由,您要查询的订单名称是:"+name)
//c.String(http.StatusOK, "hello 这里是/api/order路由")
}
func OrderDetail(c *gin.Context) {
id := c.Param("ID") //获取URL路径参数
fmt.Println("您要查询的是", id, "号订单。")
c.JSON(http.StatusOK, "hello 这里是/api/order/:ID路由,您要查询的是"+id+"号订单。")
//c.String(http.StatusOK, "hello 这里是/api/order路由")
}
func OrderList(c *gin.Context) {
var orderList []model.Order
order1 := model.Order{Name: "订单1", OrderPrice: 88}
order2 := model.Order{Name: "订单2", OrderPrice: 99}
orderList = append(orderList, order1, order2)
c.String(http.StatusOK, "hello 这里是/api/order路由,此处返回订单列表:", orderList)
// 如果要返回自定义结构体类型ReturnStruct,需要改源码,在type HandlerFunc func(*Context)后加返回值ReturnStruct即可。
//return model.ReturnStruct{Code:http.StatusOK,Message:"hello 这里是/api/order路由,此处返回订单列表!",Data:orderList}
}
URL1:http://localhost:8000/api/orderByName?name=无名
URL2:http://localhost:8000/api/order/9
order列表:
控制台日志如下:
以customer.go测试POST/PUT请求
分别以两种方式获取请求体参数
package routers
import (
"fmt"
"gin-coms/model"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func CusRoute(group *gin.RouterGroup) {
group.POST("/cus", CreateCustomer)
group.PUT("/cus", UpdateCustomer)
}
func CreateCustomer(c *gin.Context) {
var cus model.Customer
err := c.BindJSON(&cus) // 获取请求体参数,请求头为application/json
if err != nil {
log.Println(err.Error())
}
fmt.Println("用户", cus, "已创建。")
c.JSON(http.StatusOK, "用户已创建。")
}
func UpdateCustomer(c *gin.Context) {
name := c.PostForm("name") // 获取请求体参数,请求头为application/x-www-form-urlencoded
gender := c.PostForm("gender")
fmt.Println("用户", name," ",gender, "已修改。")
c.JSON(http.StatusOK, "用户已修改。")
}
测试POST
测试PUT
控制台打印: