ducky/devices

Paddy 2015-12-14

15:c24a6c5fcd8c Go to Latest

ducky/devices/vendor/bitbucket.org/ww/goautoneg/autoneg.go

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.

History
1 /*
2 HTTP Content-Type Autonegotiation.
4 The functions in this package implement the behaviour specified in
5 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
7 Copyright (c) 2011, Open Knowledge Foundation Ltd.
8 All rights reserved.
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions are
12 met:
14 Redistributions of source code must retain the above copyright
15 notice, this list of conditions and the following disclaimer.
17 Redistributions in binary form must reproduce the above copyright
18 notice, this list of conditions and the following disclaimer in
19 the documentation and/or other materials provided with the
20 distribution.
22 Neither the name of the Open Knowledge Foundation Ltd. nor the
23 names of its contributors may be used to endorse or promote
24 products derived from this software without specific prior written
25 permission.
27 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 */
41 package goautoneg
43 import (
44 "sort"
45 "strconv"
46 "strings"
47 )
49 // Structure to represent a clause in an HTTP Accept Header
50 type Accept struct {
51 Type, SubType string
52 Q float64
53 Params map[string]string
54 }
56 // For internal use, so that we can use the sort interface
57 type accept_slice []Accept
59 func (accept accept_slice) Len() int {
60 slice := []Accept(accept)
61 return len(slice)
62 }
64 func (accept accept_slice) Less(i, j int) bool {
65 slice := []Accept(accept)
66 ai, aj := slice[i], slice[j]
67 if ai.Q > aj.Q {
68 return true
69 }
70 if ai.Type != "*" && aj.Type == "*" {
71 return true
72 }
73 if ai.SubType != "*" && aj.SubType == "*" {
74 return true
75 }
76 return false
77 }
79 func (accept accept_slice) Swap(i, j int) {
80 slice := []Accept(accept)
81 slice[i], slice[j] = slice[j], slice[i]
82 }
84 // Parse an Accept Header string returning a sorted list
85 // of clauses
86 func ParseAccept(header string) (accept []Accept) {
87 parts := strings.Split(header, ",")
88 accept = make([]Accept, 0, len(parts))
89 for _, part := range parts {
90 part := strings.Trim(part, " ")
92 a := Accept{}
93 a.Params = make(map[string]string)
94 a.Q = 1.0
96 mrp := strings.Split(part, ";")
98 media_range := mrp[0]
99 sp := strings.Split(media_range, "/")
100 a.Type = strings.Trim(sp[0], " ")
102 switch {
103 case len(sp) == 1 && a.Type == "*":
104 a.SubType = "*"
105 case len(sp) == 2:
106 a.SubType = strings.Trim(sp[1], " ")
107 default:
108 continue
109 }
111 if len(mrp) == 1 {
112 accept = append(accept, a)
113 continue
114 }
116 for _, param := range mrp[1:] {
117 sp := strings.SplitN(param, "=", 2)
118 if len(sp) != 2 {
119 continue
120 }
121 token := strings.Trim(sp[0], " ")
122 if token == "q" {
123 a.Q, _ = strconv.ParseFloat(sp[1], 32)
124 } else {
125 a.Params[token] = strings.Trim(sp[1], " ")
126 }
127 }
129 accept = append(accept, a)
130 }
132 slice := accept_slice(accept)
133 sort.Sort(slice)
135 return
136 }
138 // Negotiate the most appropriate content_type given the accept header
139 // and a list of alternatives.
140 func Negotiate(header string, alternatives []string) (content_type string) {
141 asp := make([][]string, 0, len(alternatives))
142 for _, ctype := range alternatives {
143 asp = append(asp, strings.SplitN(ctype, "/", 2))
144 }
145 for _, clause := range ParseAccept(header) {
146 for i, ctsp := range asp {
147 if clause.Type == ctsp[0] && clause.SubType == ctsp[1] {
148 content_type = alternatives[i]
149 return
150 }
151 if clause.Type == ctsp[0] && clause.SubType == "*" {
152 content_type = alternatives[i]
153 return
154 }
155 if clause.Type == "*" && clause.SubType == "*" {
156 content_type = alternatives[i]
157 return
158 }
159 }
160 }
161 return
162 }