package main import ( "embed" "log" "net/http" bookmarks "git.zzyxyz.com/zzy/zzyxyz_go_api/gen/bookmarks" "git.zzyxyz.com/zzy/zzyxyz_go_api/internal/handlers" "github.com/gin-gonic/gin" ) //go:generate go tool oapi-codegen -config config/bookmark_cfg.yaml config/bookmark.yaml //go:generate go tool oapi-codegen -config config/vfs_cfg.yaml config/vfs.yaml //go:embed config/* dist/* var staticFiles embed.FS func main() { gin.SetMode(gin.ReleaseMode) 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("./data/bookmark.sqlite3"); err != nil { log.Fatal("Failed to create bookmarks server:", err) } else if permission, err := handlers.NewBookMarkPermission(); err != nil || permission == nil { log.Fatal("Failed to create bookmarks permission:", err) } else { bookmarks.RegisterHandlersWithOptions(api_router, server, *permission) } handlers.TodoHandler(api_router) } // FIXME 可能有更好的方式实现这个代码 // 提供嵌入的静态文件访问 - OpenAPI YAML 文件和 dist 目录 router.GET("/config/*filepath", func(ctx *gin.Context) { fs := http.FileServer(http.FS(staticFiles)) fs.ServeHTTP(ctx.Writer, ctx.Request) }) 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 }) var listener = "localhost:8080" log.Printf("Starting server at http://%s", listener) log.Printf("Swagger UI: http://%s/swagger/index.html", listener) log.Fatal(router.Run(listener)) }