slideshow-api/internal/api/server.go

65 lines
1.7 KiB
Go
Raw Normal View History

2023-11-28 15:52:53 +01:00
package api
import (
"encoding/json"
"net/http"
"strconv"
"git.velvettear.de/velvettear/loggo"
2023-11-28 16:34:10 +01:00
"git.velvettear.de/velvettear/slideshow-api/internal"
"git.velvettear.de/velvettear/slideshow-api/internal/config"
2023-11-28 15:52:53 +01:00
)
// 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)
}