使用热门的GIN框架,快速的搭建一个简单的网页来返回JSON数据。配置一下路由,用自定义的控制器去控制路由的跳转。
一、搭建gin
1、使用go mod管理项目,并生成go.mod文件
go mod init name
2、下载安装gin
go get -u github.com/gin-gonic/gin
生成go.mod和go.sun文件
- 编辑器还是报红,运行go mod vendor解决
3、创建main.go,在网页中返回json信息
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"msssage": "hello word",
"index": "this is the papge",
})
})
4、运行main.go文件
go run main.go
二、路由获取信息
1、使用get请求
- 在get请求的url中获取参数
//获取get的url中的值
r.GET("/login/:username", func(ctx *gin.Context) {
username := ctx.Param("username")
ctx.JSON(http.StatusOK, gin.H{
"username": username,
})
})
2、使用post请求获取参数
r.POST("/login", func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
c.JSON(http.StatusOK, gin.H{
// c.JSON:返回 JSON 格式的数据
"name": username,
"password": password,
})
})
3、获取post的json请求,用结构体接受
type Department struct {
Id int `json:"id"`
DeptName string `json:"deptName"`
}
r.POST("/loginJson", func(c *gin.Context) {
dept := &Department{}
err := c.ShouldBindJSON(&dept)
if err == nil {
fmt.Printf("%#v \n", dept)
c.JSON(http.StatusOK, dept)
} else {
c.JSON(http.StatusBadRequest, gin.H{
"err": err.Error(),
})
}
})
三、路由分组
1、创建文件
- 创建route文件夹
- 创建userRouters.go
package routers
import (
"net/http"
"github.com/gin-gonic/gin"
)
func UserRoutersInit(router *gin.Engine) {
userRouter :=router.Group("/user")
userRouter.GET("/add",func(ctx *gin.Context) {
ctx.String(http.StatusOK,"添加功能")
})
userRouter.GET("/update",func(ctx *gin.Context) {
ctx.String(http.StatusOK,"修改功能")
})
}
2、在main.go中加入路由
// 路由抽离并分组
routers.UserRoutersInit(r)
出现错误
404找不到url地址的资源,原因有
-
- url地址写错,没有和配置的路由对应
-
- 没有在main中对
*gin.Context写入路由
- 没有在main中对
add功能在Group("/user")中,所以路由地址应该是/user/add
四、用控制器控制路由
1、自定义控制器
核心是Success方法和Error方法
package controllers
import (
"net/http"
"github.com/gin-gonic/gin"
)
func (con BaseController) Success(c *gin.Context, msg string) {
c.JSON(http.StatusOK, gin.H{
"msg": msg,
})
}
func (con BaseController) Error(c *gin.Context, msg string) {
c.JSON(http.StatusBadRequest, gin.H{
"msg": msg,
})
}
2、创建usercontrol去继承basecontrol
package user
import (
"ginDemo2/controllers"
"github.com/gin-gonic/gin"
)
type UserController struct {
controllers.BaseController
}
func (con UserController) AddUser(c *gin.Context) {
con.Success(c, "添加用户--")
}
func (con UserController) EditUser(c *gin.Context) {
con.Error(c, "修改用户--")
}
3、修改路由
在userRouters.go修改一下
func DeptRoutersInit(router *gin.Engine) {
deptRouter := router.Group("/dept")
deptRouter.GET("/addDept", department.DepartmentController{}.AddDept)
deptRouter.GET("/editDept", department.DepartmentController{}.EditDept)