gin快速入门

111

mkdir gin-quickstart && cd gin-quickstart
go mod init gin-quickstart

222

go get -u github.com/gin-gonic/gin

333

创建一个名为 main.go 的文件:



touch main.go


打开 main.go 并添加以下代码:


package main
import "github.com/gin-gonic/gin"
func main() {
  router := gin.Default()
  router.GET("/ping", func(c *gin.Context) {
    c.JSON(200, gin.H{
      "message": "pong",
    })
  })
  router.Run() // listens on 0.0.0.0:8080 by default
}


第三步:运行你的 API 服务器

使用以下命令启动服务器:


Terminal window

go run main.go


在浏览器中访问 http://localhost:8080/ping,你应该会看到:


{"message":"pong"}


附加示例:在 Gin 中使用 net/http

如果你想使用 net/http 的响应码常量,也需要将其导入:


package main


import (

  "github.com/gin-gonic/gin"

  "net/http"

)


func main() {

  router := gin.Default()

  router.GET("/ping", func(c *gin.Context) {

    c.JSON(http.StatusOK, gin.H{

      "message": "pong",

    })

  })

  router.Run()

}


转载请说明出处 内容投诉内容投诉
二七九九笔记 » gin快速入门

发表评论

您需要后才能发表评论