Begin implementation on apiv1.
Begin implementing the apiv1 package, which will define the first iteration of
our API endpoints and logic. Each API package should be self-contained and able
to run without depending on each other. Think of them as interfaces into
manipulating the business logic defined in the devices package. The point is to
have total control over backwards compatibility, as long as our business logic
doesn't change. If that happens, we're in a bad place, but not as bad as it
could be.
This required us to pull in all our API tools; the api package, its
dependencies, the scopeTypes package (so we can define scopes for our API), the
trout router, etc. We also updated uuid to the latest, which now includes a
license. Hooray?
The new apiv1 package consists of a few things:
* The devices.go file defines the types the API will use to communicate, along
with some helpers to convert from API types to devices types. There's also a
stub for validating the device creation requests, which I haven't implemented
yet because I'm a pretty bad person.
* endpoints.go just contains a helper function that builds our routes and
assigns handlers to them, giving us an http.Handler in the returns that we can
listen with.
* handlers.go defines our HTTP handlers, which will read requests and write
responses, after doing the appropriate validation and executing the
appropriating business logic. Right now, we only have a handler for creating
devices, and it doesn't actually do any validation. Also, we have some
user-correctable errors being returned as 500s right now, which is Bad.
Fortunately, they're all marked with BUG, so I can at least come back to them.
* response.go defines the Response type that will be used for returning
information after a request is executed. It may eventually get some helpers,
but for now it's pretty basic.
* scopes.go defines the Scopes that we're going to be using in the package to
control access. It should probably (eventually) include a helper to register
the Scopes, or we should have a collector service that pulls in all the
packages, finds all their Scopes, and registers them. I haven't decided how I
want to manage Scope registration just yet.
We exported the getStorer function (now GetStorer) so other packages can use it.
I'm not sure how I feel about this just yet. We also had to create a WithStorer
helper method that embeds the Storer into a context.Context, so we can bootstrap
in devicesd.
We erroneously had Created in the DeviceChange struct, but there's no reason the
Created property of a Device should ever change, so it was removed from the
logic, from the struct, and from the tests.
Our CreateMany helper was erroneously creating the un-modified Devices that were
passed in, instead of the Devices that had sensible defaults filled.
We created a _very minimal_ (e.g., needs some work before it's ready for
production) devicesd package that will spin up a simple server, just so we could
take a peek at our apiv1 endpoints as they'd actually be used. (It worked. Yay?)
We should continue to expand on this with configuration, more information being
logged, etc.
11 default404Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12 w.WriteHeader(http.StatusNotFound)
13 w.Write([]byte("404 Not Found"))
16 default405Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17 w.WriteHeader(http.StatusMethodNotAllowed)
18 w.Write([]byte("405 Method Not Allowed"))
23 // RequestVars returns easy-to-access mappings of parameters to values for URL templates. Any {parameter} in
24 // your URL template will be available in the returned Header as a slice of strings, one for each instance of
25 // the {parameter}. In the case of a parameter name being used more than once in the same URL template, the
26 // values will be in the slice in the order they appeared in the template.
28 // Values can easily be accessed by using the .Get() method of the returned Header, though to access multiple
29 // values, they must be accessed through the map. All parameters use http.CanonicalHeaderKey for their formatting.
30 // When using .Get(), the parameter name will be transformed automatically. When utilising the Header as a map,
31 // the parameter name needs to have http.CanonicalHeaderKey applied manually.
32 func RequestVars(r *http.Request) http.Header {
34 for h, v := range r.Header {
35 stripped := strings.TrimPrefix(h, http.CanonicalHeaderKey("Trout-Param-"))
43 // Router defines a set of Endpoints that map requests to the http.Handlers. The http.Handler assigned to
44 // Handle404, if set, will be called when no Endpoint matches the current request. The http.Handler assigned
45 // to Handle405, if set, will be called when an Endpoint matches the current request, but has no http.Handler
46 // set for the HTTP method that the request used. Should either of these properties be unset, a default
47 // http.Handler will be used.
49 // The Router type is safe for use with empty values, but makes no attempt at concurrency-safety in adding
50 // Endpoints or in setting properties. It should also be noted that the adding Endpoints while simultaneously
51 // routing requests will lead to undefined and (almost certainly) undesirable behaviour. Routers are intended
52 // to be initialised with a set of Endpoints, and then start serving requests. Using them outside of this use
53 // case is unsupported.
56 Handle404 http.Handler
57 Handle405 http.Handler
60 func (router *Router) serve404(w http.ResponseWriter, r *http.Request, t time.Time) {
61 h := default404Handler
62 if router.Handle404 != nil {
65 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10))
69 func (router *Router) serve405(w http.ResponseWriter, r *http.Request, t time.Time) {
70 h := default405Handler
71 if router.Handle405 != nil {
74 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10))
78 func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 router.serve404(w, r, start)
84 pieces := strings.Split(strings.ToLower(strings.Trim(r.URL.Path, "/")), "/")
86 defer router.t.RUnlock()
87 branches := make([]*branch, len(pieces))
88 path, ok := router.t.match(pieces)
90 router.serve404(w, r, start)
94 for i, pos := range path {
98 v := vars(branches, pieces)
99 for key, vals := range v {
100 r.Header[http.CanonicalHeaderKey("Trout-Param-"+key)] = vals
102 ms := make([]string, len(b.methods))
104 for m := range b.methods {
108 r.Header[http.CanonicalHeaderKey("Trout-Methods")] = ms
109 h := b.methods[r.Method]
111 router.serve405(w, r, start)
114 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(start).Nanoseconds(), 10))
118 // Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces
119 // to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id`
120 // that should be filled with whatever the request has in that space.
122 // Parameters are always `/`-separated strings. There is no support for regular expressions or other limitations
123 // on what may be in those strings. A parameter is simply defined as "whatever is between these two / characters".
124 func (router *Router) Endpoint(e string) *Endpoint {
125 e = strings.Trim(e, "/")
126 e = strings.ToLower(e)
127 pieces := strings.Split(e, "/")
132 defer router.t.Unlock()
133 if router.t.branch == nil {
134 router.t.branch = &branch{
136 children: []*branch{},
139 methods: map[string]http.Handler{},
142 closest := findClosestLeaf(pieces, router.t.branch)
144 for _, pos := range closest {
147 if len(closest) == len(pieces) {
148 return (*Endpoint)(b)
150 offset := len(closest)
151 for i := offset; i < len(pieces); i++ {
154 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" {
156 piece = piece[1 : len(piece)-1]
158 b = b.addChild(piece, isParam)
160 return (*Endpoint)(b)
163 func vars(path []*branch, pieces []string) map[string][]string {
164 v := map[string][]string{}
165 for pos, p := range path {
171 v[p.key] = []string{pieces[pos]}
174 v[p.key] = append(v[p.key], pieces[pos])
179 func findClosestLeaf(pieces []string, b *branch) []int {
184 for i := 0; i < num; i++ {
187 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" {
189 piece = piece[1 : len(piece)-1]
191 offset = pickNextRoute(b, offset, piece, isParam)
194 // exhausted our options, bail
197 // no match, maybe save this and backup
198 if len(path) > len(longest) {
199 longest = append([]int{}, path...) // copy them over so they don't get modified
201 path, offset = backup(path)
206 path = append(path, offset)
207 b = b.children[offset]
211 if len(longest) < len(path) {
212 longest = append([]int{}, path...)
217 func pickNextRoute(b *branch, offset int, input string, variable bool) int {
218 count := len(b.children)
219 for i := offset; i < count; i++ {
220 if b.children[i].key == input && b.isParam == variable {
227 // Endpoint defines a single URL template that requests can be matched against. It uses
228 // URL parameters to accept variables in the URL structure and make them available to
229 // the Handlers associated with the Endpoint.
232 // Handler associates the passed http.Handler with the Endpoint. This http.Handler will be
233 // used for all requests, regardless of the HTTP method they are using, unless overridden by
234 // the Methods method. Endpoints without a http.Handler associated with them will not be
235 // considered matches for requests, unless the request was made using an HTTP method that the
236 // Endpoint has an http.Handler mapped to.
237 func (e *Endpoint) Handler(h http.Handler) {
238 (*branch)(e).setHandler("", h)
241 // Methods simple returns a Methods object that will enable the mapping of the passed HTTP
242 // request methods to a Methods object. On its own, this function does not modify anything. It
243 // should, instead, be used as a friendly shorthand to get to the Methods.Handler method.
244 func (e *Endpoint) Methods(m ...string) Methods {
251 // Methods defines a pairing of an Endpoint to the HTTP request methods that should be mapped to
252 // specific http.Handlers. Its sole purpose is to enable the Methods.Handler method.
253 type Methods struct {
258 // Handler maps a Methods object to a specific http.Handler. This overrides the http.Handler
259 // associated with the Endpoint to only handle specific HTTP method(s).
260 func (m Methods) Handler(h http.Handler) {
262 for _, method := range m.m {
263 b.setHandler(method, h)