90 lines
2.1 KiB
Go
90 lines
2.1 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"
|
|
)
|
|
|
|
func Status(w http.ResponseWriter, r *http.Request) {
|
|
header := w.Header()
|
|
header.Set("Access-Control-Allow-Origin", "*")
|
|
|
|
status := strings.TrimLeft(r.RequestURI, "/")
|
|
status, _, _ = strings.Cut(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 HandleCors(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Println("handling CORS")
|
|
if r.Header.Get("Access-Control-Request-Method") != "" {
|
|
// Set CORS headers
|
|
header := w.Header()
|
|
header.Set("Access-Control-Allow-Methods", "*")
|
|
header.Set("Access-Control-Allow-Origin", "*")
|
|
header.Set("Access-Control-Allow-Headers", "*")
|
|
}
|
|
|
|
// Adjust status code to 204
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
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, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodOptions {
|
|
HandleCors(w, r)
|
|
} else {
|
|
Status(w, r)
|
|
}
|
|
})))
|
|
}
|