fix stylesheet not being recognized by browser because of wrong MIME type + handle OPTION preflight request by browser

This commit is contained in:
2025-08-03 17:10:16 +02:00
parent 9074a57e6f
commit 0cda92df6b

View File

@@ -3,8 +3,10 @@ package miniws
import ( import (
"errors" "errors"
"log" "log"
"mime"
"net/http" "net/http"
"os" "os"
"path/filepath"
"slices" "slices"
"strconv" "strconv"
"strings" "strings"
@@ -143,6 +145,18 @@ func (ws *WebServer) fetchFileContents(filepath string) ([]byte, error) {
func (ws *WebServer) get(writer http.ResponseWriter, req *http.Request) { 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 respStatusCode := http.StatusOK
if !ws.isIpValid(req.RemoteAddr) || !ws.isUserAgentValid(req.UserAgent()) { 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 respStatusCode = http.StatusNotFound
writer.WriteHeader(respStatusCode) writer.WriteHeader(respStatusCode)
} else { } else {
writer.Header().Add("Content-Type", mime.TypeByExtension(filepath.Ext(req.URL.Path)))
sentBytesCount, _ := writer.Write(fetchedData) sentBytesCount, _ := writer.Write(fetchedData)
sentBytes = sentBytesCount sentBytes = sentBytesCount
} }