SimpleCloudNotifier/scnserver/swagger/swagger.go

74 lines
1.6 KiB
Go
Raw Normal View History

2022-11-13 19:17:07 +01:00
package swagger
import (
"embed"
_ "embed"
"github.com/gin-gonic/gin"
"gogs.mikescher.com/BlackForestBytes/goext/ginext"
2022-11-13 19:17:07 +01:00
"net/http"
"strings"
)
2022-11-30 16:46:55 +01:00
//go:embed *.html
//go:embed *.json
//go:embed *.yaml
//go:embed *.js
//go:embed *.css
2023-05-27 17:51:56 +02:00
//go:embed *.png
2022-11-30 16:46:55 +01:00
//go:embed themes/*
2022-11-13 19:17:07 +01:00
var assets embed.FS
func getAsset(fn string) ([]byte, string, bool) {
data, err := assets.ReadFile(fn)
if err != nil {
return nil, "", false
}
mime := "text/plain"
lowerFN := strings.ToLower(fn)
if strings.HasSuffix(lowerFN, ".html") || strings.HasSuffix(lowerFN, ".htm") {
mime = "text/html"
} else if strings.HasSuffix(lowerFN, ".css") {
mime = "text/css"
} else if strings.HasSuffix(lowerFN, ".js") {
mime = "text/javascript"
} else if strings.HasSuffix(lowerFN, ".json") {
mime = "application/json"
} else if strings.HasSuffix(lowerFN, ".jpeg") || strings.HasSuffix(lowerFN, ".jpg") {
mime = "image/jpeg"
} else if strings.HasSuffix(lowerFN, ".png") {
mime = "image/png"
} else if strings.HasSuffix(lowerFN, ".svg") {
mime = "image/svg+xml"
}
return data, mime, true
}
func Handle(pctx ginext.PreContext) ginext.HTTPResponse {
2022-11-13 19:17:07 +01:00
type uri struct {
2022-12-21 11:03:31 +01:00
Filename string `uri:"sub"`
2022-11-13 19:17:07 +01:00
}
var u uri
ctx, _, errResp := pctx.URI(&u).Start()
if errResp != nil {
return *errResp
2022-11-13 19:17:07 +01:00
}
defer ctx.Cancel()
2022-11-13 19:17:07 +01:00
2022-12-21 11:03:31 +01:00
u.Filename = strings.TrimLeft(u.Filename, "/")
2022-11-30 16:46:55 +01:00
2022-12-21 11:03:31 +01:00
if u.Filename == "" {
2022-11-13 19:17:07 +01:00
index, _, _ := getAsset("index.html")
return ginext.Data(http.StatusOK, "text/html", index)
2022-11-13 19:17:07 +01:00
}
2022-12-21 11:03:31 +01:00
if data, mime, ok := getAsset(u.Filename); ok {
return ginext.Data(http.StatusOK, mime, data)
2022-11-13 19:17:07 +01:00
}
return ginext.JSON(http.StatusNotFound, gin.H{"error": "AssetNotFound", "filename": u.Filename})
2022-11-13 19:17:07 +01:00
}