visedriver/request/http/server.go

93 lines
1.9 KiB
Go
Raw Permalink Normal View History

package http
import (
"net/http"
2024-09-12 04:30:23 +02:00
"strconv"
"git.defalsify.org/vise.git/logging"
"git.grassecon.net/grassrootseconomics/visedriver/request"
2025-01-11 09:33:52 +01:00
"git.grassecon.net/grassrootseconomics/visedriver/errors"
)
var (
2025-01-11 09:33:52 +01:00
logg = logging.NewVanilla().WithDomain("visedriver.http.session")
)
// HTTPRequestHandler implements the session handler for HTTP
type HTTPRequestHandler struct {
2025-01-11 09:33:52 +01:00
request.RequestHandler
}
func (f *HTTPRequestHandler) 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)
}
}
func NewHTTPRequestHandler(h request.RequestHandler) *HTTPRequestHandler {
return &HTTPRequestHandler{
2025-01-11 09:33:52 +01:00
RequestHandler: h,
}
}
func (hh *HTTPRequestHandler) 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
2025-01-04 23:27:46 +01:00
rqs := request.RequestSession{
2024-12-11 16:58:50 +01:00
Ctx: req.Context(),
2024-09-12 04:30:23 +02:00
Writer: w,
}
2025-01-11 09:33:52 +01:00
rp := hh.GetRequestParser()
cfg := hh.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-11 09:33:52 +01:00
hh.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-11 09:33:52 +01:00
hh.WriteError(w, 400, err)
return
}
2024-09-12 04:30:23 +02:00
2025-01-11 09:33:52 +01:00
rqs, err = hh.Process(rqs)
2024-09-12 04:30:23 +02:00
switch err {
2025-01-11 09:33:52 +01:00
case errors.ErrStorage:
2024-09-12 04:30:23 +02:00
code = 500
2025-01-11 09:33:52 +01:00
case errors.ErrEngineInit:
2024-09-12 04:30:23 +02:00
code = 500
2025-01-11 09:33:52 +01:00
case errors.ErrEngineExec:
2024-09-12 04:30:23 +02:00
code = 500
default:
code = 200
}
2024-09-12 04:30:23 +02:00
if code != 200 {
2025-01-11 09:33:52 +01:00
hh.WriteError(w, 500, err)
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "text/plain")
2025-01-11 09:33:52 +01:00
rqs, err = hh.Output(rqs)
rqs, perr = hh.Reset(rqs)
if err != nil {
2025-01-11 09:33:52 +01:00
hh.WriteError(w, 500, err)
return
}
if perr != nil {
2025-01-11 09:33:52 +01:00
hh.WriteError(w, 500, perr)
return
}
}