This repository has been archived by the owner on Aug 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dstest.go
186 lines (164 loc) · 4.38 KB
/
dstest.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Package dstest implements a mock Dark Sky server for testing.
package dstest
// FIXME generate response bodies for errors
import (
"errors"
"net/http"
"net/http/httptest"
"sort"
"strconv"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/twpayne/go-darksky"
)
// DefaultKey is the default key.
const DefaultKey = "key"
var (
errOutOfRange = errors.New("out of range")
//nolint: gochecknoglobals
defaultForecasts = make(map[Request]string)
)
// A Request contains parameters for a request.
type Request struct {
Latitude float64
Longitude float64
Time darksky.Time
Exclude string // A string, not a []darksky.Block so we can use Request as a map key.
Extend darksky.Extend
Lang darksky.Lang
Units darksky.Units
}
// A Server is a mock server.
type Server struct {
*httptest.Server
chi.Router
Key string
Forecasts map[Request]string
}
// An Option sets an option on a Server.
type Option func(*Server)
// WithDefaultForecasts returns an option that adds all default forecasts to a
// Server.
func WithDefaultForecasts() Option {
return func(s *Server) {
for request, forecast := range defaultForecasts {
s.Forecasts[request] = forecast
}
}
}
// WithForecast returns an option that adds a forecastStr as a response to
// request on a Server.
func WithForecast(request Request, forecastStr string) Option {
return func(s *Server) {
s.Forecasts[request] = forecastStr
}
}
// NewServer returns a new Server.
func NewServer(options ...Option) *Server {
router := chi.NewRouter()
s := &Server{
Server: httptest.NewServer(router),
Router: router,
Key: DefaultKey,
Forecasts: make(map[Request]string),
}
router.Get("/forecast/{key}/{latitude},{longitude}", s.handleForecast)
router.Get("/forecast/{key}/{latitude},{longitude},{time}", s.handleForecast)
for _, o := range options {
o(s)
}
return s
}
// NewClient returns a new darksky.Client that connects to s.
func (s *Server) NewClient(options ...darksky.ClientOption) (*darksky.Client, error) {
return darksky.NewClient(
append([]darksky.ClientOption{
darksky.WithBaseURL(s.URL),
darksky.WithHTTPClient(s.Client()),
darksky.WithKey(s.Key),
}, options...)...,
)
}
func (s *Server) handleForecast(w http.ResponseWriter, r *http.Request) {
if chi.URLParam(r, "key") != s.Key {
w.WriteHeader(http.StatusUnauthorized)
return
}
request := Request{
Lang: darksky.LangEN,
Units: darksky.UnitsUS,
}
var err error
request.Latitude, err = parseFloatFromURLParam(r, "latitude", -90, 90)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
request.Longitude, err = parseFloatFromURLParam(r, "longitude", -180, 180)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if timeStr := chi.URLParam(r, "time"); timeStr != "" {
timeVal, err := strconv.Atoi(timeStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
request.Time.Time = time.Unix(int64(timeVal), 0).UTC()
}
query := r.URL.Query()
if exclude := query.Get("exclude"); exclude != "" {
blocks := strings.Split(exclude, ",")
sort.Strings(blocks)
request.Exclude = strings.Join(blocks, ",")
}
if extend := query.Get("extend"); extend != "" {
request.Extend = darksky.Extend(extend)
}
if lang := query.Get("lang"); lang != "" {
request.Lang = darksky.Lang(lang)
}
if units := query.Get("units"); units != "" {
request.Units = darksky.Units(units)
}
forecast, ok := s.Forecasts[request]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
_, _ = w.Write([]byte(forecast))
}
// Options returns a new darksky.ForecastOptions constructed from r.
func (r *Request) Options() *darksky.ForecastOptions {
if r.Exclude == "" && r.Extend == darksky.DefaultExtend && r.Lang == darksky.DefaultLang && r.Units == darksky.DefaultUnits {
return nil
}
o := &darksky.ForecastOptions{}
if r.Exclude != "" {
for _, block := range strings.Split(r.Exclude, ",") {
o.Exclude = append(o.Exclude, darksky.Block(block))
}
}
if r.Extend != darksky.DefaultExtend {
o.Extend = r.Extend
}
if r.Lang != darksky.DefaultLang {
o.Lang = r.Lang
}
if r.Units != darksky.DefaultUnits {
o.Units = r.Units
}
return o
}
func parseFloatFromURLParam(r *http.Request, key string, min, max float64) (float64, error) {
x, err := strconv.ParseFloat(chi.URLParam(r, key), 64)
if err != nil {
return 0, err
}
if x < min || max < x {
return 0, errOutOfRange
}
return x, nil
}