简介

Gin的实现非常简单,准备开始编写属于自己的微服务吧!

创建Gin Engine

通过gin.Default()和gin.New创建Engine,区别在于Default()会默认使用Logger和Recover中间件

  1. // Default returns an Engine instance with the Logger and Recovery middleware already attached.
  2. func Default() *Engine {
  3. debugPrintWARNINGDefault()
  4. engine := New()
  5. engine.Use(Logger(), Recovery())
  6. return engine
  7. }

路由组

路由组可以在api中添加前缀,比如”/api/v1”

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. router := gin.Default()
  8. v1 := router.Group("/api/v1/todos")
  9. {
  10. v1.GET("/", func(ctx *gin.Context) { ctx.JSON(http.StatusOK, "ok") })
  11. }
  12. router.Run(":8080")
  13. }