Add OpenAPI endpoint at /openapi with Swagger documentation

This commit is contained in:
2026-05-18 21:43:06 +02:00
parent c0d1aaa4d1
commit 1d77ae491c
4 changed files with 62 additions and 53 deletions
+17 -18
View File
@@ -2,34 +2,40 @@ package server
import (
"fmt"
"music-server/cmd/docs"
"music-server/cmd/web"
"net/http"
"sort"
"strings"
_ "music-server/cmd/docs"
"github.com/a-h/templ"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/swaggo/echo-swagger" // echo-swagger middleware
//_ "github.com/swaggo/echo-swagger/example/docs" // docs is generated by Swag CLI, you have to import it.
"github.com/swaggo/echo-swagger"
)
// @Title Swagger Example API
// @version 0.5
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @Title MusicServer API
// @version 1.0
// @description API for the MusicServer application
// @termsOfService http://sanplex.xyz/terms/
// @contact.name Sebastian Olsson
// @contact.email zarnor91@gmail.com
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @license.name MIT
// @license.url http://opensource.org/licenses/MIT
// @host localhost:8080
// @BasePath /
func (s *Server) RegisterRoutes() http.Handler {
e := echo.New()
// Serve OpenAPI spec at /openapi
e.GET("/openapi", func(c echo.Context) error {
c.Response().Header().Set("Content-Type", "application/json")
_, err := c.Response().Write([]byte(docs.GetSwaggerJSON()))
return err
})
e.Use(middleware.Logger())
e.Use(middleware.Recover())
@@ -49,14 +55,7 @@ func (s *Server) RegisterRoutes() http.Handler {
e.Static("/", "/frontend")
/*swagger := http.FileServer(http.FS(web.Swagger))
e.GET("/swagger/*", echo.WrapHandler(swagger))*/
swaggerRedirect := func(c echo.Context) error {
return c.Redirect(http.StatusMovedPermanently, "/swagger/index.html")
}
e.GET("/swagger", swaggerRedirect)
e.GET("/swagger/", swaggerRedirect)
// Swagger UI
e.GET("/swagger/*", echoSwagger.WrapHandler)
index := NewIndexHandler()