fix(cors): add CORS middleware
build / Go-Build (push) Successful in 1m28s

This commit is contained in:
2026-05-26 00:48:00 +02:00
parent 54a16fab4a
commit d891321780
2 changed files with 22 additions and 2 deletions
+16
View File
@@ -0,0 +1,16 @@
package server
import "net/http"
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
+6 -2
View File
@@ -10,7 +10,10 @@ import (
"tomatentum.net/svg-templater/pkg/svg" "tomatentum.net/svg-templater/pkg/svg"
) )
var mux http.ServeMux
func PrepareHTTP() { func PrepareHTTP() {
mux = *http.NewServeMux()
registerAuthorizedFunc("/", func(w http.ResponseWriter, r *http.Request) { registerAuthorizedFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "You are authorized!") fmt.Fprintln(w, "You are authorized!")
}) })
@@ -51,13 +54,14 @@ func PrepareHTTP() {
func Start() { func Start() {
log.Println("Starting http server on :3000") log.Println("Starting http server on :3000")
if err := http.ListenAndServe(":3000", nil); err != nil { handler := corsMiddleware(&mux)
if err := http.ListenAndServe(":3000", handler); err != nil {
panic(err) panic(err)
} }
} }
func registerAuthorized(path string, handler http.Handler) { func registerAuthorized(path string, handler http.Handler) {
http.HandleFunc(path, auth.AuthMiddleware(handler)) mux.HandleFunc(path, auth.AuthMiddleware(handler))
log.Println("Registered authorized handler for", path) log.Println("Registered authorized handler for", path)
} }