From 482a31b66b53e8258369925c40fb6cdba752a37c Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Sat, 30 Oct 2021 14:29:53 +0000 Subject: [PATCH] Setup swagger and swagger UI properly --- app.go | 4 ++-- swagger.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 swagger.go diff --git a/app.go b/app.go index 707c111e..50343d3c 100644 --- a/app.go +++ b/app.go @@ -381,8 +381,8 @@ func (h *Headscale) Serve() error { r.POST("/machine/:id", h.RegistrationHandler) r.GET("/apple", h.AppleMobileConfig) r.GET("/apple/:platform", h.ApplePlatformConfig) - - r.StaticFile("/swagger/swagger.json", "gen/openapiv2/v1/headscale.swagger.json") + r.GET("/swagger", SwaggerUI) + r.GET("/swagger/v1/openapiv2.json", SwaggerAPIv1) api := r.Group("/api") api.Use(h.httpAuthenticationMiddleware) diff --git a/swagger.go b/swagger.go new file mode 100644 index 00000000..17f57697 --- /dev/null +++ b/swagger.go @@ -0,0 +1,65 @@ +package headscale + +import ( + "bytes" + _ "embed" + "net/http" + "text/template" + + "github.com/rs/zerolog/log" + + "github.com/gin-gonic/gin" +) + +//go:embed gen/openapiv2/headscale/v1/headscale.swagger.json +var apiV1JSON []byte + +func SwaggerUI(c *gin.Context) { + t := template.Must(template.New("swagger").Parse(` + + + + + + + + +
+ + +`)) + + var payload bytes.Buffer + if err := t.Execute(&payload, struct{}{}); err != nil { + log.Error(). + Caller(). + Err(err). + Msg("Could not render Swagger") + c.Data(http.StatusInternalServerError, "text/html; charset=utf-8", []byte("Could not render Swagger")) + return + } + + c.Data(http.StatusOK, "text/html; charset=utf-8", payload.Bytes()) +} + +func SwaggerAPIv1(c *gin.Context) { + c.Data(http.StatusOK, "application/json; charset=utf-8", apiV1JSON) +}