两种启动方式

  • 方式一
package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    router := gin.Default()
    router.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello World")
    })
  // 启动监听,gin会把web服务运行在本机的0.0.0.0:8080端口上
  router.Run("0.0.0.0:8080")
}
  • 方式二
package main

import (
  "github.com/gin-gonic/gin"
  "net/http"
)

func Index(context *gin.Context) {
  context.String(200, "gin demo!")
}
func main() {

  // 创建一个默认的路由
  router := gin.Default()

  // 绑定路由规则和路由函数,访问/index的路由,将由对应的函数去处理
  router.GET("/index", Index)

  // 用原生http服务的方式, router.Run本质就是http.ListenAndServe的进一步封装
  // 可以自定义优雅关闭
  http.ListenAndServe(":8080", router)
}
  • 方式二的变异
// 上面的变异方式; 部分代码片段
  router := initialize.Routers()
	srv := http.Server{
		Addr:           addr,
		Handler:        router,
		ReadTimeout:    120 * time.Second,
		WriteTimeout:   120 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		// 服务连接
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			global.Log.Error("listen", zap.Error(err))
		}
	}()

	// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	global.Log.Info("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		global.Log.Error("Server Shutdown", zap.Error(err))
	}
	global.Log.Info("Server exiting")

文件服务器

// 在golang总,没有相对文件的路径,它只有相对项目的路径
// 网页请求这个静态目录的前缀, 第二个参数是一个目录,注意,前缀不要重复
router.StaticFS("/static", http.Dir("static/static"))
// 配置单个文件, 网页请求的路由,文件的路径
router.StaticFile("/abc.png", "static/xxxx.png")

返回 json

router.GET("/json", func(c *gin.Context) {
  c.JSON(http.StatusOK, gin.H{"msg": "ok", "status": http.StatusOK})
})
// 结构体转json
router.GET("/moreJSON", func(c *gin.Context) {
  // You also can use a struct
  type Msg struct {
    Name    string `json:"user"`
    Message string
    Age  int
  }
  msg := Msg{"hw", "ok", 23}
  // 注意 msg.Name 变成了 "user" 字段
  // 以下方式都会输出 :   {"user": "hw", "Message": "ok", "Age": 23}
  c.JSON(http.StatusOK, msg)
})