使用gin框架开发提供restful接口Golang项目


1. 初始化 Go 模块

在项目目录下运行以下命令,初始化 Go 模块: bash go mod init your-module-name 例如我的模块名称为 calend:

```bash
go mod init calend
```

这会在当前目录下生成一个 go.mod 文件。


2. 添加依赖

运行以下命令,会自动添加依赖:

go mod tidy

另外一种方法,例如我的项目依赖与gin, 因此运行以下命令,添加 Gin 依赖:

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

这会将 Gin 添加到 go.mod 文件中,并下载依赖到本地。


3. 更新 main.go 文件

确保 main.go 文件内容如下:

```go package main

import ( "github.com/gin-gonic/gin" "net/http" )

// 定义日历数据结构 type CalendarData struct { Date int json:"date" GregorianYear int json:"gregorianYear" GregorianMonth int json:"gregorianMonth" }

// 获取日历数据 func getCalendarData() CalendarData { return CalendarData{ Date: 26, GregorianYear: 2025, GregorianMonth: 2 } }

func main() { // 创建 Gin 实例 r := gin.Default()

// 允许跨域
r.Use(func(c *gin.Context) {
    c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
    c.Writer.Header().Set("Access-Control-Allow-Methods", "GET")
    c.Next()
})

// 定义接口
r.GET("/api/calend", func(c *gin.Context) {
    data := getCalendarData()
    c.JSON(http.StatusOK, data)
})

// 启动服务器
r.Run(":8080")

} ```


4. 运行项目

在项目目录下运行以下命令启动服务器: bash go run main.go

如果一切正常,服务器会启动并监听 http://localhost:8080


5. 验证接口

打开浏览器或使用 curl 访问接口: bash curl http://localhost:8080/api/calend

您应该会看到类似以下的 JSON 响应: json { "date": 26, "gregorianYear": 2025, "gregorianMonth": 2 }


6. 项目结构

完成上述步骤后,您的项目结构应该如下:

```
calend/
├── go.mod
├── go.sum
└── main.go

```

  • go.mod:模块定义文件。
  • go.sum:依赖校验文件(自动生成)。
  • main.go:主程序文件。

7. 编译为可执行文件

使用 Go 的 go build 命令将项目编译为可执行文件。在项目目录下运行以下命令: bash go build -o calend.exe 这会在当前目录下生成一个名为 calend 的可执行文件(Windows 下为 calend.exe)。


通过以上步骤,第一个 使用Gin的Go 项目应该可以正常运行了。