aboutsummaryrefslogtreecommitdiff
path: root/wrap.go
blob: ab071cf6c5bb9d991568ede74da00e6056cb6305 (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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package api

import (
	"context"
	"encoding/json"
	"net/http"
)

//Wrap API handler and returns standard http.HandlerFunc function
func Wrap[RQ any, RS any](handler func(ctx context.Context, request *RQ) (RS, error)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		req := new(RQ)
		richifyRequest(req, r)
		switch r.Method {
		case http.MethodPost, http.MethodPatch, http.MethodDelete, http.MethodPut:
			if err := json.NewDecoder(r.Body).Decode(req); err != nil {
				w.WriteHeader(http.StatusBadRequest)
				_, _ = w.Write([]byte(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
		}
	}
}

func richifyRequest[RQ any](req *RQ, baseRequest *http.Request) {
	if v, ok := (any)(req).(WithHeader); ok {
		v.WithHeader(baseRequest.Header)
	}
	if v, ok := (any)(req).(WithMethod); ok {
		v.WithMethod(baseRequest.Method)
	}
}

type WithHeader interface {
	WithHeader(header http.Header)
}

type WithMethod interface {
	WithMethod(method string)
}