visedriver/internal/http/server.go

92 lines
1.8 KiB
Go
Raw Normal View History

package http
import (
"net/http"
2024-09-12 04:30:23 +02:00
"strconv"
"git.defalsify.org/vise.git/logging"
2024-09-12 04:30:23 +02:00
"git.grassecon.net/urdt/ussd/internal/handlers"
)
var (
logg = logging.NewVanilla().WithDomain("httpserver").WithContextKey("at-session-id")
)
type SessionHandler struct {
handlers.RequestHandler
}
func ToSessionHandler(h handlers.RequestHandler) *SessionHandler {
return &SessionHandler{
RequestHandler: h,
}
}
2025-01-04 08:29:22 +01:00
func (f *SessionHandler) WriteError(w http.ResponseWriter, code int, err error) {
2024-09-12 04:30:23 +02:00
s := err.Error()
w.Header().Set("Content-Length", strconv.Itoa(len(s)))
w.WriteHeader(code)
2024-12-11 16:58:50 +01:00
_, err = w.Write([]byte(s))
if err != nil {
2024-09-12 04:30:23 +02:00
logg.Errorf("error writing error!!", "err", err, "olderr", s)
w.WriteHeader(500)
}
}
2024-12-11 16:58:50 +01:00
func (f *SessionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
2024-09-12 04:30:23 +02:00
var code int
var err error
var perr error
2024-09-12 04:30:23 +02:00
rqs := handlers.RequestSession{
2024-12-11 16:58:50 +01:00
Ctx: req.Context(),
2024-09-12 04:30:23 +02:00
Writer: w,
}
rp := f.GetRequestParser()
cfg := f.GetConfig()
cfg.SessionId, err = rp.GetSessionId(req.Context(), req)
if err != nil {
2024-09-12 04:30:23 +02:00
logg.ErrorCtxf(rqs.Ctx, "", "header processing error", err)
2025-01-04 08:29:22 +01:00
f.WriteError(w, 400, err)
2024-09-12 04:30:23 +02:00
}
rqs.Config = cfg
rqs.Input, err = rp.GetInput(req)
2024-09-12 04:30:23 +02:00
if err != nil {
logg.ErrorCtxf(rqs.Ctx, "", "header processing error", err)
2025-01-04 08:29:22 +01:00
f.WriteError(w, 400, err)
return
}
2024-09-12 04:30:23 +02:00
rqs, err = f.Process(rqs)
switch err {
case handlers.ErrStorage:
code = 500
case handlers.ErrEngineInit:
code = 500
case handlers.ErrEngineExec:
code = 500
default:
code = 200
}
2024-09-12 04:30:23 +02:00
if code != 200 {
2025-01-04 08:29:22 +01:00
f.WriteError(w, 500, err)
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "text/plain")
rqs, err = f.Output(rqs)
rqs, perr = f.Reset(rqs)
if err != nil {
2025-01-04 08:29:22 +01:00
f.WriteError(w, 500, err)
return
}
if perr != nil {
2025-01-04 08:29:22 +01:00
f.WriteError(w, 500, perr)
return
}
}