Repository navigation
Expand file tree
/
Copy pathapi.go
More file actions
74 lines (65 loc) · 1.63 KB
/
Copy pathapi.go
File metadata and controls
74 lines (65 loc) · 1.63 KB
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
package http
import (
"bytes"
"net/http"
"github.com/Aize-Public/forego/api"
"github.com/Aize-Public/forego/api/openapi"
"github.com/Aize-Public/forego/ctx"
"github.com/Aize-Public/forego/ctx/log"
"github.com/Aize-Public/forego/enc"
)
type Doable interface {
Do(ctx.C) error
}
func (s *Server) MustRegisterAPI(c ctx.C, obj Doable) *openapi.PathItem {
pi, err := s.RegisterAPI(c, obj)
if err != nil {
panic(err)
}
return pi
}
func (s *Server) RegisterAPI(c ctx.C, obj Doable) (*openapi.PathItem, error) {
handler, err := api.NewServer(c, obj)
if err != nil {
return nil, err
}
f := func(c ctx.C, in []byte, r *http.Request) ([]byte, error) {
req := &api.JSON{}
if r.Body != nil {
err := req.ReadFrom(c, bytes.NewBuffer(in))
if err != nil {
return nil, ctx.NewErrorf(c, "can't read request body: %v", err)
}
defer r.Body.Close()
} else {
log.Infof(c, "can/t get body: %v", err)
}
// TODO auth
obj, err := handler.Recv(c, req)
if err != nil {
return nil, NewErrorf(c, 400, "%v", err) // receive errors are always 4xx (TODO how to handle 403?)
}
err = obj.Do(c)
if err != nil {
return nil, err
}
//log.Debugf(c, "API %+v", obj)
res := &api.JSON{}
err = handler.Send(c, obj, res)
if err != nil {
return nil, err
}
out := enc.JSON{}.Encode(c, res.Data)
log.Debugf(c, "API response %s", out)
return out, nil
}
urls := handler.URLs()
if len(urls) == 0 {
return nil, ctx.NewErrorf(c, "no URL to register for %T", obj)
}
for _, u := range handler.URLs() {
log.Debugf(c, "registering to %q", u.Path)
s.handleRequest(u.Path, f)
}
return handler.UpdateOpenAPI(c, s.OpenAPI)
}