“Golang Gin Web 框架快速入门”的版本间差异

本页内容
无编辑摘要
Neo讨论 | 贡献
第6行: 第6行:
要安装 Gin 软件包,需要先安装 Go 并设置 Go Workspace。
要安装 Gin 软件包,需要先安装 Go 并设置 Go Workspace。


1.下载并安装 gin:


<sample title="" desc="">
<sample title="1.下载并安装 gin:
" desc="">
$ go get -u github.com/gin-gonic/gin
$ go get -u github.com/gin-gonic/gin


</sample>
</sample>
2.将 gin 引入到代码中:


<sample title="" desc="">
<sample title="2.将 gin 引入到代码中:
" desc="">
import "github.com/gin-gonic/gin"
import "github.com/gin-gonic/gin"
</sample>
</sample>


3.(可选)如果使用诸如 http.StatusOK 之类的常量,则需要引入 net/http 包:


<sample title="" desc="">
<sample title="3.(可选)如果使用诸如 http.StatusOK 之类的常量,则需要引入 net/http 包:
" desc="">
import "net/http"
import "net/http"
</sample>
</sample>


创建你的项目文件夹并 cd 进去


<sample title="" desc="">
<sample title="创建你的项目文件夹并 cd 进去
" desc="">
$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
</sample>
</sample>

2022年9月27日 (二) 14:02的版本

Golang 版本要求

Go 1.13 及以上版本

安装

要安装 Gin 软件包,需要先安装 Go 并设置 Go Workspace。


1.下载并安装 gin:

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


2.将 gin 引入到代码中:

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


3.(可选)如果使用诸如 http.StatusOK 之类的常量,则需要引入 net/http 包:

import "net/http"


创建你的项目文件夹并 cd 进去

$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"

拷贝一个初始模板到你的项目里


示例

$ curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go

运行你的项目


示例

$ go run main.go

开始

不确定如何编写和执行 Go 代码? 可以查看《How to Write Go Code》.

首先,创建一个名为 example.go 的文件


示例

$ touch example.go

接下来, 将如下的代码写入 example.go 中:


示例

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() // 监听并在 0.0.0.0:8080 上启动服务
}

然后, 执行 go run example.go 命令来运行代码:

  1. 运行 example.go 并且在浏览器中访问 HOST_IP:8080/ping


示例

$ go run example.go
此页面最后编辑于2022年9月27日 (星期二) 14:02。