-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
1028 lines (910 loc) · 66.6 KB
/
index.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Building a Web App With Go, Gin and React - hakaselogs</title><link rel="icon" type="image/png" href=/images/favicon.png /><meta name="viewport" content="width=device-width, initial-scale=1">
<meta itemprop="name" content="Building a Web App With Go, Gin and React">
<meta itemprop="description" content="In this tutorial, I'll show you how easy it is to build a web application with Go and the Gin framework and add authentication to it.">
<meta itemprop="dateModified" content="2018-04-20T00:00:00+00:00" />
<meta itemprop="wordCount" content="4073">
<meta itemprop="keywords" content="go,gin-gonic,react,golang," />
<meta property="og:title" content="Building a Web App With Go, Gin and React" />
<meta property="og:description" content="In this tutorial, I'll show you how easy it is to build a web application with Go and the Gin framework and add authentication to it." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://hakaselogs.me/2018-04-20/building-a-web-app-with-go-gin-and-react/" />
<meta property="article:published_time" content="2018-04-20T00:00:00+00:00" />
<meta property="article:modified_time" content="2018-04-20T00:00:00+00:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Building a Web App With Go, Gin and React"/>
<meta name="twitter:description" content="In this tutorial, I'll show you how easy it is to build a web application with Go and the Gin framework and add authentication to it."/>
<link href='https://fonts.googleapis.com/css?family=Playfair+Display:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" media="screen" href="https://hakaselogs.me/css/normalize.css" />
<link rel="stylesheet" type="text/css" media="screen" href="https://hakaselogs.me/css/main.css" />
<link id="dark-scheme" rel="stylesheet" type="text/css" href="https://hakaselogs.me/css/dark.css" />
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script src="https://hakaselogs.me/js/main.js"></script>
</head>
<body>
<div class="container wrapper">
<div class="header">
<div class="avatar">
<a href="https://hakaselogs.me/">
<img src="https://storage.googleapis.com/gopherizeme.appspot.com/gophers/0f1736136b4fcbea61798f9d4d04a6b01f4a05ad.png" alt="hakaselogs" />
</a>
</div>
<h1 class="site-title"><a href="https://hakaselogs.me/">hakaselogs</a></h1>
<div class="site-description"><p>Notes mostly about software engineering and what I’m working on.</p><nav class="nav social">
<ul class="flat"><li><a href="https://twitter.com/codehakase" title="Twitter"><i data-feather="twitter"></i></a></li><li><a href="https://github.com/codehakase" title="Github"><i data-feather="github"></i></a></li></ul>
</nav>
</div>
<nav class="nav">
<ul class="flat">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/posts">Archive</a>
</li>
<li>
<a href="/projects">Projects</a>
</li>
<li>
<a href="/tags">Tags</a>
</li>
</ul>
</nav>
</div>
<div class="post">
<div class="post-header">
<div class="meta">
<div class="date">
<span class="day">20</span>
<span class="rest">Apr 2018</span>
</div>
</div>
<div class="matter">
<h1 class="title">Building a Web App With Go, Gin and React</h1>
</div>
</div>
<div class="markdown">
<p><strong>TL;DR:</strong> In this tutorial, I’ll show you how easy it is to build a web application with Go and the Gin framework and add authentication to it. Check out the Github <a href="https://github.com/codehakase/golang-gin">repo</a> for the code we’re going to write.</p>
<hr>
<p><strong>Gin</strong> is a high-performance micro-framework that delivers a very minimalistic framework that carries with it only the most essential features, libraries, and functionalities needed to build web applications and microservices. It makes it simple to build a request handling pipeline from modular, reusable pieces. It does this by allowing you to write middleware that can be plugged into one or more request handlers or groups of request handlers.</p>
<h2 id="gin-features">Gin Features</h2>
<p>Gin is a fast, simple yet fully featured and very efficient web framework for Go. Check out some of the features below that makes it a worthy framework to consider for your next Golang project.</p>
<ul>
<li><strong>Speed:</strong> Gin is built for speed. The framework offers a Radix tree based routing, small memory foot print. No reflection. Predictable API performance.</li>
<li><strong>Crash-Free</strong>: Gin has the capability of catching crashes or panics during runtime, and can recover from it, this way your application will be always available.</li>
<li><strong>Routing:</strong> Gin provides a routing interface to allow you express how your web application or API routes should look.</li>
<li><strong>JSON Validation:</strong> Gin can parse and validate the JSON requests easily, checking for the existence of required values.</li>
<li><strong>Error Management:</strong> Gin provides a convenient way to collect all the errors occurred during a HTTP request. Eventually, a middleware can write them to a log file, to a database and send them through the network.</li>
<li><strong>Built-In Rendering:</strong> Gin provides an easy to use API for JSON, XML, and HTML rendering.</li>
</ul>
<h2 id="prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you’ll need to have Go installed on your machine, a web browser to view the app, and a command line to execute build commands.</p>
<p><strong>Go</strong> or as its normally called; <em>“Golang”</em>, is a programming language developed by Google for building modern software. Go is a language designed to get stuff done efficiently and fast. The key benefits of Go include:</p>
<ul>
<li>Strongly typed and garbage collected</li>
<li>Blazing fast compile times</li>
<li>Concurrency built in</li>
<li>Extensive standard library</li>
</ul>
<p>Head over to the <a href="https://golang.org/dl/">downloads section</a> of the Go website, to get Go running on your machine.</p>
<h2 id="building-an-app-with-gin">Building An App With Gin</h2>
<p>We’ll be building a simple joke listing app with <strong>Gin</strong>. Our app will simply list some silly dad jokes. We are going to add authentication to it, all logged-in users will have the privilege to like and view jokes.</p>
<p>This will allow us illustrate how <strong>Gin</strong> can be used to develop web applications, and/or APIs.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38371873-6ccabb50-38e5-11e8-9b67-b97cc2ce98c6.png" alt="golang-gin-demo-shot"></p>
<p>We’ll be making use of the following functionalities offered by Gin:</p>
<ul>
<li>Middleware</li>
<li>Routing</li>
<li>Routes Grouping</li>
</ul>
<h3 id="ready-set-go">Ready, Set, Go</h3>
<p>We will write our entire Go application in a <code>main.go</code> file. Since its a small application, its going to be easy to build the application with just <code>go run</code> from the terminal.</p>
<p>We’ll create a new directory <code>golang-gin</code> in our Go workspace, and then a <code>main.go</code> file in it:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell">$ mkdir -p $GOPATH/src/github.com/user/golang-gin
$ cd $GOPATH/src/github.com/user/golang-gin
$ touch main.go
</code></pre></div><p>The content of the <code>main.go</code> file:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#00f">package</span> main
<span style="color:#00f">import</span> (
<span style="color:#a31515">"net/http"</span>
<span style="color:#a31515">"github.com/gin-gonic/contrib/static"</span>
<span style="color:#a31515">"github.com/gin-gonic/gin"</span>
)
<span style="color:#00f">func</span> main() {
<span style="color:#008000">// Set the router as the default one shipped with Gin
</span><span style="color:#008000"></span> router := gin.Default()
<span style="color:#008000">// Serve frontend static files
</span><span style="color:#008000"></span> router.Use(static.Serve(<span style="color:#a31515">"/"</span>, static.LocalFile(<span style="color:#a31515">"./views"</span>, <span style="color:#00f">true</span>)))
<span style="color:#008000">// Setup route group for the API
</span><span style="color:#008000"></span> api := router.Group(<span style="color:#a31515">"/api"</span>)
{
api.GET(<span style="color:#a31515">"/"</span>, <span style="color:#00f">func</span>(c *gin.Context) {
c.JSON(http.StatusOK, gin.H {
<span style="color:#a31515">"message"</span>: <span style="color:#a31515">"pong"</span>,
})
})
}
<span style="color:#008000">// Start and run the server
</span><span style="color:#008000"></span> router.Run(<span style="color:#a31515">":3000"</span>)
}
</code></pre></div><p>We’ll need to create some more directories for our static files. In the same directory as the <code>main.go</code> file, let’s create a <code>views</code> folder. In the <code>views</code> folder, create a <code>js</code> folder and an <code>index.html</code> file in it.</p>
<p>The <code>index.html</code> file will be very simple for now:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-html" data-lang="html"><span style="color:#00f"><!DOCTYPE html></span>
<html>
<head>
<title>Jokeish App</title>
</head>
<body>
<h1>Welcome to the Jokeish App</h1>
</body>
</html>
</code></pre></div><p>Before we test what we have to far, let’s install the added dependencies:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell">$ go get -u github.com/gin-gonic/gin
$ go get -u github.com/gin-gonic/contrib/static
</code></pre></div><p>To see what’s working, we’ll need to start our server by running <code>go run main.go</code>.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38358547-700bc822-38bd-11e8-88a6-246559fbe57f.png" alt="go-gin-gorun-1"></p>
<p>Once the application is running, navigate to <code>http://localhost:3000</code> in your browser. If all went well, you should see level 1 header text <strong>Welcome to the Jokeish App</strong> displayed.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38385072-cdaa2168-3908-11e8-9889-e9c1e713ce0a.png" alt="golang-welcome-de"></p>
<h3 id="defining-the-api">Defining The API</h3>
<p>Let’s add some more code in our <code>main.go</code> file, for our API definitions. We’ll update our <code>main</code> function with two routes <code>/jokes/</code> and <code>/jokes/like/:jokeID</code>, to the route group <code>/api/</code>.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#00f">func</span> main() {
<span style="color:#008000">// ... leave the code above untouched...
</span><span style="color:#008000"></span>
<span style="color:#008000">// Our API will consit of just two routes
</span><span style="color:#008000"></span> <span style="color:#008000">// /jokes - which will retrieve a list of jokes a user can see
</span><span style="color:#008000"></span> <span style="color:#008000">// /jokes/like/:jokeID - which will capture likes sent to a particular joke
</span><span style="color:#008000"></span> api.GET(<span style="color:#a31515">"/jokes"</span>, JokeHandler)
api.POST(<span style="color:#a31515">"/jokes/like/:jokeID"</span>, LikeJoke)
}
<span style="color:#008000">// JokeHandler retrieves a list of available jokes
</span><span style="color:#008000"></span><span style="color:#00f">func</span> JokeHandler(c *gin.Context) {
c.Header(<span style="color:#a31515">"Content-Type"</span>, <span style="color:#a31515">"application/json"</span>)
c.JSON(http.StatusOK, gin.H {
<span style="color:#a31515">"message"</span>:<span style="color:#a31515">"Jokes handler not implemented yet"</span>,
})
}
<span style="color:#008000">// LikeJoke increments the likes of a particular joke Item
</span><span style="color:#008000"></span><span style="color:#00f">func</span> LikeJoke(c *gin.Context) {
c.Header(<span style="color:#a31515">"Content-Type"</span>, <span style="color:#a31515">"application/json"</span>)
c.JSON(http.StatusOK, gin.H {
<span style="color:#a31515">"message"</span>:<span style="color:#a31515">"LikeJoke handler not implemented yet"</span>,
})
}
</code></pre></div><p>The content of the <code>main.go</code> file, should look like this:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#00f">package</span> main
<span style="color:#00f">import</span> (
<span style="color:#a31515">"net/http"</span>
<span style="color:#a31515">"github.com/gin-gonic/contrib/static"</span>
<span style="color:#a31515">"github.com/gin-gonic/gin"</span>
)
<span style="color:#00f">func</span> main() {
<span style="color:#008000">// Set the router as the default one shipped with Gin
</span><span style="color:#008000"></span> router := gin.Default()
<span style="color:#008000">// Serve frontend static files
</span><span style="color:#008000"></span> router.Use(static.Serve(<span style="color:#a31515">"/"</span>, static.LocalFile(<span style="color:#a31515">"./views"</span>, <span style="color:#00f">true</span>)))
<span style="color:#008000">// Setup route group for the API
</span><span style="color:#008000"></span> api := router.Group(<span style="color:#a31515">"/api"</span>)
{
api.GET(<span style="color:#a31515">"/"</span>, <span style="color:#00f">func</span>(c *gin.Context) {
c.JSON(http.StatusOK, gin.H {
<span style="color:#a31515">"message"</span>: <span style="color:#a31515">"pong"</span>,
})
})
}
<span style="color:#008000">// Our API will consit of just two routes
</span><span style="color:#008000"></span> <span style="color:#008000">// /jokes - which will retrieve a list of jokes a user can see
</span><span style="color:#008000"></span> <span style="color:#008000">// /jokes/like/:jokeID - which will capture likes sent to a particular joke
</span><span style="color:#008000"></span> api.GET(<span style="color:#a31515">"/jokes"</span>, JokeHandler)
api.POST(<span style="color:#a31515">"/jokes/like/:jokeID"</span>, LikeJoke)
<span style="color:#008000">// Start and run the server
</span><span style="color:#008000"></span> router.Run(<span style="color:#a31515">":3000"</span>)
}
<span style="color:#008000">// JokeHandler retrieves a list of available jokes
</span><span style="color:#008000"></span><span style="color:#00f">func</span> JokeHandler(c *gin.Context) {
c.Header(<span style="color:#a31515">"Content-Type"</span>, <span style="color:#a31515">"application/json"</span>)
c.JSON(http.StatusOK, gin.H {
<span style="color:#a31515">"message"</span>:<span style="color:#a31515">"Jokes handler not implemented yet"</span>,
})
}
<span style="color:#008000">// LikeJoke increments the likes of a particular joke Item
</span><span style="color:#008000"></span><span style="color:#00f">func</span> LikeJoke(c *gin.Context) {
c.Header(<span style="color:#a31515">"Content-Type"</span>, <span style="color:#a31515">"application/json"</span>)
c.JSON(http.StatusOK, gin.H {
<span style="color:#a31515">"message"</span>:<span style="color:#a31515">"LikeJoke handler not implemented yet"</span>,
})
}
</code></pre></div><p>Let’s run our app again <code>go run main.go</code>, and access our routes; <code>http://localhost:3000/api/jokes</code> will return a <code>200 OK</code> header response, with message <code>jokes handler not implemented yet</code>, and a POST request to <code>http://localhost:3000/api/jokes/like/1</code> returns a <code>200 OK</code> header, and message <code>Likejoke handler not implemented yet</code>.</p>
<h3 id="jokes-data">Jokes Data</h3>
<p>Since we already have our routes definition set, which does only one thing, which is to return a json response, we’ll spice our codebase a bit by adding some more code to it.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#008000">// ... leave the code above untouched...
</span><span style="color:#008000"></span>
<span style="color:#008000">// Let's create our Jokes struct. This will contain information about a Joke
</span><span style="color:#008000"></span>
<span style="color:#008000">// Joke contains information about a single Joke
</span><span style="color:#008000"></span><span style="color:#00f">type</span> Joke <span style="color:#00f">struct</span> {
ID <span style="color:#2b91af">int</span> <span style="color:#a31515">`json:"id" binding:"required"`</span>
Likes <span style="color:#2b91af">int</span> <span style="color:#a31515">`json:"likes"`</span>
Joke <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"joke" binding:"required"`</span>
}
<span style="color:#008000">// We'll create a list of jokes
</span><span style="color:#008000"></span><span style="color:#00f">var</span> jokes = []Joke{
Joke{1, 0, <span style="color:#a31515">"Did you hear about the restaurant on the moon? Great food, no atmosphere."</span>},
Joke{2, 0, <span style="color:#a31515">"What do you call a fake noodle? An Impasta."</span>},
Joke{3, 0, <span style="color:#a31515">"How many apples grow on a tree? All of them."</span>},
Joke{4, 0, <span style="color:#a31515">"Want to hear a joke about paper? Nevermind it's tearable."</span>},
Joke{5, 0, <span style="color:#a31515">"I just watched a program about beavers. It was the best dam program I've ever seen."</span>},
Joke{6, 0, <span style="color:#a31515">"Why did the coffee file a police report? It got mugged."</span>},
Joke{7, 0, <span style="color:#a31515">"How does a penguin build it's house? Igloos it together."</span>},
}
<span style="color:#00f">func</span> main() {
<span style="color:#008000">// ... leave this block untouched...
</span><span style="color:#008000"></span>}
<span style="color:#008000">// JokeHandler retrieves a list of available jokes
</span><span style="color:#008000"></span><span style="color:#00f">func</span> JokeHandler(c *gin.Context) {
c.Header(<span style="color:#a31515">"Content-Type"</span>, <span style="color:#a31515">"application/json"</span>)
c.JSON(http.StatusOK, jokes)
}
<span style="color:#008000">// LikeJoke increments the likes of a particular joke Item
</span><span style="color:#008000"></span><span style="color:#00f">func</span> LikeJoke(c *gin.Context) {
<span style="color:#008000">// confirm Joke ID sent is valid
</span><span style="color:#008000"></span> <span style="color:#008000">// remember to import the `strconv` package
</span><span style="color:#008000"></span> <span style="color:#00f">if</span> jokeid, err := strconv.Atoi(c.Param(<span style="color:#a31515">"jokeID"</span>)); err == <span style="color:#00f">nil</span> {
<span style="color:#008000">// find joke, and increment likes
</span><span style="color:#008000"></span> <span style="color:#00f">for</span> i := 0; i < len(jokes); i++ {
<span style="color:#00f">if</span> jokes[i].ID == jokeid {
jokes[i].Likes += 1
}
}
<span style="color:#008000">// return a pointer to the updated jokes list
</span><span style="color:#008000"></span> c.JSON(http.StatusOK, &jokes)
} <span style="color:#00f">else</span> {
<span style="color:#008000">// Joke ID is invalid
</span><span style="color:#008000"></span> c.AbortWithStatus(http.StatusNotFound)
}
}
<span style="color:#008000">// NB: Replace the JokeHandler and LikeJoke functions in the previous version to the ones above
</span></code></pre></div><p>With our code looking good, lets go ahead and test our API. We can test with <code>cURL</code> or <code>postman</code> , and sending a <code>GET</code> request to <code>http://localhost:3000/jokes</code> to get the full list of jokes, and a <code>POST</code> request to <code>http://localhost:3000/jokes/like/{jokeid}</code> to increment the likes of a joke.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell">$ curl http://localhost:3000/api/jokes
$ curl -X POST http://localhost:3000/api/jokes/like/4
</code></pre></div><h3 id="building-the-ui-react">Building the UI (React)</h3>
<p>We have our API in place, so let’s build a frontend to present the data from our API. For this, we’ll be using React. We won’t go too deep into React as it will be out of scope for this tutorial. If you need to learn more about React, checkout the official <a href="https://facebook.github.io/react/docs/tutorial.html">tutorial</a>. You can implement the UI with any frontend framework you’re comfortable with.</p>
<h3 id="setup">Setup</h3>
<p>We’ll edit the <code>index.html</code> file to add external libraries needed to run React, we’ll then need to create an<code>app.jsx</code> file in the <code>views/js</code> directory, which will contain our React code.</p>
<p>Our <code>index.html</code> file should look like this:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-html" data-lang="html"><span style="color:#00f"><!DOCTYPE html></span>
<html>
<head>
<meta charset=<span style="color:#a31515">"UTF-8"</span> />
<meta name=<span style="color:#a31515">"viewport"</span> content=<span style="color:#a31515">"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"</span> />
<title>Jokeish App</title>
<script src=<span style="color:#a31515">"http://code.jquery.com/jquery-2.1.4.min.js"</span>></script>
<script src=<span style="color:#a31515">"https://cdn.auth0.com/js/auth0/9.0/auth0.min.js"</span>></script>
<script type=<span style="color:#a31515">"application/javascript"</span> src=<span style="color:#a31515">"https://unpkg.com/react@16.0.0/umd/react.production.min.js"</span>></script>
<script type=<span style="color:#a31515">"application/javascript"</span> src=<span style="color:#a31515">"https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js"</span>></script>
<script type=<span style="color:#a31515">"application/javascript"</span> src=<span style="color:#a31515">"https://unpkg.com/babel-standalone@6.26.0/babel.js"</span>></script>
<script type=<span style="color:#a31515">"text/babel"</span> src=<span style="color:#a31515">"js/app.jsx"</span>></script>
<link href=<span style="color:#a31515">"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"</span> rel=<span style="color:#a31515">"stylesheet"</span>>
</head>
<body>
<div id=<span style="color:#a31515">"app"</span>></div>
</body>
</html>
</code></pre></div><h3 id="building-our-components">Building our Components</h3>
<p>In React views are broken down into components. We’ll need to build some components. An <code>App</code> component as the main entry, that launches the application, a <code>Home</code> component which will face non logged-in users, a <code>LoggedIn</code> component with content only visible by authenticated users, and a <code>Joke</code> component to display a list of jokes. We’ll write all these components in the <code>app.jsx</code> file.</p>
<h3 id="the-app-component">The App component</h3>
<p>This component bootstraps our entire React app. It decides on which component to show when a user is authenticated or not. We’ll start off with just its base, and later update it with more functionality.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#00f">class</span> App <span style="color:#00f">extends</span> React.Component {
render() {
<span style="color:#00f">if</span> (<span style="color:#00f">this</span>.loggedIn) {
<span style="color:#00f">return</span> (<LoggedIn />);
} <span style="color:#00f">else</span> {
<span style="color:#00f">return</span> (<Home />);
}
}
}
</code></pre></div><h3 id="the-home-component">The Home component</h3>
<p>This component is shown to non logged-in users. And a button which opens a Hosted lock screen (we’ll add this functionality later), where they can signup, or login.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-jsx" data-lang="jsx"><span style="color:#00f">class</span> Home <span style="color:#00f">extends</span> React.Component {
render() {
<span style="color:#00f">return</span> (
<div className=<span style="color:#a31515">"container"</span>>
<div className=<span style="color:#a31515">"col-xs-8 col-xs-offset-2 jumbotron text-center"</span>>
<h1>Jokeish</h1>
<p>A load <span style="color:#00f">of</span> Dad jokes XD</p>
<p>Sign <span style="color:#00f">in</span> to get access </p>
<a onClick={<span style="color:#00f">this</span>.authenticate} className=<span style="color:#a31515">"btn btn-primary btn-lg btn-login btn-block"</span>>Sign In</a>
</div>
</div>
)
}
}
</code></pre></div><h3 id="loggedin-component">LoggedIn component</h3>
<p>This component is displayed when a user is authenticated. It stores in its <code>state</code> an array of jokes which is populated when the component mounts.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-jsx" data-lang="jsx"><span style="color:#00f">class</span> LoggedIn <span style="color:#00f">extends</span> React.Component {
constructor(props) {
<span style="color:#00f">super</span>(props);
<span style="color:#00f">this</span>.state = {
jokes: []
}
}
render() {
<span style="color:#00f">return</span> (
<div className=<span style="color:#a31515">"container"</span>>
<div className=<span style="color:#a31515">"col-lg-12"</span>>
<br />
<span className=<span style="color:#a31515">"pull-right"</span>><a onClick={<span style="color:#00f">this</span>.logout}>Log out</a></span>
<h2>Jokeish</h2>
<p>Let<span style="">'</span>s feed you <span style="color:#00f">with</span> some funny Jokes!!!</p>
<div className=<span style="color:#a31515">"row"</span>>
{<span style="color:#00f">this</span>.state.jokes.map(<span style="color:#00f">function</span>(joke, i){
<span style="color:#00f">return</span> (<Joke key={i} joke={joke} />);
})}
</div>
</div>
</div>
)
}
}
</code></pre></div><h3 id="the-joke-component">The Joke component</h3>
<p>The <code>Joke</code> component will contain information about each item from the jokes response to be displayed.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-jsx" data-lang="jsx"><span style="color:#00f">class</span> Joke <span style="color:#00f">extends</span> React.Component {
constructor(props) {
<span style="color:#00f">super</span>(props);
<span style="color:#00f">this</span>.state = {
liked: <span style="color:#a31515">""</span>
}
<span style="color:#00f">this</span>.like = <span style="color:#00f">this</span>.like.bind(<span style="color:#00f">this</span>);
}
like() {
<span style="color:#008000">// ... we'll add this block later
</span><span style="color:#008000"></span> }
render() {
<span style="color:#00f">return</span> (
<div className=<span style="color:#a31515">"col-xs-4"</span>>
<div className=<span style="color:#a31515">"panel panel-default"</span>>
<div className=<span style="color:#a31515">"panel-heading"</span>><span style="">#</span>{<span style="color:#00f">this</span>.props.joke.id} <span className=<span style="color:#a31515">"pull-right"</span>>{<span style="color:#00f">this</span>.state.liked}</span></div>
<div className=<span style="color:#a31515">"panel-body"</span>>
{<span style="color:#00f">this</span>.props.joke.joke}
</div>
<div className=<span style="color:#a31515">"panel-footer"</span>>
{<span style="color:#00f">this</span>.props.joke.likes} Likes &nbsp;
<a onClick={<span style="color:#00f">this</span>.like} className=<span style="color:#a31515">"btn btn-default"</span>>
<span className=<span style="color:#a31515">"glyphicon glyphicon-thumbs-up"</span>></span>
</a>
</div>
</div>
</div>
)
}
}
</code></pre></div><p>We’ve written our components, now let’s tell React where to render the app. We’ll add the block of code below to the bottom of our <code>app.jsx</code> file.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript">ReactDOM.render(<App />, document.getElementById(<span style="color:#a31515">'app'</span>));
</code></pre></div><p>Let’s restart our Go server <code>go run main.go</code>, and head over to our app’s URL <code>http://localhost:3000/</code>. You’d see the <code>Home</code> component is being rendered.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38368612-a452879a-38dd-11e8-8a63-5cc7530fc9bd.png" alt="golang-gin-home-component"></p>
<h2 id="securing-our-jokes-app-with-auth0">Securing our Jokes App With Auth0</h2>
<blockquote>
<p>Disclaimer: This isn’t a sponsored content.</p>
</blockquote>
<p><strong>Auth0</strong> issues <a href="https://jwt.io/">JSON Web Tokens</a> on every login for your users. This means that you can have a solid <a href="https://auth0.com/docs/identityproviders">identity infrastructure</a>, including <a href="https://auth0.com/docs/sso/single-sign-on">single sign-on</a>, user management, support for social identity providers (Facebook, Github, Twitter, etc.), enterprise identity providers (Active Directory, LDAP, SAML, etc.) and your own database of users with just a few lines of code.</p>
<p>We can easily set up authentication in our GIN app by using Auth0. You’ll need an ccount to follow along with this part. If you don’t already have an Auth0 account, <a href="https://auth0.com/signup">sign up</a> for one now.</p>
<h3 id="creating-the-api-client">Creating the API client</h3>
<p>Our tokens will be generated with Auth0, so we need to create an API and a Client from our Auth0 dashboard. If you haven’t already, <a href="https://auth0.com/signup">sign up</a> for an Auth0 account.</p>
<p>To create a new API, navigate to the <a href="https://manage.auth0.com/#/apis">APIs section</a> in your dashboard, and click the <strong>Create API</strong> button.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38367092-a7bbfffa-38d9-11e8-949e-04542283606c.png" alt="golang-gin-apis-section"></p>
<p>Choose an API <strong>name</strong>, and an <strong>identifier</strong>. The identifier will be the <strong>audience</strong> for the middleware. The <strong>Signing Algorithm</strong> should be <strong>RS256</strong>.</p>
<p>To create a new Client, navigate to the <a href="">clients section</a> in your dashboard, and click the <strong>Create Client</strong> button, and select type <code>Regular Web Applications</code>.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38453889-025202bc-3a55-11e8-9ff6-1d5265ebecd9.png" alt="golang-gin-create-client"></p>
<p>Once the client is created, take note of the <code>client_id</code> and <code>client_secret</code>, as we’ll need it later.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38453892-09268fea-3a55-11e8-9c3d-68de4b26295d.png" alt="golang-gin-client-page"></p>
<p>We need to add the credentials needed for our API to an environment vairable. In the root directory, create a new file <code>.env</code> and add the following to it, with the details from the Auth0 dashboard:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-fallback" data-lang="fallback">export AUTH0_API_CLIENT_SECRET=""
export AUTH0_CLIENT_ID=""
export AUTH0_DOMAIN="yourdomain.auth0.com"
export AUTH0_API_AUDIENCE=""
</code></pre></div><h3 id="securing-our-api-endpoints">Securing our API Endpoints</h3>
<p>Currently, our API is open to the world, so we need to secure them, so only authorized users can access them.</p>
<p>We are going to make use of a <strong>JWT Middleware</strong> to check for a valid <em>JSON Web Token</em> from each requests hitting our Endpoints.</p>
<p>Let’s create our middleware:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go">
<span style="color:#008000">// ...
</span><span style="color:#008000"></span>
<span style="color:#00f">var</span> jwtMiddleWare *jwtmiddleware.JWTMiddleware
<span style="color:#00f">func</span> main() {
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: <span style="color:#00f">func</span>(token *jwt.Token) (<span style="color:#00f">interface</span>{}, <span style="color:#2b91af">error</span>) {
aud := os.Getenv(<span style="color:#a31515">"AUTH0_API_AUDIENCE"</span>)
checkAudience := token.Claims.(jwt.MapClaims).VerifyAudience(aud, <span style="color:#00f">false</span>)
<span style="color:#00f">if</span> !checkAudience {
<span style="color:#00f">return</span> token, errors.New(<span style="color:#a31515">"Invalid audience."</span>)
}
<span style="color:#008000">// verify iss claim
</span><span style="color:#008000"></span> iss := os.Getenv(<span style="color:#a31515">"AUTH0_DOMAIN"</span>)
checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, <span style="color:#00f">false</span>)
<span style="color:#00f">if</span> !checkIss {
<span style="color:#00f">return</span> token, errors.New(<span style="color:#a31515">"Invalid issuer."</span>)
}
cert, err := getPemCert(token)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
log.Fatalf(<span style="color:#a31515">"could not get cert: %+v"</span>, err)
}
result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
<span style="color:#00f">return</span> result, <span style="color:#00f">nil</span>
},
SigningMethod: jwt.SigningMethodRS256,
})
<span style="color:#008000">// register our actual jwtMiddleware
</span><span style="color:#008000"></span> jwtMiddleWare = jwtMiddleware
<span style="color:#008000">// ... the rest of the code below this function doesn't change yet
</span><span style="color:#008000"></span>}
<span style="color:#008000">// authMiddleware intercepts the requests, and check for a valid jwt token
</span><span style="color:#008000"></span><span style="color:#00f">func</span> authMiddleware() gin.HandlerFunc {
<span style="color:#00f">return</span> <span style="color:#00f">func</span>(c *gin.Context) {
<span style="color:#008000">// Get the client secret key
</span><span style="color:#008000"></span> err := jwtMiddleWare.CheckJWT(c.Writer, c.Request)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
<span style="color:#008000">// Token not found
</span><span style="color:#008000"></span> fmt.Println(err)
c.Abort()
c.Writer.WriteHeader(http.StatusUnauthorized)
c.Writer.Write([]byte(<span style="color:#a31515">"Unauthorized"</span>))
<span style="color:#00f">return</span>
}
}
}
</code></pre></div><p>The above code, we have a new <code>jwtMiddleWare</code> variable which is initialized in the <code>main</code> function, and is used in the <code>authMiddleware</code> middle function. If you notice, we are pulling our server-side credentials from an environment variable (one of the tenets of a <strong>12-factor app</strong>). Our middleware checks and receives a token from a request, it calls the <code>jwtMiddleWare.CheckJWT</code> method to validate the token sent.</p>
<p>Let’s also write the function to return the JSON Web Keys:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#008000">// ... the code above is untouched...
</span><span style="color:#008000"></span>
<span style="color:#008000">// Jwks stores a slice of JSON Web Keys
</span><span style="color:#008000"></span><span style="color:#00f">type</span> Jwks <span style="color:#00f">struct</span> {
Keys []JSONWebKeys <span style="color:#a31515">`json:"keys"`</span>
}
<span style="color:#00f">type</span> JSONWebKeys <span style="color:#00f">struct</span> {
Kty <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"kty"`</span>
Kid <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"kid"`</span>
Use <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"use"`</span>
N <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"n"`</span>
E <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"e"`</span>
X5c []<span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"x5c"`</span>
}
<span style="color:#00f">func</span> main() {
<span style="color:#008000">// ... the code in this method is untouched...
</span><span style="color:#008000"></span>}
<span style="color:#00f">func</span> getPemCert(token *jwt.Token) (<span style="color:#2b91af">string</span>, <span style="color:#2b91af">error</span>) {
cert := <span style="color:#a31515">""</span>
resp, err := http.Get(os.Getenv(<span style="color:#a31515">"AUTH0_DOMAIN"</span>) + <span style="color:#a31515">".well-known/jwks.json"</span>)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
<span style="color:#00f">return</span> cert, err
}
<span style="color:#00f">defer</span> resp.Body.Close()
<span style="color:#00f">var</span> jwks = Jwks{}
err = json.NewDecoder(resp.Body).Decode(&jwks)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
<span style="color:#00f">return</span> cert, err
}
x5c := jwks.Keys[0].X5c
<span style="color:#00f">for</span> k, v := <span style="color:#00f">range</span> x5c {
<span style="color:#00f">if</span> token.Header[<span style="color:#a31515">"kid"</span>] == jwks.Keys[k].Kid {
cert = <span style="color:#a31515">"-----BEGIN CERTIFICATE-----\n"</span> + v + <span style="color:#a31515">"\n-----END CERTIFICATE-----"</span>
}
}
<span style="color:#00f">if</span> cert == <span style="color:#a31515">""</span> {
<span style="color:#00f">return</span> cert, errors.New(<span style="color:#a31515">"unable to find appropriate key."</span>)
}
<span style="color:#00f">return</span> cert, <span style="color:#00f">nil</span>
}
</code></pre></div><h3 id="using-the-jwt-middleware">Using the JWT Middleware</h3>
<p>Using the middleware is very straight forward. We just pass it as a parameter to our routes definition.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go">...
api.GET(<span style="color:#a31515">"/jokes"</span>, authMiddleware(), JokeHandler)
api.POST(<span style="color:#a31515">"/jokes/like/:jokeID"</span>, authMiddleware(), LikeJoke)
...
</code></pre></div><p>Our <code>main.go</code> file should look like this:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#00f">package</span> main
<span style="color:#00f">import</span> (
<span style="color:#a31515">"encoding/json"</span>
<span style="color:#a31515">"errors"</span>
<span style="color:#a31515">"fmt"</span>
<span style="color:#a31515">"log"</span>
<span style="color:#a31515">"net/http"</span>
<span style="color:#a31515">"os"</span>
<span style="color:#a31515">"strconv"</span>
jwtmiddleware <span style="color:#a31515">"github.com/auth0/go-jwt-middleware"</span>
jwt <span style="color:#a31515">"github.com/dgrijalva/jwt-go"</span>
<span style="color:#a31515">"github.com/gin-gonic/contrib/static"</span>
<span style="color:#a31515">"github.com/gin-gonic/gin"</span>
)
<span style="color:#00f">type</span> Response <span style="color:#00f">struct</span> {
Message <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"message"`</span>
}
<span style="color:#00f">type</span> Jwks <span style="color:#00f">struct</span> {
Keys []JSONWebKeys <span style="color:#a31515">`json:"keys"`</span>
}
<span style="color:#00f">type</span> JSONWebKeys <span style="color:#00f">struct</span> {
Kty <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"kty"`</span>
Kid <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"kid"`</span>
Use <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"use"`</span>
N <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"n"`</span>
E <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"e"`</span>
X5c []<span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"x5c"`</span>
}
<span style="color:#00f">type</span> Joke <span style="color:#00f">struct</span> {
ID <span style="color:#2b91af">int</span> <span style="color:#a31515">`json:"id" binding:"required"`</span>
Likes <span style="color:#2b91af">int</span> <span style="color:#a31515">`json:"likes"`</span>
Joke <span style="color:#2b91af">string</span> <span style="color:#a31515">`json:"joke" binding:"required"`</span>
}
<span style="color:#008000">/** we'll create a list of jokes */</span>
<span style="color:#00f">var</span> jokes = []Joke{
Joke{1, 0, <span style="color:#a31515">"Did you hear about the restaurant on the moon? Great food, no atmosphere."</span>},
Joke{2, 0, <span style="color:#a31515">"What do you call a fake noodle? An Impasta."</span>},
Joke{3, 0, <span style="color:#a31515">"How many apples grow on a tree? All of them."</span>},
Joke{4, 0, <span style="color:#a31515">"Want to hear a joke about paper? Nevermind it's tearable."</span>},
Joke{5, 0, <span style="color:#a31515">"I just watched a program about beavers. It was the best dam program I've ever seen."</span>},
Joke{6, 0, <span style="color:#a31515">"Why did the coffee file a police report? It got mugged."</span>},
Joke{7, 0, <span style="color:#a31515">"How does a penguin build it's house? Igloos it together."</span>},
}
<span style="color:#00f">var</span> jwtMiddleWare *jwtmiddleware.JWTMiddleware
<span style="color:#00f">func</span> main() {
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: <span style="color:#00f">func</span>(token *jwt.Token) (<span style="color:#00f">interface</span>{}, <span style="color:#2b91af">error</span>) {
aud := os.Getenv(<span style="color:#a31515">"AUTH0_API_AUDIENCE"</span>)
checkAudience := token.Claims.(jwt.MapClaims).VerifyAudience(aud, <span style="color:#00f">false</span>)
<span style="color:#00f">if</span> !checkAudience {
<span style="color:#00f">return</span> token, errors.New(<span style="color:#a31515">"Invalid audience."</span>)
}
<span style="color:#008000">// verify iss claim
</span><span style="color:#008000"></span> iss := os.Getenv(<span style="color:#a31515">"AUTH0_DOMAIN"</span>)
checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, <span style="color:#00f">false</span>)
<span style="color:#00f">if</span> !checkIss {
<span style="color:#00f">return</span> token, errors.New(<span style="color:#a31515">"Invalid issuer."</span>)
}
cert, err := getPemCert(token)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
log.Fatalf(<span style="color:#a31515">"could not get cert: %+v"</span>, err)
}
result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
<span style="color:#00f">return</span> result, <span style="color:#00f">nil</span>
},
SigningMethod: jwt.SigningMethodRS256,
})
jwtMiddleWare = jwtMiddleware
<span style="color:#008000">// Set the router as the default one shipped with Gin
</span><span style="color:#008000"></span> router := gin.Default()
<span style="color:#008000">// Serve the frontend
</span><span style="color:#008000"></span> router.Use(static.Serve(<span style="color:#a31515">"/"</span>, static.LocalFile(<span style="color:#a31515">"./views"</span>, <span style="color:#00f">true</span>)))
api := router.Group(<span style="color:#a31515">"/api"</span>)
{
api.GET(<span style="color:#a31515">"/"</span>, <span style="color:#00f">func</span>(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
<span style="color:#a31515">"message"</span>: <span style="color:#a31515">"pong"</span>,
})
})
api.GET(<span style="color:#a31515">"/jokes"</span>, authMiddleware(), JokeHandler)
api.POST(<span style="color:#a31515">"/jokes/like/:jokeID"</span>, authMiddleware(), LikeJoke)
}
<span style="color:#008000">// Start the app
</span><span style="color:#008000"></span> router.Run(<span style="color:#a31515">":3000"</span>)
}
<span style="color:#00f">func</span> getPemCert(token *jwt.Token) (<span style="color:#2b91af">string</span>, <span style="color:#2b91af">error</span>) {
cert := <span style="color:#a31515">""</span>
resp, err := http.Get(os.Getenv(<span style="color:#a31515">"AUTH0_DOMAIN"</span>) + <span style="color:#a31515">".well-known/jwks.json"</span>)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
<span style="color:#00f">return</span> cert, err
}
<span style="color:#00f">defer</span> resp.Body.Close()
<span style="color:#00f">var</span> jwks = Jwks{}
err = json.NewDecoder(resp.Body).Decode(&jwks)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
<span style="color:#00f">return</span> cert, err
}
x5c := jwks.Keys[0].X5c
<span style="color:#00f">for</span> k, v := <span style="color:#00f">range</span> x5c {
<span style="color:#00f">if</span> token.Header[<span style="color:#a31515">"kid"</span>] == jwks.Keys[k].Kid {
cert = <span style="color:#a31515">"-----BEGIN CERTIFICATE-----\n"</span> + v + <span style="color:#a31515">"\n-----END CERTIFICATE-----"</span>
}
}
<span style="color:#00f">if</span> cert == <span style="color:#a31515">""</span> {
<span style="color:#00f">return</span> cert, errors.New(<span style="color:#a31515">"unable to find appropriate key"</span>)
}
<span style="color:#00f">return</span> cert, <span style="color:#00f">nil</span>
}
<span style="color:#008000">// authMiddleware intercepts the requests, and check for a valid jwt token
</span><span style="color:#008000"></span><span style="color:#00f">func</span> authMiddleware() gin.HandlerFunc {
<span style="color:#00f">return</span> <span style="color:#00f">func</span>(c *gin.Context) {
<span style="color:#008000">// Get the client secret key
</span><span style="color:#008000"></span> err := jwtMiddleWare.CheckJWT(c.Writer, c.Request)
<span style="color:#00f">if</span> err != <span style="color:#00f">nil</span> {
<span style="color:#008000">// Token not found
</span><span style="color:#008000"></span> fmt.Println(err)
c.Abort()
c.Writer.WriteHeader(http.StatusUnauthorized)
c.Writer.Write([]byte(<span style="color:#a31515">"Unauthorized"</span>))
<span style="color:#00f">return</span>
}
}
}
<span style="color:#008000">// JokeHandler returns a list of jokes available (in memory)
</span><span style="color:#008000"></span><span style="color:#00f">func</span> JokeHandler(c *gin.Context) {
c.Header(<span style="color:#a31515">"Content-Type"</span>, <span style="color:#a31515">"application/json"</span>)
c.JSON(http.StatusOK, jokes)
}
<span style="color:#00f">func</span> LikeJoke(c *gin.Context) {
<span style="color:#008000">// Check joke ID is valid
</span><span style="color:#008000"></span> <span style="color:#00f">if</span> jokeid, err := strconv.Atoi(c.Param(<span style="color:#a31515">"jokeID"</span>)); err == <span style="color:#00f">nil</span> {
<span style="color:#008000">// find joke and increment likes
</span><span style="color:#008000"></span> <span style="color:#00f">for</span> i := 0; i < len(jokes); i++ {
<span style="color:#00f">if</span> jokes[i].ID == jokeid {
jokes[i].Likes = jokes[i].Likes + 1
}
}
c.JSON(http.StatusOK, &jokes)
} <span style="color:#00f">else</span> {
<span style="color:#008000">// the jokes ID is invalid
</span><span style="color:#008000"></span> c.AbortWithStatus(http.StatusNotFound)
}
}
</code></pre></div><p>Let’s install the <code>jwtmiddleware</code> libraries:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell">$ go get -u github.com/auth0/go-jwt-middleware
$ go get -u github.com/dgrijalva/jwt-go
</code></pre></div><p>Let’s source our environment file, and restart our app server:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="">$</span> source .env
<span style="">$</span> <span style="color:#00f">go</span> run main.<span style="color:#00f">go</span>
</code></pre></div><p>Now if we try accessing any of the endpoints, you’d be faced with a <code>401 Unauthorized</code> error. That’s because we need to send along a token with the request.</p>
<h3 id="login-with-auth0-and-react">Login with Auth0 and React</h3>
<p>Let’s implement a login system, so users can login or create accounts, so they have access to our jokes. We’ll add to our <code>app.jsx</code> file, the following Auth0 credentials:</p>
<ul>
<li><code>AUTH0_CLIENT_ID</code></li>
<li><code>AUTH0_DOMAIN</code></li>
<li><code>AUTH0_CALLBACK_URL</code> - The URL of your app</li>
<li><code>AUTH0_API_AUDIENCE</code></li>
</ul>
<blockquote>
<p>You can find the <code>AUTH0_CLIENT_ID</code>, <code>AUTH0_DOMAIN</code>, and <code>AUTH0_API_AUDIENCE</code> data from your Auth0 <a href="https://manage.auth0.com/">management dashboard</a>.</p>
</blockquote>
<p>We need to set a <code>callback</code> which Auth0 redirects to. Navigate to the Clients section in your dashboard, and in the settings, let’s set the callback to <code>http://localhost:3000</code>:</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38453893-0cf84032-3a55-11e8-9b03-d26ba1d3e56a.png" alt="auth0-golang-gin-allowed-callbacks"></p>
<p>With the credentials in place, lets update our React components.</p>
<h4 id="app-component">APP component</h4>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-jsx" data-lang="jsx"><span style="color:#00f">const</span> AUTH0_CLIENT_ID = <span style="color:#a31515">"aIAOt9fkMZKrNsSsFqbKj5KTI0ObTDPP"</span>;
<span style="color:#00f">const</span> AUTH0_DOMAIN = <span style="color:#a31515">"hakaselabs.auth0.com"</span>;
<span style="color:#00f">const</span> AUTH0_CALLBACK_URL = location.href;
<span style="color:#00f">const</span> AUTH0_API_AUDIENCE = <span style="color:#a31515">"golang-gin"</span>;
<span style="color:#00f">class</span> App <span style="color:#00f">extends</span> React.Component {
parseHash() {
<span style="color:#00f">this</span>.auth0 = <span style="color:#00f">new</span> auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
<span style="color:#00f">this</span>.auth0.parseHash(window.location.hash, (err, authResult) => {
<span style="color:#00f">if</span> (err) {
<span style="color:#00f">return</span> console.log(err);
}
<span style="color:#00f">if</span> (
authResult !== <span style="color:#00f">null</span> &&
authResult.accessToken !== <span style="color:#00f">null</span> &&
authResult.idToken !== <span style="color:#00f">null</span>
) {
localStorage.setItem(<span style="color:#a31515">"access_token"</span>, authResult.accessToken);
localStorage.setItem(<span style="color:#a31515">"id_token"</span>, authResult.idToken);
localStorage.setItem(
<span style="color:#a31515">"profile"</span>,
JSON.stringify(authResult.idTokenPayload)
);
window.location = window.location.href.substr(
0,
window.location.href.indexOf(<span style="color:#a31515">"#"</span>)
);
}
});
}
setup() {
$.ajaxSetup({
beforeSend: (r) => {
<span style="color:#00f">if</span> (localStorage.getItem(<span style="color:#a31515">"access_token"</span>)) {
r.setRequestHeader(
<span style="color:#a31515">"Authorization"</span>,
<span style="color:#a31515">"Bearer "</span> + localStorage.getItem(<span style="color:#a31515">"access_token"</span>)
);
}
}
});
}
setState() {
<span style="color:#00f">let</span> idToken = localStorage.getItem(<span style="color:#a31515">"id_token"</span>);
<span style="color:#00f">if</span> (idToken) {
<span style="color:#00f">this</span>.loggedIn = <span style="color:#00f">true</span>;
} <span style="color:#00f">else</span> {
<span style="color:#00f">this</span>.loggedIn = <span style="color:#00f">false</span>;
}
}
componentWillMount() {
<span style="color:#00f">this</span>.setup();
<span style="color:#00f">this</span>.parseHash();
<span style="color:#00f">this</span>.setState();
}
render() {
<span style="color:#00f">if</span> (<span style="color:#00f">this</span>.loggedIn) {
<span style="color:#00f">return</span> <LoggedIn />;
}
<span style="color:#00f">return</span> <Home />;
}
}
</code></pre></div><p>We updated the App component with three component methods (<code>setup</code>, <code>parseHash</code> and <code>setState</code>), and a lifecycle method <code>componentWillMount</code>. The <code>parseHash</code> method, initializes the <code>auth0</code> <code>webAuth</code> client, and parses the hash to a more readable format, saving them to localSt. to show the lock screen, capture and store the user token and add the correct authorization header to any requests to our API</p>
<h4 id="home-component">Home component</h4>
<p>Our Home component will be updated, we’ll add the functionality for the <code>authenticate</code> method, which will trigger the hosted lock screen to display, and allow our users login or signup.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-jsx" data-lang="jsx"><span style="color:#00f">class</span> Home <span style="color:#00f">extends</span> React.Component {
constructor(props) {
<span style="color:#00f">super</span>(props);
<span style="color:#00f">this</span>.authenticate = <span style="color:#00f">this</span>.authenticate.bind(<span style="color:#00f">this</span>);
}
authenticate() {
<span style="color:#00f">this</span>.WebAuth = <span style="color:#00f">new</span> auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID,
scope: <span style="color:#a31515">"openid profile"</span>,
audience: AUTH0_API_AUDIENCE,
responseType: <span style="color:#a31515">"token id_token"</span>,
redirectUri: AUTH0_CALLBACK_URL
});
<span style="color:#00f">this</span>.WebAuth.authorize();
}
render() {
<span style="color:#00f">return</span> (
<div className=<span style="color:#a31515">"container"</span>>
<div className=<span style="color:#a31515">"row"</span>>
<div className=<span style="color:#a31515">"col-xs-8 col-xs-offset-2 jumbotron text-center"</span>>
<h1>Jokeish</h1>
<p>A load <span style="color:#00f">of</span> Dad jokes XD</p>
<p>Sign <span style="color:#00f">in</span> to get access </p>
<a
onClick={<span style="color:#00f">this</span>.authenticate}
className=<span style="color:#a31515">"btn btn-primary btn-lg btn-login btn-block"</span>
>
Sign In
</a>
</div>
</div>
</div>
);
}
}
</code></pre></div><h4 id="loggedin-component-1">LoggedIn Component</h4>
<p>We will update the <code>LoggedIn</code> component to communicate with our API, and pull all jokes, pass each joke as a <code>prop</code> to the <code>Joke</code> component, which renders a bootstrap pannel. Let’s write those:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-jsx" data-lang="jsx"><span style="color:#00f">class</span> LoggedIn <span style="color:#00f">extends</span> React.Component {
constructor(props) {
<span style="color:#00f">super</span>(props);
<span style="color:#00f">this</span>.state = {
jokes: []
};
<span style="color:#00f">this</span>.serverRequest = <span style="color:#00f">this</span>.serverRequest.bind(<span style="color:#00f">this</span>);
<span style="color:#00f">this</span>.logout = <span style="color:#00f">this</span>.logout.bind(<span style="color:#00f">this</span>);
}
logout() {
localStorage.removeItem(<span style="color:#a31515">"id_token"</span>);
localStorage.removeItem(<span style="color:#a31515">"access_token"</span>);
localStorage.removeItem(<span style="color:#a31515">"profile"</span>);
location.reload();
}
serverRequest() {
$.get(<span style="color:#a31515">"http://localhost:3000/api/jokes"</span>, res => {
<span style="color:#00f">this</span>.setState({
jokes: res
});
});
}
componentDidMount() {
<span style="color:#00f">this</span>.serverRequest();
}
render() {
<span style="color:#00f">return</span> (
<div className=<span style="color:#a31515">"container"</span>>
<br />
<span className=<span style="color:#a31515">"pull-right"</span>>
<a onClick={<span style="color:#00f">this</span>.logout}>Log out</a>
</span>
<h2>Jokeish</h2>
<p>Let<span style="">'</span>s feed you <span style="color:#00f">with</span> some funny Jokes!!!</p>
<div className=<span style="color:#a31515">"row"</span>>
<div className=<span style="color:#a31515">"container"</span>>
{<span style="color:#00f">this</span>.state.jokes.map(<span style="color:#00f">function</span>(joke, i) {
<span style="color:#00f">return</span> <Joke key={i} joke={joke} />;
})}
</div>
</div>
</div>
);
}
}
</code></pre></div><h4 id="joke-component">Joke Component</h4>
<p>We’ll also update the <code>Joke</code> component to format each Joke item passed to it from the Parent compoent (<code>LoggedIn</code>), and add a <code>like</code> method, which will increment the likes of a Joke.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-jsx" data-lang="jsx"><span style="color:#00f">class</span> Joke <span style="color:#00f">extends</span> React.Component {
constructor(props) {
<span style="color:#00f">super</span>(props);
<span style="color:#00f">this</span>.state = {
liked: <span style="color:#a31515">""</span>,
jokes: []
};
<span style="color:#00f">this</span>.like = <span style="color:#00f">this</span>.like.bind(<span style="color:#00f">this</span>);
<span style="color:#00f">this</span>.serverRequest = <span style="color:#00f">this</span>.serverRequest.bind(<span style="color:#00f">this</span>);
}
like() {
<span style="color:#00f">let</span> joke = <span style="color:#00f">this</span>.props.joke;
<span style="color:#00f">this</span>.serverRequest(joke);
}
serverRequest(joke) {
$.post(
<span style="color:#a31515">"http://localhost:3000/api/jokes/like/"</span> + joke.id,
{ like: 1 },
res => {
console.log(<span style="color:#a31515">"res... "</span>, res);
<span style="color:#00f">this</span>.setState({ liked: <span style="color:#a31515">"Liked!"</span>, jokes: res });
<span style="color:#00f">this</span>.props.jokes = res;
}
);
}
render() {
<span style="color:#00f">return</span> (
<div className=<span style="color:#a31515">"col-xs-4"</span>>
<div className=<span style="color:#a31515">"panel panel-default"</span>>
<div className=<span style="color:#a31515">"panel-heading"</span>>
<span style="">#</span>{<span style="color:#00f">this</span>.props.joke.id}{<span style="color:#a31515">" "</span>}
<span className=<span style="color:#a31515">"pull-right"</span>>{<span style="color:#00f">this</span>.state.liked}</span>
</div>
<div className=<span style="color:#a31515">"panel-body"</span>>{<span style="color:#00f">this</span>.props.joke.joke}</div>
<div className=<span style="color:#a31515">"panel-footer"</span>>
{<span style="color:#00f">this</span>.props.joke.likes} Likes &nbsp;
<a onClick={<span style="color:#00f">this</span>.like} className=<span style="color:#a31515">"btn btn-default"</span>>
<span className=<span style="color:#a31515">"glyphicon glyphicon-thumbs-up"</span> />
</a>
</div>
</div>
</div>
)
}
}
</code></pre></div><h3 id="putting-it-all-together">Putting it all together</h3>
<p>With the UI and API complete, we can test our app. We’ll start of by booting our server <code>source .env && go run main.go</code>, and the navigate to <code>http://localhost:3000</code> from any browser, you should see the <code>Home</code> component with a signin button. Clicking on the signin button will redirect to a hosted Lock page, create an account or login, to continue using the application.</p>
<p><img src="https://user-images.githubusercontent.com/9336187/38368612-a452879a-38dd-11e8-8a63-5cc7530fc9bd.png" alt="golang-gin-home-component">
<em>Home</em></p>
<p><img src="https://user-images.githubusercontent.com/9336187/38369278-4685f35c-38df-11e8-97ac-98b2b9d07bab.png" alt="golang-gin-login-screen">
<em>Auth0 Hosted Lock Screen</em></p>
<p><img src="https://user-images.githubusercontent.com/9336187/38371873-6ccabb50-38e5-11e8-9b67-b97cc2ce98c6.png" alt="golang-gin-demo-shot">
<em>LoggedIn App view</em></p>
<h3 id="conclusion">Conclusion</h3>
<p>Congrats! You have learned how to build an application and an API with Go and the GIN framework.</p>
<p>This tutorial is designed to help you get started on building and adding authentication to a Golang app with the GIN framework.</p>
<p>Did I miss something important? Let me know of it in the comments.</p>
</div>
<div>
<br>
<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CK7DTK7L&placement=hakaselogsme" id="_carbonads_js"></script>
</div>
<div class="tags">
<ul class="flat">
<li><a href="/tags/go">go</a></li>
<li><a href="/tags/gin-gonic">gin-gonic</a></li>
<li><a href="/tags/react">react</a></li>