package api import ( "net/http" "strconv" "strings" "time" "git.velvettear.de/velvettear/loggo" "git.velvettear.de/velvettear/slideshow-api/internal" "git.velvettear.de/velvettear/slideshow-api/internal/config" ) // start the web server func Run() { address := config.ServerAddress + ":" + strconv.Itoa(config.ServerPort) loggo.Info("starting web server...", "address: "+address) registerHandlers() error := http.ListenAndServe(address, nil) if error != nil { loggo.Fatal("encountered an error starting the web server", "address: "+address, error.Error()) } } // register the handlers func registerHandlers() { http.HandleFunc("/", serveRandomImageName) http.HandleFunc("/image/", serveImage) http.HandleFunc("/palette/", servePalette) } // request url: '/' - serve the name of a random image func serveRandomImageName(writer http.ResponseWriter, request *http.Request) { timestamp := time.Now().UnixMilli() var response response response.Content, response.error = internal.GetRandomImage() if response.error != nil { response.StatusCode = 404 } response.send(writer) loggo.DebugTimed("served random image '"+response.Content.(string)+"'", timestamp) } // request url: '/image' - serve an image func serveImage(writer http.ResponseWriter, request *http.Request) { var response response image, _ := strings.CutPrefix(request.URL.Path, "/image/") image, error := internal.GetImagePath(image) if error != nil { response.error = error response.StatusCode = 404 response.send(writer) return } streamImage(writer, image, request.URL.Query().Get("resolution")) } // request url: '/palette' - serve the color palette of an image func servePalette(writer http.ResponseWriter, request *http.Request) { var response response image, _ := strings.CutPrefix(request.URL.Path, "/palette/") image, error := internal.GetImagePath(image) if error != nil { response.error = error response.StatusCode = 404 response.send(writer) return } amount, _ := strconv.Atoi(request.URL.Query().Get("colors")) if amount <= 0 { amount = 16 } streamColorPalette(writer, image, amount, request.URL.Query().Get("algorithm")) }