golang 创建Gin项目

安装步骤

  1. ​​确保已安装 Go​​
    首先确保你已经安装了 Go (1.13+) 并正确配置了 GOPATH 和 GOROOT。

     
     
    go version
     
     
  2. ​​初始化你的项目(如果尚未初始化)​​my-gin-app为你自定义的项目名称

     
     
    mkdir my-gin-app && cd my-gin-app go mod init my-gin-app
     
     
  3. ​​下载 Gin 框架​​
    使用 go get 命令下载 Gin:

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

    或者,如果你使用 Go Modules(推荐):

     
     
    go mod tidy
     
     
  4. ​​验证安装​​
    创建一个简单的测试文件 main.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 }
     
     
  5. ​​运行测试程序​​

     
     
    go run main.go
     
     

    然后在浏览器中访问 http://localhost:8080/ping,你应该会看到 {"message":"pong"} 的响应。

其他注意事项

  • 如果你在中国大陆,可能会遇到下载慢的问题,可以设置 Go 模块代理:

     
     
    go env -w GOPROXY=https://goproxy.cn,direct
     
     
  • 对于生产环境,建议使用 gin.SetMode(gin.ReleaseMode) 来禁用调试模式

  • 最新版本的 Gin 文档可以在其 GitHub 仓库找到:https://github.com/gin-gonic/gin

posted @ 2025-05-24 11:36  幽暗天琴  阅读(103)  评论(0)    收藏  举报