Files
svg-templater/internal/routes/download.go
Tueem 205b70eeab
All checks were successful
build / Go-Build (push) Successful in 1m38s
build / Go-Build (pull_request) Successful in 39s
feat(template): add Templating functionality and endpoint
2026-02-09 11:09:19 +01:00

106 lines
2.2 KiB
Go

package routes
import (
"encoding/json"
"log"
"net/http"
"net/url"
"path/filepath"
"strconv"
"tomatentum.net/svg-templater/pkg/format"
"tomatentum.net/svg-templater/pkg/svg/actions"
)
type downloadRequest struct {
TemplateKeys map[string]string
}
type downloadResponse struct {
Url string
}
func DownloadSVG(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
http.Error(w, "Incorrect Content-Type. Needs application/json.", http.StatusUnsupportedMediaType)
return
}
var request downloadRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var err error
id := r.PathValue("id")
if id == "" {
http.Error(w, "No ID provided", http.StatusBadRequest)
return
}
widthString := r.URL.Query().Get("w")
width := 0
if widthString != "" {
width, err = strconv.Atoi(widthString)
if err != nil {
http.Error(w, "Invalid w parameter", http.StatusBadRequest)
return
}
}
heightString := r.URL.Query().Get("h")
height := 0
if heightString != "" {
height, err = strconv.Atoi(heightString)
if err != nil {
http.Error(w, "Invalid h parameter", http.StatusBadRequest)
return
}
}
convParam := format.ConversionParameters{
Format: r.URL.Query().Get("format"),
Width: width,
Height: height,
}
if convParam.Format == "" {
convParam.Format = "svg"
}
templateParam := actions.TemplateParameters{
Id: id,
Keys: request.TemplateKeys,
}
filename, err := actions.ProvideFile(&templateParam, &convParam)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
urlparsed := getPublicUrl(r, filename)
log.Printf("Made %s available as %s\n", id, urlparsed)
response := downloadResponse{
Url: urlparsed,
}
w.Header().Add("Content-Type", "application/json")
json, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(json)
}
func getPublicUrl(r *http.Request, path string) string {
newURL := url.URL{
Host: r.Host,
Path: filepath.Join("public", path),
}
newURL.Scheme = "http"
if r.TLS != nil {
newURL.Scheme = "https"
}
return newURL.String()
}