feat(api): 初始化项目基础结构与API定义 新增 `.gitignore` 文件,忽略编译输出、生成代码及数据库文件。 新增 `README.md`,包含 Gin 框架和 Swagger 工具的安装与使用说明。 新增 `config/api.yaml`,定义 bookmarks 相关的文件夹与书签操作的 OpenAPI 3.0 接口规范。 新增 `config/cfg.yaml`,配置 oapi-codegen 工具生成 Gin 服务和模型代码。 新增 `go.mod` 和 `go.sum` 文件,初始化 Go 模块并引入 Gin、GORM、SQLite 及 oapi-codegen 等依赖。 ```
71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"embed"
|
|
"log"
|
|
"net/http"
|
|
|
|
"git.zzyxyz.com/zzy/zzyxyz_go_api/gen/api"
|
|
"git.zzyxyz.com/zzy/zzyxyz_go_api/internal/handlers"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
//go:generate go tool oapi-codegen -config config/cfg.yaml config/api.yaml
|
|
|
|
//go:embed config/api.yaml dist/*
|
|
var staticFiles embed.FS
|
|
|
|
func Helloworld(g *gin.Context) {
|
|
g.JSON(http.StatusOK, "helloworld")
|
|
}
|
|
|
|
func main() {
|
|
router := gin.Default()
|
|
|
|
router.GET("/ping", func(c *gin.Context) {
|
|
c.JSON(200, gin.H{
|
|
"message": "pong",
|
|
})
|
|
})
|
|
|
|
api_router := router.Group("/api")
|
|
{
|
|
// create a type that satisfies the `api.ServerInterface`,
|
|
// which contains an implementation of every operation from the generated code
|
|
if server, err := handlers.NewBookMarks("user.sqlite3"); err != nil {
|
|
log.Fatal("Failed to create bookmarks server:", err)
|
|
} else {
|
|
api.RegisterHandlers(api_router, server)
|
|
}
|
|
|
|
eg := api_router.Group("/example")
|
|
{
|
|
eg.GET("/helloworld", Helloworld)
|
|
}
|
|
}
|
|
|
|
handlers.TodoHandler(api_router)
|
|
|
|
// FIXME 可能有更好的方式实现这个代码
|
|
// 提供嵌入的静态文件访问 - OpenAPI YAML 文件和 dist 目录
|
|
router.GET("/swagger.yaml", func(c *gin.Context) {
|
|
file, _ := staticFiles.ReadFile("config/api.yaml")
|
|
c.Data(http.StatusOK, "application/x-yaml", file)
|
|
})
|
|
router.GET("/swagger/*filepath", func(ctx *gin.Context) {
|
|
// 直接修改请求路径实现映射
|
|
r := ctx.Request
|
|
originalPath := r.URL.Path
|
|
// 将 /swagger/* 映射为 /dist/*
|
|
r.URL.Path = "/dist" + ctx.Param("filepath")
|
|
|
|
fs := http.FileServer(http.FS(staticFiles))
|
|
fs.ServeHTTP(ctx.Writer, r)
|
|
|
|
// 恢复原始路径
|
|
r.URL.Path = originalPath
|
|
})
|
|
log.Fatal(router.Run("127.0.0.1:8080"))
|
|
}
|