slideshow-api/internal/api/server.go

71 lines
2 KiB
Go
Raw Normal View History

2023-11-28 15:52:53 +01:00
package api
import (
"net/http"
"strconv"
"strings"
"time"
2023-11-28 15:52:53 +01:00
"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("/", serveRandomImageName)
http.HandleFunc("/image/", serveImage)
http.HandleFunc("/palette/", servePalette)
2023-11-28 15:52:53 +01:00
}
// 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
2023-11-28 15:52:53 +01:00
}
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)
2023-11-28 15:52:53 +01:00
if error != nil {
response.error = error
response.StatusCode = 404
response.send(writer)
2023-11-28 15:52:53 +01:00
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)
2023-11-28 15:52:53 +01:00
if error != nil {
response.error = error
response.StatusCode = 404
response.send(writer)
2023-11-28 15:52:53 +01:00
return
}
streamColorPalette(writer, image)
2023-11-28 15:52:53 +01:00
}