-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.go
73 lines (66 loc) · 1.56 KB
/
cli.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
package backend
import (
"bytes"
"encoding/json"
"fmt"
"github.com/zeebo/errs"
"go.uber.org/zap"
"net/http"
"net/http/httptest"
)
type Cli struct {
endpoint *Endpoint
service *Service
}
func NewCliDispatcher() *Cli {
logger := zap.NewExample()
service := NewService(logger)
endpoint := NewEndpoint(logger, service)
return &Cli{
service: service,
endpoint: endpoint,
}
}
func (c *Cli) Dispatch(cmd string, args []string) error {
switch cmd {
case "status":
return c.handleMessage("GET", c.endpoint.Status, nil)
case "local-images":
return c.handleMessage("GET", c.endpoint.LocalImages, nil)
case "pull":
return c.handleMessage("POST", c.endpoint.Pull, nil)
case "start":
return c.handleMessage("POST", c.endpoint.Start, nil)
case "stop":
return c.handleMessage("POST", c.endpoint.Stop, nil)
case "config":
return c.handleMessage("POST", c.endpoint.Configure, struct {
Bucket string `json:"bucket"`
Grant string `json:"grant"`
}{
Bucket: args[0],
Grant: args[1],
})
}
return errs.New("Unsupported cmd " + cmd)
}
func (c *Cli) handleMessage(method string, h func(w http.ResponseWriter, r *http.Request), input interface{}) (err error) {
s := []byte{}
if input != nil {
s, err = json.Marshal(input)
if err != nil {
return errs.Wrap(err)
}
}
r, err := http.NewRequest(method, "", bytes.NewReader(s))
if err != nil {
return errs.Wrap(err)
}
recorder := httptest.NewRecorder()
h(recorder, r)
if recorder.Code != 200 {
return errs.New(recorder.Body.String())
}
fmt.Println(recorder.Body.String())
return nil
}