gin框架

1、Hello World

  1. 创建gomod:go mod init 项目名称

  2. 下载gin依赖:go get -u github.com/gin-gonic/gin

  3. 创建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")
    }
    
    
  4. 运行:go run main.go

2、响应界面

  1. 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>
    
  2. 返回

    // 返回一个前端页面
    	// 加载静态页面
    	ginServer.LoadHTMLGlob("template/*")
    	// 加载资源文件
    	ginServer.Static("static", "./static")
    	ginServer.GET("/myIndex", func(ctx *gin.Context) {
    		ctx.HTML(http.StatusOK, "index.html", gin.H{"msg": "后台传递的参数"})
    	})
    

3、获取url参数

1、获取url?的方式

ginServer.GET("/getUrl1", func(ctx *gin.Context) {
		userName := ctx.Query("userName")
		ctx.JSON(http.StatusOK, gin.H{"userName": userName})
	})

2、获取url根据RestFul风格

ginServer.GET("/getUrl2/:userName", func(ctx *gin.Context) {
		userName := ctx.Param("userName")
		ctx.JSON(http.StatusOK, gin.H{"userName": userName})
	})

3、获取JSON格式

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})
	})

4、获取前端表格

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})
	})

4、路由

1、重定向

ginServer.GET("toIndex", func(ctx *gin.Context) {
		ctx.Redirect(http.StatusMovedPermanently, "/myIndex")
	})

2、noRouter

// 404
	ginServer.NoRoute(func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "404.html", nil)
	})

3、路由组

userGroup := ginServer.Group("/user")
	{
		userGroup.GET("/get", func(ctx *gin.Context) {
			ctx.JSON(http.StatusOK, gin.H{"data": "成功"})
		})
	}

5、中间件

// 定一个拦截器
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")
}

你可能感兴趣的:(golang,gin,java,json)