How to use Gin to create a web server
Known for its speed and small memory footprint, Gin is one of the most popular and widely used Go web frameworks. It provides features like routing, middleware support, and JSON validation, making it great for building high-performance REST APIs.
So, how do we use Gin to create a web server? Here's a step-by-step guide to help you get started:
1. First, install Go if you haven't already
- install (
https://go.dev/
)

- set up Go environment variables(Windows)
The default installation directory is
C:\Program Files\Go
Right-click➡️Personalize➡️system➡️about➡️Advanced system settings➡️Environment Variables➡️system variables section
Create a new system variable named GOROOT
with the value C:\Program Files\Go
.
Then, add %GOROOT%\bin
to the Path
variable.
- verify the installation
go version

- configure your GOPROXY(If you're behind a proxy or your network setup requires this, run one of the following commands)
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
go env -w GOPROXY=https://mirrors.cloud.tencent.com/go,direct
// You can check the current proxy configuration with
go env GOPROXY
// Clear the Go module cache
go clean --modcache
2. Create a new project directory and initialize it:
mkdir gin-server
cd gin-server
go mod init example.com/gin-server
go get -u github.com/gin-gonic/gin
3. Create a main.go file with a basic Gin server:
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(":8080") // listen and serve on 0.0.0.0:8080
}
4. Run the application
go run main.go
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!