jsFetch/tests/server/main.go

90 lines
2.7 KiB
Go
Raw Normal View History

2024-10-28 09:47:23 +00:00
package main
import (
"fmt"
"github.com/go-chi/chi/v5"
"io"
"net/http"
"os"
)
func main() {
r := chi.NewRouter()
r.Use(func(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, HEAD")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Success, Error")
next.ServeHTTP(w, r)
})
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
file, err := os.ReadFile("../client/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Get("/main.wasm", func(w http.ResponseWriter, r *http.Request) {
file, err := os.ReadFile("../client/main.wasm")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Options("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, HEAD")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Success, Error")
})
r.Options("/reportTestResults", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, HEAD")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Success, Error")
})
r.Head("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Success", "true")
})
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("hello"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Post("/hello", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Get("/reportTestResults", func(w http.ResponseWriter, r *http.Request) {
success := r.Header.Get("Success")
if success == "true" {
fmt.Println("Test passed")
os.Exit(0)
} else {
fmt.Println("Test failed... " + r.Header.Get("Error"))
os.Exit(1)
}
})
err := http.ListenAndServeTLS(":8080", "server.crt", "server.key", r)
if err != nil {
fmt.Println(err)
return
}
}