wolbodge/routes/api.go
2025-03-22 15:42:01 +01:00

53 lines
1.3 KiB
Go

package routes
import (
"fmt"
"log"
"net/http"
"strings"
"time"
"git.1e99.eu/1e99/wolbodge/sessions"
)
func APIStartSession(logger *log.Logger, storage sessions.Storage) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
err := req.ParseMultipartForm(10 * 1024)
if err != nil {
http.Error(res, "", http.StatusBadRequest)
return
}
description := req.FormValue("description")
if strings.TrimSpace(description) == "" {
description = "description"
}
session, err := storage.StartSession(description, time.Now())
if err != nil {
http.Error(res, "", http.StatusInternalServerError)
return
}
fmt.Fprintf(res, "%s", session.Id)
logger.Printf("Started new session for %s via API (id = %s, description = \"%s\")", req.RemoteAddr, session.Id, session.Description)
}
}
func APIEndSession(logger *log.Logger, storage sessions.Storage) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
sessionId := req.PathValue("session_id")
err := storage.EndSession(sessionId)
switch {
case err == sessions.ErrUnknownSession:
http.Error(res, "", http.StatusNotFound)
return
case err != nil:
http.Error(res, "", http.StatusInternalServerError)
return
}
logger.Printf("Ended session for %s via API (id = %s)", req.RemoteAddr, sessionId)
}
}