commit 17bce0a91471e8f78aa9bfd0fd06c1eacbf2998d Author: Dan Jones Date: Wed Nov 29 16:06:55 2023 -0600 🔖 It works! diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..432e1e0 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module codeberg.org/danjones000/http-go-status + +go 1.21.4 + +require github.com/julienschmidt/httprouter v1.3.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..096c54e --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..b9b699b --- /dev/null +++ b/main.go @@ -0,0 +1,88 @@ +package main + +import ( + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + + "github.com/julienschmidt/httprouter" +) + +func Status(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + header := w.Header() + header.Set("Access-Control-Allow-Origin", "*") + + status := ps.ByName("status") + fmt.Printf("Got %s status\n", status) + if status == "" { + status = "200" + } + + ret, err := strconv.Atoi(status) + + if err != nil || ret < 100 || ret > 599 { + if err != nil { + fmt.Printf("Got an error: %s\n", err.Error()) + } else { + fmt.Printf("Requested status %d\n", ret) + } + ret = 200 + } + fmt.Printf("Returning %d\n", ret) + + w.WriteHeader(ret) +} + +func GetRouter() *httprouter.Router { + router := httprouter.New() + + // We don't handle OPTIONS, so that we can support CORS + methods := [8]string{ + http.MethodGet, + http.MethodHead, + http.MethodPost, + http.MethodPut, + http.MethodPatch, + http.MethodDelete, + http.MethodConnect, + http.MethodTrace} + for _, method := range methods { + router.Handle(method, "/:status", Status) + } + + // Handle CORS preflight requests + router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Access-Control-Request-Method") != "" { + // Set CORS headers + header := w.Header() + header.Set("Access-Control-Allow-Methods", header.Get("Allow")) + header.Set("Access-Control-Allow-Origin", "*") + } + + // Adjust status code to 204 + w.WriteHeader(http.StatusNoContent) + }) + + return router +} + +func GetPort() string { + port := os.Getenv("PORT") + if port == "" { + port = ":80" + } + if !strings.HasPrefix(port, ":") { + port = ":" + port + } + + return port +} + +func main() { + port := GetPort() + fmt.Printf("Listening on %s\n", port) + log.Fatal(http.ListenAndServe(port, GetRouter())) +}