• Gin_02_单文件拆解基本模块


    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"log"
    	"net/http"
    	"time"
    )
    
    // ApiResponse 封装一个响应结构体
    type ApiResponse struct {
    	Code    uint8  `json:"code"`
    	Msg     string `json:"msg"`
    	MsgCode uint8  `json:"msg_code"`
    	Data    gin.H  `json:"data"`
    }
    
    // CreateEngine 创建Gin.Engine
    func CreateEngine() *gin.Engine {
    	engine := gin.New()
    	RegisterMiddleware(engine)
    	RegisterRoute(engine)
    	return engine
    }
    
    // RegisterMiddleware 注册中间件
    func RegisterMiddleware(engine *gin.Engine) {
    	engine.Use(gin.Logger())
    	engine.Use(gin.Recovery())
    }
    
    // HelloView 第一个视图函数
    func HelloView(ctx *gin.Context) {
    	ctx.JSON(http.StatusOK, ApiResponse{
    		Code:    1,
    		Msg:     "请求成功",
    		MsgCode: 100,
    		Data: gin.H{
    			"url":      ctx.Request.URL.String(),
    			"method":   ctx.Request.Method,
    			"datetime": time.Now().Format("2006-01-02 15:04:05"),
    			"message":  "Hello, Gin!",
    		},
    	})
    }
    
    // NotFound 404视图函数
    func NotFound(ctx *gin.Context) {
    	ctx.JSON(http.StatusNotFound, ApiResponse{
    		Code:    0,
    		Msg:     "请求失败",
    		MsgCode: 104,
    		Data:    nil,
    	})
    }
    
    // RegisterRoute 路由注册
    func RegisterRoute(engine *gin.Engine) {
    	engine.GET("/hello", HelloView)
    	engine.POST("/hello", HelloView)
    	// 路由组
    	ApiV1Group := engine.Group("/v1")
    	{
    		ApiV1Group.GET("/hello", HelloView)
    		ApiV1Group.POST("/hello", HelloView)
    	}
    	// 404 返回接口数据
    	engine.NoRoute(NotFound)
    }
    
    func main() {
    	engine := CreateEngine()
    	// 启动Gin服务
    	if err := engine.Run("127.0.0.1:8081"); err != nil {
    		log.Panicf("服务启动失败:%v
    ", err)
    	}
    }
    
    
  • 相关阅读:
    puppet之模板和类
    puppet之资源
    puppet自动化安装服务
    puppet自动化搭建lnmp架构
    puppet工简介一
    CDN杂谈
    cdn工作原理
    mysql之innodb存储引擎
    Android应用开发基础篇(11)-----ViewFlipper
    Android应用开发基础篇(10)-----Menu(菜单)
  • 原文地址:https://www.cnblogs.com/carp-li/p/15111131.html
Copyright © 2020-2023  润新知