forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
79 lines (67 loc) · 2.16 KB
/
service.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
package service
import (
"net/http"
"github.com/NYTimes/gizmo/config/combined"
"github.com/NYTimes/gizmo/pubsub"
"github.com/NYTimes/gizmo/pubsub/aws"
"github.com/NYTimes/gizmo/server"
"github.com/NYTimes/gziphandler"
"github.com/Sirupsen/logrus"
)
type (
// JSONPubService will implement server.JSONPubService and
// handle all requests to the server.
JSONPubService struct {
pub pubsub.Publisher
}
)
// NewJSONPubService will instantiate a JSONPubService
// with the given configuration.
func NewJSONPubService(cfg *combined.Config) *JSONPubService {
pub, err := aws.NewPublisher(cfg.SNS)
if err != nil {
server.Log.Fatal("unable to init publisher: ", err)
}
return &JSONPubService{pub}
}
// Prefix returns the string prefix used for all endpoints within
// this service.
func (s *JSONPubService) Prefix() string {
return "/svc/nyt"
}
// Middleware provides an http.Handler hook wrapped around all requests.
// In this implementation, we're using a GzipHandler middleware to
// compress our responses.
func (s *JSONPubService) Middleware(h http.Handler) http.Handler {
return gziphandler.GzipHandler(h)
}
// JSONMiddleware provides a JSONEndpoint hook wrapped around all requests.
// In this implementation, we're using it to provide application logging and to check errors
// and provide generic responses.
func (s *JSONPubService) JSONMiddleware(j server.JSONEndpoint) server.JSONEndpoint {
return func(r *http.Request) (int, interface{}, error) {
status, res, err := j(r)
if err != nil {
server.LogWithFields(r).WithFields(logrus.Fields{
"error": err,
}).Error("problems with serving request")
return http.StatusServiceUnavailable, nil, &jsonErr{"sorry, this service is unavailable"}
}
server.LogWithFields(r).Info("success!")
return status, res, nil
}
}
// JSONEndpoints is a listing of all endpoints available in the JSONPubService.
func (s *JSONPubService) JSONEndpoints() map[string]map[string]server.JSONEndpoint {
return map[string]map[string]server.JSONEndpoint{
"/cats": map[string]server.JSONEndpoint{
"PUT": s.PublishCats,
},
}
}
type jsonErr struct {
Err string `json:"error"`
}
func (e *jsonErr) Error() string {
return e.Err
}