创建gomod:go mod init 项目名称
下载gin依赖:go get -u github.com/gin-gonic/gin
创建main.go文件
package main
import "github.com/gin-gonic/gin"
func main() {
// 创建一个默认服务
ginServer := gin.Default()
// Get请求
ginServer.GET("/hello", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"msg": "hello Gin"})
})
// 端口
ginServer.Run(":8081")
}
运行:go run main.go
index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link ref="stylesheet" href="/static/css/index.css">
<script src="/static/js/index.js">script>
<title>Documenttitle>
head>
<body>
<h1>吕竟h1>
{{.msg}}
body>
html>
返回
// 返回一个前端页面
// 加载静态页面
ginServer.LoadHTMLGlob("template/*")
// 加载资源文件
ginServer.Static("static", "./static")
ginServer.GET("/myIndex", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.html", gin.H{"msg": "后台传递的参数"})
})
ginServer.GET("/getUrl1", func(ctx *gin.Context) {
userName := ctx.Query("userName")
ctx.JSON(http.StatusOK, gin.H{"userName": userName})
})
ginServer.GET("/getUrl2/:userName", func(ctx *gin.Context) {
userName := ctx.Param("userName")
ctx.JSON(http.StatusOK, gin.H{"userName": userName})
})
ginServer.POST("/getJSON", func(ctx *gin.Context) {
// 获取JSON
data, _ := ctx.GetRawData()
//JSON转为数组
var m map[string]interface{}
json.Unmarshal(data, &m)
ctx.JSON(http.StatusOK, gin.H{"data": m})
})
ginServer.POST("getForm", func(ctx *gin.Context) {
username := ctx.PostForm("username")
password := ctx.PostForm("password")
ctx.JSON(http.StatusOK, gin.H{"username": username, "password": password})
})
ginServer.GET("toIndex", func(ctx *gin.Context) {
ctx.Redirect(http.StatusMovedPermanently, "/myIndex")
})
// 404
ginServer.NoRoute(func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "404.html", nil)
})
userGroup := ginServer.Group("/user")
{
userGroup.GET("/get", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"data": "成功"})
})
}
// 定一个拦截器
func myHandle() gin.HandlerFunc {
return func(ctx *gin.Context) {
log.Println("进拦截")
// 设置值
ctx.Set("session", "id:xx")
// 可以进行拦截或者放行
ctx.Next()
ctx.Abort()
}
}
func main() {
// 创建一个默认服务
ginServer := gin.Default()// 端口
// 中间件,拦截器
ginServer.GET("/test", myHandle(), func(ctx *gin.Context) {
handleValue := ctx.MustGet("session")
ctx.JSON(http.StatusOK, gin.H{"handleValue": handleValue})
})
ginServer.Run(":8081")
}