• golang-gin框架


    import (
        "github.com/gin-gonic/gin"
        "net/http"
        "github.com/sirupsen/logrus"
    )
    
    
    // 1、最简单gin
    func GinSample(){
        engine := gin.Default()
        engine.Any("/",func(context *gin.Context){
            context.String(http.StatusOK,"hello world")
        })
        engine.Run(":9025")
    }
    
    // 2、gin各种方法
    func GinFunc(){
        engine := gin.Default()
    
        // get
        engine.GET("/get",func(context *gin.Context){
            context.JSON(http.StatusOK,gin.H{"message":"hello world","status":"done"})
        })
    
        // put
        engine.PUT("/put",func(context *gin.Context){
            context.String(http.StatusOK,"put ok")
        })
    
        // post
        engine.POST("/post",nil)
        //...
        engine.Run(":9025")
    }
    
    // 3、gin 解析入参
    func GinGetParam(){
        engine := gin.Default()
        engine.GET("/get/:name/*action",func(context *gin.Context){
            name := context.Param("Guest")
            action := context.Param("action")
            context.String(http.StatusOK,"welcome " + name + action)
        })
        engine.Run(":9025")
    }
    
    // 4、gin 路由组
    func GinGroup(){
        engine := gin.Default()
        v1 := engine.Group("/v1")
        {
            v1.GET("/get",nil) // handlers待实现
            v1.POST("post",nil)
        }
    
        v2 := engine.Group("/v2")
        {
            v2.GET("/get",nil)
            v2.POST("/post",nil)
        }
        engine.Run(":9025")
    }
    
    // 5、中间件
    func Middle() {
        router := gin.Default()
    
        // 注册一个路由,使用了 middleware1,middleware2 两个中间件
        router.GET("/someGet", middleware1, middleware2, handler)
    
        // 默认绑定 :8080
        router.Run()
    }
    
    func handler(c *gin.Context) {
        logrus.Println("exec handler")
    }
    
    func middleware1(c *gin.Context){
        // do something
        c.Next()
    
    }
    
    func middleware2(c *gin.Context){
        // do something
        c.Next()
    }
  • 相关阅读:
    Servlet3.0-使用注解定义Servlet
    poj 1256 Anagram—next_permutation的神奇应用
    poj 1664 放苹果 (划分数)
    poj 1011 Sticks
    poj和hdu部分基础算法分类及难度排序
    Notepad++支持jQuery、html5、css3
    Codeforces Round #395 (Div. 2) C. Timofey and a tree
    Codeforces Round #390 (Div. 2) D. Fedor and coupons
    bazel-编译动态库
    bazel-编译多目标
  • 原文地址:https://www.cnblogs.com/zengyjun/p/10096909.html
Copyright © 2020-2023  润新知