blob: d497b24a0e532b3985b2d904da4364708467d30d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
)
//Wrap API handler and returns standard http handler function
func Wrap[RQ any, RS any](handler func(ctx context.Context, request *RQ) (RS, error)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
req := new(RQ)
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(fmt.Sprintf("Fail to parse request body: %s", err.Error())))
return
}
resp, err := handler(r.Context(), req)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
if err := json.NewEncoder(w).Encode(resp); err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
}
}
|