From 0cda92df6b5f9fe4ed3b19a44c6050740532092a Mon Sep 17 00:00:00 2001 From: Solar Date: Sun, 3 Aug 2025 17:10:16 +0200 Subject: [PATCH] fix stylesheet not being recognized by browser because of wrong MIME type + handle OPTION preflight request by browser --- miniws/webserver.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/miniws/webserver.go b/miniws/webserver.go index 11f4bac..7edda33 100644 --- a/miniws/webserver.go +++ b/miniws/webserver.go @@ -3,8 +3,10 @@ package miniws import ( "errors" "log" + "mime" "net/http" "os" + "path/filepath" "slices" "strconv" "strings" @@ -143,6 +145,18 @@ func (ws *WebServer) fetchFileContents(filepath string) ([]byte, error) { func (ws *WebServer) get(writer http.ResponseWriter, req *http.Request) { + // handle OPTION preflight request + if origin := req.Header.Get("Origin"); origin != "" { + writer.Header().Set("Access-Control-Allow-Origin", origin) + writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") + writer.Header().Set("Access-Control-Allow-Headers", + "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") + } + // Stop here if its Preflighted OPTIONS request + if req.Method == "OPTIONS" { + return + } + respStatusCode := http.StatusOK if !ws.isIpValid(req.RemoteAddr) || !ws.isUserAgentValid(req.UserAgent()) { @@ -158,6 +172,7 @@ func (ws *WebServer) get(writer http.ResponseWriter, req *http.Request) { respStatusCode = http.StatusNotFound writer.WriteHeader(respStatusCode) } else { + writer.Header().Add("Content-Type", mime.TypeByExtension(filepath.Ext(req.URL.Path))) sentBytesCount, _ := writer.Write(fetchedData) sentBytes = sentBytesCount }