forked from go-swagger/go-swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
155 lines (126 loc) · 3.89 KB
/
main.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
package main
import (
"log"
"net/http"
"os"
"sync"
"sync/atomic"
"github.com/go-openapi/errors"
"github.com/go-openapi/loads"
"github.com/go-openapi/loads/fmts"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/runtime/middleware/untyped"
)
func init() {
loads.AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc)
}
func main() {
if len(os.Args) == 1 {
log.Fatalln("this command requires the swagger spec as argument")
}
log.Printf("loading %q as contract for the server", os.Args[1])
specDoc, err := loads.Spec(os.Args[1])
if err != nil {
log.Fatalln(err)
}
// our spec doesn't have application/json in the consumes or produces
// so we need to clear those settings out
api := untyped.NewAPI(specDoc).WithoutJSONDefaults()
// register serializers
mediaType := "application/io.goswagger.examples.todo-list.v1+json"
api.DefaultConsumes = mediaType
api.DefaultProduces = mediaType
api.RegisterConsumer(mediaType, runtime.JSONConsumer())
api.RegisterProducer(mediaType, runtime.JSONProducer())
// register the operation handlers
api.RegisterOperation("GET", "/", findTodos)
api.RegisterOperation("POST", "/", addOne)
api.RegisterOperation("PUT", "/{id}", updateOne)
api.RegisterOperation("DELETE", "/{id}", destroyOne)
// validate the API descriptor, to ensure we don't have any unhandled operations
if err := api.Validate(); err != nil {
log.Fatalln(err)
}
// construct the application context for this server
// use the loaded spec document and the api descriptor with the default router
app := middleware.NewContext(specDoc, api, nil)
log.Println("serving", specDoc.Spec().Info.Title, "at http://localhost:8000")
// serve the api with spec and UI
if err := http.ListenAndServe(":8000", app.APIHandler(nil)); err != nil {
log.Fatalln(err)
}
}
var findTodos = runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) {
log.Println("received 'findTodos'")
log.Printf("%#v\n", params)
return items, nil
})
var addOne = runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) {
log.Println("received 'addOne'")
log.Printf("%#v\n", params)
body := params.(map[string]interface{})["body"].(map[string]interface{})
addItem(body)
return body, nil
})
var updateOne = runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) {
log.Println("received 'updateOne'")
log.Printf("%#v\n", params)
data := params.(map[string]interface{})
id := data["id"].(int64)
body := data["body"].(map[string]interface{})
return updateItem(id, body)
})
var destroyOne = runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) {
log.Println("received 'destroyOne'")
log.Printf("%#v\n", params)
removeItem(params.(map[string]interface{})["id"].(int64))
return nil, nil
})
var items = []map[string]interface{}{
{"id": int64(1), "description": "feed dog", "completed": true},
{"id": int64(2), "description": "feed cat"},
}
var itemsLock = &sync.Mutex{}
var lastItemID int64 = 2
func newItemID() int64 {
return atomic.AddInt64(&lastItemID, 1)
}
func addItem(item map[string]interface{}) {
itemsLock.Lock()
defer itemsLock.Unlock()
item["id"] = newItemID()
items = append(items, item)
}
func updateItem(id int64, body map[string]interface{}) (map[string]interface{}, error) {
itemsLock.Lock()
defer itemsLock.Unlock()
item, err := itemByID(id)
if err != nil {
return nil, err
}
delete(body, "id")
for k, v := range body {
item[k] = v
}
return item, nil
}
func removeItem(id int64) {
itemsLock.Lock()
defer itemsLock.Unlock()
var newItems []map[string]interface{}
for _, item := range items {
if item["id"].(int64) != id {
newItems = append(newItems, item)
}
}
items = newItems
}
func itemByID(id int64) (map[string]interface{}, error) {
for _, item := range items {
if item["id"].(int64) == id {
return item, nil
}
}
return nil, errors.NotFound("not found: item %d", id)
}