package api import ( "encoding/json" "net/http" "strconv" "git.velvettear.de/velvettear/loggo" "git.velvettear.de/velvettear/slideshow/internal" "git.velvettear.de/velvettear/slideshow/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("/", handleImageRequest) } // handle the request to '/image' func handleImageRequest(writer http.ResponseWriter, request *http.Request) { if !internal.HasFoundImages() { writer.WriteHeader(404) return } name, data, error := internal.GetRandomImage() if error != nil { loggo.Error("encountered an error getting a random image", error.Error()) writer.WriteHeader(501) writer.Write([]byte("encountered an internal server error (" + error.Error() + ")\n")) return } palette, error := internal.GetColorPalette(data) if error != nil { writer.WriteHeader(501) writer.Write([]byte("encountered an internal server error (" + error.Error() + ")\n")) return } bytes, error := json.Marshal(struct { Name string Palette string Data []byte }{ name, palette, data, }) if error != nil { loggo.Error("encountered an error marshalling the json response", error.Error()) writer.WriteHeader(501) writer.Write([]byte("encountered an internal server error (" + error.Error() + ")\n")) return } writer.Write(bytes) }