This repository has been archived by the owner on Mar 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
endpoint.go
78 lines (65 loc) · 2.34 KB
/
endpoint.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
package command
import (
"errors"
"fmt"
"net/http"
"time"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/metrics"
"github.com/micromdm/mdm"
"golang.org/x/net/context"
)
var errEmptyRequest = errors.New("request must contain UDID of the device")
type Endpoints struct {
NewCommandEndpoint endpoint.Endpoint
}
// MakeNewCommandEndpoint creates an endpoint which creates new MDM Commands.
func MakeNewCommandEndpoint(svc Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(newCommandRequest)
if req.UDID == "" || req.RequestType == "" {
return newCommandResponse{Err: errEmptyRequest}, nil
}
payload, err := svc.NewCommand(ctx, req.CommandRequest)
if err != nil {
return newCommandResponse{Err: err}, nil
}
return newCommandResponse{Payload: payload}, nil
}
}
// EndpointInstrumentingMiddleware returns an endpoint middleware that records
// the duration of each invocation to the passed histogram. The middleware adds
// a single field: "success", which is "true" if no error is returned, and
// "false" otherwise.
func EndpointInstrumentingMiddleware(duration metrics.Histogram) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
defer func(begin time.Time) {
duration.With("success", fmt.Sprint(err == nil)).Observe(time.Since(begin).Seconds())
}(time.Now())
return next(ctx, request)
}
}
}
// EndpointLoggingMiddleware returns an endpoint middleware that logs the
// duration of each invocation, and the resulting error, if any.
func EndpointLoggingMiddleware(logger log.Logger) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
defer func(begin time.Time) {
logger.Log("error", err, "took", time.Since(begin))
}(time.Now())
return next(ctx, request)
}
}
}
type newCommandRequest struct {
*mdm.CommandRequest
}
type newCommandResponse struct {
Payload *mdm.Payload `json:"payload,omitempty"`
Err error `json:"error,omitempty"`
}
func (r newCommandResponse) error() error { return r.Err }
func (r newCommandResponse) status() int { return http.StatusCreated }