-
Notifications
You must be signed in to change notification settings - Fork 2
/
go_http_api.html
317 lines (241 loc) · 8.78 KB
/
go_http_api.html
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Building Web Services (HTTP APIs) with Go</title>
<meta name="generator" content="Slide Show (S9) 2.3.0 on Ruby 2.1.4 (2014-10-27) [i686-linux]">
<meta name="author" content="Your Name Here" >
<!-- helper/macro that lets you add (CSS3) gradient using headers
see http://slideshow.rubyforge.org/themes.html
-->
<!-- S6 style sheet links -->
<link rel="stylesheet" href="go_http_api.css" media="projection" id="styleProjection">
<link rel="stylesheet" href="s6/screen.css" media="screen" id="styleScreen">
<link rel="stylesheet" href="s6/print.css" media="print">
<!-- S6 JS -->
<script src="s6/jquery.js"></script>
<script src="s6/jquery.slideshow.js"></script>
<script>
$(document).ready( function() {
Slideshow.init();
} );
</script>
<!-- Better Browser Banner for Microsoft Internet Explorer (IE) -->
<!--[if IE]>
<script src="s6/jquery.microsoft.js"></script>
<![endif]-->
</head>
<body>
<div class="layout">
<div id="header"></div>
<div id="footer">
<h1>Your Footer Here</h1>
<h2>Your Subfooter Here</h2>
</div>
</div>
<div class="presentation">
<div class='slide '>
<!-- === begin markdown block ===
generated by markdown 1.1.1 on Ruby 2.1.4 (2014-10-27) [i686-linux]
on 2014-11-20 11:16:48 +0100 with Markdown engine redcarpet (3.2.0) w/ HTML render
using extensions: ["no_intra_emphasis","fenced_code_blocks","tables","strikethrough"]
-->
<!-- _S9SLIDE_ -->
<h1>What's football.db? What's sportkit?</h1>
<p>Free open public domain football datasets (leagues, teams, matches, etc.) -> <a href="https://github.com/openfootball"><code>github.com/openfootball</code></a></p>
<pre><code>Quarter-finals - 1st Leg
[Tue Apr/1]
20.45 FC Barcelona 1-1 Atlético Madrid @ Camp Nou, Barcelona
[Neymar 71'; Diego 56']
20.45 Manchester United 1-1 Bayern München @ Old Trafford, Manchester
[Vidić 58'; Schweinsteiger 67']
[Wed Apr/2]
20.45 Real Madrid 3-0 Borussia Dortmund @ Santiago Bernabéu, Madrid
[Bale 3' Isco 27' Ronaldo 57']
20.45 Paris Saint-Germain 3-1 Chelsea FC @ Parc des Princes, Paris
[Lavezzi 4' Luiz 61' (o.g.) Pastore 90+3'; Hazard 27' (pen.)]
</code></pre>
<p>or in JSON via HTTP <code>GET /events</code></p>
<pre><code>[
{"key":"en.2014/15","title":"English Premier League 2014/15"},
{"key":"de.2014/15","title":"Deutsche Bundesliga 2014/15"},
{"key":"at.2014/15","title":"Österr. Bundesliga 2014/15"},
...
]
</code></pre>
<p>Includes sportkit - starter kit for HTTP JSON API - Go Edition -> <a href="https://github.com/sportkit"><code>github.com/sportkit</code></a></p>
</div>
<div class='slide '>
<!-- _S9SLIDE_ -->
<h1>Go Structs, Structs, Structs</h1>
<p><code>sportkit/database_structs.go</code>:</p>
<pre><code>type Event struct {
Key string
Title string
}
type Team struct {
Key string
Title string
Code string
}
</code></pre>
<p>NOTE: Go ids (names) starting with capital letter (upper case) are public (by definition).</p>
<pre><code>type JsEvent struct {
Key string `json:"key"`
Title string `json:"title"`
}
type JsTeam struct {
Key string `json:"key"`
Title string `json:"title"`
Code string `json:"code"`
}
</code></pre>
</div>
<div class='slide '>
<!-- _S9SLIDE_ -->
<h1>Database Queries</h1>
<p><code>sportkit/database_finders.go</code>:</p>
<pre><code>query :=
`SELECT
e.[key] AS event_key,
l.title || ' ' || s.title AS event_name
FROM events e
INNER JOIN seasons s ON s.id = e.season_id
INNER JOIN leagues l ON l.id = e.league_id`
</code></pre>
<p>NOTE: Go "raw" strings with backquotes (`) let you use multi-line string literals.</p>
<pre><code>import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log"
)
</code></pre>
<p>NOTE: You can use Go packages "hosted" on Github. Works "out-of-the-box".
Use <code>go get github.com/mattn/go-sqlite3</code> to install.</p>
<pre><code>func FetchEvents() []Event {
db, err := sql.Open( "sqlite3", "./football.db" )
if err != nil {
log.Fatal(err)
}
rows, err := db.Query( query )
if err != nil {
log.Fatal(err)
}
defer rows.Close()
events := []Event{}
for rows.Next() {
var r Event
err = rows.Scan( &r.Key, &r.Title )
if err != nil {
log.Fatal(err)
}
events = append( events, r ) // add new row
}
return events
}
</code></pre>
<p>NOTE: Go has NO exceptions; function (almost) always returns error (<code>err</code>) types.</p>
<p>Why no exceptions? Go's headline feature is concurrency (w/ Go (co)routines and channels) -
exceptions do NOT really work in an (asynchronous) concurrent world.</p>
</div>
<div class='slide '>
<!-- _S9SLIDE_ -->
<h1>Generate (Encode) JSON</h1>
<pre><code>import (
"encoding/json"
)
</code></pre>
<pre><code>func GetEvents() (interface{},error) {
// step 1: fetch records
events := FetchEvents()
// step 2: map to json structs for serialization/marshalling
type JsEvent struct {
Key string `json:"key"`
Title string `json:"title"`
}
data := []*JsEvent{}
for _,event := range events {
data = append( data, &JsEvent {
Key: event.Key,
Title: event.Title, } )
}
return json.Marshal( data )
}
</code></pre>
<p>NOTE: <code>interface{}</code> is the Go version of the any object type (<code>void*</code>).</p>
</div>
<div class='slide '>
<!-- _S9SLIDE_ -->
<h1>Serve via HTTP</h1>
<pre><code>import (
"net/http"
"net/url"
"fmt"
"strings"
)
</code></pre>
<pre><code>func main() {
addr := ":9292"
fmt.Println( "Starting web server listening on " + addr + "..." )
fmt.Println( "Use Ctrl-C to stop" )
http.HandleFunc( "/", handleFunc )
http.ListenAndServe( addr, nil )
fmt.Println( "Bye" )
}
</code></pre>
<pre><code>func handleFunc( w http.ResponseWriter, r *http.Request ) {
log.Println( "handle url.path: " + r.URL.Path )
eventsRoute, _ := regexp.Compile( "^/events$" )
if eventsRoute.MatchString( r.URL.Path ) {
b, err := GetEvents()
if err != nil {
fmt.Fprintf( w, err.Error() )
}
else {
fmt.Fprintf( w, string(b) )
}
}
else {
fmt.Fprintf( w, "No route match found for " + r.URL.Path )
}
}
</code></pre>
</div>
<div class='slide '>
<!-- _S9SLIDE_ -->
<h1>Why Go? - Faster, Faster, Faster</h1>
<p>Use what works for you.</p>
<p>Kind of a "better" more "modern" C.</p>
<p>Code gets compiled (to machine-code ahead-of-time) and linked
to let you build (small-ish) zero-dependency
all-in-one binary (file) programs.</p>
<p>No virtual machine or byte code runtime or just-in-time compiler machinery needed;
includes garbage collector.</p>
<h2>Go's Headline Features</h2>
<ul>
<li>Fast Builds - Imports, Package Structure, etc.</li>
<li>Concurreny - Go (co)-routines, channels
e.g. "agent model" - no threads, no shared state/variables - message passing w/ agents, etc.</li>
</ul>
</div>
<div class='slide '>
<!-- _S9SLIDE_ -->
<h1>That's it. Thanks.</h1>
<h3>Questions? Comments?</h3>
<h3>Go Links</h3>
<ul>
<li><a href="http://go-database-sql.org">Go SQL Tutorial (Series)</a></li>
<li><a href="https://github.com/jmoiron/sqlx">sqlx package</a> - general extensions to database/sql e.g. includes <code>rows.StructScan()</code></li>
<li><a href="https://howistart.org/posts/go/1">How I start (Go Edition</a> - builds a small HTTP JSON API wrapper/proxy for weather service</li>
<li><a href="http://learnxinyminutes.com/docs/go">Learn Go in 5 Minutes</a> - single-page "cheatsheet" - "real-world" code w/ comments</li>
</ul>
<h3>Free Online Go Books</h3>
<ul>
<li><a href="http://www.golangbootcamp.com/book">The Go Bootcamp Book</a> by Matt Aimonetti</li>
<li><a href="http://www.golang-book.com">An Introduction to Programming in Go</a> by Caleb Doxsey</li>
</ul>
<!-- === end markdown block === -->
</div>
</div><!-- presentation -->
</body>
</html>