2023-11-29 16:06:55 -06:00
|
|
|
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 == "" {
|
2023-11-29 16:16:51 -06:00
|
|
|
port = ":8080"
|
2023-11-29 16:06:55 -06:00
|
|
|
}
|
|
|
|
|
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()))
|
|
|
|
|
}
|