-
Notifications
You must be signed in to change notification settings - Fork 11
/
doc.go
1310 lines (957 loc) · 42.5 KB
/
doc.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
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
// Copyright (c) 2017 The Ion Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Ion nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Package ion provides a beautifully expressive and easy to use foundation for your next website, API, or distributed app.
Source code and other details for the project are available at GitHub:
https://github.com/get-ion/ion
Current Version
1.1.0
Installation
The only requirement is the Go Programming Language, at least version 1.8.x
$ go get -u github.com/get-ion/ion
Example code:
package main
import (
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
)
// User is just a bindable object structure.
type User struct {
Username string `json:"username"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
City string `json:"city"`
Age int `json:"age"`
}
func main() {
app := ion.New()
// Define templates using the std html/template engine.
// Parse and load all files inside "./views" folder with ".html" file extension.
// Reload the templates on each request (development mode).
app.RegisterView(ion.HTML("./views", ".html").Reload(true))
// Regster custom handler for specific http errors.
app.OnErrorCode(ion.StatusInternalServerError, func(ctx context.Context) {
// .Values are used to communicate between handlers, middleware.
errMessage := ctx.Values().GetString("error")
if errMessage != "" {
ctx.Writef("Internal server error: %s", errMessage)
return
}
ctx.Writef("(Unexpected) internal server error")
})
app.Use(func(ctx context.Context) {
ctx.Application().Logger().Infof("Begin request for path: %s", ctx.Path())
ctx.Next()
})
// app.Done(func(ctx context.Context) {})
// Method POST: http://localhost:8080/decode
app.Post("/decode", func(ctx context.Context) {
var user User
ctx.ReadJSON(&user)
ctx.Writef("%s %s is %d years old and comes from %s", user.Firstname, user.Lastname, user.Age, user.City)
})
// Method GET: http://localhost:8080/encode
app.Get("/encode", func(ctx context.Context) {
doe := User{
Username: "Johndoe",
Firstname: "John",
Lastname: "Doe",
City: "Neither FBI knows!!!",
Age: 25,
}
ctx.JSON(doe)
})
// Method GET: http://localhost:8080/profile/anytypeofstring
app.Get("/profile/{username:string}", profileByUsername)
usersRoutes := app.Party("/users", logThisMiddleware)
{
// Method GET: http://localhost:8080/users/42
usersRoutes.Get("/{id:int min(1)}", getUserByID)
// Method POST: http://localhost:8080/users/create
usersRoutes.Post("/create", createUser)
}
// Listen for incoming HTTP/1.x & HTTP/2 clients on localhost port 8080.
app.Run(ion.Addr(":8080"), ion.WithCharset("UTF-8"))
}
func logThisMiddleware(ctx context.Context) {
ctx.Application().Logger().Infof("Path: %s | IP: %s", ctx.Path(), ctx.RemoteAddr())
// .Next is required to move forward to the chain of handlers,
// if missing then it stops the execution at this handler.
ctx.Next()
}
func profileByUsername(ctx context.Context) {
// .Params are used to get dynamic path parameters.
username := ctx.Params().Get("username")
ctx.ViewData("Username", username)
// renders "./views/users/profile.html"
// with {{ .Username }} equals to the username dynamic path parameter.
ctx.View("users/profile.html")
}
func getUserByID(ctx context.Context) {
userID := ctx.Params().Get("id") // Or convert directly using: .Values().GetInt/GetInt64 etc...
// your own db fetch here instead of user :=...
user := User{Username: "username" + userID}
ctx.XML(user)
}
func createUser(ctx context.Context) {
var user User
err := ctx.ReadForm(&user)
if err != nil {
ctx.Values().Set("error", "creating user, read and parse form failed. "+err.Error())
ctx.StatusCode(ion.StatusInternalServerError)
return
}
// renders "./views/users/create_verification.html"
// with {{ . }} equals to the User object, i.e {{ .Username }} , {{ .Firstname}} etc...
ctx.ViewData("", user)
ctx.View("users/create_verification.html")
}
Listening and gracefully shutdown
You can listen to a server using any type of net.Listener or http.Server instance.
The method for initialization of the server should be passed at the end, via `Run` function.
Below you'll read some usage examples:
// Listening on tcp with network address 0.0.0.0:8080
app.Run(ion.Addr(":8080"))
// Same as before but using a custom http.Server which may being used somewhere else too
app.Run(ion.Server(&http.Server{Addr:":8080"}))
// Using a custom net.Listener
l, err := net.Listen("tcp4", ":8080")
if err != nil {
panic(err)
}
app.Run(ion.Listener(l))
// TLS using files
app.Run(ion.TLS("127.0.0.1:443", "mycert.cert", "mykey.key"))
// Automatic TLS
app.Run(ion.AutoTLS("localhost:443"))
// UNIX socket
l, err := netutil.UNIX("/tmpl/srv.sock", 0666)
if err != nil {
panic(err)
}
app.Run(ion.Listener(l))
// Using any func() error,
// the responsibility of starting up a listener is up to you with this way,
// for the sake of simplicity we will use the
// ListenAndServe function of the `net/http` package.
app.Run(ion.Raw(&http.Server{Addr:":8080"}).ListenAndServe)
UNIX and BSD hosts can take advandage of the reuse port feature.
Example code:
package main
import (
// Package tcplisten provides customizable TCP net.Listener with various
// performance-related options:
//
// - SO_REUSEPORT. This option allows linear scaling server performance
// on multi-CPU servers.
// See https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/ for details.
//
// - TCP_DEFER_ACCEPT. This option expects the server reads from the accepted
// connection before writing to them.
//
// - TCP_FASTOPEN. See https://lwn.net/Articles/508865/ for details.
"github.com/valyala/tcplisten"
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
)
// $ go get github.com/valyala/tcplisten
// $ go run main.go
func main() {
app := ion.New()
app.Get("/", func(ctx context.Context) {
ctx.HTML("<b>Hello World!</b>")
})
listenerCfg := tcplisten.Config{
ReusePort: true,
DeferAccept: true,
FastOpen: true,
}
l, err := listenerCfg.NewListener("tcp", ":8080")
if err != nil {
panic(err)
}
app.Run(ion.Listener(l))
}
That's all with listening, you have the full control when you need it.
Let's continue by learning how to catch CONTROL+C/COMMAND+C or unix kill command and shutdown the server gracefuly.
Gracefully Shutdown on CONTROL+C/COMMAND+C or when kill command sent is ENABLED BY-DEFAULT.
In order to manually manage what to do when app is interrupted,
we have to disable the default behavior with the option `WithoutInterruptHandler`
and register a new interrupt handler (globally, across all possible hosts).
Example code:
package main
import (
stdContext "context"
"time"
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
)
func main() {
app := ion.New()
ion.RegisterOnInterrupt(func() {
timeout := 5 * time.Second
ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout)
defer cancel()
// close all hosts
app.Shutdown(ctx)
})
app.Get("/", func(ctx context.Context) {
ctx.HTML(" <h1>hi, I just exist in order to see if the server is closed</h1>")
})
// http://localhost:8080
app.Run(ion.Addr(":8080"), ion.WithoutInterruptHandler)
}
Read more about listening and gracefully shutdown by navigating to:
https://github.com/get-ion/ion/tree/master/_examples/#http-listening
Routing
All HTTP methods are supported, developers can also register handlers for same paths for different methods.
The first parameter is the HTTP Method,
second parameter is the request path of the route,
third variadic parameter should contains one or more context.Handler executed
by the registered order when a user requests for that specific resouce path from the server.
Example code:
app := ion.New()
app.Handle("GET", "/contact", func(ctx context.Context){
ctx.HTML("<h1> Hello from /contact </h1>")
})
In order to make things easier for the user, ion provides functions for all HTTP Methods.
The first parameter is the request path of the route,
second variadic parameter should contains one or more context.Handler executed
by the registered order when a user requests for that specific resouce path from the server.
Example code:
app := ion.New()
// Method: "GET"
app.Get("/", handler)
// Method: "POST"
app.Post("/", handler)
// Method: "PUT"
app.Put("/", handler)
// Method: "DELETE"
app.Delete("/", handler)
// Method: "OPTIONS"
app.Options("/", handler)
// Method: "TRACE"
app.Trace("/", handler)
// Method: "CONNECT"
app.Connect("/", handler)
// Method: "HEAD"
app.Head("/", handler)
// Method: "PATCH"
app.Patch("/", handler)
// register the route for all HTTP Methods
app.Any("/", handler)
func handler(ctx context.Context){
ctx.Writef("Hello from method: %s and path: %s", ctx.Method(), ctx.Path())
}
Grouping Routes
A set of routes that are being groupped by path prefix can (optionally) share the same middleware handlers and template layout.
A group can have a nested group too.
`.Party` is being used to group routes, developers can declare an unlimited number of (nested) groups.
Example code:
users:= app.Party("/users", myAuthHandler)
// http://myhost.com/users/42/profile
users.Get("/{userid:int}/profile", userProfileHandler)
// http://myhost.com/users/messages/1
users.Get("/inbox/{messageid:int}", userMessageHandler)
app.Run(ion.Addr("myhost.com:80"))
Custom HTTP Errors
ion developers are able to register their own handlers for http statuses like 404 not found, 500 internal server error and so on.
Example code:
// when 404 then render the template $templatedir/errors/404.html
app.OnErrorCode(ion.StatusNotFound, func(ctx context.Context){
ctx.View("errors/404.html")
})
app.OnErrorCode(500, func(ctx context.Context){
// ...
})
Basic HTTP API
With the help of ion's expressionist router you can build any form of API you desire, with
safety.
Example code:
package main
import (
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
)
func main() {
app := ion.New()
// registers a custom handler for 404 not found http (error) status code,
// fires when route not found or manually by ctx.StatusCode(ion.StatusNotFound).
app.OnErrorCode(ion.StatusNotFound, notFoundHandler)
// GET -> HTTP Method
// / -> Path
// func(ctx context.Context) -> The route's handler.
//
// Third receiver should contains the route's handler(s), they are executed by order.
app.Handle("GET", "/", func(ctx context.Context) {
// navigate to the middle of $GOPATH/src/github.com/get-ion/ion/context/context.go
// to overview all context's method (there a lot of them, read that and you will learn how ion works too)
ctx.HTML("Hello from " + ctx.Path()) // Hello from /
})
app.Get("/home", func(ctx context.Context) {
ctx.Writef(`Same as app.Handle("GET", "/", [...])`)
})
app.Get("/donate", donateHandler, donateFinishHandler)
// Pssst, don't forget dynamic-path example for more "magic"!
app.Get("/api/users/{userid:int min(1)}", func(ctx context.Context) {
userID, err := ctx.Params().GetInt("userid")
if err != nil {
ctx.Writef("error while trying to parse userid parameter," +
"this will never happen if :int is being used because if it's not integer it will fire Not Found automatically.")
ctx.StatusCode(ion.StatusBadRequest)
return
}
ctx.JSON(map[string]interface{}{
// you can pass any custom structured go value of course.
"user_id": userID,
})
})
// app.Post("/", func(ctx context.Context){}) -> for POST http method.
// app.Put("/", func(ctx context.Context){})-> for "PUT" http method.
// app.Delete("/", func(ctx context.Context){})-> for "DELETE" http method.
// app.Options("/", func(ctx context.Context){})-> for "OPTIONS" http method.
// app.Trace("/", func(ctx context.Context){})-> for "TRACE" http method.
// app.Head("/", func(ctx context.Context){})-> for "HEAD" http method.
// app.Connect("/", func(ctx context.Context){})-> for "CONNECT" http method.
// app.Patch("/", func(ctx context.Context){})-> for "PATCH" http method.
// app.Any("/", func(ctx context.Context){}) for all http methods.
// More than one route can contain the same path with a different http mapped method.
// You can catch any route creation errors with:
// route, err := app.Get(...)
// set a name to a route: route.Name = "myroute"
// You can also group routes by path prefix, sharing middleware(s) and done handlers.
adminRoutes := app.Party("/admin", adminMiddleware)
adminRoutes.Done(func(ctx context.Context) { // executes always last if ctx.Next()
ctx.Application().Logger().Infof("response sent to " + ctx.Path())
})
// adminRoutes.Layout("/views/layouts/admin.html") // set a view layout for these routes, see more at view examples.
// GET: http://localhost:8080/admin
adminRoutes.Get("/", func(ctx context.Context) {
// [...]
ctx.StatusCode(ion.StatusOK) // default is 200 == ion.StatusOK
ctx.HTML("<h1>Hello from admin/</h1>")
ctx.Next() // in order to execute the party's "Done" Handler(s)
})
// GET: http://localhost:8080/admin/login
adminRoutes.Get("/login", func(ctx context.Context) {
// [...]
})
// POST: http://localhost:8080/admin/login
adminRoutes.Post("/login", func(ctx context.Context) {
// [...]
})
// subdomains, easier than ever, should add localhost or 127.0.0.1 into your hosts file,
// etc/hosts on unix or C:/windows/system32/drivers/etc/hosts on windows.
v1 := app.Party("v1.")
{ // braces are optional, it's just type of style, to group the routes visually.
// http://v1.localhost:8080
v1.Get("/", func(ctx context.Context) {
ctx.HTML("Version 1 API. go to <a href='" + ctx.Path() + "/api" + "'>/api/users</a>")
})
usersAPI := v1.Party("/api/users")
{
// http://v1.localhost:8080/api/users
usersAPI.Get("/", func(ctx context.Context) {
ctx.Writef("All users")
})
// http://v1.localhost:8080/api/users/42
usersAPI.Get("/{userid:int}", func(ctx context.Context) {
ctx.Writef("user with id: %s", ctx.Params().Get("userid"))
})
}
}
// wildcard subdomains.
wildcardSubdomain := app.Party("*.")
{
wildcardSubdomain.Get("/", func(ctx context.Context) {
ctx.Writef("Subdomain can be anything, now you're here from: %s", ctx.Subdomain())
})
}
// http://localhost:8080
// http://localhost:8080/home
// http://localhost:8080/donate
// http://localhost:8080/api/users/42
// http://localhost:8080/admin
// http://localhost:8080/admin/login
//
// http://localhost:8080/api/users/0
// http://localhost:8080/api/users/blabla
// http://localhost:8080/wontfound
//
// if hosts edited:
// http://v1.localhost:8080
// http://v1.localhost:8080/api/users
// http://v1.localhost:8080/api/users/42
// http://anything.localhost:8080
app.Run(ion.Addr(":8080"))
}
func adminMiddleware(ctx context.Context) {
// [...]
ctx.Next() // to move to the next handler, or don't that if you have any auth logic.
}
func donateHandler(ctx context.Context) {
ctx.Writef("Just like an inline handler, but it can be " +
"used by other package, anywhere in your project.")
// let's pass a value to the next handler
// Values is the way handlers(or middleware) are communicating between each other.
ctx.Values().Set("donate_url", "https://github.com/get-ion/ion#buy-me-a-cup-of-coffee")
ctx.Next() // in order to execute the next handler in the chain, look donate route.
}
func donateFinishHandler(ctx context.Context) {
// values can be any type of object so we could cast the value to a string
// but ion provides an easy to do that, if donate_url is not defined, then it returns an empty string instead.
donateURL := ctx.Values().GetString("donate_url")
ctx.Application().Logger().Infof("donate_url value was: " + donateURL)
ctx.Writef("\n\nDonate sent(?).")
}
func notFoundHandler(ctx context.Context) {
ctx.HTML("Custom route for 404 not found http code, here you can render a view, html, json <b>any valid response</b>.")
}
Parameterized Path
At the previous example,
we've seen static routes, group of routes, subdomains, wildcard subdomains, a small example of parameterized path
with a single known paramete and custom http errors, now it's time to see wildcard parameters and macros.
ion, like net/http std package registers route's handlers
by a Handler, the ion' type of handler is just a func(ctx context.Context)
where context comes from github.com/get-ion/ion/context.
Until go 1.9 you will have to import that package too, after go 1.9 this will be not be necessary.
ion has the easiest and the most powerful routing process you have ever meet.
At the same time,
ion has its own interpeter(yes like a programming language)
for route's path syntax and their dynamic path parameters parsing and evaluation,
I am calling them "macros" for shortcut.
How? It calculates its needs and if not any special regexp needed then it just
registers the route with the low-level path syntax,
otherwise it pre-compiles the regexp and adds the necessary middleware(s).
Standard macro types for parameters:
+------------------------+
| {param:string} |
+------------------------+
string type
anything
+------------------------+
| {param:int} |
+------------------------+
int type
only numbers (0-9)
+------------------------+
| {param:alphabetical} |
+------------------------+
alphabetical/letter type
letters only (upper or lowercase)
+------------------------+
| {param:file} |
+------------------------+
file type
letters (upper or lowercase)
numbers (0-9)
underscore (_)
dash (-)
point (.)
no spaces ! or other character
+------------------------+
| {param:path} |
+------------------------+
path type
anything, should be the last part, more than one path segment,
i.e: /path1/path2/path3 , ctx.Params().GetString("param") == "/path1/path2/path3"
if type is missing then parameter's type is defaulted to string, so
{param} == {param:string}.
If a function not found on that type then the "string"'s types functions are being used.
i.e:
{param:int min(3)}
Besides the fact that ion provides the basic types and some default "macro funcs"
you are able to register your own too!.
Register a named path parameter function:
app.Macros().Int.RegisterFunc("min", func(argument int) func(paramValue string) bool {
[...]
return true/false -> true means valid.
})
at the func(argument ...) you can have any standard type, it will be validated before the server starts
so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool.
{param:string equal(ion)} , "ion" will be the argument here:
app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool {
return func(paramValue string){ return argument == paramValue }
})
Example code:
// you can use the "string" type which is valid for a single path parameter that can be anything.
app.Get("/username/{name}", func(ctx context.Context) {
ctx.Writef("Hello %s", ctx.Params().Get("name"))
}) // type is missing = {name:string}
// Let's register our first macro attached to int macro type.
// "min" = the function
// "minValue" = the argument of the function
// func(string) bool = the macro's path parameter evaluator, this executes in serve time when
// a user requests a path which contains the :int macro type with the min(...) macro parameter function.
app.Macros().Int.RegisterFunc("min", func(minValue int) func(string) bool {
// do anything before serve here [...]
// at this case we don't need to do anything
return func(paramValue string) bool {
n, err := strconv.Atoi(paramValue)
if err != nil {
return false
}
return n >= minValue
}
})
// http://localhost:8080/profile/id>=1
// this will throw 404 even if it's found as route on : /profile/0, /profile/blabla, /profile/-1
// macro parameter functions are optional of course.
app.Get("/profile/{id:int min(1)}", func(ctx context.Context) {
// second parameter is the error but it will always nil because we use macros,
// the validaton already happened.
id, _ := ctx.Params().GetInt("id")
ctx.Writef("Hello id: %d", id)
})
// to change the error code per route's macro evaluator:
app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx context.Context) {
id, _ := ctx.Params().GetInt("id")
friendid, _ := ctx.Params().GetInt("friendid")
ctx.Writef("Hello id: %d looking for friend id: ", id, friendid)
}) // this will throw e 504 error code instead of 404 if all route's macros not passed.
// http://localhost:8080/game/a-zA-Z/level/0-9
// remember, alphabetical is lowercase or uppercase letters only.
app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx context.Context) {
ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level"))
})
// let's use a trivial custom regexp that validates a single path parameter
// which its value is only lowercase letters.
// http://localhost:8080/lowercase/anylowercase
app.Get("/lowercase/{name:string regexp(^[a-z]+)}", func(ctx context.Context) {
ctx.Writef("name should be only lowercase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
})
// http://localhost:8080/single_file/app.js
app.Get("/single_file/{myfile:file}", func(ctx context.Context) {
ctx.Writef("file type validates if the parameter value has a form of a file name, got: %s", ctx.Params().Get("myfile"))
})
// http://localhost:8080/myfiles/any/directory/here/
// this is the only macro type that accepts any number of path segments.
app.Get("/myfiles/{directory:path}", func(ctx context.Context) {
ctx.Writef("path type accepts any number of path segments, path after /myfiles/ is: %s", ctx.Params().Get("directory"))
})
// for wildcard path (any number of path segments) without validation you can use:
// /myfiles/*directory
// "{param}"'s performance is exactly the same of ":param"'s.
// alternatives -> ":param" for single path parameter and "*paramPath" for wildcard path parameter
// acquire them by ctx.Params().Get as always.
if err := app.Run(ion.Addr(":8080")); err != nil {
panic(err)
}
}
A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed.
If route failed to be registered, the app will panic without any warnings
if you didn't catch the second return value(error) on .Handle/.Get....
Last, do not confuse ctx.Values() with ctx.Params().
Path parameter's values goes to ctx.Params() and context's local storage
that can be used to communicate between handlers and middleware(s) goes to
ctx.Values(), path parameters and the rest of any custom values are separated for your own good.
Run
$ go run main.go
Static Files
// StaticServe serves a directory as web resource
// it's the simpliest form of the Static* functions
// Almost same usage as StaticWeb
// accepts only one required parameter which is the systemPath,
// the same path will be used to register the GET and HEAD method routes.
// If second parameter is empty, otherwise the requestPath is the second parameter
// it uses gzip compression (compression on each request, no file cache).
//
// Returns the GET *Route.
StaticServe(systemPath string, requestPath ...string) (*Route, error)
// StaticContent registers a GET and HEAD method routes to the requestPath
// that are ready to serve raw static bytes, memory cached.
//
// Returns the GET *Route.
StaticContent(reqPath string, cType string, content []byte) (*Route, error)
// StaticEmbedded used when files are distributed inside the app executable, using go-bindata mostly
// First parameter is the request path, the path which the files in the vdir will be served to, for example "/static"
// Second parameter is the (virtual) directory path, for example "./assets"
// Third parameter is the Asset function
// Forth parameter is the AssetNames function.
//
// Returns the GET *Route.
//
// Example: https://github.com/get-ion/ion/tree/master/_examples/file-server/embedding-files-into-app
StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), namesFn func() []string) (*Route, error)
// Favicon serves static favicon
// accepts 2 parameters, second is optional
// favPath (string), declare the system directory path of the __.ico
// requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first,
// you can declare your own path if you have more than one favicon (desktop, mobile and so on)
//
// this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico
// (nothing special that you can't handle by yourself).
// Note that you have to call it on every favicon you have to serve automatically (desktop, mobile and so on).
//
// Returns the GET *Route.
Favicon(favPath string, requestPath ...string) (*Route, error)
// StaticWeb returns a handler that serves HTTP requests
// with the contents of the file system rooted at directory.
//
// first parameter: the route path
// second parameter: the system directory
// third OPTIONAL parameter: the exception routes
// (= give priority to these routes instead of the static handler)
// for more options look app.StaticHandler.
//
// app.StaticWeb("/static", "./static")
//
// As a special case, the returned file server redirects any request
// ending in "/index.html" to the same path, without the final
// "index.html".
//
// StaticWeb calls the StaticHandler(systemPath, listingDirectories: false, gzip: false ).
//
// Returns the GET *Route.
StaticWeb(requestPath string, systemPath string, exceptRoutes ...*Route) (*Route, error)
Example code:
package main
import (
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
)
func main() {
app := ion.New()
// This will serve the ./static/favicons/ion_32_32.ico to: localhost:8080/favicon.ico
app.Favicon("./static/favicons/ion_32_32.ico")
// app.Favicon("./static/favicons/ion_32_32.ico", "/favicon_48_48.ico")
// This will serve the ./static/favicons/ion_32_32.ico to: localhost:8080/favicon_48_48.ico
app.Get("/", func(ctx context.Context) {
ctx.HTML(`<a href="/favicon.ico"> press here to see the favicon.ico</a>.
At some browsers like chrome, it should be visible at the top-left side of the browser's window,
because some browsers make requests to the /favicon.ico automatically,
so ion serves your favicon in that path too (you can change it).`)
}) // if favicon doesn't show to you, try to clear your browser's cache.
app.Run(ion.Addr(":8080"))
}
More examples can be found here: https://github.com/get-ion/ion/tree/master/_examples/beginner/file-server
Middleware Ecosystem
Middleware is just a concept of ordered chain of handlers.
Middleware can be registered globally, per-party, per-subdomain and per-route.
Example code:
// globally
// before any routes, appends the middleware to all routes
app.Use(func(ctx context.Context){
// ... any code here
ctx.Next() // in order to continue to the next handler,
// if that is missing then the next in chain handlers will be not executed,
// useful for authentication middleware
})
// globally
// after or before any routes, prepends the middleware to all routes
app.UseGlobal(handler1, handler2, handler3)
// per-route
app.Post("/login", authenticationHandler, loginPageHandler)
// per-party(group of routes)
users := app.Party("/users", usersMiddleware)
users.Get("/", usersIndex)
// per-subdomain
mysubdomain := app.Party("mysubdomain.", firstMiddleware)
mysubdomain.Use(secondMiddleware)
mysubdomain.Get("/", mysubdomainIndex)
// per wildcard, dynamic subdomain
dynamicSub := app.Party(".*", firstMiddleware, secondMiddleware)
dynamicSub.Get("/", func(ctx context.Context){
ctx.Writef("Hello from subdomain: "+ ctx.Subdomain())
})
ion is able to wrap and convert any external, third-party Handler you used to use to your web application.
Let's convert the https://github.com/rs/cors net/http external middleware which returns a `next form` handler.
Example code:
package main
import (
"github.com/rs/cors"
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
)
func main() {
app := ion.New()
corsOptions := cors.Options{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
}
corsWrapper := cors.New(corsOptions).ServeHTTP
app.WrapRouter(corsWrapper)
v1 := app.Party("/api/v1")
{
v1.Get("/", h)
v1.Put("/put", h)
v1.Post("/post", h)
}
app.Run(ion.Addr(":8080"))
}
func h(ctx context.Context) {
ctx.Application().Logger().Infof(ctx.Path())
ctx.Writef("Hello from %s", ctx.Path())
}
View Engine
ion supports 5 template engines out-of-the-box, developers can still use any external golang template engine,
as `context.ResponseWriter()` is an `io.Writer`.
All of these five template engines have common features with common API,
like Layout, Template Funcs, Party-specific layout, partial rendering and more.
The standard html,
its template parser is the golang.org/pkg/html/template/.
Django,
its template parser is the github.com/flosch/pongo2
Pug(Jade),
its template parser is the github.com/Joker/jade
Handlebars,
its template parser is the github.com/aymerick/raymond
Amber,
its template parser is the github.com/eknkc/amber
Example code:
package main
import (
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
)
func main() {
app := ion.New() // defaults to these
// - standard html | ion.HTML(...)
// - django | ion.Django(...)
// - pug(jade) | ion.Pug(...)
// - handlebars | ion.Handlebars(...)
// - amber | ion.Amber(...)
tmpl := ion.HTML("./templates", ".html")
tmpl.Reload(true) // reload templates on each request (development mode)