// main.go // (Run: go build && ./yourapp) // This server serves the static files for the client from "./public" // and provides endpoints to load/save a single .excalidraw file. // // Make sure to create a "public" folder and build the SolidJS client into it. package main import ( "encoding/json" "io" "log" "net/http" "os" ) const stateFile = "drawing.excalidraw" func main() { http.Handle("/", http.FileServer(http.Dir("public"))) http.HandleFunc("/api/state", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusOK) return } if r.Method == http.MethodGet { w.Header().Set("Content-Type", "application/json") data, err := os.ReadFile(stateFile) if err != nil { log.Println("No file yet or error reading file:", err) // If no file yet, return empty object w.Write([]byte(`{}`)) return } w.Write(data) return } else if r.Method == http.MethodPost { log.Println("POST /api/state") body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "cannot read body", http.StatusBadRequest) return } // Validate JSON var js interface{} if err := json.Unmarshal(body, &js); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } if err := os.WriteFile(stateFile, body, 0644); err != nil { http.Error(w, "cannot save file", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) return } http.Error(w, "method not allowed", http.StatusMethodNotAllowed) }) log.Println("Server running on http://localhost:8080") http.ListenAndServe(":8080", nil) }