-
Notifications
You must be signed in to change notification settings - Fork 17
/
json_body_manual.go
86 lines (69 loc) · 2.2 KB
/
json_body_manual.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//go:build go1.18
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/swaggest/jsonschema-go"
"github.com/swaggest/rest/request"
"github.com/swaggest/usecase"
)
func jsonBodyManual() usecase.Interactor {
type outputWithJSON struct {
Header string `json:"inHeader"`
Query jsonschema.Date `json:"inQuery" deprecated:"true"`
Path string `json:"inPath"`
JSONPayload
}
u := usecase.NewInteractor(func(ctx context.Context, in inputWithJSON, out *outputWithJSON) (err error) {
out.Query = in.Query
out.Header = in.Header
out.Path = in.Path
out.JSONPayload = in.JSONPayload
return nil
})
u.SetTitle("Request With JSON Body and manual decoder")
u.SetDescription("Request with JSON body and query/header/path params, response with JSON body and data from request.")
return u
}
type JSONPayload struct {
ID int `json:"id"`
Name string `json:"name"`
}
type inputWithJSON struct {
Header string `header:"X-Header" description:"Simple scalar value in header."`
Query jsonschema.Date `query:"in_query" description:"Simple scalar value in query."`
Path string `path:"in-path" description:"Simple scalar value in path"`
NamedStruct JSONPayload `json:"namedStruct" deprecated:"true"`
JSONPayload
}
var _ request.Loader = &inputWithJSON{}
func (i *inputWithJSON) LoadFromHTTPRequest(r *http.Request) (err error) {
defer func() {
if err := r.Body.Close(); err != nil {
log.Printf("failed to close request body: %s", err.Error())
}
}()
b, err := io.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("failed to read request body: %w", err)
}
if err = json.Unmarshal(b, i); err != nil {
return fmt.Errorf("failsed to unmarshal request body: %w", err)
}
i.Header = r.Header.Get("X-Header")
if err := i.Query.UnmarshalText([]byte(r.URL.Query().Get("in_query"))); err != nil {
return fmt.Errorf("failed to decode in_query %q: %w", r.URL.Query().Get("in_query"), err)
}
if routeCtx := chi.RouteContext(r.Context()); routeCtx != nil {
i.Path = routeCtx.URLParam("in-path")
} else {
return errors.New("missing path params in context")
}
return nil
}