ussd/internal/http/at/server.go

99 lines
1.9 KiB
Go
Raw Normal View History

2025-01-04 09:02:44 +01:00
package at
2024-09-14 14:55:45 +02:00
import (
"io"
"net/http"
2025-01-04 08:29:22 +01:00
"git.defalsify.org/vise.git/logging"
2024-09-14 14:55:45 +02:00
"git.grassecon.net/urdt/ussd/internal/handlers"
2025-01-04 08:29:22 +01:00
httpserver "git.grassecon.net/urdt/ussd/internal/http"
)
var (
logg = logging.NewVanilla().WithDomain("atserver").WithContextKey("AT-SessionId")
2024-09-14 14:55:45 +02:00
)
type ATSessionHandler struct {
2025-01-04 08:29:22 +01:00
*httpserver.SessionHandler
2024-09-14 14:55:45 +02:00
}
func NewATSessionHandler(h handlers.RequestHandler) *ATSessionHandler {
return &ATSessionHandler{
2025-01-04 08:29:22 +01:00
SessionHandler: httpserver.ToSessionHandler(h),
2024-09-14 14:55:45 +02:00
}
}
func (ash *ATSessionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var code int
var err error
rqs := handlers.RequestSession{
Ctx: req.Context(),
Writer: w,
}
rp := ash.GetRequestParser()
cfg := ash.GetConfig()
cfg.SessionId, err = rp.GetSessionId(req.Context(), req)
2024-09-14 14:55:45 +02:00
if err != nil {
logg.ErrorCtxf(rqs.Ctx, "", "header processing error", err)
2025-01-04 08:29:22 +01:00
ash.WriteError(w, 400, err)
return
2024-09-14 14:55:45 +02:00
}
rqs.Config = cfg
rqs.Input, err = rp.GetInput(req)
if err != nil {
logg.ErrorCtxf(rqs.Ctx, "", "header processing error", err)
2025-01-04 08:29:22 +01:00
ash.WriteError(w, 400, err)
2024-09-14 14:55:45 +02:00
return
}
rqs, err = ash.Process(rqs)
2024-09-14 14:55:45 +02:00
switch err {
case nil: // set code to 200 if no err
code = 200
case handlers.ErrStorage, handlers.ErrEngineInit, handlers.ErrEngineExec, handlers.ErrEngineType:
2024-09-14 14:55:45 +02:00
code = 500
default:
code = 500
2024-09-14 14:55:45 +02:00
}
if code != 200 {
2025-01-04 08:29:22 +01:00
ash.WriteError(w, 500, err)
2024-09-14 14:55:45 +02:00
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "text/plain")
rqs, err = ash.Output(rqs)
2024-09-14 14:55:45 +02:00
if err != nil {
2025-01-04 08:29:22 +01:00
ash.WriteError(w, 500, err)
2024-09-14 14:55:45 +02:00
return
}
rqs, err = ash.Reset(rqs)
if err != nil {
2025-01-04 08:29:22 +01:00
ash.WriteError(w, 500, err)
2024-09-14 14:55:45 +02:00
return
}
}
func (ash *ATSessionHandler) Output(rqs handlers.RequestSession) (handlers.RequestSession, error) {
2024-09-14 14:55:45 +02:00
var err error
var prefix string
if rqs.Continue {
prefix = "CON "
} else {
prefix = "END "
}
_, err = io.WriteString(rqs.Writer, prefix)
if err != nil {
return rqs, err
}
2024-09-20 21:15:24 +02:00
_, err = rqs.Engine.Flush(rqs.Ctx, rqs.Writer)
2024-09-14 14:55:45 +02:00
return rqs, err
2025-01-04 08:29:22 +01:00
}