zoukankan      html  css  js  c++  java
  • 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()
    }
  • 相关阅读:
    Mybatis 使用 mapper 接口规范的 一对一, 一对多,多对多映射
    mybatis mapper接口开发dao层
    使用 maven 搭建web开发基本架构
    mybatis dao 层开发简易版 非整合 spring
    mybatis 不整合spring 入门小例子
    spring+spring mvc+JdbcTemplate 入门小例子
    PythonCharm 配置本地反向代理激活
    Python 算法实现
    不写一行代码,绿色三层我也行
    pythonday
  • 原文地址:https://www.cnblogs.com/zengyjun/p/10096909.html
Copyright © 2011-2022 走看看