http-go-status/main.go
2025-11-01 17:09:16 -05:00

104 lines
2.4 KiB
Go

/*
Copyright (c) 2023-2025 Dan Jones
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see https://www.gnu.org/licenses/
*/
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 = ":8080"
}
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()))
}