-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.go
72 lines (61 loc) · 2.57 KB
/
request.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package httpsuite
import (
"encoding/json"
"errors"
"github.com/go-chi/chi/v5"
"net/http"
"reflect"
)
// RequestParamSetter defines the interface used to set the parameters to the HTTP request object by the request parser.
// Implementing this interface allows custom handling of URL parameters.
type RequestParamSetter interface {
// SetParam assigns a value to a specified field in the request struct.
// The fieldName parameter is the name of the field, and value is the value to set.
SetParam(fieldName, value string) error
}
// ParseRequest parses the incoming HTTP request into a specified struct type, handling JSON decoding and URL parameters.
// It validates the parsed request and returns it along with any potential errors.
// The pathParams variadic argument allows specifying URL parameters to be extracted.
// If an error occurs during parsing, validation, or parameter setting, it responds with an appropriate HTTP status.
func ParseRequest[T RequestParamSetter](w http.ResponseWriter, r *http.Request, pathParams ...string) (T, error) {
var request T
var empty T
defer func() {
_ = r.Body.Close()
}()
if r.Body != http.NoBody {
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
SendResponse[any](w, http.StatusBadRequest, nil,
[]Error{{Code: http.StatusBadRequest, Message: "Invalid JSON format"}}, nil)
return empty, err
}
}
// If body wasn't parsed request may be nil and cause problems ahead
if isRequestNil(request) {
request = reflect.New(reflect.TypeOf(request).Elem()).Interface().(T)
}
// Parse URL parameters
for _, key := range pathParams {
value := chi.URLParam(r, key)
if value == "" {
SendResponse[any](w, http.StatusBadRequest, nil,
[]Error{{Code: http.StatusBadRequest, Message: "Parameter " + key + " not found in request"}}, nil)
return empty, errors.New("missing parameter: " + key)
}
if err := request.SetParam(key, value); err != nil {
SendResponse[any](w, http.StatusInternalServerError, nil,
[]Error{{Code: http.StatusInternalServerError, Message: "Failed to set field " + key, Details: err.Error()}}, nil)
return empty, err
}
}
// Validate the combined request struct
if validationErr := IsRequestValid(request); validationErr != nil {
SendResponse[any](w, http.StatusBadRequest, nil,
[]Error{{Code: http.StatusBadRequest, Message: "Validation error", Details: validationErr}}, nil)
return empty, errors.New("validation error")
}
return request, nil
}
func isRequestNil(i interface{}) bool {
return i == nil || (reflect.ValueOf(i).Kind() == reflect.Ptr && reflect.ValueOf(i).IsNil())
}