-
Notifications
You must be signed in to change notification settings - Fork 224
/
service.go
86 lines (73 loc) · 2.29 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
80
81
82
83
84
85
86
package service
import (
"net/http"
"github.com/NYTimes/gizmo/server"
"github.com/NYTimes/gziphandler"
"github.com/sirupsen/logrus"
"github.com/NYTimes/gizmo/examples/nyt"
)
type (
// JSONService will implement server.JSONService and
// handle all requests to the server.
JSONService struct {
client nyt.Client
}
// Config is a struct to contain all the needed
// configuration for our JSONService
Config struct {
Server *server.Config
MostPopularToken string
SemanticToken string
}
)
// NewJSONService will instantiate a JSONService
// with the given configuration.
func NewJSONService(cfg *Config) *JSONService {
return &JSONService{
nyt.NewClient(cfg.MostPopularToken, cfg.SemanticToken),
}
}
// Prefix returns the string prefix used for all endpoints within
// this service.
func (s *JSONService) 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 *JSONService) 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 *JSONService) 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 JSONService.
func (s *JSONService) JSONEndpoints() map[string]map[string]server.JSONEndpoint {
return map[string]map[string]server.JSONEndpoint{
"/most-popular/{resourceType}/{section}/{timeframe}": map[string]server.JSONEndpoint{
"GET": s.GetMostPopular,
},
"/cats": map[string]server.JSONEndpoint{
"GET": s.GetCats,
},
}
}
type jsonErr struct {
Err string `json:"error"`
}
func (e *jsonErr) Error() string {
return e.Err
}