31

Gin框架介绍

 5 years ago
source link: https://studygolang.com/articles/14860?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

准备工作

  1. 确认本地环境的 $GOPATH
  • Windows 下使用 echo %GOPATH%
  • Linux 下使用 echo $GOPATH
  1. 获取远程包 go get github.com/gin-gonic/gin
//升级安装请增加参数 -u
go get -u github.com/gin-gonic/gin
  1. 输入 go version 确认本地环境的 Golang 版本

第一个案例程序

  1. 在您的 $GOPATH 目录下创建子文件夹 $GOPATH/src/gin-first
  2. 切换到上述子文件夹下创建 main.go
  3. 复制如下内容到 main.go

First

  1. 创建如下文件夹 $GOPATH/src/gin-first
  2. 在上述文件夹下创建 main.go
  3. 复制下面的内容到 main.go
  4. 在命令行窗口中运行 go run main.go
  5. 在浏览器中打开 http://127.0.0.1:8080/ping 可以看到返回内容 pong

如果您使用 macOSLinux ,您也可以在 Shell 窗口中输入如下命令

curl http://127.0.0.1:8080/ping

看到返回 pong

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

运行

  1. 上述子文件夹下运行 go run main.go
  2. 将看到输出内容 [GIN-debug] Listening and serving HTTP on :8080
  3. 打开浏览器访问 http://127.0.0.1:8080/ping 可以看到返回 pong

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK