aicra/handler.go

108 lines
2.2 KiB
Go
Raw Normal View History

package aicra
import (
2021-03-28 17:05:43 +00:00
"log"
"net/http"
2019-04-30 22:02:28 +00:00
"git.xdrm.io/go/aicra/api"
"git.xdrm.io/go/aicra/internal/config"
"git.xdrm.io/go/aicra/internal/reqdata"
)
2021-03-28 17:03:16 +00:00
// Handler wraps the builder to handle requests
type Handler Builder
2021-03-28 17:03:16 +00:00
// ServeHTTP implements http.Handler
func (s Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2021-03-28 17:05:43 +00:00
defer func() {
if rc := recover(); rc != nil {
log.Printf("recovering request: %s\n", rc)
// try to send error response
api.EmptyResponse().WithError(api.ErrUncallableService).ServeHTTP(w, r)
}
}()
2021-03-28 17:03:16 +00:00
defer r.Body.Close()
2021-03-28 17:03:16 +00:00
// 1. find a matching service from config
var service = s.conf.Find(r)
if service == nil {
handleError(api.ErrUnknownService, w, r)
return
}
// 2. extract request data
2021-03-28 17:03:16 +00:00
var input, err = extractInput(service, *r)
if err != nil {
handleError(api.ErrMissingParam, w, r)
return
}
// 3. find a matching handler
var handler *apiHandler
2021-03-28 17:03:16 +00:00
for _, h := range s.handlers {
if h.Method == service.Method && h.Path == service.Pattern {
handler = h
}
}
2021-03-28 17:03:16 +00:00
// 4. fail on no matching handler
if handler == nil {
handleError(api.ErrUncallableService, w, r)
return
}
2021-03-28 17:03:16 +00:00
// 5. pass execution to the handler
var outData, outErr = handler.dyn.Handle(input.Data)
2021-03-28 17:03:16 +00:00
// 6. build res from returned data
var res = api.EmptyResponse().WithError(outErr)
for key, value := range outData {
2021-03-28 17:03:16 +00:00
// find original name from 'rename' field
for name, param := range service.Output {
if param.Rename == key {
2021-03-28 17:03:16 +00:00
res.SetData(name, value)
}
}
}
// 7. apply headers
2021-03-28 17:03:16 +00:00
w.Header().Set("Content-Type", "application/json; charset=utf-8")
for key, values := range res.Headers {
for _, value := range values {
2021-03-28 17:03:16 +00:00
w.Header().Add(key, value)
}
}
2021-03-28 17:03:16 +00:00
res.ServeHTTP(w, r)
}
func handleError(err api.Err, w http.ResponseWriter, r *http.Request) {
var response = api.EmptyResponse().WithError(err)
response.ServeHTTP(w, r)
}
2021-03-28 17:03:16 +00:00
func extractInput(service *config.Service, req http.Request) (*reqdata.T, error) {
var dataset = reqdata.New(service)
// URI data
var err = dataset.GetURI(req)
if err != nil {
return nil, err
}
// query data
err = dataset.GetQuery(req)
if err != nil {
return nil, err
}
// form/json data
err = dataset.GetForm(req)
if err != nil {
return nil, err
}
return dataset, nil
}