gin-1.2/000077500000000000000000000000001312613627200121345ustar00rootroot00000000000000gin-1.2/.gitignore000066400000000000000000000000641312613627200141240ustar00rootroot00000000000000vendor/* !vendor/vendor.json coverage.out count.out gin-1.2/.travis.yml000066400000000000000000000010511312613627200142420ustar00rootroot00000000000000language: go sudo: false go: - 1.6.x - 1.7.x - 1.8.x - master git: depth: 3 install: - make install script: - make vet - make fmt-check - make embedmd - make misspell-check - make test after_success: - bash <(curl -s https://codecov.io/bash) notifications: webhooks: urls: - https://webhooks.gitter.im/e/7f95bf605c4d356372f4 on_success: change # options: [always|never|change] default: always on_failure: always # options: [always|never|change] default: always on_start: false # default: false gin-1.2/AUTHORS.md000066400000000000000000000077661312613627200136230ustar00rootroot00000000000000List of all the awesome people working to make Gin the best Web Framework in Go. ## gin 0.x series authors **Maintainer:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) People and companies, who have contributed, in alphabetical order. **@858806258 (杰哥)** - Fix typo in example **@achedeuzot (Klemen Sever)** - Fix newline debug printing **@adammck (Adam Mckaig)** - Add MIT license **@AlexanderChen1989 (Alexander)** - Typos in README **@alexanderdidenko (Aleksandr Didenko)** - Add support multipart/form-data **@alexandernyquist (Alexander Nyquist)** - Using template.Must to fix multiple return issue - ★ Added support for OPTIONS verb - ★ Setting response headers before calling WriteHeader - Improved documentation for model binding - ★ Added Content.Redirect() - ★ Added tons of Unit tests **@austinheap (Austin Heap)** - Added travis CI integration **@andredublin (Andre Dublin)** - Fix typo in comment **@bredov (Ludwig Valda Vasquez)** - Fix html templating in debug mode **@bluele (Jun Kimura)** - Fixes code examples in README **@chad-russell** - ★ Support for serializing gin.H into XML **@dickeyxxx (Jeff Dickey)** - Typos in README - Add example about serving static files **@donileo (Adonis)** - Add NoMethod handler **@dutchcoders (DutchCoders)** - ★ Fix security bug that allows client to spoof ip - Fix typo. r.HTMLTemplates -> SetHTMLTemplate **@el3ctro- (Joshua Loper)** - Fix typo in example **@ethankan (Ethan Kan)** - Unsigned integers in binding **(Evgeny Persienko)** - Validate sub structures **@frankbille (Frank Bille)** - Add support for HTTP Realm Auth **@fmd (Fareed Dudhia)** - Fix typo. SetHTTPTemplate -> SetHTMLTemplate **@ironiridis (Christopher Harrington)** - Remove old reference **@jammie-stackhouse (Jamie Stackhouse)** - Add more shortcuts for router methods **@jasonrhansen** - Fix spelling and grammar errors in documentation **@JasonSoft (Jason Lee)** - Fix typo in comment **@joiggama (Ignacio Galindo)** - Add utf-8 charset header on renders **@julienschmidt (Julien Schmidt)** - gofmt the code examples **@kelcecil (Kel Cecil)** - Fix readme typo **@kyledinh (Kyle Dinh)** - Adds RunTLS() **@LinusU (Linus Unnebäck)** - Small fixes in README **@loongmxbt (Saint Asky)** - Fix typo in example **@lucas-clemente (Lucas Clemente)** - ★ work around path.Join removing trailing slashes from routes **@mattn (Yasuhiro Matsumoto)** - Improve color logger **@mdigger (Dmitry Sedykh)** - Fixes Form binding when content-type is x-www-form-urlencoded - No repeat call c.Writer.Status() in gin.Logger - Fixes Content-Type for json render **@mirzac (Mirza Ceric)** - Fix debug printing **@mopemope (Yutaka Matsubara)** - ★ Adds Godep support (Dependencies Manager) - Fix variadic parameter in the flexible render API - Fix Corrupted plain render - Add Pluggable View Renderer Example **@msemenistyi (Mykyta Semenistyi)** - update Readme.md. Add code to String method **@msoedov (Sasha Myasoedov)** - ★ Adds tons of unit tests. **@ngerakines (Nick Gerakines)** - ★ Improves API, c.GET() doesn't panic - Adds MustGet() method **@r8k (Rajiv Kilaparti)** - Fix Port usage in README. **@rayrod2030 (Ray Rodriguez)** - Fix typo in example **@rns** - Fix typo in example **@RobAWilkinson (Robert Wilkinson)** - Add example of forms and params **@rogierlommers (Rogier Lommers)** - Add updated static serve example **@se77en (Damon Zhao)** - Improve color logging **@silasb (Silas Baronda)** - Fixing quotes in README **@SkuliOskarsson (Skuli Oskarsson)** - Fixes some texts in README II **@slimmy (Jimmy Pettersson)** - Added messages for required bindings **@smira (Andrey Smirnov)** - Add support for ignored/unexported fields in binding **@superalsrk (SRK.Lyu)** - Update httprouter godeps **@tebeka (Miki Tebeka)** - Use net/http constants instead of numeric values **@techjanitor** - Update context.go reserved IPs **@yosssi (Keiji Yoshida)** - Fix link in README **@yuyabee** - Fixed README gin-1.2/BENCHMARKS.md000066400000000000000000000664441312613627200141110ustar00rootroot00000000000000**Machine:** intel i7 ivy bridge quad-core. 8GB RAM. **Date:** June 4th, 2015 [https://github.com/gin-gonic/go-http-routing-benchmark](https://github.com/gin-gonic/go-http-routing-benchmark) ``` BenchmarkAce_Param 5000000 372 ns/op 32 B/op 1 allocs/op BenchmarkBear_Param 1000000 1165 ns/op 424 B/op 5 allocs/op BenchmarkBeego_Param 1000000 2440 ns/op 720 B/op 10 allocs/op BenchmarkBone_Param 1000000 1067 ns/op 384 B/op 3 allocs/op BenchmarkDenco_Param 5000000 240 ns/op 32 B/op 1 allocs/op BenchmarkEcho_Param 10000000 130 ns/op 0 B/op 0 allocs/op BenchmarkGin_Param 10000000 133 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_Param 1000000 1826 ns/op 656 B/op 9 allocs/op BenchmarkGoji_Param 2000000 957 ns/op 336 B/op 2 allocs/op BenchmarkGoJsonRest_Param 1000000 2021 ns/op 657 B/op 14 allocs/op BenchmarkGoRestful_Param 200000 8825 ns/op 2496 B/op 31 allocs/op BenchmarkGorillaMux_Param 500000 3340 ns/op 784 B/op 9 allocs/op BenchmarkHttpRouter_Param 10000000 152 ns/op 32 B/op 1 allocs/op BenchmarkHttpTreeMux_Param 2000000 717 ns/op 336 B/op 2 allocs/op BenchmarkKocha_Param 3000000 423 ns/op 56 B/op 3 allocs/op BenchmarkMacaron_Param 1000000 3410 ns/op 1104 B/op 11 allocs/op BenchmarkMartini_Param 200000 7101 ns/op 1152 B/op 12 allocs/op BenchmarkPat_Param 1000000 2040 ns/op 656 B/op 14 allocs/op BenchmarkPossum_Param 1000000 2048 ns/op 624 B/op 7 allocs/op BenchmarkR2router_Param 1000000 1144 ns/op 432 B/op 6 allocs/op BenchmarkRevel_Param 200000 6725 ns/op 1672 B/op 28 allocs/op BenchmarkRivet_Param 1000000 1121 ns/op 464 B/op 5 allocs/op BenchmarkTango_Param 1000000 1479 ns/op 256 B/op 10 allocs/op BenchmarkTigerTonic_Param 1000000 3393 ns/op 992 B/op 19 allocs/op BenchmarkTraffic_Param 300000 5525 ns/op 1984 B/op 23 allocs/op BenchmarkVulcan_Param 2000000 924 ns/op 98 B/op 3 allocs/op BenchmarkZeus_Param 1000000 1084 ns/op 368 B/op 3 allocs/op BenchmarkAce_Param5 3000000 614 ns/op 160 B/op 1 allocs/op BenchmarkBear_Param5 1000000 1617 ns/op 469 B/op 5 allocs/op BenchmarkBeego_Param5 1000000 3373 ns/op 992 B/op 13 allocs/op BenchmarkBone_Param5 1000000 1478 ns/op 432 B/op 3 allocs/op BenchmarkDenco_Param5 3000000 570 ns/op 160 B/op 1 allocs/op BenchmarkEcho_Param5 5000000 256 ns/op 0 B/op 0 allocs/op BenchmarkGin_Param5 10000000 222 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_Param5 1000000 2789 ns/op 928 B/op 12 allocs/op BenchmarkGoji_Param5 1000000 1287 ns/op 336 B/op 2 allocs/op BenchmarkGoJsonRest_Param5 1000000 3670 ns/op 1105 B/op 17 allocs/op BenchmarkGoRestful_Param5 200000 10756 ns/op 2672 B/op 31 allocs/op BenchmarkGorillaMux_Param5 300000 5543 ns/op 912 B/op 9 allocs/op BenchmarkHttpRouter_Param5 5000000 403 ns/op 160 B/op 1 allocs/op BenchmarkHttpTreeMux_Param5 1000000 1089 ns/op 336 B/op 2 allocs/op BenchmarkKocha_Param5 1000000 1682 ns/op 440 B/op 10 allocs/op BenchmarkMacaron_Param5 300000 4596 ns/op 1376 B/op 14 allocs/op BenchmarkMartini_Param5 100000 15703 ns/op 1280 B/op 12 allocs/op BenchmarkPat_Param5 300000 5320 ns/op 1008 B/op 42 allocs/op BenchmarkPossum_Param5 1000000 2155 ns/op 624 B/op 7 allocs/op BenchmarkR2router_Param5 1000000 1559 ns/op 432 B/op 6 allocs/op BenchmarkRevel_Param5 200000 8184 ns/op 2024 B/op 35 allocs/op BenchmarkRivet_Param5 1000000 1914 ns/op 528 B/op 9 allocs/op BenchmarkTango_Param5 1000000 3280 ns/op 944 B/op 18 allocs/op BenchmarkTigerTonic_Param5 200000 11638 ns/op 2519 B/op 53 allocs/op BenchmarkTraffic_Param5 200000 8941 ns/op 2280 B/op 31 allocs/op BenchmarkVulcan_Param5 1000000 1279 ns/op 98 B/op 3 allocs/op BenchmarkZeus_Param5 1000000 1574 ns/op 416 B/op 3 allocs/op BenchmarkAce_Param20 1000000 1528 ns/op 640 B/op 1 allocs/op BenchmarkBear_Param20 300000 4906 ns/op 1633 B/op 5 allocs/op BenchmarkBeego_Param20 200000 10529 ns/op 3868 B/op 17 allocs/op BenchmarkBone_Param20 300000 7362 ns/op 2539 B/op 5 allocs/op BenchmarkDenco_Param20 1000000 1884 ns/op 640 B/op 1 allocs/op BenchmarkEcho_Param20 2000000 689 ns/op 0 B/op 0 allocs/op BenchmarkGin_Param20 3000000 545 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_Param20 200000 9437 ns/op 3804 B/op 16 allocs/op BenchmarkGoji_Param20 500000 3987 ns/op 1246 B/op 2 allocs/op BenchmarkGoJsonRest_Param20 100000 12799 ns/op 4492 B/op 21 allocs/op BenchmarkGoRestful_Param20 100000 19451 ns/op 5244 B/op 33 allocs/op BenchmarkGorillaMux_Param20 100000 12456 ns/op 3275 B/op 11 allocs/op BenchmarkHttpRouter_Param20 1000000 1333 ns/op 640 B/op 1 allocs/op BenchmarkHttpTreeMux_Param20 300000 6490 ns/op 2187 B/op 4 allocs/op BenchmarkKocha_Param20 300000 5335 ns/op 1808 B/op 27 allocs/op BenchmarkMacaron_Param20 200000 11325 ns/op 4252 B/op 18 allocs/op BenchmarkMartini_Param20 20000 64419 ns/op 3644 B/op 14 allocs/op BenchmarkPat_Param20 50000 24672 ns/op 4888 B/op 151 allocs/op BenchmarkPossum_Param20 1000000 2085 ns/op 624 B/op 7 allocs/op BenchmarkR2router_Param20 300000 6809 ns/op 2283 B/op 8 allocs/op BenchmarkRevel_Param20 100000 16600 ns/op 5551 B/op 54 allocs/op BenchmarkRivet_Param20 200000 8428 ns/op 2620 B/op 26 allocs/op BenchmarkTango_Param20 100000 16302 ns/op 8224 B/op 48 allocs/op BenchmarkTigerTonic_Param20 30000 46828 ns/op 10538 B/op 178 allocs/op BenchmarkTraffic_Param20 50000 28871 ns/op 7998 B/op 66 allocs/op BenchmarkVulcan_Param20 1000000 2267 ns/op 98 B/op 3 allocs/op BenchmarkZeus_Param20 300000 6828 ns/op 2507 B/op 5 allocs/op BenchmarkAce_ParamWrite 3000000 502 ns/op 40 B/op 2 allocs/op BenchmarkBear_ParamWrite 1000000 1303 ns/op 424 B/op 5 allocs/op BenchmarkBeego_ParamWrite 1000000 2489 ns/op 728 B/op 11 allocs/op BenchmarkBone_ParamWrite 1000000 1181 ns/op 384 B/op 3 allocs/op BenchmarkDenco_ParamWrite 5000000 315 ns/op 32 B/op 1 allocs/op BenchmarkEcho_ParamWrite 10000000 237 ns/op 8 B/op 1 allocs/op BenchmarkGin_ParamWrite 5000000 336 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_ParamWrite 1000000 2079 ns/op 664 B/op 10 allocs/op BenchmarkGoji_ParamWrite 1000000 1092 ns/op 336 B/op 2 allocs/op BenchmarkGoJsonRest_ParamWrite 1000000 3329 ns/op 1136 B/op 19 allocs/op BenchmarkGoRestful_ParamWrite 200000 9273 ns/op 2504 B/op 32 allocs/op BenchmarkGorillaMux_ParamWrite 500000 3919 ns/op 792 B/op 10 allocs/op BenchmarkHttpRouter_ParamWrite 10000000 223 ns/op 32 B/op 1 allocs/op BenchmarkHttpTreeMux_ParamWrite 2000000 788 ns/op 336 B/op 2 allocs/op BenchmarkKocha_ParamWrite 3000000 549 ns/op 56 B/op 3 allocs/op BenchmarkMacaron_ParamWrite 500000 4558 ns/op 1216 B/op 16 allocs/op BenchmarkMartini_ParamWrite 200000 8850 ns/op 1256 B/op 16 allocs/op BenchmarkPat_ParamWrite 500000 3679 ns/op 1088 B/op 19 allocs/op BenchmarkPossum_ParamWrite 1000000 2114 ns/op 624 B/op 7 allocs/op BenchmarkR2router_ParamWrite 1000000 1320 ns/op 432 B/op 6 allocs/op BenchmarkRevel_ParamWrite 200000 8048 ns/op 2128 B/op 33 allocs/op BenchmarkRivet_ParamWrite 1000000 1393 ns/op 472 B/op 6 allocs/op BenchmarkTango_ParamWrite 2000000 819 ns/op 136 B/op 5 allocs/op BenchmarkTigerTonic_ParamWrite 300000 5860 ns/op 1440 B/op 25 allocs/op BenchmarkTraffic_ParamWrite 200000 7429 ns/op 2400 B/op 27 allocs/op BenchmarkVulcan_ParamWrite 2000000 972 ns/op 98 B/op 3 allocs/op BenchmarkZeus_ParamWrite 1000000 1226 ns/op 368 B/op 3 allocs/op BenchmarkAce_GithubStatic 5000000 294 ns/op 0 B/op 0 allocs/op BenchmarkBear_GithubStatic 3000000 575 ns/op 88 B/op 3 allocs/op BenchmarkBeego_GithubStatic 1000000 1561 ns/op 368 B/op 7 allocs/op BenchmarkBone_GithubStatic 200000 12301 ns/op 2880 B/op 60 allocs/op BenchmarkDenco_GithubStatic 20000000 74.6 ns/op 0 B/op 0 allocs/op BenchmarkEcho_GithubStatic 10000000 176 ns/op 0 B/op 0 allocs/op BenchmarkGin_GithubStatic 10000000 159 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_GithubStatic 1000000 1116 ns/op 304 B/op 6 allocs/op BenchmarkGoji_GithubStatic 5000000 413 ns/op 0 B/op 0 allocs/op BenchmarkGoRestful_GithubStatic 30000 55200 ns/op 3520 B/op 36 allocs/op BenchmarkGoJsonRest_GithubStatic 1000000 1504 ns/op 337 B/op 12 allocs/op BenchmarkGorillaMux_GithubStatic 100000 23620 ns/op 464 B/op 8 allocs/op BenchmarkHttpRouter_GithubStatic 20000000 78.3 ns/op 0 B/op 0 allocs/op BenchmarkHttpTreeMux_GithubStatic 20000000 84.9 ns/op 0 B/op 0 allocs/op BenchmarkKocha_GithubStatic 20000000 111 ns/op 0 B/op 0 allocs/op BenchmarkMacaron_GithubStatic 1000000 2686 ns/op 752 B/op 8 allocs/op BenchmarkMartini_GithubStatic 100000 22244 ns/op 832 B/op 11 allocs/op BenchmarkPat_GithubStatic 100000 13278 ns/op 3648 B/op 76 allocs/op BenchmarkPossum_GithubStatic 1000000 1429 ns/op 480 B/op 4 allocs/op BenchmarkR2router_GithubStatic 2000000 726 ns/op 144 B/op 5 allocs/op BenchmarkRevel_GithubStatic 300000 6271 ns/op 1288 B/op 25 allocs/op BenchmarkRivet_GithubStatic 3000000 474 ns/op 112 B/op 2 allocs/op BenchmarkTango_GithubStatic 1000000 1842 ns/op 256 B/op 10 allocs/op BenchmarkTigerTonic_GithubStatic 5000000 361 ns/op 48 B/op 1 allocs/op BenchmarkTraffic_GithubStatic 30000 47197 ns/op 18920 B/op 149 allocs/op BenchmarkVulcan_GithubStatic 1000000 1415 ns/op 98 B/op 3 allocs/op BenchmarkZeus_GithubStatic 1000000 2522 ns/op 512 B/op 11 allocs/op BenchmarkAce_GithubParam 3000000 578 ns/op 96 B/op 1 allocs/op BenchmarkBear_GithubParam 1000000 1592 ns/op 464 B/op 5 allocs/op BenchmarkBeego_GithubParam 1000000 2891 ns/op 784 B/op 11 allocs/op BenchmarkBone_GithubParam 300000 6440 ns/op 1456 B/op 16 allocs/op BenchmarkDenco_GithubParam 3000000 514 ns/op 128 B/op 1 allocs/op BenchmarkEcho_GithubParam 5000000 292 ns/op 0 B/op 0 allocs/op BenchmarkGin_GithubParam 10000000 242 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_GithubParam 1000000 2343 ns/op 720 B/op 10 allocs/op BenchmarkGoji_GithubParam 1000000 1566 ns/op 336 B/op 2 allocs/op BenchmarkGoJsonRest_GithubParam 1000000 2828 ns/op 721 B/op 15 allocs/op BenchmarkGoRestful_GithubParam 10000 177711 ns/op 2816 B/op 35 allocs/op BenchmarkGorillaMux_GithubParam 100000 13591 ns/op 816 B/op 9 allocs/op BenchmarkHttpRouter_GithubParam 5000000 352 ns/op 96 B/op 1 allocs/op BenchmarkHttpTreeMux_GithubParam 2000000 973 ns/op 336 B/op 2 allocs/op BenchmarkKocha_GithubParam 2000000 889 ns/op 128 B/op 5 allocs/op BenchmarkMacaron_GithubParam 500000 4047 ns/op 1168 B/op 12 allocs/op BenchmarkMartini_GithubParam 50000 28982 ns/op 1184 B/op 12 allocs/op BenchmarkPat_GithubParam 200000 8747 ns/op 2480 B/op 56 allocs/op BenchmarkPossum_GithubParam 1000000 2158 ns/op 624 B/op 7 allocs/op BenchmarkR2router_GithubParam 1000000 1352 ns/op 432 B/op 6 allocs/op BenchmarkRevel_GithubParam 200000 7673 ns/op 1784 B/op 30 allocs/op BenchmarkRivet_GithubParam 1000000 1573 ns/op 480 B/op 6 allocs/op BenchmarkTango_GithubParam 1000000 2418 ns/op 480 B/op 13 allocs/op BenchmarkTigerTonic_GithubParam 300000 6048 ns/op 1440 B/op 28 allocs/op BenchmarkTraffic_GithubParam 100000 20143 ns/op 6024 B/op 55 allocs/op BenchmarkVulcan_GithubParam 1000000 2224 ns/op 98 B/op 3 allocs/op BenchmarkZeus_GithubParam 500000 4156 ns/op 1312 B/op 12 allocs/op BenchmarkAce_GithubAll 10000 109482 ns/op 13792 B/op 167 allocs/op BenchmarkBear_GithubAll 10000 287490 ns/op 79952 B/op 943 allocs/op BenchmarkBeego_GithubAll 3000 562184 ns/op 146272 B/op 2092 allocs/op BenchmarkBone_GithubAll 500 2578716 ns/op 648016 B/op 8119 allocs/op BenchmarkDenco_GithubAll 20000 94955 ns/op 20224 B/op 167 allocs/op BenchmarkEcho_GithubAll 30000 58705 ns/op 0 B/op 0 allocs/op BenchmarkGin_GithubAll 30000 50991 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_GithubAll 5000 449648 ns/op 133280 B/op 1889 allocs/op BenchmarkGoji_GithubAll 2000 689748 ns/op 56113 B/op 334 allocs/op BenchmarkGoJsonRest_GithubAll 5000 537769 ns/op 135995 B/op 2940 allocs/op BenchmarkGoRestful_GithubAll 100 18410628 ns/op 797236 B/op 7725 allocs/op BenchmarkGorillaMux_GithubAll 200 8036360 ns/op 153137 B/op 1791 allocs/op BenchmarkHttpRouter_GithubAll 20000 63506 ns/op 13792 B/op 167 allocs/op BenchmarkHttpTreeMux_GithubAll 10000 165927 ns/op 56112 B/op 334 allocs/op BenchmarkKocha_GithubAll 10000 171362 ns/op 23304 B/op 843 allocs/op BenchmarkMacaron_GithubAll 2000 817008 ns/op 224960 B/op 2315 allocs/op BenchmarkMartini_GithubAll 100 12609209 ns/op 237952 B/op 2686 allocs/op BenchmarkPat_GithubAll 300 4830398 ns/op 1504101 B/op 32222 allocs/op BenchmarkPossum_GithubAll 10000 301716 ns/op 97440 B/op 812 allocs/op BenchmarkR2router_GithubAll 10000 270691 ns/op 77328 B/op 1182 allocs/op BenchmarkRevel_GithubAll 1000 1491919 ns/op 345553 B/op 5918 allocs/op BenchmarkRivet_GithubAll 10000 283860 ns/op 84272 B/op 1079 allocs/op BenchmarkTango_GithubAll 5000 473821 ns/op 87078 B/op 2470 allocs/op BenchmarkTigerTonic_GithubAll 2000 1120131 ns/op 241088 B/op 6052 allocs/op BenchmarkTraffic_GithubAll 200 8708979 ns/op 2664762 B/op 22390 allocs/op BenchmarkVulcan_GithubAll 5000 353392 ns/op 19894 B/op 609 allocs/op BenchmarkZeus_GithubAll 2000 944234 ns/op 300688 B/op 2648 allocs/op BenchmarkAce_GPlusStatic 5000000 251 ns/op 0 B/op 0 allocs/op BenchmarkBear_GPlusStatic 3000000 415 ns/op 72 B/op 3 allocs/op BenchmarkBeego_GPlusStatic 1000000 1416 ns/op 352 B/op 7 allocs/op BenchmarkBone_GPlusStatic 10000000 192 ns/op 32 B/op 1 allocs/op BenchmarkDenco_GPlusStatic 30000000 47.6 ns/op 0 B/op 0 allocs/op BenchmarkEcho_GPlusStatic 10000000 131 ns/op 0 B/op 0 allocs/op BenchmarkGin_GPlusStatic 10000000 131 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_GPlusStatic 1000000 1035 ns/op 288 B/op 6 allocs/op BenchmarkGoji_GPlusStatic 5000000 304 ns/op 0 B/op 0 allocs/op BenchmarkGoJsonRest_GPlusStatic 1000000 1286 ns/op 337 B/op 12 allocs/op BenchmarkGoRestful_GPlusStatic 200000 9649 ns/op 2160 B/op 30 allocs/op BenchmarkGorillaMux_GPlusStatic 1000000 2346 ns/op 464 B/op 8 allocs/op BenchmarkHttpRouter_GPlusStatic 30000000 42.7 ns/op 0 B/op 0 allocs/op BenchmarkHttpTreeMux_GPlusStatic 30000000 49.5 ns/op 0 B/op 0 allocs/op BenchmarkKocha_GPlusStatic 20000000 74.8 ns/op 0 B/op 0 allocs/op BenchmarkMacaron_GPlusStatic 1000000 2520 ns/op 736 B/op 8 allocs/op BenchmarkMartini_GPlusStatic 300000 5310 ns/op 832 B/op 11 allocs/op BenchmarkPat_GPlusStatic 5000000 398 ns/op 96 B/op 2 allocs/op BenchmarkPossum_GPlusStatic 1000000 1434 ns/op 480 B/op 4 allocs/op BenchmarkR2router_GPlusStatic 2000000 646 ns/op 144 B/op 5 allocs/op BenchmarkRevel_GPlusStatic 300000 6172 ns/op 1272 B/op 25 allocs/op BenchmarkRivet_GPlusStatic 3000000 444 ns/op 112 B/op 2 allocs/op BenchmarkTango_GPlusStatic 1000000 1400 ns/op 208 B/op 10 allocs/op BenchmarkTigerTonic_GPlusStatic 10000000 213 ns/op 32 B/op 1 allocs/op BenchmarkTraffic_GPlusStatic 1000000 3091 ns/op 1208 B/op 16 allocs/op BenchmarkVulcan_GPlusStatic 2000000 863 ns/op 98 B/op 3 allocs/op BenchmarkZeus_GPlusStatic 10000000 237 ns/op 16 B/op 1 allocs/op BenchmarkAce_GPlusParam 3000000 435 ns/op 64 B/op 1 allocs/op BenchmarkBear_GPlusParam 1000000 1205 ns/op 448 B/op 5 allocs/op BenchmarkBeego_GPlusParam 1000000 2494 ns/op 720 B/op 10 allocs/op BenchmarkBone_GPlusParam 1000000 1126 ns/op 384 B/op 3 allocs/op BenchmarkDenco_GPlusParam 5000000 325 ns/op 64 B/op 1 allocs/op BenchmarkEcho_GPlusParam 10000000 168 ns/op 0 B/op 0 allocs/op BenchmarkGin_GPlusParam 10000000 170 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_GPlusParam 1000000 1895 ns/op 656 B/op 9 allocs/op BenchmarkGoji_GPlusParam 1000000 1071 ns/op 336 B/op 2 allocs/op BenchmarkGoJsonRest_GPlusParam 1000000 2282 ns/op 657 B/op 14 allocs/op BenchmarkGoRestful_GPlusParam 100000 19400 ns/op 2560 B/op 33 allocs/op BenchmarkGorillaMux_GPlusParam 500000 5001 ns/op 784 B/op 9 allocs/op BenchmarkHttpRouter_GPlusParam 10000000 240 ns/op 64 B/op 1 allocs/op BenchmarkHttpTreeMux_GPlusParam 2000000 797 ns/op 336 B/op 2 allocs/op BenchmarkKocha_GPlusParam 3000000 505 ns/op 56 B/op 3 allocs/op BenchmarkMacaron_GPlusParam 1000000 3668 ns/op 1104 B/op 11 allocs/op BenchmarkMartini_GPlusParam 200000 10672 ns/op 1152 B/op 12 allocs/op BenchmarkPat_GPlusParam 1000000 2376 ns/op 704 B/op 14 allocs/op BenchmarkPossum_GPlusParam 1000000 2090 ns/op 624 B/op 7 allocs/op BenchmarkR2router_GPlusParam 1000000 1233 ns/op 432 B/op 6 allocs/op BenchmarkRevel_GPlusParam 200000 6778 ns/op 1704 B/op 28 allocs/op BenchmarkRivet_GPlusParam 1000000 1279 ns/op 464 B/op 5 allocs/op BenchmarkTango_GPlusParam 1000000 1981 ns/op 272 B/op 10 allocs/op BenchmarkTigerTonic_GPlusParam 500000 3893 ns/op 1064 B/op 19 allocs/op BenchmarkTraffic_GPlusParam 200000 6585 ns/op 2000 B/op 23 allocs/op BenchmarkVulcan_GPlusParam 1000000 1233 ns/op 98 B/op 3 allocs/op BenchmarkZeus_GPlusParam 1000000 1350 ns/op 368 B/op 3 allocs/op BenchmarkAce_GPlus2Params 3000000 512 ns/op 64 B/op 1 allocs/op BenchmarkBear_GPlus2Params 1000000 1564 ns/op 464 B/op 5 allocs/op BenchmarkBeego_GPlus2Params 1000000 3043 ns/op 784 B/op 11 allocs/op BenchmarkBone_GPlus2Params 1000000 3152 ns/op 736 B/op 7 allocs/op BenchmarkDenco_GPlus2Params 3000000 431 ns/op 64 B/op 1 allocs/op BenchmarkEcho_GPlus2Params 5000000 247 ns/op 0 B/op 0 allocs/op BenchmarkGin_GPlus2Params 10000000 219 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_GPlus2Params 1000000 2363 ns/op 720 B/op 10 allocs/op BenchmarkGoji_GPlus2Params 1000000 1540 ns/op 336 B/op 2 allocs/op BenchmarkGoJsonRest_GPlus2Params 1000000 2872 ns/op 721 B/op 15 allocs/op BenchmarkGoRestful_GPlus2Params 100000 23030 ns/op 2720 B/op 35 allocs/op BenchmarkGorillaMux_GPlus2Params 200000 10516 ns/op 816 B/op 9 allocs/op BenchmarkHttpRouter_GPlus2Params 5000000 273 ns/op 64 B/op 1 allocs/op BenchmarkHttpTreeMux_GPlus2Params 2000000 939 ns/op 336 B/op 2 allocs/op BenchmarkKocha_GPlus2Params 2000000 844 ns/op 128 B/op 5 allocs/op BenchmarkMacaron_GPlus2Params 500000 3914 ns/op 1168 B/op 12 allocs/op BenchmarkMartini_GPlus2Params 50000 35759 ns/op 1280 B/op 16 allocs/op BenchmarkPat_GPlus2Params 200000 7089 ns/op 2304 B/op 41 allocs/op BenchmarkPossum_GPlus2Params 1000000 2093 ns/op 624 B/op 7 allocs/op BenchmarkR2router_GPlus2Params 1000000 1320 ns/op 432 B/op 6 allocs/op BenchmarkRevel_GPlus2Params 200000 7351 ns/op 1800 B/op 30 allocs/op BenchmarkRivet_GPlus2Params 1000000 1485 ns/op 480 B/op 6 allocs/op BenchmarkTango_GPlus2Params 1000000 2111 ns/op 448 B/op 12 allocs/op BenchmarkTigerTonic_GPlus2Params 300000 6271 ns/op 1528 B/op 28 allocs/op BenchmarkTraffic_GPlus2Params 100000 14886 ns/op 3312 B/op 34 allocs/op BenchmarkVulcan_GPlus2Params 1000000 1883 ns/op 98 B/op 3 allocs/op BenchmarkZeus_GPlus2Params 1000000 2686 ns/op 784 B/op 6 allocs/op BenchmarkAce_GPlusAll 300000 5912 ns/op 640 B/op 11 allocs/op BenchmarkBear_GPlusAll 100000 16448 ns/op 5072 B/op 61 allocs/op BenchmarkBeego_GPlusAll 50000 32916 ns/op 8976 B/op 129 allocs/op BenchmarkBone_GPlusAll 50000 25836 ns/op 6992 B/op 76 allocs/op BenchmarkDenco_GPlusAll 500000 4462 ns/op 672 B/op 11 allocs/op BenchmarkEcho_GPlusAll 500000 2806 ns/op 0 B/op 0 allocs/op BenchmarkGin_GPlusAll 500000 2579 ns/op 0 B/op 0 allocs/op BenchmarkGocraftWeb_GPlusAll 50000 25223 ns/op 8144 B/op 116 allocs/op BenchmarkGoji_GPlusAll 100000 14237 ns/op 3696 B/op 22 allocs/op BenchmarkGoJsonRest_GPlusAll 50000 29227 ns/op 8221 B/op 183 allocs/op BenchmarkGoRestful_GPlusAll 10000 203144 ns/op 36064 B/op 441 allocs/op BenchmarkGorillaMux_GPlusAll 20000 80906 ns/op 9712 B/op 115 allocs/op BenchmarkHttpRouter_GPlusAll 500000 3040 ns/op 640 B/op 11 allocs/op BenchmarkHttpTreeMux_GPlusAll 200000 9627 ns/op 3696 B/op 22 allocs/op BenchmarkKocha_GPlusAll 200000 8108 ns/op 976 B/op 43 allocs/op BenchmarkMacaron_GPlusAll 30000 48083 ns/op 13968 B/op 142 allocs/op BenchmarkMartini_GPlusAll 10000 196978 ns/op 15072 B/op 178 allocs/op BenchmarkPat_GPlusAll 30000 58865 ns/op 16880 B/op 343 allocs/op BenchmarkPossum_GPlusAll 100000 19685 ns/op 6240 B/op 52 allocs/op BenchmarkR2router_GPlusAll 100000 16251 ns/op 5040 B/op 76 allocs/op BenchmarkRevel_GPlusAll 20000 93489 ns/op 21656 B/op 368 allocs/op BenchmarkRivet_GPlusAll 100000 16907 ns/op 5408 B/op 64 allocs/op ``` gin-1.2/CHANGELOG.md000066400000000000000000000157661312613627200137640ustar00rootroot00000000000000# CHANGELOG ### Gin 1.2 - [NEW] Switch from godeps to govendor - [NEW] Add support for Let's Encrypt via gin-gonic/autotls - [NEW] Improve README examples and add extra at examples folder - [NEW] Improved support with App Engine - [NEW] Add custom template delimiters, see #860 - [NEW] Add Template Func Maps, see #962 - [NEW] Add \*context.Handler(), see #928 - [NEW] Add \*context.GetRawData() - [NEW] Add \*context.GetHeader() (request) - [NEW] Add \*context.AbortWithStatusJSON() (JSON content type) - [NEW] Add \*context.Keys type cast helpers - [NEW] Add \*context.ShouldBindWith() - [NEW] Add \*context.MustBindWith() - [NEW] Add \*engine.SetFuncMap() - [DEPRECATE] On next release: \*context.BindWith(), see #855 - [FIX] Refactor render - [FIX] Reworked tests - [FIX] logger now supports cygwin - [FIX] Use X-Forwarded-For before X-Real-Ip - [FIX] time.Time binding (#904) ### Gin 1.1.4 - [NEW] Support google appengine for IsTerminal func ### Gin 1.1.3 - [FIX] Reverted Logger: skip ANSI color commands ### Gin 1.1 - [NEW] Implement QueryArray and PostArray methods - [NEW] Refactor GetQuery and GetPostForm - [NEW] Add contribution guide - [FIX] Corrected typos in README - [FIX] Removed additional Iota - [FIX] Changed imports to gopkg instead of github in README (#733) - [FIX] Logger: skip ANSI color commands if output is not a tty ### Gin 1.0rc2 (...) - [PERFORMANCE] Fast path for writing Content-Type. - [PERFORMANCE] Much faster 404 routing - [PERFORMANCE] Allocation optimizations - [PERFORMANCE] Faster root tree lookup - [PERFORMANCE] Zero overhead, String() and JSON() rendering. - [PERFORMANCE] Faster ClientIP parsing - [PERFORMANCE] Much faster SSE implementation - [NEW] Benchmarks suite - [NEW] Bind validation can be disabled and replaced with custom validators. - [NEW] More flexible HTML render - [NEW] Multipart and PostForm bindings - [NEW] Adds method to return all the registered routes - [NEW] Context.HandlerName() returns the main handler's name - [NEW] Adds Error.IsType() helper - [FIX] Binding multipart form - [FIX] Integration tests - [FIX] Crash when binding non struct object in Context. - [FIX] RunTLS() implementation - [FIX] Logger() unit tests - [FIX] Adds SetHTMLTemplate() warning - [FIX] Context.IsAborted() - [FIX] More unit tests - [FIX] JSON, XML, HTML renders accept custom content-types - [FIX] gin.AbortIndex is unexported - [FIX] Better approach to avoid directory listing in StaticFS() - [FIX] Context.ClientIP() always returns the IP with trimmed spaces. - [FIX] Better warning when running in debug mode. - [FIX] Google App Engine integration. debugPrint does not use os.Stdout - [FIX] Fixes integer overflow in error type - [FIX] Error implements the json.Marshaller interface - [FIX] MIT license in every file ### Gin 1.0rc1 (May 22, 2015) - [PERFORMANCE] Zero allocation router - [PERFORMANCE] Faster JSON, XML and text rendering - [PERFORMANCE] Custom hand optimized HttpRouter for Gin - [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations - [NEW] Built-in support for golang.org/x/net/context - [NEW] Any(path, handler). Create a route that matches any path - [NEW] Refactored rendering pipeline (faster and static typeded) - [NEW] Refactored errors API - [NEW] IndentedJSON() prints pretty JSON - [NEW] Added gin.DefaultWriter - [NEW] UNIX socket support - [NEW] RouterGroup.BasePath is exposed - [NEW] JSON validation using go-validate-yourself (very powerful options) - [NEW] Completed suite of unit tests - [NEW] HTTP streaming with c.Stream() - [NEW] StaticFile() creates a router for serving just one file. - [NEW] StaticFS() has an option to disable directory listing. - [NEW] StaticFS() for serving static files through virtual filesystems - [NEW] Server-Sent Events native support - [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler - [NEW] Added LoggerWithWriter() middleware - [NEW] Added RecoveryWithWriter() middleware - [NEW] Added DefaultPostFormValue() - [NEW] Added DefaultFormValue() - [NEW] Added DefaultParamValue() - [FIX] BasicAuth() when using custom realm - [FIX] Bug when serving static files in nested routing group - [FIX] Redirect using built-in http.Redirect() - [FIX] Logger when printing the requested path - [FIX] Documentation typos - [FIX] Context.Engine renamed to Context.engine - [FIX] Better debugging messages - [FIX] ErrorLogger - [FIX] Debug HTTP render - [FIX] Refactored binding and render modules - [FIX] Refactored Context initialization - [FIX] Refactored BasicAuth() - [FIX] NoMethod/NoRoute handlers - [FIX] Hijacking http - [FIX] Better support for Google App Engine (using log instead of fmt) ### Gin 0.6 (Mar 9, 2015) - [NEW] Support multipart/form-data - [NEW] NoMethod handler - [NEW] Validate sub structures - [NEW] Support for HTTP Realm Auth - [FIX] Unsigned integers in binding - [FIX] Improve color logger ### Gin 0.5 (Feb 7, 2015) - [NEW] Content Negotiation - [FIX] Solved security bug that allow a client to spoof ip - [FIX] Fix unexported/ignored fields in binding ### Gin 0.4 (Aug 21, 2014) - [NEW] Development mode - [NEW] Unit tests - [NEW] Add Content.Redirect() - [FIX] Deferring WriteHeader() - [FIX] Improved documentation for model binding ### Gin 0.3 (Jul 18, 2014) - [PERFORMANCE] Normal log and error log are printed in the same call. - [PERFORMANCE] Improve performance of NoRouter() - [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults. - [NEW] Flexible rendering API - [NEW] Add Context.File() - [NEW] Add shorcut RunTLS() for http.ListenAndServeTLS - [FIX] Rename NotFound404() to NoRoute() - [FIX] Errors in context are purged - [FIX] Adds HEAD method in Static file serving - [FIX] Refactors Static() file serving - [FIX] Using keyed initialization to fix app-engine integration - [FIX] Can't unmarshal JSON array, #63 - [FIX] Renaming Context.Req to Context.Request - [FIX] Check application/x-www-form-urlencoded when parsing form ### Gin 0.2b (Jul 08, 2014) - [PERFORMANCE] Using sync.Pool to allocatio/gc overhead - [NEW] Travis CI integration - [NEW] Completely new logger - [NEW] New API for serving static files. gin.Static() - [NEW] gin.H() can be serialized into XML - [NEW] Typed errors. Errors can be typed. Internet/external/custom. - [NEW] Support for Godeps - [NEW] Travis/Godocs badges in README - [NEW] New Bind() and BindWith() methods for parsing request body. - [NEW] Add Content.Copy() - [NEW] Add context.LastError() - [NEW] Add shorcut for OPTIONS HTTP method - [FIX] Tons of README fixes - [FIX] Header is written before body - [FIX] BasicAuth() and changes API a little bit - [FIX] Recovery() middleware only prints panics - [FIX] Context.Get() does not panic anymore. Use MustGet() instead. - [FIX] Multiple http.WriteHeader() in NotFound handlers - [FIX] Engine.Run() panics if http server can't be setted up - [FIX] Crash when route path doesn't start with '/' - [FIX] Do not update header when status code is negative - [FIX] Setting response headers before calling WriteHeader in context.String() - [FIX] Add MIT license - [FIX] Changes behaviour of ErrorLogger() and Logger() gin-1.2/LICENSE000066400000000000000000000021031312613627200131350ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 Manuel Martínez-Almeida Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. gin-1.2/Makefile000066400000000000000000000025311312613627200135750ustar00rootroot00000000000000GOFMT ?= gofmt "-s" PACKAGES ?= $(shell go list ./... | grep -v /vendor/) GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*") all: build install: deps govendor sync .PHONY: test test: go test -v -covermode=count -coverprofile=coverage.out .PHONY: fmt fmt: $(GOFMT) -w $(GOFILES) .PHONY: fmt-check fmt-check: # get all go files and run go fmt on them @diff=$$($(GOFMT) -d $(GOFILES)); \ if [ -n "$$diff" ]; then \ echo "Please run 'make fmt' and commit the result:"; \ echo "$${diff}"; \ exit 1; \ fi; vet: go vet $(PACKAGES) deps: @hash govendor > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ go get -u github.com/kardianos/govendor; \ fi @hash embedmd > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ go get -u github.com/campoy/embedmd; \ fi embedmd: embedmd -d *.md .PHONY: lint lint: @hash golint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ go get -u github.com/golang/lint/golint; \ fi for PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done; .PHONY: misspell-check misspell-check: @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ go get -u github.com/client9/misspell/cmd/misspell; \ fi misspell -error $(GOFILES) .PHONY: misspell misspell: @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ go get -u github.com/client9/misspell/cmd/misspell; \ fi misspell -w $(GOFILES) gin-1.2/README.md000066400000000000000000000557641312613627200134340ustar00rootroot00000000000000# Gin Web Framework [![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin) [![codecov](https://codecov.io/gh/gin-gonic/gin/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-gonic/gin) [![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin) [![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin) [![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin. ![Gin console logger](https://gin-gonic.github.io/gin/other/console.png) ```sh $ cat test.go ``` ```go package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 } ``` ## Benchmarks Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) [See all benchmarks](/BENCHMARKS.md) Benchmark name | (1) | (2) | (3) | (4) --------------------------------|----------:|----------:|----------:|------: BenchmarkAce_GithubAll | 10000 | 109482 | 13792 | 167 BenchmarkBear_GithubAll | 10000 | 287490 | 79952 | 943 BenchmarkBeego_GithubAll | 3000 | 562184 | 146272 | 2092 BenchmarkBone_GithubAll | 500 | 2578716 | 648016 | 8119 BenchmarkDenco_GithubAll | 20000 | 94955 | 20224 | 167 BenchmarkEcho_GithubAll | 30000 | 58705 | 0 | 0 **BenchmarkGin_GithubAll** | **30000** | **50991** | **0** | **0** BenchmarkGocraftWeb_GithubAll | 5000 | 449648 | 133280 | 1889 BenchmarkGoji_GithubAll | 2000 | 689748 | 56113 | 334 BenchmarkGoJsonRest_GithubAll | 5000 | 537769 | 135995 | 2940 BenchmarkGoRestful_GithubAll | 100 | 18410628 | 797236 | 7725 BenchmarkGorillaMux_GithubAll | 200 | 8036360 | 153137 | 1791 BenchmarkHttpRouter_GithubAll | 20000 | 63506 | 13792 | 167 BenchmarkHttpTreeMux_GithubAll | 10000 | 165927 | 56112 | 334 BenchmarkKocha_GithubAll | 10000 | 171362 | 23304 | 843 BenchmarkMacaron_GithubAll | 2000 | 817008 | 224960 | 2315 BenchmarkMartini_GithubAll | 100 | 12609209 | 237952 | 2686 BenchmarkPat_GithubAll | 300 | 4830398 | 1504101 | 32222 BenchmarkPossum_GithubAll | 10000 | 301716 | 97440 | 812 BenchmarkR2router_GithubAll | 10000 | 270691 | 77328 | 1182 BenchmarkRevel_GithubAll | 1000 | 1491919 | 345553 | 5918 BenchmarkRivet_GithubAll | 10000 | 283860 | 84272 | 1079 BenchmarkTango_GithubAll | 5000 | 473821 | 87078 | 2470 BenchmarkTigerTonic_GithubAll | 2000 | 1120131 | 241088 | 6052 BenchmarkTraffic_GithubAll | 200 | 8708979 | 2664762 | 22390 BenchmarkVulcan_GithubAll | 5000 | 353392 | 19894 | 609 BenchmarkZeus_GithubAll | 2000 | 944234 | 300688 | 2648 (1): Total Repetitions (2): Single Repetition Duration (ns/op) (3): Heap Memory (B/op) (4): Average Allocations per Repetition (allocs/op) ## Gin v1. stable - [x] Zero allocation router. - [x] Still the fastest http router and framework. From routing to writing. - [x] Complete suite of unit tests - [x] Battle tested - [x] API frozen, new releases will not break your code. ## Start using it 1. Download and install it: ```sh $ go get github.com/gin-gonic/gin ``` 2. Import it in your code: ```go import "github.com/gin-gonic/gin" ``` 3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`. ```go import "net/http" ``` ## API Examples ### Using GET, POST, PUT, PATCH, DELETE and OPTIONS ```go func main() { // Disable Console Color // gin.DisableConsoleColor() // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/someGet", getting) router.POST("/somePost", posting) router.PUT("/somePut", putting) router.DELETE("/someDelete", deleting) router.PATCH("/somePatch", patching) router.HEAD("/someHead", head) router.OPTIONS("/someOptions", options) // By default it serves on :8080 unless a // PORT environment variable was defined. router.Run() // router.Run(":3000") for a hard coded port } ``` ### Parameters in path ```go func main() { router := gin.Default() // This handler will match /user/john but will not match neither /user/ or /user router.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) // However, this one will match /user/john/ and also /user/john/send // If no other routers match /user/john, it will redirect to /user/john/ router.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") message := name + " is " + action c.String(http.StatusOK, message) }) router.Run(":8080") } ``` ### Querystring parameters ```go func main() { router := gin.Default() // Query string parameters are parsed using the existing underlying request object. // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe router.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname", "Guest") lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname") c.String(http.StatusOK, "Hello %s %s", firstname, lastname) }) router.Run(":8080") } ``` ### Multipart/Urlencoded Form ```go func main() { router := gin.Default() router.POST("/form_post", func(c *gin.Context) { message := c.PostForm("message") nick := c.DefaultPostForm("nick", "anonymous") c.JSON(200, gin.H{ "status": "posted", "message": message, "nick": nick, }) }) router.Run(":8080") } ``` ### Another example: query + post form ``` POST /post?id=1234&page=1 HTTP/1.1 Content-Type: application/x-www-form-urlencoded name=manu&message=this_is_great ``` ```go func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { id := c.Query("id") page := c.DefaultQuery("page", "0") name := c.PostForm("name") message := c.PostForm("message") fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message) }) router.Run(":8080") } ``` ``` id: 1234; page: 1; name: manu; message: this_is_great ``` ### Upload files #### Single file References issue [#774](https://github.com/gin-gonic/gin/issues/774) and detail [example code](examples/upload-file/single). ```go func main() { router := gin.Default() router.POST("/upload", func(c *gin.Context) { // single file file, _ := c.FormFile("file") log.Println(file.Filename) c.String(http.StatusOK, fmt.Printf("'%s' uploaded!", file.Filename)) }) router.Run(":8080") } ``` How to `curl`: ```bash curl -X POST http://localhost:8080/upload \ -F "file=@/Users/appleboy/test.zip" \ -H "Content-Type: multipart/form-data" ``` #### Multiple files See the detail [example code](examples/upload-file/multiple). ```go func main() { router := gin.Default() router.POST("/upload", func(c *gin.Context) { // Multipart form form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { log.Println(file.Filename) } c.String(http.StatusOK, fmt.Printf("%d files uploaded!", len(files))) }) router.Run(":8080") } ``` How to `curl`: ```bash curl -X POST http://localhost:8080/upload \ -F "upload[]=@/Users/appleboy/test1.zip" \ -F "upload[]=@/Users/appleboy/test2.zip" \ -H "Content-Type: multipart/form-data" ``` ### Grouping routes ```go func main() { router := gin.Default() // Simple group: v1 v1 := router.Group("/v1") { v1.POST("/login", loginEndpoint) v1.POST("/submit", submitEndpoint) v1.POST("/read", readEndpoint) } // Simple group: v2 v2 := router.Group("/v2") { v2.POST("/login", loginEndpoint) v2.POST("/submit", submitEndpoint) v2.POST("/read", readEndpoint) } router.Run(":8080") } ``` ### Blank Gin without middleware by default Use ```go r := gin.New() ``` instead of ```go r := gin.Default() ``` ### Using middleware ```go func main() { // Creates a router without any middleware by default r := gin.New() // Global middleware r.Use(gin.Logger()) r.Use(gin.Recovery()) // Per route middleware, you can add as many as you desire. r.GET("/benchmark", MyBenchLogger(), benchEndpoint) // Authorization group // authorized := r.Group("/", AuthRequired()) // exactly the same as: authorized := r.Group("/") // per group middleware! in this case we use the custom created // AuthRequired() middleware just in the "authorized" group. authorized.Use(AuthRequired()) { authorized.POST("/login", loginEndpoint) authorized.POST("/submit", submitEndpoint) authorized.POST("/read", readEndpoint) // nested group testing := authorized.Group("testing") testing.GET("/analytics", analyticsEndpoint) } // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Model binding and validation To bind a request body into a type, use model binding. We currently support binding of JSON, XML and standard form values (foo=bar&boo=baz). Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`. When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use BindWith. You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, the current request will fail with an error. ```go // Binding from JSON type Login struct { User string `form:"user" json:"user" binding:"required"` Password string `form:"password" json:"password" binding:"required"` } func main() { router := gin.Default() // Example for binding JSON ({"user": "manu", "password": "123"}) router.POST("/loginJSON", func(c *gin.Context) { var json Login if c.BindJSON(&json) == nil { if json.User == "manu" && json.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } } }) // Example for binding a HTML form (user=manu&password=123) router.POST("/loginForm", func(c *gin.Context) { var form Login // This will infer what binder to use depending on the content-type header. if c.Bind(&form) == nil { if form.User == "manu" && form.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } } }) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` ### Bind Query String See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292). ```go package main import "log" import "github.com/gin-gonic/gin" type Person struct { Name string `form:"name"` Address string `form:"address"` } func main() { route := gin.Default() route.GET("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person // If `GET`, only `Form` binding engine (`query`) used. // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`). // See more at https://github.com/gin-gonic/gin/blob/develop/binding/binding.go#L45 if c.Bind(&person) == nil { log.Println(person.Name) log.Println(person.Address) } c.String(200, "Success") } ``` ### Multipart/Urlencoded binding ```go package main import ( "github.com/gin-gonic/gin" ) type LoginForm struct { User string `form:"user" binding:"required"` Password string `form:"password" binding:"required"` } func main() { router := gin.Default() router.POST("/login", func(c *gin.Context) { // you can bind multipart form with explicit binding declaration: // c.MustBindWith(&form, binding.Form) // or you can simply use autobinding with Bind method: var form LoginForm // in this case proper binding will be automatically selected if c.Bind(&form) == nil { if form.User == "user" && form.Password == "password" { c.JSON(200, gin.H{"status": "you are logged in"}) } else { c.JSON(401, gin.H{"status": "unauthorized"}) } } }) router.Run(":8080") } ``` Test it with: ```sh $ curl -v --form user=user --form password=password http://localhost:8080/login ``` ### XML, JSON and YAML rendering ```go func main() { r := gin.Default() // gin.H is a shortcut for map[string]interface{} r.GET("/someJSON", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/moreJSON", func(c *gin.Context) { // You also can use a struct var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // Note that msg.Name becomes "user" in the JSON // Will output : {"user": "Lena", "Message": "hey", "Number": 123} c.JSON(http.StatusOK, msg) }) r.GET("/someXML", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Serving static files ```go func main() { router := gin.Default() router.Static("/assets", "./assets") router.StaticFS("/more_static", http.Dir("my_file_system")) router.StaticFile("/favicon.ico", "./resources/favicon.ico") // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` ### HTML rendering Using LoadHTMLGlob() or LoadHTMLFiles() ```go func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", }) }) router.Run(":8080") } ``` templates/index.tmpl ```html

{{ .title }}

``` Using templates with same name in different directories ```go func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ "title": "Posts", }) }) router.GET("/users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ "title": "Users", }) }) router.Run(":8080") } ``` templates/posts/index.tmpl ```html {{ define "posts/index.tmpl" }}

{{ .title }}

Using posts/index.tmpl

{{ end }} ``` templates/users/index.tmpl ```html {{ define "users/index.tmpl" }}

{{ .title }}

Using users/index.tmpl

{{ end }} ``` You can also use your own html template render ```go import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") } ``` You may use custom delims ```go r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates")) ``` #### Add custom template funcs main.go ```go ... func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d/%02d/%02d", year, month, day) } ... router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) ... router.GET("/raw", func(c *Context) { c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) ... ``` raw.tmpl ```html Date: {[{.now | formatAsDate}]} ``` Result: ``` Date: 2017/07/01 ``` ### Multitemplate Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`. ### Redirects Issuing a HTTP redirect is easy: ```go r.GET("/test", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") }) ``` Both internal and external locations are supported. ### Custom Middleware ```go func Logger() gin.HandlerFunc { return func(c *gin.Context) { t := time.Now() // Set example variable c.Set("example", "12345") // before request c.Next() // after request latency := time.Since(t) log.Print(latency) // access the status we are sending status := c.Writer.Status() log.Println(status) } } func main() { r := gin.New() r.Use(Logger()) r.GET("/test", func(c *gin.Context) { example := c.MustGet("example").(string) // it would print: "12345" log.Println(example) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Using BasicAuth() middleware ```go // simulate some private data var secrets = gin.H{ "foo": gin.H{"email": "foo@bar.com", "phone": "123433"}, "austin": gin.H{"email": "austin@example.com", "phone": "666"}, "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"}, } func main() { r := gin.Default() // Group using gin.BasicAuth() middleware // gin.Accounts is a shortcut for map[string]string authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{ "foo": "bar", "austin": "1234", "lena": "hello2", "manu": "4321", })) // /admin/secrets endpoint // hit "localhost:8080/admin/secrets authorized.GET("/secrets", func(c *gin.Context) { // get user, it was set by the BasicAuth middleware user := c.MustGet(gin.AuthUserKey).(string) if secret, ok := secrets[user]; ok { c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret}) } else { c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("}) } }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Goroutines inside a middleware When starting inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy. ```go func main() { r := gin.Default() r.GET("/long_async", func(c *gin.Context) { // create copy to be used inside the goroutine cCp := c.Copy() go func() { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) // note that you are using the copied context "cCp", IMPORTANT log.Println("Done! in path " + cCp.Request.URL.Path) }() }) r.GET("/long_sync", func(c *gin.Context) { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) // since we are NOT using a goroutine, we do not have to copy the context log.Println("Done! in path " + c.Request.URL.Path) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Custom HTTP configuration Use `http.ListenAndServe()` directly, like this: ```go func main() { router := gin.Default() http.ListenAndServe(":8080", router) } ``` or ```go func main() { router := gin.Default() s := &http.Server{ Addr: ":8080", Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() } ``` ### Support Let's Encrypt example for 1-line LetsEncrypt HTTPS servers. [embedmd]:# (examples/auto-tls/example1.go go) ```go package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) log.Fatal(autotls.Run(r, "example1.com", "example2.com")) } ``` example for custom autocert manager. [embedmd]:# (examples/auto-tls/example2.go go) ```go package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" "golang.org/x/crypto/acme/autocert" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) m := autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"), Cache: autocert.DirCache("/var/www/.cache"), } log.Fatal(autotls.RunWithManager(r, m)) } ``` ### Graceful restart or stop Do you want to graceful restart or stop your web server? There are some ways this can be done. We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details. ```go router := gin.Default() router.GET("/", handler) // [...] endless.ListenAndServe(":4242", router) ``` An alternative to endless: * [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. * [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server. * [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers. If you are using Go 1.8, you may not need to use this library! Consider using http.Server's built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. See the full [graceful-shutdown](./examples/graceful-shutdown) example with gin. [embedmd]:# (examples/graceful-shutdown/graceful-shutdown/server.go go) ```go // +build go1.8 package main import ( "context" "log" "net/http" "os" "os/signal" "time" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { time.Sleep(5 * time.Second) c.String(http.StatusOK, "Welcome Gin Server") }) srv := &http.Server{ Addr: ":8080", Handler: router, } go func() { // service connections if err := srv.ListenAndServe(); err != nil { log.Printf("listen: %s\n", err) } }() // Wait for interrupt signal to gracefully shutdown the server with // a timeout of 5 seconds. quit := make(chan os.Signal) signal.Notify(quit, os.Interrupt) <-quit log.Println("Shutdown Server ...") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server Shutdown:", err) } log.Println("Server exist") } ``` ## Contributing - With issues: - Use the search tool before opening a new issue. - Please provide source code and commit sha if you found a bug. - Review existing issues and provide feedback or react to them. - With pull requests: - Open your pull request against develop - Your pull request should have no more than two commits, if not you should squash them. - It should pass all tests in the available continuous integrations systems such as TravisCI. - You should add/modify tests to cover your proposed code changes. - If your pull request contains a new feature, please document it on the README. ## Users Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework. * [drone](https://github.com/drone/drone): Drone is a Continuous Delivery platform built on Docker, written in Go * [gorush](https://github.com/appleboy/gorush): A push notification server written in Go. gin-1.2/auth.go000066400000000000000000000054421312613627200134310ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "crypto/subtle" "encoding/base64" "strconv" ) const AuthUserKey = "user" type ( Accounts map[string]string authPair struct { Value string User string } authPairs []authPair ) func (a authPairs) searchCredential(authValue string) (string, bool) { if len(authValue) == 0 { return "", false } for _, pair := range a { if pair.Value == authValue { return pair.User, true } } return "", false } // BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where // the key is the user name and the value is the password, as well as the name of the Realm. // If the realm is empty, "Authorization Required" will be used by default. // (see http://tools.ietf.org/html/rfc2617#section-1.2) func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { if realm == "" { realm = "Authorization Required" } realm = "Basic realm=" + strconv.Quote(realm) pairs := processAccounts(accounts) return func(c *Context) { // Search user in the slice of allowed credentials user, found := pairs.searchCredential(c.Request.Header.Get("Authorization")) if !found { // Credentials doesn't match, we return 401 and abort handlers chain. c.Header("WWW-Authenticate", realm) c.AbortWithStatus(401) } else { // The user credentials was found, set user's id to key AuthUserKey in this context, the userId can be read later using // c.MustGet(gin.AuthUserKey) c.Set(AuthUserKey, user) } } } // BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where // the key is the user name and the value is the password. func BasicAuth(accounts Accounts) HandlerFunc { return BasicAuthForRealm(accounts, "") } func processAccounts(accounts Accounts) authPairs { assert1(len(accounts) > 0, "Empty list of authorized credentials") pairs := make(authPairs, 0, len(accounts)) for user, password := range accounts { assert1(len(user) > 0, "User can not be empty") value := authorizationHeader(user, password) pairs = append(pairs, authPair{ Value: value, User: user, }) } return pairs } func authorizationHeader(user, password string) string { base := user + ":" + password return "Basic " + base64.StdEncoding.EncodeToString([]byte(base)) } func secureCompare(given, actual string) bool { if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 { return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1 } /* Securely compare actual to itself to keep constant time, but always return false */ return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false } gin-1.2/auth_test.go000066400000000000000000000076521312613627200144750ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "encoding/base64" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestBasicAuth(t *testing.T) { pairs := processAccounts(Accounts{ "admin": "password", "foo": "bar", "bar": "foo", }) assert.Len(t, pairs, 3) assert.Contains(t, pairs, authPair{ User: "bar", Value: "Basic YmFyOmZvbw==", }) assert.Contains(t, pairs, authPair{ User: "foo", Value: "Basic Zm9vOmJhcg==", }) assert.Contains(t, pairs, authPair{ User: "admin", Value: "Basic YWRtaW46cGFzc3dvcmQ=", }) } func TestBasicAuthFails(t *testing.T) { assert.Panics(t, func() { processAccounts(nil) }) assert.Panics(t, func() { processAccounts(Accounts{ "": "password", "foo": "bar", }) }) } func TestBasicAuthSearchCredential(t *testing.T) { pairs := processAccounts(Accounts{ "admin": "password", "foo": "bar", "bar": "foo", }) user, found := pairs.searchCredential(authorizationHeader("admin", "password")) assert.Equal(t, user, "admin") assert.True(t, found) user, found = pairs.searchCredential(authorizationHeader("foo", "bar")) assert.Equal(t, user, "foo") assert.True(t, found) user, found = pairs.searchCredential(authorizationHeader("bar", "foo")) assert.Equal(t, user, "bar") assert.True(t, found) user, found = pairs.searchCredential(authorizationHeader("admins", "password")) assert.Empty(t, user) assert.False(t, found) user, found = pairs.searchCredential(authorizationHeader("foo", "bar ")) assert.Empty(t, user) assert.False(t, found) user, found = pairs.searchCredential("") assert.Empty(t, user) assert.False(t, found) } func TestBasicAuthAuthorizationHeader(t *testing.T) { assert.Equal(t, authorizationHeader("admin", "password"), "Basic YWRtaW46cGFzc3dvcmQ=") } func TestBasicAuthSecureCompare(t *testing.T) { assert.True(t, secureCompare("1234567890", "1234567890")) assert.False(t, secureCompare("123456789", "1234567890")) assert.False(t, secureCompare("12345678900", "1234567890")) assert.False(t, secureCompare("1234567891", "1234567890")) } func TestBasicAuthSucceed(t *testing.T) { accounts := Accounts{"admin": "password"} router := New() router.Use(BasicAuth(accounts)) router.GET("/login", func(c *Context) { c.String(200, c.MustGet(AuthUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/login", nil) req.Header.Set("Authorization", authorizationHeader("admin", "password")) router.ServeHTTP(w, req) assert.Equal(t, w.Code, 200) assert.Equal(t, w.Body.String(), "admin") } func TestBasicAuth401(t *testing.T) { called := false accounts := Accounts{"foo": "bar"} router := New() router.Use(BasicAuth(accounts)) router.GET("/login", func(c *Context) { called = true c.String(200, c.MustGet(AuthUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/login", nil) req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) router.ServeHTTP(w, req) assert.False(t, called) assert.Equal(t, w.Code, 401) assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"Authorization Required\"") } func TestBasicAuth401WithCustomRealm(t *testing.T) { called := false accounts := Accounts{"foo": "bar"} router := New() router.Use(BasicAuthForRealm(accounts, "My Custom \"Realm\"")) router.GET("/login", func(c *Context) { called = true c.String(200, c.MustGet(AuthUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/login", nil) req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) router.ServeHTTP(w, req) assert.False(t, called) assert.Equal(t, w.Code, 401) assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"My Custom \\\"Realm\\\"\"") } gin-1.2/benchmarks_test.go000066400000000000000000000074701312613627200156470ustar00rootroot00000000000000// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "html/template" "net/http" "os" "testing" ) func BenchmarkOneRoute(B *testing.B) { router := New() router.GET("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func BenchmarkRecoveryMiddleware(B *testing.B) { router := New() router.Use(Recovery()) router.GET("/", func(c *Context) {}) runRequest(B, router, "GET", "/") } func BenchmarkLoggerMiddleware(B *testing.B) { router := New() router.Use(LoggerWithWriter(newMockWriter())) router.GET("/", func(c *Context) {}) runRequest(B, router, "GET", "/") } func BenchmarkManyHandlers(B *testing.B) { router := New() router.Use(Recovery(), LoggerWithWriter(newMockWriter())) router.Use(func(c *Context) {}) router.Use(func(c *Context) {}) router.GET("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func Benchmark5Params(B *testing.B) { DefaultWriter = os.Stdout router := New() router.Use(func(c *Context) {}) router.GET("/param/:param1/:params2/:param3/:param4/:param5", func(c *Context) {}) runRequest(B, router, "GET", "/param/path/to/parameter/john/12345") } func BenchmarkOneRouteJSON(B *testing.B) { router := New() data := struct { Status string `json:"status"` }{"ok"} router.GET("/json", func(c *Context) { c.JSON(200, data) }) runRequest(B, router, "GET", "/json") } var htmlContentType = []string{"text/html; charset=utf-8"} func BenchmarkOneRouteHTML(B *testing.B) { router := New() t := template.Must(template.New("index").Parse(`

{{.}}

`)) router.SetHTMLTemplate(t) router.GET("/html", func(c *Context) { c.HTML(200, "index", "hola") }) runRequest(B, router, "GET", "/html") } func BenchmarkOneRouteSet(B *testing.B) { router := New() router.GET("/ping", func(c *Context) { c.Set("key", "value") }) runRequest(B, router, "GET", "/ping") } func BenchmarkOneRouteString(B *testing.B) { router := New() router.GET("/text", func(c *Context) { c.String(200, "this is a plain text") }) runRequest(B, router, "GET", "/text") } func BenchmarkManyRoutesFist(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func BenchmarkManyRoutesLast(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, "OPTIONS", "/ping") } func Benchmark404(B *testing.B) { router := New() router.Any("/something", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func Benchmark404Many(B *testing.B) { router := New() router.GET("/", func(c *Context) {}) router.GET("/path/to/something", func(c *Context) {}) router.GET("/post/:id", func(c *Context) {}) router.GET("/view/:id", func(c *Context) {}) router.GET("/favicon.ico", func(c *Context) {}) router.GET("/robots.txt", func(c *Context) {}) router.GET("/delete/:id", func(c *Context) {}) router.GET("/user/:id/:mode", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, "GET", "/viewfake") } type mockWriter struct { headers http.Header } func newMockWriter() *mockWriter { return &mockWriter{ http.Header{}, } } func (m *mockWriter) Header() (h http.Header) { return m.headers } func (m *mockWriter) Write(p []byte) (n int, err error) { return len(p), nil } func (m *mockWriter) WriteString(s string) (n int, err error) { return len(s), nil } func (m *mockWriter) WriteHeader(int) {} func runRequest(B *testing.B, r *Engine, method, path string) { // create fake request req, err := http.NewRequest(method, path, nil) if err != nil { panic(err) } w := newMockWriter() B.ReportAllocs() B.ResetTimer() for i := 0; i < B.N; i++ { r.ServeHTTP(w, req) } } gin-1.2/binding/000077500000000000000000000000001312613627200135465ustar00rootroot00000000000000gin-1.2/binding/binding.go000066400000000000000000000037601312613627200155150ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import "net/http" const ( MIMEJSON = "application/json" MIMEHTML = "text/html" MIMEXML = "application/xml" MIMEXML2 = "text/xml" MIMEPlain = "text/plain" MIMEPOSTForm = "application/x-www-form-urlencoded" MIMEMultipartPOSTForm = "multipart/form-data" MIMEPROTOBUF = "application/x-protobuf" MIMEMSGPACK = "application/x-msgpack" MIMEMSGPACK2 = "application/msgpack" ) type Binding interface { Name() string Bind(*http.Request, interface{}) error } type StructValidator interface { // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. // If the received type is not a struct, any validation should be skipped and nil must be returned. // If the received type is a struct or pointer to a struct, the validation should be performed. // If the struct is not valid or the validation itself fails, a descriptive error should be returned. // Otherwise nil must be returned. ValidateStruct(interface{}) error } var Validator StructValidator = &defaultValidator{} var ( JSON = jsonBinding{} XML = xmlBinding{} Form = formBinding{} FormPost = formPostBinding{} FormMultipart = formMultipartBinding{} ProtoBuf = protobufBinding{} MsgPack = msgpackBinding{} ) func Default(method, contentType string) Binding { if method == "GET" { return Form } switch contentType { case MIMEJSON: return JSON case MIMEXML, MIMEXML2: return XML case MIMEPROTOBUF: return ProtoBuf case MIMEMSGPACK, MIMEMSGPACK2: return MsgPack default: //case MIMEPOSTForm, MIMEMultipartPOSTForm: return Form } } func validate(obj interface{}) error { if Validator == nil { return nil } return Validator.ValidateStruct(obj) } gin-1.2/binding/binding_test.go000066400000000000000000000145221312613627200165520ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "mime/multipart" "net/http" "testing" "github.com/gin-gonic/gin/binding/example" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" "github.com/ugorji/go/codec" ) type FooStruct struct { Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required"` } type FooBarStruct struct { FooStruct Bar string `msgpack:"bar" json:"bar" form:"bar" xml:"bar" binding:"required"` } func TestBindingDefault(t *testing.T) { assert.Equal(t, Default("GET", ""), Form) assert.Equal(t, Default("GET", MIMEJSON), Form) assert.Equal(t, Default("POST", MIMEJSON), JSON) assert.Equal(t, Default("PUT", MIMEJSON), JSON) assert.Equal(t, Default("POST", MIMEXML), XML) assert.Equal(t, Default("PUT", MIMEXML2), XML) assert.Equal(t, Default("POST", MIMEPOSTForm), Form) assert.Equal(t, Default("PUT", MIMEPOSTForm), Form) assert.Equal(t, Default("POST", MIMEMultipartPOSTForm), Form) assert.Equal(t, Default("PUT", MIMEMultipartPOSTForm), Form) assert.Equal(t, Default("POST", MIMEPROTOBUF), ProtoBuf) assert.Equal(t, Default("PUT", MIMEPROTOBUF), ProtoBuf) assert.Equal(t, Default("POST", MIMEMSGPACK), MsgPack) assert.Equal(t, Default("PUT", MIMEMSGPACK2), MsgPack) } func TestBindingJSON(t *testing.T) { testBodyBinding(t, JSON, "json", "/", "/", `{"foo": "bar"}`, `{"bar": "foo"}`) } func TestBindingForm(t *testing.T) { testFormBinding(t, "POST", "/", "/", "foo=bar&bar=foo", "bar2=foo") } func TestBindingForm2(t *testing.T) { testFormBinding(t, "GET", "/?foo=bar&bar=foo", "/?bar2=foo", "", "") } func TestBindingXML(t *testing.T) { testBodyBinding(t, XML, "xml", "/", "/", "bar", "foo") } func createFormPostRequest() *http.Request { req, _ := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo")) req.Header.Set("Content-Type", MIMEPOSTForm) return req } func createFormMultipartRequest() *http.Request { boundary := "--testboundary" body := new(bytes.Buffer) mw := multipart.NewWriter(body) defer mw.Close() mw.SetBoundary(boundary) mw.WriteField("foo", "bar") mw.WriteField("bar", "foo") req, _ := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body) req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary) return req } func TestBindingFormPost(t *testing.T) { req := createFormPostRequest() var obj FooBarStruct FormPost.Bind(req, &obj) assert.Equal(t, obj.Foo, "bar") assert.Equal(t, obj.Bar, "foo") } func TestBindingFormMultipart(t *testing.T) { req := createFormMultipartRequest() var obj FooBarStruct FormMultipart.Bind(req, &obj) assert.Equal(t, obj.Foo, "bar") assert.Equal(t, obj.Bar, "foo") } func TestBindingProtoBuf(t *testing.T) { test := &example.Test{ Label: proto.String("yes"), } data, _ := proto.Marshal(test) testProtoBodyBinding(t, ProtoBuf, "protobuf", "/", "/", string(data), string(data[1:])) } func TestBindingMsgPack(t *testing.T) { test := FooStruct{ Foo: "bar", } h := new(codec.MsgpackHandle) assert.NotNil(t, h) buf := bytes.NewBuffer([]byte{}) assert.NotNil(t, buf) err := codec.NewEncoder(buf, h).Encode(test) assert.NoError(t, err) data := buf.Bytes() testMsgPackBodyBinding(t, MsgPack, "msgpack", "/", "/", string(data), string(data[1:])) } func TestValidationFails(t *testing.T) { var obj FooStruct req := requestWithBody("POST", "/", `{"bar": "foo"}`) err := JSON.Bind(req, &obj) assert.Error(t, err) } func TestValidationDisabled(t *testing.T) { backup := Validator Validator = nil defer func() { Validator = backup }() var obj FooStruct req := requestWithBody("POST", "/", `{"bar": "foo"}`) err := JSON.Bind(req, &obj) assert.NoError(t, err) } func TestExistsSucceeds(t *testing.T) { type HogeStruct struct { Hoge *int `json:"hoge" binding:"exists"` } var obj HogeStruct req := requestWithBody("POST", "/", `{"hoge": 0}`) err := JSON.Bind(req, &obj) assert.NoError(t, err) } func TestExistsFails(t *testing.T) { type HogeStruct struct { Hoge *int `json:"foo" binding:"exists"` } var obj HogeStruct req := requestWithBody("POST", "/", `{"boen": 0}`) err := JSON.Bind(req, &obj) assert.Error(t, err) } func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) { b := Form assert.Equal(t, b.Name(), "form") obj := FooBarStruct{} req := requestWithBody(method, path, body) if method == "POST" { req.Header.Add("Content-Type", MIMEPOSTForm) } err := b.Bind(req, &obj) assert.NoError(t, err) assert.Equal(t, obj.Foo, "bar") assert.Equal(t, obj.Bar, "foo") obj = FooBarStruct{} req = requestWithBody(method, badPath, badBody) err = JSON.Bind(req, &obj) assert.Error(t, err) } func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) { assert.Equal(t, b.Name(), name) obj := FooStruct{} req := requestWithBody("POST", path, body) err := b.Bind(req, &obj) assert.NoError(t, err) assert.Equal(t, obj.Foo, "bar") obj = FooStruct{} req = requestWithBody("POST", badPath, badBody) err = JSON.Bind(req, &obj) assert.Error(t, err) } func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) { assert.Equal(t, b.Name(), name) obj := example.Test{} req := requestWithBody("POST", path, body) req.Header.Add("Content-Type", MIMEPROTOBUF) err := b.Bind(req, &obj) assert.NoError(t, err) assert.Equal(t, *obj.Label, "yes") obj = example.Test{} req = requestWithBody("POST", badPath, badBody) req.Header.Add("Content-Type", MIMEPROTOBUF) err = ProtoBuf.Bind(req, &obj) assert.Error(t, err) } func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) { assert.Equal(t, b.Name(), name) obj := FooStruct{} req := requestWithBody("POST", path, body) req.Header.Add("Content-Type", MIMEMSGPACK) err := b.Bind(req, &obj) assert.NoError(t, err) assert.Equal(t, obj.Foo, "bar") obj = FooStruct{} req = requestWithBody("POST", badPath, badBody) req.Header.Add("Content-Type", MIMEMSGPACK) err = MsgPack.Bind(req, &obj) assert.Error(t, err) } func requestWithBody(method, path, body string) (req *http.Request) { req, _ = http.NewRequest(method, path, bytes.NewBufferString(body)) return } gin-1.2/binding/default_validator.go000066400000000000000000000016651312613627200175760ustar00rootroot00000000000000// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "reflect" "sync" "gopkg.in/go-playground/validator.v8" ) type defaultValidator struct { once sync.Once validate *validator.Validate } var _ StructValidator = &defaultValidator{} func (v *defaultValidator) ValidateStruct(obj interface{}) error { if kindOfData(obj) == reflect.Struct { v.lazyinit() if err := v.validate.Struct(obj); err != nil { return error(err) } } return nil } func (v *defaultValidator) lazyinit() { v.once.Do(func() { config := &validator.Config{TagName: "binding"} v.validate = validator.New(config) }) } func kindOfData(data interface{}) reflect.Kind { value := reflect.ValueOf(data) valueType := value.Kind() if valueType == reflect.Ptr { valueType = value.Elem().Kind() } return valueType } gin-1.2/binding/example/000077500000000000000000000000001312613627200152015ustar00rootroot00000000000000gin-1.2/binding/example/test.pb.go000066400000000000000000000047401312613627200171140ustar00rootroot00000000000000// Code generated by protoc-gen-go. // source: test.proto // DO NOT EDIT! /* Package example is a generated protocol buffer package. It is generated from these files: test.proto It has these top-level messages: Test */ package example import proto "github.com/golang/protobuf/proto" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = math.Inf type FOO int32 const ( FOO_X FOO = 17 ) var FOO_name = map[int32]string{ 17: "X", } var FOO_value = map[string]int32{ "X": 17, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") if err != nil { return err } *x = FOO(value) return nil } type Test struct { Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Test) Reset() { *m = Test{} } func (m *Test) String() string { return proto.CompactTextString(m) } func (*Test) ProtoMessage() {} const Default_Test_Type int32 = 77 func (m *Test) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *Test) GetType() int32 { if m != nil && m.Type != nil { return *m.Type } return Default_Test_Type } func (m *Test) GetReps() []int64 { if m != nil { return m.Reps } return nil } func (m *Test) GetOptionalgroup() *Test_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } type Test_OptionalGroup struct { RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } func (*Test_OptionalGroup) ProtoMessage() {} func (m *Test_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } func init() { proto.RegisterEnum("example.FOO", FOO_name, FOO_value) } gin-1.2/binding/example/test.proto000066400000000000000000000003521312613627200172450ustar00rootroot00000000000000package example; enum FOO {X=17;}; message Test { required string label = 1; optional int32 type = 2[default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4{ required string RequiredField = 5; } } gin-1.2/binding/form.go000066400000000000000000000023131312613627200150370ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import "net/http" type formBinding struct{} type formPostBinding struct{} type formMultipartBinding struct{} func (formBinding) Name() string { return "form" } func (formBinding) Bind(req *http.Request, obj interface{}) error { if err := req.ParseForm(); err != nil { return err } req.ParseMultipartForm(32 << 10) // 32 MB if err := mapForm(obj, req.Form); err != nil { return err } return validate(obj) } func (formPostBinding) Name() string { return "form-urlencoded" } func (formPostBinding) Bind(req *http.Request, obj interface{}) error { if err := req.ParseForm(); err != nil { return err } if err := mapForm(obj, req.PostForm); err != nil { return err } return validate(obj) } func (formMultipartBinding) Name() string { return "multipart/form-data" } func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error { if err := req.ParseMultipartForm(32 << 10); err != nil { return err } if err := mapForm(obj, req.MultipartForm.Value); err != nil { return err } return validate(obj) } gin-1.2/binding/form_mapping.go000066400000000000000000000107261312613627200165610ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "reflect" "strconv" "time" ) func mapForm(ptr interface{}, form map[string][]string) error { typ := reflect.TypeOf(ptr).Elem() val := reflect.ValueOf(ptr).Elem() for i := 0; i < typ.NumField(); i++ { typeField := typ.Field(i) structField := val.Field(i) if !structField.CanSet() { continue } structFieldKind := structField.Kind() inputFieldName := typeField.Tag.Get("form") if inputFieldName == "" { inputFieldName = typeField.Name // if "form" tag is nil, we inspect if the field is a struct. // this would not make sense for JSON parsing but it does for a form // since data is flatten if structFieldKind == reflect.Struct { err := mapForm(structField.Addr().Interface(), form) if err != nil { return err } continue } } inputValue, exists := form[inputFieldName] if !exists { continue } numElems := len(inputValue) if structFieldKind == reflect.Slice && numElems > 0 { sliceOf := structField.Type().Elem().Kind() slice := reflect.MakeSlice(structField.Type(), numElems, numElems) for i := 0; i < numElems; i++ { if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil { return err } } val.Field(i).Set(slice) } else { if _, isTime := structField.Interface().(time.Time); isTime { if err := setTimeField(inputValue[0], typeField, structField); err != nil { return err } continue } if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil { return err } } } return nil } func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error { switch valueKind { case reflect.Int: return setIntField(val, 0, structField) case reflect.Int8: return setIntField(val, 8, structField) case reflect.Int16: return setIntField(val, 16, structField) case reflect.Int32: return setIntField(val, 32, structField) case reflect.Int64: return setIntField(val, 64, structField) case reflect.Uint: return setUintField(val, 0, structField) case reflect.Uint8: return setUintField(val, 8, structField) case reflect.Uint16: return setUintField(val, 16, structField) case reflect.Uint32: return setUintField(val, 32, structField) case reflect.Uint64: return setUintField(val, 64, structField) case reflect.Bool: return setBoolField(val, structField) case reflect.Float32: return setFloatField(val, 32, structField) case reflect.Float64: return setFloatField(val, 64, structField) case reflect.String: structField.SetString(val) default: return errors.New("Unknown type") } return nil } func setIntField(val string, bitSize int, field reflect.Value) error { if val == "" { val = "0" } intVal, err := strconv.ParseInt(val, 10, bitSize) if err == nil { field.SetInt(intVal) } return err } func setUintField(val string, bitSize int, field reflect.Value) error { if val == "" { val = "0" } uintVal, err := strconv.ParseUint(val, 10, bitSize) if err == nil { field.SetUint(uintVal) } return err } func setBoolField(val string, field reflect.Value) error { if val == "" { val = "false" } boolVal, err := strconv.ParseBool(val) if err == nil { field.SetBool(boolVal) } return nil } func setFloatField(val string, bitSize int, field reflect.Value) error { if val == "" { val = "0.0" } floatVal, err := strconv.ParseFloat(val, bitSize) if err == nil { field.SetFloat(floatVal) } return err } func setTimeField(val string, structField reflect.StructField, value reflect.Value) error { timeFormat := structField.Tag.Get("time_format") if timeFormat == "" { return errors.New("Blank time format") } if val == "" { value.Set(reflect.ValueOf(time.Time{})) return nil } l := time.Local if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC { l = time.UTC } t, err := time.ParseInLocation(timeFormat, val, l) if err != nil { return err } value.Set(reflect.ValueOf(t)) return nil } // Don't pass in pointers to bind to. Can lead to bugs. See: // https://github.com/codegangsta/martini-contrib/issues/40 // https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659 func ensureNotPointer(obj interface{}) { if reflect.TypeOf(obj).Kind() == reflect.Ptr { panic("Pointers are not accepted as binding models") } } gin-1.2/binding/json.go000066400000000000000000000007611312613627200150520ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "encoding/json" "net/http" ) type jsonBinding struct{} func (jsonBinding) Name() string { return "json" } func (jsonBinding) Bind(req *http.Request, obj interface{}) error { decoder := json.NewDecoder(req.Body) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) } gin-1.2/binding/msgpack.go000066400000000000000000000012301312613627200155160ustar00rootroot00000000000000// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "net/http" "github.com/ugorji/go/codec" ) type msgpackBinding struct{} func (msgpackBinding) Name() string { return "msgpack" } func (msgpackBinding) Bind(req *http.Request, obj interface{}) error { if err := codec.NewDecoder(req.Body, new(codec.MsgpackHandle)).Decode(&obj); err != nil { //var decoder *codec.Decoder = codec.NewDecoder(req.Body, &codec.MsgpackHandle) //if err := decoder.Decode(&obj); err != nil { return err } return validate(obj) } gin-1.2/binding/protobuf.go000066400000000000000000000013671312613627200157440ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "io/ioutil" "net/http" "github.com/golang/protobuf/proto" ) type protobufBinding struct{} func (protobufBinding) Name() string { return "protobuf" } func (protobufBinding) Bind(req *http.Request, obj interface{}) error { buf, err := ioutil.ReadAll(req.Body) if err != nil { return err } if err = proto.Unmarshal(buf, obj.(proto.Message)); err != nil { return err } //Here it's same to return validate(obj), but util now we cann't add `binding:""` to the struct //which automatically generate by gen-proto return nil //return validate(obj) } gin-1.2/binding/validate_test.go000066400000000000000000000103041312613627200167230ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "testing" "time" "github.com/stretchr/testify/assert" ) type testInterface interface { String() string } type substructNoValidation struct { IString string IInt int } type mapNoValidationSub map[string]substructNoValidation type structNoValidationValues struct { substructNoValidation Boolean bool Uinteger uint Integer int Integer8 int8 Integer16 int16 Integer32 int32 Integer64 int64 Uinteger8 uint8 Uinteger16 uint16 Uinteger32 uint32 Uinteger64 uint64 Float32 float32 Float64 float64 String string Date time.Time Struct substructNoValidation InlinedStruct struct { String []string Integer int } IntSlice []int IntPointerSlice []*int StructPointerSlice []*substructNoValidation StructSlice []substructNoValidation InterfaceSlice []testInterface UniversalInterface interface{} CustomInterface testInterface FloatMap map[string]float32 StructMap mapNoValidationSub } func createNoValidationValues() structNoValidationValues { integer := 1 s := structNoValidationValues{ Boolean: true, Uinteger: 1 << 29, Integer: -10000, Integer8: 120, Integer16: -20000, Integer32: 1 << 29, Integer64: 1 << 61, Uinteger8: 250, Uinteger16: 50000, Uinteger32: 1 << 31, Uinteger64: 1 << 62, Float32: 123.456, Float64: 123.456789, String: "text", Date: time.Time{}, CustomInterface: &bytes.Buffer{}, Struct: substructNoValidation{}, IntSlice: []int{-3, -2, 1, 0, 1, 2, 3}, IntPointerSlice: []*int{&integer}, StructSlice: []substructNoValidation{}, UniversalInterface: 1.2, FloatMap: map[string]float32{ "foo": 1.23, "bar": 232.323, }, StructMap: mapNoValidationSub{ "foo": substructNoValidation{}, "bar": substructNoValidation{}, }, // StructPointerSlice []noValidationSub // InterfaceSlice []testInterface } s.InlinedStruct.Integer = 1000 s.InlinedStruct.String = []string{"first", "second"} s.IString = "substring" s.IInt = 987654 return s } func TestValidateNoValidationValues(t *testing.T) { origin := createNoValidationValues() test := createNoValidationValues() empty := structNoValidationValues{} assert.Nil(t, validate(test)) assert.Nil(t, validate(&test)) assert.Nil(t, validate(empty)) assert.Nil(t, validate(&empty)) assert.Equal(t, origin, test) } type structNoValidationPointer struct { substructNoValidation Boolean bool Uinteger *uint Integer *int Integer8 *int8 Integer16 *int16 Integer32 *int32 Integer64 *int64 Uinteger8 *uint8 Uinteger16 *uint16 Uinteger32 *uint32 Uinteger64 *uint64 Float32 *float32 Float64 *float64 String *string Date *time.Time Struct *substructNoValidation IntSlice *[]int IntPointerSlice *[]*int StructPointerSlice *[]*substructNoValidation StructSlice *[]substructNoValidation InterfaceSlice *[]testInterface FloatMap *map[string]float32 StructMap *mapNoValidationSub } func TestValidateNoValidationPointers(t *testing.T) { //origin := createNoValidation_values() //test := createNoValidation_values() empty := structNoValidationPointer{} //assert.Nil(t, validate(test)) //assert.Nil(t, validate(&test)) assert.Nil(t, validate(empty)) assert.Nil(t, validate(&empty)) //assert.Equal(t, origin, test) } type Object map[string]interface{} func TestValidatePrimitives(t *testing.T) { obj := Object{"foo": "bar", "bar": 1} assert.NoError(t, validate(obj)) assert.NoError(t, validate(&obj)) assert.Equal(t, obj, Object{"foo": "bar", "bar": 1}) obj2 := []Object{{"foo": "bar", "bar": 1}, {"foo": "bar", "bar": 1}} assert.NoError(t, validate(obj2)) assert.NoError(t, validate(&obj2)) nu := 10 assert.NoError(t, validate(nu)) assert.NoError(t, validate(&nu)) assert.Equal(t, nu, 10) str := "value" assert.NoError(t, validate(str)) assert.NoError(t, validate(&str)) assert.Equal(t, str, "value") } gin-1.2/binding/xml.go000066400000000000000000000007531312613627200147020ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "encoding/xml" "net/http" ) type xmlBinding struct{} func (xmlBinding) Name() string { return "xml" } func (xmlBinding) Bind(req *http.Request, obj interface{}) error { decoder := xml.NewDecoder(req.Body) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) } gin-1.2/codecov.yml000066400000000000000000000001561312613627200143030ustar00rootroot00000000000000coverage: notify: gitter: default: url: https://webhooks.gitter.im/e/d90dcdeeab2f1e357165 gin-1.2/context.go000066400000000000000000000537021312613627200141560ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "io" "io/ioutil" "math" "mime/multipart" "net" "net/http" "net/url" "strings" "time" "github.com/gin-contrib/sse" "github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/render" ) // Content-Type MIME of the most common data formats const ( MIMEJSON = binding.MIMEJSON MIMEHTML = binding.MIMEHTML MIMEXML = binding.MIMEXML MIMEXML2 = binding.MIMEXML2 MIMEPlain = binding.MIMEPlain MIMEPOSTForm = binding.MIMEPOSTForm MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm ) const ( defaultMemory = 32 << 20 // 32 MB abortIndex int8 = math.MaxInt8 / 2 ) // Context is the most important part of gin. It allows us to pass variables between middleware, // manage the flow, validate the JSON of a request and render a JSON response for example. type Context struct { writermem responseWriter Request *http.Request Writer ResponseWriter Params Params handlers HandlersChain index int8 engine *Engine Keys map[string]interface{} Errors errorMsgs Accepted []string } /************************************/ /********** CONTEXT CREATION ********/ /************************************/ func (c *Context) reset() { c.Writer = &c.writermem c.Params = c.Params[0:0] c.handlers = nil c.index = -1 c.Keys = nil c.Errors = c.Errors[0:0] c.Accepted = nil } // Copy returns a copy of the current context that can be safely used outside the request's scope. // This has to be used when the context has to be passed to a goroutine. func (c *Context) Copy() *Context { var cp = *c cp.writermem.ResponseWriter = nil cp.Writer = &cp.writermem cp.index = abortIndex cp.handlers = nil return &cp } // HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", this // function will return "main.handleGetUsers" func (c *Context) HandlerName() string { return nameOfFunction(c.handlers.Last()) } // Handler returns the main handler. func (c *Context) Handler() HandlerFunc { return c.handlers.Last() } /************************************/ /*********** FLOW CONTROL ***********/ /************************************/ // Next should be used only inside middleware. // It executes the pending handlers in the chain inside the calling handler. // See example in GitHub. func (c *Context) Next() { c.index++ s := int8(len(c.handlers)) for ; c.index < s; c.index++ { c.handlers[c.index](c) } } // IsAborted returns true if the current context was aborted. func (c *Context) IsAborted() bool { return c.index >= abortIndex } // Abort prevents pending handlers from being called. Note that this will not stop the current handler. // Let's say you have an authorization middleware that validates that the current request is authorized. If the // authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers // for this request are not called. func (c *Context) Abort() { c.index = abortIndex } // AbortWithStatus calls `Abort()` and writes the headers with the specified status code. // For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401). func (c *Context) AbortWithStatus(code int) { c.Status(code) c.Writer.WriteHeaderNow() c.Abort() } // AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body // It also sets the Content-Type as "application/json". func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) { c.Abort() c.JSON(code, jsonObj) } // AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and // pushes the specified error to `c.Errors`. // See Context.Error() for more details. func (c *Context) AbortWithError(code int, err error) *Error { c.AbortWithStatus(code) return c.Error(err) } /************************************/ /********* ERROR MANAGEMENT *********/ /************************************/ // Attaches an error to the current context. The error is pushed to a list of errors. // It's a good idea to call Error for each error that occurred during the resolution of a request. // A middleware can be used to collect all the errors // and push them to a database together, print a log, or append it in the HTTP response. func (c *Context) Error(err error) *Error { var parsedError *Error switch err.(type) { case *Error: parsedError = err.(*Error) default: parsedError = &Error{ Err: err, Type: ErrorTypePrivate, } } c.Errors = append(c.Errors, parsedError) return parsedError } /************************************/ /******** METADATA MANAGEMENT********/ /************************************/ // Set is used to store a new key/value pair exclusively for this context. // It also lazy initializes c.Keys if it was not used previously. func (c *Context) Set(key string, value interface{}) { if c.Keys == nil { c.Keys = make(map[string]interface{}) } c.Keys[key] = value } // Get returns the value for the given key, ie: (value, true). // If the value does not exists it returns (nil, false) func (c *Context) Get(key string) (value interface{}, exists bool) { value, exists = c.Keys[key] return } // MustGet returns the value for the given key if it exists, otherwise it panics. func (c *Context) MustGet(key string) interface{} { if value, exists := c.Get(key); exists { return value } panic("Key \"" + key + "\" does not exist") } // GetString returns the value associated with the key as a string. func (c *Context) GetString(key string) (s string) { if val, ok := c.Get(key); ok && val != nil { s, _ = val.(string) } return } // GetBool returns the value associated with the key as a boolean. func (c *Context) GetBool(key string) (b bool) { if val, ok := c.Get(key); ok && val != nil { b, _ = val.(bool) } return } // GetInt returns the value associated with the key as an integer. func (c *Context) GetInt(key string) (i int) { if val, ok := c.Get(key); ok && val != nil { i, _ = val.(int) } return } // GetInt64 returns the value associated with the key as an integer. func (c *Context) GetInt64(key string) (i64 int64) { if val, ok := c.Get(key); ok && val != nil { i64, _ = val.(int64) } return } // GetFloat64 returns the value associated with the key as a float64. func (c *Context) GetFloat64(key string) (f64 float64) { if val, ok := c.Get(key); ok && val != nil { f64, _ = val.(float64) } return } // GetTime returns the value associated with the key as time. func (c *Context) GetTime(key string) (t time.Time) { if val, ok := c.Get(key); ok && val != nil { t, _ = val.(time.Time) } return } // GetDuration returns the value associated with the key as a duration. func (c *Context) GetDuration(key string) (d time.Duration) { if val, ok := c.Get(key); ok && val != nil { d, _ = val.(time.Duration) } return } // GetStringSlice returns the value associated with the key as a slice of strings. func (c *Context) GetStringSlice(key string) (ss []string) { if val, ok := c.Get(key); ok && val != nil { ss, _ = val.([]string) } return } // GetStringMap returns the value associated with the key as a map of interfaces. func (c *Context) GetStringMap(key string) (sm map[string]interface{}) { if val, ok := c.Get(key); ok && val != nil { sm, _ = val.(map[string]interface{}) } return } // GetStringMapString returns the value associated with the key as a map of strings. func (c *Context) GetStringMapString(key string) (sms map[string]string) { if val, ok := c.Get(key); ok && val != nil { sms, _ = val.(map[string]string) } return } // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) { if val, ok := c.Get(key); ok && val != nil { smss, _ = val.(map[string][]string) } return } /************************************/ /************ INPUT DATA ************/ /************************************/ // Param returns the value of the URL param. // It is a shortcut for c.Params.ByName(key) // router.GET("/user/:id", func(c *gin.Context) { // // a GET request to /user/john // id := c.Param("id") // id == "john" // }) func (c *Context) Param(key string) string { return c.Params.ByName(key) } // Query returns the keyed url query value if it exists, // otherwise it returns an empty string `("")`. // It is shortcut for `c.Request.URL.Query().Get(key)` // GET /path?id=1234&name=Manu&value= // c.Query("id") == "1234" // c.Query("name") == "Manu" // c.Query("value") == "" // c.Query("wtf") == "" func (c *Context) Query(key string) string { value, _ := c.GetQuery(key) return value } // DefaultQuery returns the keyed url query value if it exists, // otherwise it returns the specified defaultValue string. // See: Query() and GetQuery() for further information. // GET /?name=Manu&lastname= // c.DefaultQuery("name", "unknown") == "Manu" // c.DefaultQuery("id", "none") == "none" // c.DefaultQuery("lastname", "none") == "" func (c *Context) DefaultQuery(key, defaultValue string) string { if value, ok := c.GetQuery(key); ok { return value } return defaultValue } // GetQuery is like Query(), it returns the keyed url query value // if it exists `(value, true)` (even when the value is an empty string), // otherwise it returns `("", false)`. // It is shortcut for `c.Request.URL.Query().Get(key)` // GET /?name=Manu&lastname= // ("Manu", true) == c.GetQuery("name") // ("", false) == c.GetQuery("id") // ("", true) == c.GetQuery("lastname") func (c *Context) GetQuery(key string) (string, bool) { if values, ok := c.GetQueryArray(key); ok { return values[0], ok } return "", false } // QueryArray returns a slice of strings for a given query key. // The length of the slice depends on the number of params with the given key. func (c *Context) QueryArray(key string) []string { values, _ := c.GetQueryArray(key) return values } // GetQueryArray returns a slice of strings for a given query key, plus // a boolean value whether at least one value exists for the given key. func (c *Context) GetQueryArray(key string) ([]string, bool) { req := c.Request if values, ok := req.URL.Query()[key]; ok && len(values) > 0 { return values, true } return []string{}, false } // PostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns an empty string `("")`. func (c *Context) PostForm(key string) string { value, _ := c.GetPostForm(key) return value } // DefaultPostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns the specified defaultValue string. // See: PostForm() and GetPostForm() for further information. func (c *Context) DefaultPostForm(key, defaultValue string) string { if value, ok := c.GetPostForm(key); ok { return value } return defaultValue } // GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded // form or multipart form when it exists `(value, true)` (even when the value is an empty string), // otherwise it returns ("", false). // For example, during a PATCH request to update the user's email: // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" // email= --> ("", true) := GetPostForm("email") // set email to "" // --> ("", false) := GetPostForm("email") // do nothing with email func (c *Context) GetPostForm(key string) (string, bool) { if values, ok := c.GetPostFormArray(key); ok { return values[0], ok } return "", false } // PostFormArray returns a slice of strings for a given form key. // The length of the slice depends on the number of params with the given key. func (c *Context) PostFormArray(key string) []string { values, _ := c.GetPostFormArray(key) return values } // GetPostFormArray returns a slice of strings for a given form key, plus // a boolean value whether at least one value exists for the given key. func (c *Context) GetPostFormArray(key string) ([]string, bool) { req := c.Request req.ParseForm() req.ParseMultipartForm(defaultMemory) if values := req.PostForm[key]; len(values) > 0 { return values, true } if req.MultipartForm != nil && req.MultipartForm.File != nil { if values := req.MultipartForm.Value[key]; len(values) > 0 { return values, true } } return []string{}, false } // FormFile returns the first file for the provided form key. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) { _, fh, err := c.Request.FormFile(name) return fh, err } // MultipartForm is the parsed multipart form, including file uploads. func (c *Context) MultipartForm() (*multipart.Form, error) { err := c.Request.ParseMultipartForm(defaultMemory) return c.Request.MultipartForm, err } // Bind checks the Content-Type to select a binding engine automatically, // Depending the "Content-Type" header different bindings are used: // "application/json" --> JSON binding // "application/xml" --> XML binding // otherwise --> returns an error // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It decodes the json payload into the struct specified as a pointer. // Like ParseBody() but this method also writes a 400 error if the json is not valid. func (c *Context) Bind(obj interface{}) error { b := binding.Default(c.Request.Method, c.ContentType()) return c.MustBindWith(obj, b) } // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON) func (c *Context) BindJSON(obj interface{}) error { return c.MustBindWith(obj, binding.JSON) } // MustBindWith binds the passed struct pointer using the specified binding // engine. It will abort the request with HTTP 400 if any error ocurrs. // See the binding package. func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) { if err = c.ShouldBindWith(obj, b); err != nil { c.AbortWithError(400, err).SetType(ErrorTypeBind) } return } // ShouldBindWith binds the passed struct pointer using the specified binding // engine. // See the binding package. func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error { return b.Bind(c.Request, obj) } // ClientIP implements a best effort algorithm to return the real client IP, it parses // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP. func (c *Context) ClientIP() string { if c.engine.ForwardedByClientIP { clientIP := c.requestHeader("X-Forwarded-For") if index := strings.IndexByte(clientIP, ','); index >= 0 { clientIP = clientIP[0:index] } clientIP = strings.TrimSpace(clientIP) if len(clientIP) > 0 { return clientIP } clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip")) if len(clientIP) > 0 { return clientIP } } if c.engine.AppEngine { if addr := c.Request.Header.Get("X-Appengine-Remote-Addr"); addr != "" { return addr } } if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil { return ip } return "" } // ContentType returns the Content-Type header of the request. func (c *Context) ContentType() string { return filterFlags(c.requestHeader("Content-Type")) } // IsWebsocket returns true if the request headers indicate that a websocket // handshake is being initiated by the client. func (c *Context) IsWebsocket() bool { if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") && strings.ToLower(c.requestHeader("Upgrade")) == "websocket" { return true } return false } func (c *Context) requestHeader(key string) string { if values, _ := c.Request.Header[key]; len(values) > 0 { return values[0] } return "" } /************************************/ /******** RESPONSE RENDERING ********/ /************************************/ // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function func bodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: return false case status == 204: return false case status == 304: return false } return true } func (c *Context) Status(code int) { c.writermem.WriteHeader(code) } // Header is a intelligent shortcut for c.Writer.Header().Set(key, value) // It writes a header in the response. // If value == "", this method removes the header `c.Writer.Header().Del(key)` func (c *Context) Header(key, value string) { if len(value) == 0 { c.Writer.Header().Del(key) } else { c.Writer.Header().Set(key, value) } } // GetHeader returns value from request headers func (c *Context) GetHeader(key string) string { return c.requestHeader(key) } // GetRawData return stream data func (c *Context) GetRawData() ([]byte, error) { return ioutil.ReadAll(c.Request.Body) } func (c *Context) SetCookie( name string, value string, maxAge int, path string, domain string, secure bool, httpOnly bool, ) { if path == "" { path = "/" } http.SetCookie(c.Writer, &http.Cookie{ Name: name, Value: url.QueryEscape(value), MaxAge: maxAge, Path: path, Domain: domain, Secure: secure, HttpOnly: httpOnly, }) } func (c *Context) Cookie(name string) (string, error) { cookie, err := c.Request.Cookie(name) if err != nil { return "", err } val, _ := url.QueryUnescape(cookie.Value) return val, nil } func (c *Context) Render(code int, r render.Render) { c.Status(code) if !bodyAllowedForStatus(code) { r.WriteContentType(c.Writer) c.Writer.WriteHeaderNow() return } if err := r.Render(c.Writer); err != nil { panic(err) } } // HTML renders the HTTP template specified by its file name. // It also updates the HTTP code and sets the Content-Type as "text/html". // See http://golang.org/doc/articles/wiki/ func (c *Context) HTML(code int, name string, obj interface{}) { instance := c.engine.HTMLRender.Instance(name, obj) c.Render(code, instance) } // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. // It also sets the Content-Type as "application/json". // WARNING: we recommend to use this only for development purposes since printing pretty JSON is // more CPU and bandwidth consuming. Use Context.JSON() instead. func (c *Context) IndentedJSON(code int, obj interface{}) { c.Render(code, render.IndentedJSON{Data: obj}) } // JSON serializes the given struct as JSON into the response body. // It also sets the Content-Type as "application/json". func (c *Context) JSON(code int, obj interface{}) { c.Render(code, render.JSON{Data: obj}) } // XML serializes the given struct as XML into the response body. // It also sets the Content-Type as "application/xml". func (c *Context) XML(code int, obj interface{}) { c.Render(code, render.XML{Data: obj}) } // YAML serializes the given struct as YAML into the response body. func (c *Context) YAML(code int, obj interface{}) { c.Render(code, render.YAML{Data: obj}) } // String writes the given string into the response body. func (c *Context) String(code int, format string, values ...interface{}) { c.Render(code, render.String{Format: format, Data: values}) } // Redirect returns a HTTP redirect to the specific location. func (c *Context) Redirect(code int, location string) { c.Render(-1, render.Redirect{ Code: code, Location: location, Request: c.Request, }) } // Data writes some data into the body stream and updates the HTTP code. func (c *Context) Data(code int, contentType string, data []byte) { c.Render(code, render.Data{ ContentType: contentType, Data: data, }) } // File writes the specified file into the body stream in a efficient way. func (c *Context) File(filepath string) { http.ServeFile(c.Writer, c.Request, filepath) } // SSEvent writes a Server-Sent Event into the body stream. func (c *Context) SSEvent(name string, message interface{}) { c.Render(-1, sse.Event{ Event: name, Data: message, }) } func (c *Context) Stream(step func(w io.Writer) bool) { w := c.Writer clientGone := w.CloseNotify() for { select { case <-clientGone: return default: keepOpen := step(w) w.Flush() if !keepOpen { return } } } } /************************************/ /******** CONTENT NEGOTIATION *******/ /************************************/ type Negotiate struct { Offered []string HTMLName string HTMLData interface{} JSONData interface{} XMLData interface{} Data interface{} } func (c *Context) Negotiate(code int, config Negotiate) { switch c.NegotiateFormat(config.Offered...) { case binding.MIMEJSON: data := chooseData(config.JSONData, config.Data) c.JSON(code, data) case binding.MIMEHTML: data := chooseData(config.HTMLData, config.Data) c.HTML(code, config.HTMLName, data) case binding.MIMEXML: data := chooseData(config.XMLData, config.Data) c.XML(code, data) default: c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) } } func (c *Context) NegotiateFormat(offered ...string) string { assert1(len(offered) > 0, "you must provide at least one offer") if c.Accepted == nil { c.Accepted = parseAccept(c.requestHeader("Accept")) } if len(c.Accepted) == 0 { return offered[0] } for _, accepted := range c.Accepted { for _, offert := range offered { if accepted == offert { return offert } } } return "" } func (c *Context) SetAccepted(formats ...string) { c.Accepted = formats } /************************************/ /***** GOLANG.ORG/X/NET/CONTEXT *****/ /************************************/ func (c *Context) Deadline() (deadline time.Time, ok bool) { return } func (c *Context) Done() <-chan struct{} { return nil } func (c *Context) Err() error { return nil } func (c *Context) Value(key interface{}) interface{} { if key == 0 { return c.Request } if keyAsString, ok := key.(string); ok { val, _ := c.Get(keyAsString) return val } return nil } gin-1.2/context_appengine.go000066400000000000000000000003631312613627200161770ustar00rootroot00000000000000// +build appengine // Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin func init() { defaultAppEngine = true } gin-1.2/context_test.go000066400000000000000000001067021312613627200152140ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "html/template" "mime/multipart" "net/http" "net/http/httptest" "reflect" "strings" "testing" "time" "github.com/gin-contrib/sse" "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) var _ context.Context = &Context{} // Unit tests TODO // func (c *Context) File(filepath string) { // func (c *Context) Negotiate(code int, config Negotiate) { // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) { // test that information is not leaked when reusing Contexts (using the Pool) func createMultipartRequest() *http.Request { boundary := "--testboundary" body := new(bytes.Buffer) mw := multipart.NewWriter(body) defer mw.Close() must(mw.SetBoundary(boundary)) must(mw.WriteField("foo", "bar")) must(mw.WriteField("bar", "10")) must(mw.WriteField("bar", "foo2")) must(mw.WriteField("array", "first")) must(mw.WriteField("array", "second")) must(mw.WriteField("id", "")) must(mw.WriteField("time_local", "31/12/2016 14:55")) must(mw.WriteField("time_utc", "31/12/2016 14:55")) req, err := http.NewRequest("POST", "/", body) must(err) req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary) return req } func must(err error) { if err != nil { panic(err.Error()) } } func TestContextFormFile(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) w, err := mw.CreateFormFile("file", "test") if assert.NoError(t, err) { w.Write([]byte("test")) } mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f, err := c.FormFile("file") if assert.NoError(t, err) { assert.Equal(t, "test", f.Filename) } } func TestContextMultipartForm(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) mw.WriteField("foo", "bar") mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f, err := c.MultipartForm() if assert.NoError(t, err) { assert.NotNil(t, f) } } func TestContextReset(t *testing.T) { router := New() c := router.allocateContext() assert.Equal(t, c.engine, router) c.index = 2 c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()} c.Params = Params{Param{}} c.Error(errors.New("test")) c.Set("foo", "bar") c.reset() assert.False(t, c.IsAborted()) assert.Nil(t, c.Keys) assert.Nil(t, c.Accepted) assert.Len(t, c.Errors, 0) assert.Empty(t, c.Errors.Errors()) assert.Empty(t, c.Errors.ByType(ErrorTypeAny)) assert.Len(t, c.Params, 0) assert.EqualValues(t, c.index, -1) assert.Equal(t, c.Writer.(*responseWriter), &c.writermem) } func TestContextHandlers(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) assert.Nil(t, c.handlers) assert.Nil(t, c.handlers.Last()) c.handlers = HandlersChain{} assert.NotNil(t, c.handlers) assert.Nil(t, c.handlers.Last()) f := func(c *Context) {} g := func(c *Context) {} c.handlers = HandlersChain{f} compareFunc(t, f, c.handlers.Last()) c.handlers = HandlersChain{f, g} compareFunc(t, g, c.handlers.Last()) } // TestContextSetGet tests that a parameter is set correctly on the // current context and can be retrieved using Get. func TestContextSetGet(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("foo", "bar") value, err := c.Get("foo") assert.Equal(t, value, "bar") assert.True(t, err) value, err = c.Get("foo2") assert.Nil(t, value) assert.False(t, err) assert.Equal(t, c.MustGet("foo"), "bar") assert.Panics(t, func() { c.MustGet("no_exist") }) } func TestContextSetGetValues(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("string", "this is a string") c.Set("int32", int32(-42)) c.Set("int64", int64(42424242424242)) c.Set("uint64", uint64(42)) c.Set("float32", float32(4.2)) c.Set("float64", 4.2) var a interface{} = 1 c.Set("intInterface", a) assert.Exactly(t, c.MustGet("string").(string), "this is a string") assert.Exactly(t, c.MustGet("int32").(int32), int32(-42)) assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242)) assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42)) assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2)) assert.Exactly(t, c.MustGet("float64").(float64), 4.2) assert.Exactly(t, c.MustGet("intInterface").(int), 1) } func TestContextGetString(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("string", "this is a string") assert.Equal(t, "this is a string", c.GetString("string")) } func TestContextSetGetBool(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("bool", true) assert.Equal(t, true, c.GetBool("bool")) } func TestContextGetInt(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("int", 1) assert.Equal(t, 1, c.GetInt("int")) } func TestContextGetInt64(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("int64", int64(42424242424242)) assert.Equal(t, int64(42424242424242), c.GetInt64("int64")) } func TestContextGetFloat64(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("float64", 4.2) assert.Equal(t, 4.2, c.GetFloat64("float64")) } func TestContextGetTime(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) t1, _ := time.Parse("1/2/2006 15:04:05", "01/01/2017 12:00:00") c.Set("time", t1) assert.Equal(t, t1, c.GetTime("time")) } func TestContextGetDuration(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("duration", time.Second) assert.Equal(t, time.Second, c.GetDuration("duration")) } func TestContextGetStringSlice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("slice", []string{"foo"}) assert.Equal(t, []string{"foo"}, c.GetStringSlice("slice")) } func TestContextGetStringMap(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) var m = make(map[string]interface{}) m["foo"] = 1 c.Set("map", m) assert.Equal(t, m, c.GetStringMap("map")) assert.Equal(t, 1, c.GetStringMap("map")["foo"]) } func TestContextGetStringMapString(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) var m = make(map[string]string) m["foo"] = "bar" c.Set("map", m) assert.Equal(t, m, c.GetStringMapString("map")) assert.Equal(t, "bar", c.GetStringMapString("map")["foo"]) } func TestContextGetStringMapStringSlice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) var m = make(map[string][]string) m["foo"] = []string{"foo"} c.Set("map", m) assert.Equal(t, m, c.GetStringMapStringSlice("map")) assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"]) } func TestContextCopy(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.index = 2 c.Request, _ = http.NewRequest("POST", "/hola", nil) c.handlers = HandlersChain{func(c *Context) {}} c.Params = Params{Param{Key: "foo", Value: "bar"}} c.Set("foo", "bar") cp := c.Copy() assert.Nil(t, cp.handlers) assert.Nil(t, cp.writermem.ResponseWriter) assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter)) assert.Equal(t, cp.Request, c.Request) assert.Equal(t, cp.index, abortIndex) assert.Equal(t, cp.Keys, c.Keys) assert.Equal(t, cp.engine, c.engine) assert.Equal(t, cp.Params, c.Params) } func TestContextHandlerName(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest} assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName()) } func handlerNameTest(c *Context) { } var handlerTest HandlerFunc = func(c *Context) { } func TestContextHandler(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.handlers = HandlersChain{func(c *Context) {}, handlerTest} assert.Equal(t, reflect.ValueOf(handlerTest).Pointer(), reflect.ValueOf(c.Handler()).Pointer()) } func TestContextQuery(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil) value, ok := c.GetQuery("foo") assert.True(t, ok) assert.Equal(t, value, "bar") assert.Equal(t, c.DefaultQuery("foo", "none"), "bar") assert.Equal(t, c.Query("foo"), "bar") value, ok = c.GetQuery("page") assert.True(t, ok) assert.Equal(t, value, "10") assert.Equal(t, c.DefaultQuery("page", "0"), "10") assert.Equal(t, c.Query("page"), "10") value, ok = c.GetQuery("id") assert.True(t, ok) assert.Empty(t, value) assert.Equal(t, c.DefaultQuery("id", "nada"), "") assert.Empty(t, c.Query("id")) value, ok = c.GetQuery("NoKey") assert.False(t, ok) assert.Empty(t, value) assert.Equal(t, c.DefaultQuery("NoKey", "nada"), "nada") assert.Empty(t, c.Query("NoKey")) // postform should not mess value, ok = c.GetPostForm("page") assert.False(t, ok) assert.Empty(t, value) assert.Empty(t, c.PostForm("foo")) } func TestContextQueryAndPostForm(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second") c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body) c.Request.Header.Add("Content-Type", MIMEPOSTForm) assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar") assert.Equal(t, c.PostForm("foo"), "bar") assert.Empty(t, c.Query("foo")) value, ok := c.GetPostForm("page") assert.True(t, ok) assert.Equal(t, value, "11") assert.Equal(t, c.DefaultPostForm("page", "0"), "11") assert.Equal(t, c.PostForm("page"), "11") assert.Equal(t, c.Query("page"), "") value, ok = c.GetPostForm("both") assert.True(t, ok) assert.Empty(t, value) assert.Empty(t, c.PostForm("both")) assert.Equal(t, c.DefaultPostForm("both", "nothing"), "") assert.Equal(t, c.Query("both"), "GET") value, ok = c.GetQuery("id") assert.True(t, ok) assert.Equal(t, value, "main") assert.Equal(t, c.DefaultPostForm("id", "000"), "000") assert.Equal(t, c.Query("id"), "main") assert.Empty(t, c.PostForm("id")) value, ok = c.GetQuery("NoKey") assert.False(t, ok) assert.Empty(t, value) value, ok = c.GetPostForm("NoKey") assert.False(t, ok) assert.Empty(t, value) assert.Equal(t, c.DefaultPostForm("NoKey", "nada"), "nada") assert.Equal(t, c.DefaultQuery("NoKey", "nothing"), "nothing") assert.Empty(t, c.PostForm("NoKey")) assert.Empty(t, c.Query("NoKey")) var obj struct { Foo string `form:"foo"` ID string `form:"id"` Page int `form:"page"` Both string `form:"both"` Array []string `form:"array[]"` } assert.NoError(t, c.Bind(&obj)) assert.Equal(t, obj.Foo, "bar") assert.Equal(t, obj.ID, "main") assert.Equal(t, obj.Page, 11) assert.Equal(t, obj.Both, "") assert.Equal(t, obj.Array, []string{"first", "second"}) values, ok := c.GetQueryArray("array[]") assert.True(t, ok) assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.QueryArray("array[]") assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.QueryArray("nokey") assert.Equal(t, 0, len(values)) values = c.QueryArray("both") assert.Equal(t, 1, len(values)) assert.Equal(t, "GET", values[0]) } func TestContextPostFormMultipart(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request = createMultipartRequest() var obj struct { Foo string `form:"foo"` Bar string `form:"bar"` BarAsInt int `form:"bar"` Array []string `form:"array"` ID string `form:"id"` TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"` TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"` BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"` } assert.NoError(t, c.Bind(&obj)) assert.Equal(t, obj.Foo, "bar") assert.Equal(t, obj.Bar, "10") assert.Equal(t, obj.BarAsInt, 10) assert.Equal(t, obj.Array, []string{"first", "second"}) assert.Equal(t, obj.ID, "") assert.Equal(t, obj.TimeLocal.Format("02/01/2006 15:04"), "31/12/2016 14:55") assert.Equal(t, obj.TimeLocal.Location(), time.Local) assert.Equal(t, obj.TimeUTC.Format("02/01/2006 15:04"), "31/12/2016 14:55") assert.Equal(t, obj.TimeUTC.Location(), time.UTC) assert.True(t, obj.BlankTime.IsZero()) value, ok := c.GetQuery("foo") assert.False(t, ok) assert.Empty(t, value) assert.Empty(t, c.Query("bar")) assert.Equal(t, c.DefaultQuery("id", "nothing"), "nothing") value, ok = c.GetPostForm("foo") assert.True(t, ok) assert.Equal(t, value, "bar") assert.Equal(t, c.PostForm("foo"), "bar") value, ok = c.GetPostForm("array") assert.True(t, ok) assert.Equal(t, value, "first") assert.Equal(t, c.PostForm("array"), "first") assert.Equal(t, c.DefaultPostForm("bar", "nothing"), "10") value, ok = c.GetPostForm("id") assert.True(t, ok) assert.Empty(t, value) assert.Empty(t, c.PostForm("id")) assert.Empty(t, c.DefaultPostForm("id", "nothing")) value, ok = c.GetPostForm("nokey") assert.False(t, ok) assert.Empty(t, value) assert.Equal(t, c.DefaultPostForm("nokey", "nothing"), "nothing") values, ok := c.GetPostFormArray("array") assert.True(t, ok) assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.PostFormArray("array") assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.PostFormArray("nokey") assert.Equal(t, 0, len(values)) values = c.PostFormArray("foo") assert.Equal(t, 1, len(values)) assert.Equal(t, "bar", values[0]) } func TestContextSetCookie(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.SetCookie("user", "gin", 1, "/", "localhost", true, true) assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure") } func TestContextSetCookiePathEmpty(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.SetCookie("user", "gin", 1, "", "localhost", true, true) assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure") } func TestContextGetCookie(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("GET", "/get", nil) c.Request.Header.Set("Cookie", "user=gin") cookie, _ := c.Cookie("user") assert.Equal(t, cookie, "gin") _, err := c.Cookie("nokey") assert.Error(t, err) } func TestContextBodyAllowedForStatus(t *testing.T) { assert.Equal(t, false, bodyAllowedForStatus(102)) assert.Equal(t, false, bodyAllowedForStatus(204)) assert.Equal(t, false, bodyAllowedForStatus(304)) assert.Equal(t, true, bodyAllowedForStatus(500)) } type TestPanicRender struct { } func (*TestPanicRender) Render(http.ResponseWriter) error { return errors.New("TestPanicRender") } func (*TestPanicRender) WriteContentType(http.ResponseWriter) {} func TestContextRenderPanicIfErr(t *testing.T) { defer func() { r := recover() assert.Equal(t, "TestPanicRender", fmt.Sprint(r)) }() w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Render(http.StatusOK, &TestPanicRender{}) assert.Fail(t, "Panic not detected") } // Tests that the response is serialized as JSON // and Content-Type is set to application/json func TestContextRenderJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.JSON(201, H{"foo": "bar"}) assert.Equal(t, 201, w.Code) assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type")) } // Tests that no JSON is rendered if code is 204 func TestContextRenderNoContentJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.JSON(204, H{"foo": "bar"}) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type")) } // Tests that the response is serialized as JSON // we change the content-type before func TestContextRenderAPIJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Header("Content-Type", "application/vnd.api+json") c.JSON(201, H{"foo": "bar"}) assert.Equal(t, 201, w.Code) assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String()) assert.Equal(t, "application/vnd.api+json", w.HeaderMap.Get("Content-Type")) } // Tests that no Custom JSON is rendered if code is 204 func TestContextRenderNoContentAPIJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Header("Content-Type", "application/vnd.api+json") c.JSON(204, H{"foo": "bar"}) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json") } // Tests that the response is serialized as JSON // and Content-Type is set to application/json func TestContextRenderIndentedJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}}) assert.Equal(t, w.Code, 201) assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8") } // Tests that no Custom JSON is rendered if code is 204 func TestContextRenderNoContentIndentedJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.IndentedJSON(204, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}}) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8") } // Tests that the response executes the templates // and responds with Content-Type set to text/html func TestContextRenderHTML(t *testing.T) { w := httptest.NewRecorder() c, router := CreateTestContext(w) templ := template.Must(template.New("t").Parse(`Hello {{.name}}`)) router.SetHTMLTemplate(templ) c.HTML(201, "t", H{"name": "alexandernyquist"}) assert.Equal(t, w.Code, 201) assert.Equal(t, w.Body.String(), "Hello alexandernyquist") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8") } // Tests that no HTML is rendered if code is 204 func TestContextRenderNoContentHTML(t *testing.T) { w := httptest.NewRecorder() c, router := CreateTestContext(w) templ := template.Must(template.New("t").Parse(`Hello {{.name}}`)) router.SetHTMLTemplate(templ) c.HTML(204, "t", H{"name": "alexandernyquist"}) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8") } // TestContextXML tests that the response is serialized as XML // and Content-Type is set to application/xml func TestContextRenderXML(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.XML(201, H{"foo": "bar"}) assert.Equal(t, w.Code, 201) assert.Equal(t, w.Body.String(), "bar") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8") } // Tests that no XML is rendered if code is 204 func TestContextRenderNoContentXML(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.XML(204, H{"foo": "bar"}) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8") } // TestContextString tests that the response is returned // with Content-Type set to text/plain func TestContextRenderString(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.String(201, "test %s %d", "string", 2) assert.Equal(t, w.Code, 201) assert.Equal(t, w.Body.String(), "test string 2") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") } // Tests that no String is rendered if code is 204 func TestContextRenderNoContentString(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.String(204, "test %s %d", "string", 2) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") } // TestContextString tests that the response is returned // with Content-Type set to text/html func TestContextRenderHTMLString(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Header("Content-Type", "text/html; charset=utf-8") c.String(201, "%s %d", "string", 3) assert.Equal(t, w.Code, 201) assert.Equal(t, w.Body.String(), "string 3") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8") } // Tests that no HTML String is rendered if code is 204 func TestContextRenderNoContentHTMLString(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Header("Content-Type", "text/html; charset=utf-8") c.String(204, "%s %d", "string", 3) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8") } // TestContextData tests that the response can be written from `bytesting` // with specified MIME type func TestContextRenderData(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Data(201, "text/csv", []byte(`foo,bar`)) assert.Equal(t, w.Code, 201) assert.Equal(t, w.Body.String(), "foo,bar") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv") } // Tests that no Custom Data is rendered if code is 204 func TestContextRenderNoContentData(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Data(204, "text/csv", []byte(`foo,bar`)) assert.Equal(t, 204, w.Code) assert.Equal(t, "", w.Body.String()) assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv") } func TestContextRenderSSE(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.SSEvent("float", 1.5) c.Render(-1, sse.Event{ Id: "123", Data: "text", }) c.SSEvent("chat", H{ "foo": "bar", "bar": "foo", }) assert.Equal(t, strings.Replace(w.Body.String(), " ", "", -1), strings.Replace("event:float\ndata:1.5\n\nid:123\ndata:text\n\nevent:chat\ndata:{\"bar\":\"foo\",\"foo\":\"bar\"}\n\n", " ", "", -1)) } func TestContextRenderFile(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("GET", "/", nil) c.File("./gin.go") assert.Equal(t, w.Code, 200) assert.Contains(t, w.Body.String(), "func New() *Engine {") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") } // TestContextRenderYAML tests that the response is serialized as YAML // and Content-Type is set to application/x-yaml func TestContextRenderYAML(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.YAML(201, H{"foo": "bar"}) assert.Equal(t, w.Code, 201) assert.Equal(t, w.Body.String(), "foo: bar\n") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8") } func TestContextHeaders(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Header("Content-Type", "text/plain") c.Header("X-Custom", "value") assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain") assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value") c.Header("Content-Type", "text/html") c.Header("X-Custom", "") assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html") _, exist := c.Writer.Header()["X-Custom"] assert.False(t, exist) } // TODO func TestContextRenderRedirectWithRelativePath(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "http://example.com", nil) assert.Panics(t, func() { c.Redirect(299, "/new_path") }) assert.Panics(t, func() { c.Redirect(309, "/new_path") }) c.Redirect(301, "/path") c.Writer.WriteHeaderNow() assert.Equal(t, w.Code, 301) assert.Equal(t, w.Header().Get("Location"), "/path") } func TestContextRenderRedirectWithAbsolutePath(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "http://example.com", nil) c.Redirect(302, "http://google.com") c.Writer.WriteHeaderNow() assert.Equal(t, w.Code, 302) assert.Equal(t, w.Header().Get("Location"), "http://google.com") } func TestContextRenderRedirectWith201(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "http://example.com", nil) c.Redirect(201, "/resource") c.Writer.WriteHeaderNow() assert.Equal(t, w.Code, 201) assert.Equal(t, w.Header().Get("Location"), "/resource") } func TestContextRenderRedirectAll(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "http://example.com", nil) assert.Panics(t, func() { c.Redirect(200, "/resource") }) assert.Panics(t, func() { c.Redirect(202, "/resource") }) assert.Panics(t, func() { c.Redirect(299, "/resource") }) assert.Panics(t, func() { c.Redirect(309, "/resource") }) assert.NotPanics(t, func() { c.Redirect(300, "/resource") }) assert.NotPanics(t, func() { c.Redirect(308, "/resource") }) } func TestContextNegotiationWithJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "", nil) c.Negotiate(200, Negotiate{ Offered: []string{MIMEJSON, MIMEXML}, Data: H{"foo": "bar"}, }) assert.Equal(t, 200, w.Code) assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type")) } func TestContextNegotiationWithXML(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "", nil) c.Negotiate(200, Negotiate{ Offered: []string{MIMEXML, MIMEJSON}, Data: H{"foo": "bar"}, }) assert.Equal(t, 200, w.Code) assert.Equal(t, "bar", w.Body.String()) assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type")) } func TestContextNegotiationWithHTML(t *testing.T) { w := httptest.NewRecorder() c, router := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "", nil) templ := template.Must(template.New("t").Parse(`Hello {{.name}}`)) router.SetHTMLTemplate(templ) c.Negotiate(200, Negotiate{ Offered: []string{MIMEHTML}, Data: H{"name": "gin"}, HTMLName: "t", }) assert.Equal(t, 200, w.Code) assert.Equal(t, "Hello gin", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type")) } func TestContextNegotiationNotSupport(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "", nil) c.Negotiate(200, Negotiate{ Offered: []string{MIMEPOSTForm}, }) assert.Equal(t, 406, w.Code) assert.Equal(t, c.index, abortIndex) assert.True(t, c.IsAborted()) } func TestContextNegotiationFormat(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "", nil) assert.Panics(t, func() { c.NegotiateFormat() }) assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON) assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML) } func TestContextNegotiationFormatWithAccept(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", nil) c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML) assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML) assert.Equal(t, c.NegotiateFormat(MIMEJSON), "") } func TestContextNegotiationFormatCustum(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", nil) c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") c.Accepted = nil c.SetAccepted(MIMEJSON, MIMEXML) assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON) assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML) assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON) } func TestContextIsAborted(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) assert.False(t, c.IsAborted()) c.Abort() assert.True(t, c.IsAborted()) c.Next() assert.True(t, c.IsAborted()) c.index++ assert.True(t, c.IsAborted()) } // TestContextData tests that the response can be written from `bytesting` // with specified MIME type func TestContextAbortWithStatus(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.index = 4 c.AbortWithStatus(401) assert.Equal(t, c.index, abortIndex) assert.Equal(t, c.Writer.Status(), 401) assert.Equal(t, w.Code, 401) assert.True(t, c.IsAborted()) } type testJSONAbortMsg struct { Foo string `json:"foo"` Bar string `json:"bar"` } func TestContextAbortWithStatusJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.index = 4 in := new(testJSONAbortMsg) in.Bar = "barValue" in.Foo = "fooValue" c.AbortWithStatusJSON(415, in) assert.Equal(t, c.index, abortIndex) assert.Equal(t, c.Writer.Status(), 415) assert.Equal(t, w.Code, 415) assert.True(t, c.IsAborted()) contentType := w.Header().Get("Content-Type") assert.Equal(t, contentType, "application/json; charset=utf-8") buf := new(bytes.Buffer) buf.ReadFrom(w.Body) jsonStringBody := buf.String() assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody) } func TestContextError(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) assert.Empty(t, c.Errors) c.Error(errors.New("first error")) assert.Len(t, c.Errors, 1) assert.Equal(t, c.Errors.String(), "Error #01: first error\n") c.Error(&Error{ Err: errors.New("second error"), Meta: "some data 2", Type: ErrorTypePublic, }) assert.Len(t, c.Errors, 2) assert.Equal(t, c.Errors[0].Err, errors.New("first error")) assert.Nil(t, c.Errors[0].Meta) assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate) assert.Equal(t, c.Errors[1].Err, errors.New("second error")) assert.Equal(t, c.Errors[1].Meta, "some data 2") assert.Equal(t, c.Errors[1].Type, ErrorTypePublic) assert.Equal(t, c.Errors.Last(), c.Errors[1]) } func TestContextTypedError(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Error(errors.New("externo 0")).SetType(ErrorTypePublic) c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate) for _, err := range c.Errors.ByType(ErrorTypePublic) { assert.Equal(t, err.Type, ErrorTypePublic) } for _, err := range c.Errors.ByType(ErrorTypePrivate) { assert.Equal(t, err.Type, ErrorTypePrivate) } assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"}) } func TestContextAbortWithError(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.AbortWithError(401, errors.New("bad input")).SetMeta("some input") assert.Equal(t, w.Code, 401) assert.Equal(t, c.index, abortIndex) assert.True(t, c.IsAborted()) } func TestContextClientIP(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", nil) c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ") c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30") c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50") c.Request.RemoteAddr = " 40.40.40.40:42123 " assert.Equal(t, "20.20.20.20", c.ClientIP()) c.Request.Header.Del("X-Forwarded-For") assert.Equal(t, "10.10.10.10", c.ClientIP()) c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ") assert.Equal(t, "30.30.30.30", c.ClientIP()) c.Request.Header.Del("X-Forwarded-For") c.Request.Header.Del("X-Real-IP") c.engine.AppEngine = true assert.Equal(t, "50.50.50.50", c.ClientIP()) c.Request.Header.Del("X-Appengine-Remote-Addr") assert.Equal(t, "40.40.40.40", c.ClientIP()) // no port c.Request.RemoteAddr = "50.50.50.50" assert.Equal(t, "", c.ClientIP()) } func TestContextContentType(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", nil) c.Request.Header.Set("Content-Type", "application/json; charset=utf-8") assert.Equal(t, c.ContentType(), "application/json") } func TestContextAutoBindJSON(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}")) c.Request.Header.Add("Content-Type", MIMEJSON) var obj struct { Foo string `json:"foo"` Bar string `json:"bar"` } assert.NoError(t, c.Bind(&obj)) assert.Equal(t, obj.Bar, "foo") assert.Equal(t, obj.Foo, "bar") assert.Empty(t, c.Errors) } func TestContextBindWithJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}")) c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type var obj struct { Foo string `json:"foo"` Bar string `json:"bar"` } assert.NoError(t, c.BindJSON(&obj)) assert.Equal(t, obj.Bar, "foo") assert.Equal(t, obj.Foo, "bar") assert.Equal(t, w.Body.Len(), 0) } func TestContextBadAutoBind(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}")) c.Request.Header.Add("Content-Type", MIMEJSON) var obj struct { Foo string `json:"foo"` Bar string `json:"bar"` } assert.False(t, c.IsAborted()) assert.Error(t, c.Bind(&obj)) c.Writer.WriteHeaderNow() assert.Empty(t, obj.Bar) assert.Empty(t, obj.Foo) assert.Equal(t, w.Code, 400) assert.True(t, c.IsAborted()) } func TestContextGolangContext(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}")) assert.NoError(t, c.Err()) assert.Nil(t, c.Done()) ti, ok := c.Deadline() assert.Equal(t, ti, time.Time{}) assert.False(t, ok) assert.Equal(t, c.Value(0), c.Request) assert.Nil(t, c.Value("foo")) c.Set("foo", "bar") assert.Equal(t, c.Value("foo"), "bar") assert.Nil(t, c.Value(1)) } func TestWebsocketsRequired(t *testing.T) { // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2 c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("GET", "/chat", nil) c.Request.Header.Set("Host", "server.example.com") c.Request.Header.Set("Upgrade", "websocket") c.Request.Header.Set("Connection", "Upgrade") c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") c.Request.Header.Set("Origin", "http://example.com") c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat") c.Request.Header.Set("Sec-WebSocket-Version", "13") assert.True(t, c.IsWebsocket()) // Normal request, no websocket required. c, _ = CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("GET", "/chat", nil) c.Request.Header.Set("Host", "server.example.com") assert.False(t, c.IsWebsocket()) } func TestGetRequestHeaderValue(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("GET", "/chat", nil) c.Request.Header.Set("Gin-Version", "1.0.0") assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version")) assert.Equal(t, "", c.GetHeader("Connection")) } func TestContextGetRawData(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) body := bytes.NewBufferString("Fetch binary post data") c.Request, _ = http.NewRequest("POST", "/", body) c.Request.Header.Add("Content-Type", MIMEPOSTForm) data, err := c.GetRawData() assert.Nil(t, err) assert.Equal(t, "Fetch binary post data", string(data)) } gin-1.2/debug.go000066400000000000000000000034101312613627200135470ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "html/template" "log" ) func init() { log.SetFlags(0) } // IsDebugging returns true if the framework is running in debug mode. // Use SetMode(gin.Release) to switch to disable the debug mode. func IsDebugging() bool { return ginMode == debugCode } func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) handlerName := nameOfFunction(handlers.Last()) debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } } func debugPrintLoadTemplate(tmpl *template.Template) { if IsDebugging() { var buf bytes.Buffer for _, tmpl := range tmpl.Templates() { buf.WriteString("\t- ") buf.WriteString(tmpl.Name()) buf.WriteString("\n") } debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) } } func debugPrint(format string, values ...interface{}) { if IsDebugging() { log.Printf("[GIN-debug] "+format, values...) } } func debugPrintWARNINGNew() { debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) `) } func debugPrintWARNINGSetHTMLTemplate() { debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization. ie. before any route is registered or the router is listening in a socket: router := gin.Default() router.SetHTMLTemplate(template) // << good place `) } func debugPrintError(err error) { if err != nil { debugPrint("[ERROR] %v\n", err) } } gin-1.2/debug_test.go000066400000000000000000000047761312613627200146260ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "html/template" "io" "log" "os" "testing" "github.com/stretchr/testify/assert" ) // TODO // func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) { // func debugPrint(format string, values ...interface{}) { func TestIsDebugging(t *testing.T) { SetMode(DebugMode) assert.True(t, IsDebugging()) SetMode(ReleaseMode) assert.False(t, IsDebugging()) SetMode(TestMode) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { var w bytes.Buffer setup(&w) defer teardown() SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) debugPrint("DEBUG this!") assert.Empty(t, w.String()) SetMode(DebugMode) debugPrint("these are %d %s\n", 2, "error messages") assert.Equal(t, w.String(), "[GIN-debug] these are 2 error messages\n") } func TestDebugPrintError(t *testing.T) { var w bytes.Buffer setup(&w) defer teardown() SetMode(DebugMode) debugPrintError(nil) assert.Empty(t, w.String()) debugPrintError(errors.New("this is an error")) assert.Equal(t, w.String(), "[GIN-debug] [ERROR] this is an error\n") } func TestDebugPrintRoutes(t *testing.T) { var w bytes.Buffer setup(&w) defer teardown() debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, w.String()) } func TestDebugPrintLoadTemplate(t *testing.T) { var w bytes.Buffer setup(&w) defer teardown() templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./fixtures/basic/hello.tmpl")) debugPrintLoadTemplate(templ) assert.Equal(t, w.String(), "[GIN-debug] Loaded HTML Templates (2): \n\t- \n\t- hello.tmpl\n\n") } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { var w bytes.Buffer setup(&w) defer teardown() debugPrintWARNINGSetHTMLTemplate() assert.Equal(t, w.String(), "[GIN-debug] [WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called\nat initialization. ie. before any route is registered or the router is listening in a socket:\n\n\trouter := gin.Default()\n\trouter.SetHTMLTemplate(template) // << good place\n\n") } func setup(w io.Writer) { SetMode(DebugMode) log.SetOutput(w) } func teardown() { SetMode(TestMode) log.SetOutput(os.Stdout) } gin-1.2/deprecated.go000066400000000000000000000015611312613627200145660ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "github.com/gin-gonic/gin/binding" "log" ) func (c *Context) GetCookie(name string) (string, error) { log.Println("GetCookie() method is deprecated. Use Cookie() instead.") return c.Cookie(name) } // BindWith binds the passed struct pointer using the specified binding engine. // See the binding package. func (c *Context) BindWith(obj interface{}, b binding.Binding) error { log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to be deprecated, please check issue #662 and either use MustBindWith() if you want HTTP 400 to be automatically returned if any error occur, of use ShouldBindWith() if you need to manage the error.`) return c.MustBindWith(obj, b) } gin-1.2/errors.go000066400000000000000000000062421312613627200140030ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "encoding/json" "fmt" "reflect" ) type ErrorType uint64 const ( ErrorTypeBind ErrorType = 1 << 63 // used when c.Bind() fails ErrorTypeRender ErrorType = 1 << 62 // used when c.Render() fails ErrorTypePrivate ErrorType = 1 << 0 ErrorTypePublic ErrorType = 1 << 1 ErrorTypeAny ErrorType = 1<<64 - 1 ErrorTypeNu = 2 ) type ( Error struct { Err error Type ErrorType Meta interface{} } errorMsgs []*Error ) var _ error = &Error{} func (msg *Error) SetType(flags ErrorType) *Error { msg.Type = flags return msg } func (msg *Error) SetMeta(data interface{}) *Error { msg.Meta = data return msg } func (msg *Error) JSON() interface{} { json := H{} if msg.Meta != nil { value := reflect.ValueOf(msg.Meta) switch value.Kind() { case reflect.Struct: return msg.Meta case reflect.Map: for _, key := range value.MapKeys() { json[key.String()] = value.MapIndex(key).Interface() } default: json["meta"] = msg.Meta } } if _, ok := json["error"]; !ok { json["error"] = msg.Error() } return json } // MarshalJSON implements the json.Marshaller interface func (msg *Error) MarshalJSON() ([]byte, error) { return json.Marshal(msg.JSON()) } // Implements the error interface func (msg Error) Error() string { return msg.Err.Error() } func (msg *Error) IsType(flags ErrorType) bool { return (msg.Type & flags) > 0 } // Returns a readonly copy filtered the byte. // ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic func (a errorMsgs) ByType(typ ErrorType) errorMsgs { if len(a) == 0 { return nil } if typ == ErrorTypeAny { return a } var result errorMsgs for _, msg := range a { if msg.IsType(typ) { result = append(result, msg) } } return result } // Returns the last error in the slice. It returns nil if the array is empty. // Shortcut for errors[len(errors)-1] func (a errorMsgs) Last() *Error { length := len(a) if length > 0 { return a[length-1] } return nil } // Returns an array will all the error messages. // Example: // c.Error(errors.New("first")) // c.Error(errors.New("second")) // c.Error(errors.New("third")) // c.Errors.Errors() // == []string{"first", "second", "third"} func (a errorMsgs) Errors() []string { if len(a) == 0 { return nil } errorStrings := make([]string, len(a)) for i, err := range a { errorStrings[i] = err.Error() } return errorStrings } func (a errorMsgs) JSON() interface{} { switch len(a) { case 0: return nil case 1: return a.Last().JSON() default: json := make([]interface{}, len(a)) for i, err := range a { json[i] = err.JSON() } return json } } func (a errorMsgs) MarshalJSON() ([]byte, error) { return json.Marshal(a.JSON()) } func (a errorMsgs) String() string { if len(a) == 0 { return "" } var buffer bytes.Buffer for i, msg := range a { fmt.Fprintf(&buffer, "Error #%02d: %s\n", (i + 1), msg.Err) if msg.Meta != nil { fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) } } return buffer.String() } gin-1.2/errors_test.go000066400000000000000000000060521312613627200150410ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "encoding/json" "errors" "testing" "github.com/stretchr/testify/assert" ) func TestError(t *testing.T) { baseError := errors.New("test error") err := &Error{ Err: baseError, Type: ErrorTypePrivate, } assert.Equal(t, err.Error(), baseError.Error()) assert.Equal(t, err.JSON(), H{"error": baseError.Error()}) assert.Equal(t, err.SetType(ErrorTypePublic), err) assert.Equal(t, err.Type, ErrorTypePublic) assert.Equal(t, err.SetMeta("some data"), err) assert.Equal(t, err.Meta, "some data") assert.Equal(t, err.JSON(), H{ "error": baseError.Error(), "meta": "some data", }) jsonBytes, _ := json.Marshal(err) assert.Equal(t, string(jsonBytes), "{\"error\":\"test error\",\"meta\":\"some data\"}") err.SetMeta(H{ "status": "200", "data": "some data", }) assert.Equal(t, err.JSON(), H{ "error": baseError.Error(), "status": "200", "data": "some data", }) err.SetMeta(H{ "error": "custom error", "status": "200", "data": "some data", }) assert.Equal(t, err.JSON(), H{ "error": "custom error", "status": "200", "data": "some data", }) type customError struct { status string data string } err.SetMeta(customError{status: "200", data: "other data"}) assert.Equal(t, err.JSON(), customError{status: "200", data: "other data"}) } func TestErrorSlice(t *testing.T) { errs := errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"}, {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}}, } assert.Equal(t, errs, errs.ByType(ErrorTypeAny)) assert.Equal(t, errs.Last().Error(), "third") assert.Equal(t, errs.Errors(), []string{"first", "second", "third"}) assert.Equal(t, errs.ByType(ErrorTypePublic).Errors(), []string{"third"}) assert.Equal(t, errs.ByType(ErrorTypePrivate).Errors(), []string{"first", "second"}) assert.Equal(t, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors(), []string{"first", "second", "third"}) assert.Empty(t, errs.ByType(ErrorTypeBind)) assert.Empty(t, errs.ByType(ErrorTypeBind).String()) assert.Equal(t, errs.String(), `Error #01: first Error #02: second Meta: some data Error #03: third Meta: map[status:400] `) assert.Equal(t, errs.JSON(), []interface{}{ H{"error": "first"}, H{"error": "second", "meta": "some data"}, H{"error": "third", "status": "400"}, }) jsonBytes, _ := json.Marshal(errs) assert.Equal(t, string(jsonBytes), "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]") errs = errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, } assert.Equal(t, errs.JSON(), H{"error": "first"}) jsonBytes, _ = json.Marshal(errs) assert.Equal(t, string(jsonBytes), "{\"error\":\"first\"}") errs = errorMsgs{} assert.Nil(t, errs.Last()) assert.Nil(t, errs.JSON()) assert.Empty(t, errs.String()) } gin-1.2/examples/000077500000000000000000000000001312613627200137525ustar00rootroot00000000000000gin-1.2/examples/app-engine/000077500000000000000000000000001312613627200157755ustar00rootroot00000000000000gin-1.2/examples/app-engine/README.md000066400000000000000000000007411312613627200172560ustar00rootroot00000000000000# Guide to run Gin under App Engine LOCAL Development Server 1. Download, install and setup Go in your computer. (That includes setting your `$GOPATH`.) 2. Download SDK for your platform from here: `https://developers.google.com/appengine/downloads?hl=es#Google_App_Engine_SDK_for_Go` 3. Download Gin source code using: `$ go get github.com/gin-gonic/gin` 4. Navigate to examples folder: `$ cd $GOPATH/src/github.com/gin-gonic/gin/examples/` 5. Run it: `$ goapp serve app-engine/`gin-1.2/examples/app-engine/app.yaml000066400000000000000000000001421312613627200174360ustar00rootroot00000000000000application: hello version: 1 runtime: go api_version: go1 handlers: - url: /.* script: _go_appgin-1.2/examples/app-engine/hello.go000066400000000000000000000007151312613627200174320ustar00rootroot00000000000000package hello import ( "net/http" "github.com/gin-gonic/gin" ) // This function's name is a must. App Engine uses it to drive the requests properly. func init() { // Starts a new Gin instance with no middle-ware r := gin.New() // Define your handlers r.GET("/", func(c *gin.Context) { c.String(200, "Hello World!") }) r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) // Handle all requests using net/http http.Handle("/", r) } gin-1.2/examples/auto-tls/000077500000000000000000000000001312613627200155225ustar00rootroot00000000000000gin-1.2/examples/auto-tls/example1.go000066400000000000000000000004231312613627200175640ustar00rootroot00000000000000package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) log.Fatal(autotls.Run(r, "example1.com", "example2.com")) } gin-1.2/examples/auto-tls/example2.go000066400000000000000000000007361312613627200175740ustar00rootroot00000000000000package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" "golang.org/x/crypto/acme/autocert" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) m := autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"), Cache: autocert.DirCache("/var/www/.cache"), } log.Fatal(autotls.RunWithManager(r, m)) } gin-1.2/examples/basic/000077500000000000000000000000001312613627200150335ustar00rootroot00000000000000gin-1.2/examples/basic/main.go000066400000000000000000000022751312613627200163140ustar00rootroot00000000000000package main import ( "github.com/gin-gonic/gin" ) var DB = make(map[string]string) func main() { // Disable Console Color // gin.DisableConsoleColor() r := gin.Default() // Ping test r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) // Get user value r.GET("/user/:name", func(c *gin.Context) { user := c.Params.ByName("name") value, ok := DB[user] if ok { c.JSON(200, gin.H{"user": user, "value": value}) } else { c.JSON(200, gin.H{"user": user, "status": "no value"}) } }) // Authorized group (uses gin.BasicAuth() middleware) // Same than: // authorized := r.Group("/") // authorized.Use(gin.BasicAuth(gin.Credentials{ // "foo": "bar", // "manu": "123", //})) authorized := r.Group("/", gin.BasicAuth(gin.Accounts{ "foo": "bar", // user:foo password:bar "manu": "123", // user:manu password:123 })) authorized.POST("admin", func(c *gin.Context) { user := c.MustGet(gin.AuthUserKey).(string) // Parse JSON var json struct { Value string `json:"value" binding:"required"` } if c.Bind(&json) == nil { DB[user] = json.Value c.JSON(200, gin.H{"status": "ok"}) } }) // Listen and Server in 0.0.0.0:8080 r.Run(":8080") } gin-1.2/examples/graceful-shutdown/000077500000000000000000000000001312613627200174135ustar00rootroot00000000000000gin-1.2/examples/graceful-shutdown/close/000077500000000000000000000000001312613627200205205ustar00rootroot00000000000000gin-1.2/examples/graceful-shutdown/close/server.go000066400000000000000000000013511312613627200223550ustar00rootroot00000000000000// +build go1.8 package main import ( "log" "net/http" "os" "os/signal" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Welcome Gin Server") }) server := &http.Server{ Addr: ":8080", Handler: router, } quit := make(chan os.Signal) signal.Notify(quit, os.Interrupt) go func() { <-quit log.Println("receive interrupt signal") if err := server.Close(); err != nil { log.Fatal("Server Close:", err) } }() if err := server.ListenAndServe(); err != nil { if err == http.ErrServerClosed { log.Println("Server closed under request") } else { log.Fatal("Server closed unexpect") } } log.Println("Server exist") } gin-1.2/examples/graceful-shutdown/graceful-shutdown/000077500000000000000000000000001312613627200230545ustar00rootroot00000000000000gin-1.2/examples/graceful-shutdown/graceful-shutdown/server.go000066400000000000000000000016001312613627200247060ustar00rootroot00000000000000// +build go1.8 package main import ( "context" "log" "net/http" "os" "os/signal" "time" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { time.Sleep(5 * time.Second) c.String(http.StatusOK, "Welcome Gin Server") }) srv := &http.Server{ Addr: ":8080", Handler: router, } go func() { // service connections if err := srv.ListenAndServe(); err != nil { log.Printf("listen: %s\n", err) } }() // Wait for interrupt signal to gracefully shutdown the server with // a timeout of 5 seconds. quit := make(chan os.Signal) signal.Notify(quit, os.Interrupt) <-quit log.Println("Shutdown Server ...") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server Shutdown:", err) } log.Println("Server exist") } gin-1.2/examples/realtime-chat/000077500000000000000000000000001312613627200164715ustar00rootroot00000000000000gin-1.2/examples/realtime-chat/Makefile000066400000000000000000000002501312613627200201260ustar00rootroot00000000000000all: deps build .PHONY: deps deps: go get -d -v github.com/dustin/go-broadcast/... .PHONY: build build: deps go build -o realtime-chat main.go rooms.go template.go gin-1.2/examples/realtime-chat/main.go000066400000000000000000000020601312613627200177420ustar00rootroot00000000000000package main import ( "fmt" "io" "math/rand" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.SetHTMLTemplate(html) router.GET("/room/:roomid", roomGET) router.POST("/room/:roomid", roomPOST) router.DELETE("/room/:roomid", roomDELETE) router.GET("/stream/:roomid", stream) router.Run(":8080") } func stream(c *gin.Context) { roomid := c.Param("roomid") listener := openListener(roomid) defer closeListener(roomid, listener) c.Stream(func(w io.Writer) bool { c.SSEvent("message", <-listener) return true }) } func roomGET(c *gin.Context) { roomid := c.Param("roomid") userid := fmt.Sprint(rand.Int31()) c.HTML(200, "chat_room", gin.H{ "roomid": roomid, "userid": userid, }) } func roomPOST(c *gin.Context) { roomid := c.Param("roomid") userid := c.PostForm("user") message := c.PostForm("message") room(roomid).Submit(userid + ": " + message) c.JSON(200, gin.H{ "status": "success", "message": message, }) } func roomDELETE(c *gin.Context) { roomid := c.Param("roomid") deleteBroadcast(roomid) } gin-1.2/examples/realtime-chat/rooms.go000066400000000000000000000012331312613627200201560ustar00rootroot00000000000000package main import "github.com/dustin/go-broadcast" var roomChannels = make(map[string]broadcast.Broadcaster) func openListener(roomid string) chan interface{} { listener := make(chan interface{}) room(roomid).Register(listener) return listener } func closeListener(roomid string, listener chan interface{}) { room(roomid).Unregister(listener) close(listener) } func deleteBroadcast(roomid string) { b, ok := roomChannels[roomid] if ok { b.Close() delete(roomChannels, roomid) } } func room(roomid string) broadcast.Broadcaster { b, ok := roomChannels[roomid] if !ok { b = broadcast.NewBroadcaster(10) roomChannels[roomid] = b } return b } gin-1.2/examples/realtime-chat/template.go000066400000000000000000000030021312613627200206260ustar00rootroot00000000000000package main import "html/template" var html = template.Must(template.New("chat_room").Parse(` {{.roomid}}

Welcome to {{.roomid}} room

User: Message:
`)) gin-1.2/examples/upload-file/000077500000000000000000000000001312613627200161535ustar00rootroot00000000000000gin-1.2/examples/upload-file/multiple/000077500000000000000000000000001312613627200200065ustar00rootroot00000000000000gin-1.2/examples/upload-file/multiple/main.go000066400000000000000000000013101312613627200212540ustar00rootroot00000000000000package main import ( "fmt" "io" "net/http" "os" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.Static("/", "./public") router.POST("/upload", func(c *gin.Context) { name := c.PostForm("name") email := c.PostForm("email") // Multipart form form, _ := c.MultipartForm() files := form.File["files"] for _, file := range files { // Source src, _ := file.Open() defer src.Close() // Destination dst, _ := os.Create(file.Filename) defer dst.Close() // Copy io.Copy(dst, src) } c.String(http.StatusOK, fmt.Sprintf("Uploaded successfully %d files with fields name=%s and email=%s.", len(files), name, email)) }) router.Run(":8080") } gin-1.2/examples/upload-file/multiple/public/000077500000000000000000000000001312613627200212645ustar00rootroot00000000000000gin-1.2/examples/upload-file/multiple/public/index.html000066400000000000000000000007071312613627200232650ustar00rootroot00000000000000 Multiple file upload

Upload multiple files with fields

Name:
Email:
Files:

gin-1.2/examples/upload-file/single/000077500000000000000000000000001312613627200174345ustar00rootroot00000000000000gin-1.2/examples/upload-file/single/main.go000066400000000000000000000011551312613627200207110ustar00rootroot00000000000000package main import ( "fmt" "io" "net/http" "os" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.Static("/", "./public") router.POST("/upload", func(c *gin.Context) { name := c.PostForm("name") email := c.PostForm("email") // Source file, _ := c.FormFile("file") src, _ := file.Open() defer src.Close() // Destination dst, _ := os.Create(file.Filename) defer dst.Close() // Copy io.Copy(dst, src) c.String(http.StatusOK, fmt.Sprintf("File %s uploaded successfully with fields name=%s and email=%s.", file.Filename, name, email)) }) router.Run(":8080") } gin-1.2/examples/upload-file/single/public/000077500000000000000000000000001312613627200207125ustar00rootroot00000000000000gin-1.2/examples/upload-file/single/public/index.html000066400000000000000000000006601312613627200227110ustar00rootroot00000000000000 Single file upload

Upload single file with fields

Name:
Email:
Files:

gin-1.2/fixtures/000077500000000000000000000000001312613627200140055ustar00rootroot00000000000000gin-1.2/fixtures/basic/000077500000000000000000000000001312613627200150665ustar00rootroot00000000000000gin-1.2/fixtures/basic/hello.tmpl000066400000000000000000000000321312613627200170620ustar00rootroot00000000000000

Hello {[{.name}]}

gin-1.2/fixtures/basic/raw.tmpl000066400000000000000000000000401312613627200165470ustar00rootroot00000000000000Date: {[{.now | formatAsDate}]} gin-1.2/fs.go000066400000000000000000000021311312613627200130700ustar00rootroot00000000000000// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "os" ) type ( onlyfilesFS struct { fs http.FileSystem } neuteredReaddirFile struct { http.File } ) // Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally // in router.Static(). // if listDirectory == true, then it works the same as http.Dir() otherwise it returns // a filesystem that prevents http.FileServer() to list the directory files. func Dir(root string, listDirectory bool) http.FileSystem { fs := http.Dir(root) if listDirectory { return fs } return &onlyfilesFS{fs} } // Conforms to http.Filesystem func (fs onlyfilesFS) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return neuteredReaddirFile{f}, nil } // Overrides the http.File default implementation func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) { // this disables directory listing return nil, nil } gin-1.2/gin.go000066400000000000000000000310521312613627200132410ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "html/template" "net" "net/http" "os" "sync" "github.com/gin-gonic/gin/render" ) // Version is Framework's version const Version = "v1.2" var default404Body = []byte("404 page not found") var default405Body = []byte("405 method not allowed") var defaultAppEngine bool type HandlerFunc func(*Context) type HandlersChain []HandlerFunc // Last returns the last handler in the chain. ie. the last handler is the main own. func (c HandlersChain) Last() HandlerFunc { length := len(c) if length > 0 { return c[length-1] } return nil } type ( RoutesInfo []RouteInfo RouteInfo struct { Method string Path string Handler string } // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. // Create an instance of Engine, by using New() or Default() Engine struct { RouterGroup delims render.Delims HTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool ForwardedByClientIP bool // #726 #755 If enabled, it will thrust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // If enabled, the url.RawPath will be used to find parameters. UseRawPath bool // If true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool } ) var _ IRouter = &Engine{} // New returns a new blank Engine instance without any middleware attached. // By default the configuration is: // - RedirectTrailingSlash: true // - RedirectFixedPath: false // - HandleMethodNotAllowed: false // - ForwardedByClientIP: true // - UseRawPath: false // - UnescapePathValues: true func New() *Engine { debugPrintWARNINGNew() engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, AppEngine: defaultAppEngine, UseRawPath: false, UnescapePathValues: true, trees: make(methodTrees, 0, 9), delims: render.Delims{"{{", "}}"}, } engine.RouterGroup.engine = engine engine.pool.New = func() interface{} { return engine.allocateContext() } return engine } // Default returns an Engine instance with the Logger and Recovery middleware already attached. func Default() *Engine { engine := New() engine.Use(Logger(), Recovery()) return engine } func (engine *Engine) allocateContext() *Context { return &Context{engine: engine} } func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{left, right} return engine } func (engine *Engine) LoadHTMLGlob(pattern string) { if IsDebugging() { debugPrintLoadTemplate(template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseGlob(pattern))) engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} } else { templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseGlob(pattern)) engine.SetHTMLTemplate(templ) } } func (engine *Engine) LoadHTMLFiles(files ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} } else { templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) engine.SetHTMLTemplate(templ) } } func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 { debugPrintWARNINGSetHTMLTemplate() } engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} } func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } // NoRoute adds handlers for NoRoute. It return a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } // NoMethod sets the handlers called when... TODO func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } // Use attachs a global middleware to the router. ie. the middleware attached though Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } func (engine *Engine) rebuild404Handlers() { engine.allNoRoute = engine.combineHandlers(engine.noRoute) } func (engine *Engine) rebuild405Handlers() { engine.allNoMethod = engine.combineHandlers(engine.noMethod) } func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { assert1(path[0] == '/', "path must begin with '/'") assert1(len(method) > 0, "HTTP method can not be empty") assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers) root := engine.trees.get(method) if root == nil { root = new(node) engine.trees = append(engine.trees, methodTree{method: method, root: root}) } root.addRoute(path, handlers) } // Routes returns a slice of registered routes, including some useful information, such as: // the http method, path and the handler name. func (engine *Engine) Routes() (routes RoutesInfo) { for _, tree := range engine.trees { routes = iterate("", tree.method, routes, tree.root) } return routes } func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { path += root.path if len(root.handlers) > 0 { routes = append(routes, RouteInfo{ Method: method, Path: path, Handler: nameOfFunction(root.handlers.Last()), }) } for _, child := range root.children { routes = iterate(path, method, routes, child) } return routes } // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) err = http.ListenAndServe(address, engine) return } // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) { debugPrint("Listening and serving HTTPS on %s\n", addr) defer func() { debugPrintError(err) }() err = http.ListenAndServeTLS(addr, certFile, keyFile, engine) return } // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (ie. a file). // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunUnix(file string) (err error) { debugPrint("Listening and serving HTTP on unix:/%s", file) defer func() { debugPrintError(err) }() os.Remove(file) listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() err = http.Serve(listener, engine) return } // Conforms to the http.Handler interface. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } // Re-enter a context that has been rewritten. // This can be done by setting c.Request.Path to your new target. // Disclaimer: You can loop yourself to death with this, use wisely. func (engine *Engine) HandleContext(c *Context) { c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } func (engine *Engine) handleHTTPRequest(context *Context) { httpMethod := context.Request.Method var path string var unescape bool if engine.UseRawPath && len(context.Request.URL.RawPath) > 0 { path = context.Request.URL.RawPath unescape = engine.UnescapePathValues } else { path = context.Request.URL.Path unescape = false } // Find root of the tree for the given HTTP method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method == httpMethod { root := t[i].root // Find route in tree handlers, params, tsr := root.getValue(path, context.Params, unescape) if handlers != nil { context.handlers = handlers context.Params = params context.Next() context.writermem.WriteHeaderNow() return } if httpMethod != "CONNECT" && path != "/" { if tsr && engine.RedirectTrailingSlash { redirectTrailingSlash(context) return } if engine.RedirectFixedPath && redirectFixedPath(context, root, engine.RedirectFixedPath) { return } } break } } // TODO: unit test if engine.HandleMethodNotAllowed { for _, tree := range engine.trees { if tree.method != httpMethod { if handlers, _, _ := tree.root.getValue(path, nil, unescape); handlers != nil { context.handlers = engine.allNoMethod serveError(context, 405, default405Body) return } } } } context.handlers = engine.allNoRoute serveError(context, 404, default404Body) } var mimePlain = []string{MIMEPlain} func serveError(c *Context, code int, defaultMessage []byte) { c.writermem.status = code c.Next() if !c.writermem.Written() { if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain c.Writer.Write(defaultMessage) } else { c.writermem.WriteHeaderNow() } } } func redirectTrailingSlash(c *Context) { req := c.Request path := req.URL.Path code := 301 // Permanent redirect, request with GET method if req.Method != "GET" { code = 307 } if len(path) > 1 && path[len(path)-1] == '/' { req.URL.Path = path[:len(path)-1] } else { req.URL.Path = path + "/" } debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String()) http.Redirect(c.Writer, req, req.URL.String(), code) c.writermem.WriteHeaderNow() } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { req := c.Request path := req.URL.Path fixedPath, found := root.findCaseInsensitivePath( cleanPath(path), trailingSlash, ) if found { code := 301 // Permanent redirect, request with GET method if req.Method != "GET" { code = 307 } req.URL.Path = string(fixedPath) debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String()) http.Redirect(c.Writer, req, req.URL.String(), code) c.writermem.WriteHeaderNow() return true } return false } gin-1.2/ginS/000077500000000000000000000000001312613627200130345ustar00rootroot00000000000000gin-1.2/ginS/README.md000066400000000000000000000003721312613627200143150ustar00rootroot00000000000000# Gin Default Server This is API experiment for Gin. ```go package main import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/ginS" ) func main() { ginS.GET("/", func(c *gin.Context) { c.String(200, "Hello World") }) ginS.Run() } ``` gin-1.2/ginS/gins.go000066400000000000000000000112731312613627200143270ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package ginS import ( "html/template" "net/http" "sync" . "github.com/gin-gonic/gin" ) var once sync.Once var internalEngine *Engine func engine() *Engine { once.Do(func() { internalEngine = Default() }) return internalEngine } func LoadHTMLGlob(pattern string) { engine().LoadHTMLGlob(pattern) } func LoadHTMLFiles(files ...string) { engine().LoadHTMLFiles(files...) } func SetHTMLTemplate(templ *template.Template) { engine().SetHTMLTemplate(templ) } // NoRoute adds handlers for NoRoute. It return a 404 code by default. func NoRoute(handlers ...HandlerFunc) { engine().NoRoute(handlers...) } // NoMethod sets the handlers called when... TODO func NoMethod(handlers ...HandlerFunc) { engine().NoMethod(handlers...) } // Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. // For example, all the routes that use a common middlware for authorization could be grouped. func Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return engine().Group(relativePath, handlers...) } func Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { return engine().Handle(httpMethod, relativePath, handlers...) } // POST is a shortcut for router.Handle("POST", path, handle) func POST(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().POST(relativePath, handlers...) } // GET is a shortcut for router.Handle("GET", path, handle) func GET(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().GET(relativePath, handlers...) } // DELETE is a shortcut for router.Handle("DELETE", path, handle) func DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().DELETE(relativePath, handlers...) } // PATCH is a shortcut for router.Handle("PATCH", path, handle) func PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().PATCH(relativePath, handlers...) } // PUT is a shortcut for router.Handle("PUT", path, handle) func PUT(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().PUT(relativePath, handlers...) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) func OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().OPTIONS(relativePath, handlers...) } // HEAD is a shortcut for router.Handle("HEAD", path, handle) func HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().HEAD(relativePath, handlers...) } func Any(relativePath string, handlers ...HandlerFunc) IRoutes { return engine().Any(relativePath, handlers...) } func StaticFile(relativePath, filepath string) IRoutes { return engine().StaticFile(relativePath, filepath) } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // router.Static("/static", "/var/www") func Static(relativePath, root string) IRoutes { return engine().Static(relativePath, root) } func StaticFS(relativePath string, fs http.FileSystem) IRoutes { return engine().StaticFS(relativePath, fs) } // Use attachs a global middleware to the router. ie. the middlewares attached though Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func Use(middlewares ...HandlerFunc) IRoutes { return engine().Use(middlewares...) } // Run : The router is attached to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine undefinitelly unless an error happens. func Run(addr ...string) (err error) { return engine().Run(addr...) } // RunTLS : The router is attached to a http.Server and starts listening and serving HTTPS requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine undefinitelly unless an error happens. func RunTLS(addr string, certFile string, keyFile string) (err error) { return engine().RunTLS(addr, certFile, keyFile) } // RunUnix : The router is attached to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (ie. a file) // Note: this method will block the calling goroutine undefinitelly unless an error happens. func RunUnix(file string) (err error) { return engine().RunUnix(file) } gin-1.2/gin_integration_test.go000066400000000000000000000067721312613627200167160ustar00rootroot00000000000000// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bufio" "fmt" "io/ioutil" "net" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/stretchr/testify/assert" ) func testRequest(t *testing.T, url string) { resp, err := http.Get(url) assert.NoError(t, err) defer resp.Body.Close() body, ioerr := ioutil.ReadAll(resp.Body) assert.NoError(t, ioerr) assert.Equal(t, "it worked", string(body), "resp body should match") assert.Equal(t, "200 OK", resp.Status, "should get a 200") } func TestRunEmpty(t *testing.T) { os.Setenv("PORT", "") router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.Run()) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) assert.Error(t, router.Run(":8080")) testRequest(t, "http://localhost:8080/example") } func TestRunEmptyWithEnv(t *testing.T) { os.Setenv("PORT", "3123") router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.Run()) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) assert.Error(t, router.Run(":3123")) testRequest(t, "http://localhost:3123/example") } func TestRunTooMuchParams(t *testing.T) { router := New() assert.Panics(t, func() { router.Run("2", "2") }) } func TestRunWithPort(t *testing.T) { router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.Run(":5150")) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) assert.Error(t, router.Run(":5150")) testRequest(t, "http://localhost:5150/example") } func TestUnixSocket(t *testing.T) { router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.RunUnix("/tmp/unix_unit_test")) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) c, err := net.Dial("unix", "/tmp/unix_unit_test") assert.NoError(t, err) fmt.Fprintf(c, "GET /example HTTP/1.0\r\n\r\n") scanner := bufio.NewScanner(c) var response string for scanner.Scan() { response += scanner.Text() } assert.Contains(t, response, "HTTP/1.0 200", "should get a 200") assert.Contains(t, response, "it worked", "resp body should match") } func TestBadUnixSocket(t *testing.T) { router := New() assert.Error(t, router.RunUnix("#/tmp/unix_unit_test")) } func TestWithHttptestWithAutoSelectedPort(t *testing.T) { router := New() router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) ts := httptest.NewServer(router) defer ts.Close() testRequest(t, ts.URL+"/example") } // func TestWithHttptestWithSpecifiedPort(t *testing.T) { // router := New() // router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) // l, _ := net.Listen("tcp", ":8033") // ts := httptest.Server{ // Listener: l, // Config: &http.Server{Handler: router}, // } // ts.Start() // defer ts.Close() // testRequest(t, "http://localhost:8033/example") // } gin-1.2/gin_test.go000066400000000000000000000235761312613627200143140ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "io/ioutil" "net/http" "reflect" "testing" "time" "github.com/stretchr/testify/assert" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d/%02d/%02d", year, month, day) } func setupHTMLFiles(t *testing.T) func() { go func() { SetMode(TestMode) router := New() router.Delims("{[{", "}]}") router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) router.LoadHTMLFiles("./fixtures/basic/hello.tmpl", "./fixtures/basic/raw.tmpl") router.GET("/test", func(c *Context) { c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"}) }) router.GET("/raw", func(c *Context) { c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) router.Run(":8888") }() t.Log("waiting 1 second for server startup") time.Sleep(1 * time.Second) return func() {} } func setupHTMLGlob(t *testing.T) func() { go func() { SetMode(DebugMode) router := New() router.Delims("{[{", "}]}") router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) router.LoadHTMLGlob("./fixtures/basic/*") router.GET("/test", func(c *Context) { c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"}) }) router.GET("/raw", func(c *Context) { c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) router.Run(":8888") }() t.Log("waiting 1 second for server startup") time.Sleep(1 * time.Second) return func() {} } //TODO func TestLoadHTMLGlob(t *testing.T) { td := setupHTMLGlob(t) res, err := http.Get("http://127.0.0.1:8888/test") if err != nil { fmt.Println(err) } resp, _ := ioutil.ReadAll(res.Body) assert.Equal(t, "

Hello world

", string(resp[:])) td() } func TestLoadHTMLGlobFromFuncMap(t *testing.T) { time.Now() td := setupHTMLGlob(t) res, err := http.Get("http://127.0.0.1:8888/raw") if err != nil { fmt.Println(err) } resp, _ := ioutil.ReadAll(res.Body) assert.Equal(t, "Date: 2017/07/01\n", string(resp[:])) td() } // func (engine *Engine) LoadHTMLFiles(files ...string) { // func (engine *Engine) RunTLS(addr string, cert string, key string) error { func init() { SetMode(TestMode) } func TestCreateEngine(t *testing.T) { router := New() assert.Equal(t, "/", router.basePath) assert.Equal(t, router.engine, router) assert.Empty(t, router.Handlers) } // func TestLoadHTMLDebugMode(t *testing.T) { // router := New() // SetMode(DebugMode) // router.LoadHTMLGlob("*.testtmpl") // r := router.HTMLRender.(render.HTMLDebug) // assert.Empty(t, r.Files) // assert.Equal(t, r.Glob, "*.testtmpl") // // router.LoadHTMLFiles("index.html.testtmpl", "login.html.testtmpl") // r = router.HTMLRender.(render.HTMLDebug) // assert.Empty(t, r.Glob) // assert.Equal(t, r.Files, []string{"index.html", "login.html"}) // SetMode(TestMode) // } func TestLoadHTMLFiles(t *testing.T) { td := setupHTMLFiles(t) res, err := http.Get("http://127.0.0.1:8888/test") if err != nil { fmt.Println(err) } resp, _ := ioutil.ReadAll(res.Body) assert.Equal(t, "

Hello world

", string(resp[:])) td() } func TestLoadHTMLFilesFuncMap(t *testing.T) { time.Now() td := setupHTMLFiles(t) res, err := http.Get("http://127.0.0.1:8888/raw") if err != nil { fmt.Println(err) } resp, _ := ioutil.ReadAll(res.Body) assert.Equal(t, "Date: 2017/07/01\n", string(resp[:])) td() } func TestLoadHTMLReleaseMode(t *testing.T) { } func TestAddRoute(t *testing.T) { router := New() router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}}) assert.Len(t, router.trees, 1) assert.NotNil(t, router.trees.get("GET")) assert.Nil(t, router.trees.get("POST")) router.addRoute("POST", "/", HandlersChain{func(_ *Context) {}}) assert.Len(t, router.trees, 2) assert.NotNil(t, router.trees.get("GET")) assert.NotNil(t, router.trees.get("POST")) router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}}) assert.Len(t, router.trees, 2) } func TestAddRouteFails(t *testing.T) { router := New() assert.Panics(t, func() { router.addRoute("", "/", HandlersChain{func(_ *Context) {}}) }) assert.Panics(t, func() { router.addRoute("GET", "a", HandlersChain{func(_ *Context) {}}) }) assert.Panics(t, func() { router.addRoute("GET", "/", HandlersChain{}) }) router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}}) assert.Panics(t, func() { router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}}) }) } func TestCreateDefaultRouter(t *testing.T) { router := Default() assert.Len(t, router.Handlers, 2) } func TestNoRouteWithoutGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} router := New() router.NoRoute(middleware0) assert.Nil(t, router.Handlers) assert.Len(t, router.noRoute, 1) assert.Len(t, router.allNoRoute, 1) compareFunc(t, router.noRoute[0], middleware0) compareFunc(t, router.allNoRoute[0], middleware0) router.NoRoute(middleware1, middleware0) assert.Len(t, router.noRoute, 2) assert.Len(t, router.allNoRoute, 2) compareFunc(t, router.noRoute[0], middleware1) compareFunc(t, router.allNoRoute[0], middleware1) compareFunc(t, router.noRoute[1], middleware0) compareFunc(t, router.allNoRoute[1], middleware0) } func TestNoRouteWithGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} var middleware2 HandlerFunc = func(c *Context) {} router := New() router.Use(middleware2) router.NoRoute(middleware0) assert.Len(t, router.allNoRoute, 2) assert.Len(t, router.Handlers, 1) assert.Len(t, router.noRoute, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.noRoute[0], middleware0) compareFunc(t, router.allNoRoute[0], middleware2) compareFunc(t, router.allNoRoute[1], middleware0) router.Use(middleware1) assert.Len(t, router.allNoRoute, 3) assert.Len(t, router.Handlers, 2) assert.Len(t, router.noRoute, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.Handlers[1], middleware1) compareFunc(t, router.noRoute[0], middleware0) compareFunc(t, router.allNoRoute[0], middleware2) compareFunc(t, router.allNoRoute[1], middleware1) compareFunc(t, router.allNoRoute[2], middleware0) } func TestNoMethodWithoutGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} router := New() router.NoMethod(middleware0) assert.Empty(t, router.Handlers) assert.Len(t, router.noMethod, 1) assert.Len(t, router.allNoMethod, 1) compareFunc(t, router.noMethod[0], middleware0) compareFunc(t, router.allNoMethod[0], middleware0) router.NoMethod(middleware1, middleware0) assert.Len(t, router.noMethod, 2) assert.Len(t, router.allNoMethod, 2) compareFunc(t, router.noMethod[0], middleware1) compareFunc(t, router.allNoMethod[0], middleware1) compareFunc(t, router.noMethod[1], middleware0) compareFunc(t, router.allNoMethod[1], middleware0) } func TestRebuild404Handlers(t *testing.T) { } func TestNoMethodWithGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} var middleware2 HandlerFunc = func(c *Context) {} router := New() router.Use(middleware2) router.NoMethod(middleware0) assert.Len(t, router.allNoMethod, 2) assert.Len(t, router.Handlers, 1) assert.Len(t, router.noMethod, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.noMethod[0], middleware0) compareFunc(t, router.allNoMethod[0], middleware2) compareFunc(t, router.allNoMethod[1], middleware0) router.Use(middleware1) assert.Len(t, router.allNoMethod, 3) assert.Len(t, router.Handlers, 2) assert.Len(t, router.noMethod, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.Handlers[1], middleware1) compareFunc(t, router.noMethod[0], middleware0) compareFunc(t, router.allNoMethod[0], middleware2) compareFunc(t, router.allNoMethod[1], middleware1) compareFunc(t, router.allNoMethod[2], middleware0) } func compareFunc(t *testing.T, a, b interface{}) { sf1 := reflect.ValueOf(a) sf2 := reflect.ValueOf(b) if sf1.Pointer() != sf2.Pointer() { t.Error("different functions") } } func TestListOfRoutes(t *testing.T) { router := New() router.GET("/favicon.ico", handlerTest1) router.GET("/", handlerTest1) group := router.Group("/users") { group.GET("/", handlerTest2) group.GET("/:id", handlerTest1) group.POST("/:id", handlerTest2) } router.Static("/static", ".") list := router.Routes() assert.Len(t, list, 7) assertRoutePresent(t, list, RouteInfo{ Method: "GET", Path: "/favicon.ico", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$", }) assertRoutePresent(t, list, RouteInfo{ Method: "GET", Path: "/", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$", }) assertRoutePresent(t, list, RouteInfo{ Method: "GET", Path: "/users/", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$", }) assertRoutePresent(t, list, RouteInfo{ Method: "GET", Path: "/users/:id", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$", }) assertRoutePresent(t, list, RouteInfo{ Method: "POST", Path: "/users/:id", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$", }) } func assertRoutePresent(t *testing.T, gotRoutes RoutesInfo, wantRoute RouteInfo) { for _, gotRoute := range gotRoutes { if gotRoute.Path == wantRoute.Path && gotRoute.Method == wantRoute.Method { assert.Regexp(t, wantRoute.Handler, gotRoute.Handler) return } } t.Errorf("route not found: %v", wantRoute) } func handlerTest1(c *Context) {} func handlerTest2(c *Context) {} gin-1.2/githubapi_test.go000066400000000000000000000310741312613627200155030ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "math/rand" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" ) type route struct { method string path string } // http://developer.github.com/v3/ var githubAPI = []route{ // OAuth Authorizations {"GET", "/authorizations"}, {"GET", "/authorizations/:id"}, {"POST", "/authorizations"}, //{"PUT", "/authorizations/clients/:client_id"}, //{"PATCH", "/authorizations/:id"}, {"DELETE", "/authorizations/:id"}, {"GET", "/applications/:client_id/tokens/:access_token"}, {"DELETE", "/applications/:client_id/tokens"}, {"DELETE", "/applications/:client_id/tokens/:access_token"}, // Activity {"GET", "/events"}, {"GET", "/repos/:owner/:repo/events"}, {"GET", "/networks/:owner/:repo/events"}, {"GET", "/orgs/:org/events"}, {"GET", "/users/:user/received_events"}, {"GET", "/users/:user/received_events/public"}, {"GET", "/users/:user/events"}, {"GET", "/users/:user/events/public"}, {"GET", "/users/:user/events/orgs/:org"}, {"GET", "/feeds"}, {"GET", "/notifications"}, {"GET", "/repos/:owner/:repo/notifications"}, {"PUT", "/notifications"}, {"PUT", "/repos/:owner/:repo/notifications"}, {"GET", "/notifications/threads/:id"}, //{"PATCH", "/notifications/threads/:id"}, {"GET", "/notifications/threads/:id/subscription"}, {"PUT", "/notifications/threads/:id/subscription"}, {"DELETE", "/notifications/threads/:id/subscription"}, {"GET", "/repos/:owner/:repo/stargazers"}, {"GET", "/users/:user/starred"}, {"GET", "/user/starred"}, {"GET", "/user/starred/:owner/:repo"}, {"PUT", "/user/starred/:owner/:repo"}, {"DELETE", "/user/starred/:owner/:repo"}, {"GET", "/repos/:owner/:repo/subscribers"}, {"GET", "/users/:user/subscriptions"}, {"GET", "/user/subscriptions"}, {"GET", "/repos/:owner/:repo/subscription"}, {"PUT", "/repos/:owner/:repo/subscription"}, {"DELETE", "/repos/:owner/:repo/subscription"}, {"GET", "/user/subscriptions/:owner/:repo"}, {"PUT", "/user/subscriptions/:owner/:repo"}, {"DELETE", "/user/subscriptions/:owner/:repo"}, // Gists {"GET", "/users/:user/gists"}, {"GET", "/gists"}, //{"GET", "/gists/public"}, //{"GET", "/gists/starred"}, {"GET", "/gists/:id"}, {"POST", "/gists"}, //{"PATCH", "/gists/:id"}, {"PUT", "/gists/:id/star"}, {"DELETE", "/gists/:id/star"}, {"GET", "/gists/:id/star"}, {"POST", "/gists/:id/forks"}, {"DELETE", "/gists/:id"}, // Git Data {"GET", "/repos/:owner/:repo/git/blobs/:sha"}, {"POST", "/repos/:owner/:repo/git/blobs"}, {"GET", "/repos/:owner/:repo/git/commits/:sha"}, {"POST", "/repos/:owner/:repo/git/commits"}, //{"GET", "/repos/:owner/:repo/git/refs/*ref"}, {"GET", "/repos/:owner/:repo/git/refs"}, {"POST", "/repos/:owner/:repo/git/refs"}, //{"PATCH", "/repos/:owner/:repo/git/refs/*ref"}, //{"DELETE", "/repos/:owner/:repo/git/refs/*ref"}, {"GET", "/repos/:owner/:repo/git/tags/:sha"}, {"POST", "/repos/:owner/:repo/git/tags"}, {"GET", "/repos/:owner/:repo/git/trees/:sha"}, {"POST", "/repos/:owner/:repo/git/trees"}, // Issues {"GET", "/issues"}, {"GET", "/user/issues"}, {"GET", "/orgs/:org/issues"}, {"GET", "/repos/:owner/:repo/issues"}, {"GET", "/repos/:owner/:repo/issues/:number"}, {"POST", "/repos/:owner/:repo/issues"}, //{"PATCH", "/repos/:owner/:repo/issues/:number"}, {"GET", "/repos/:owner/:repo/assignees"}, {"GET", "/repos/:owner/:repo/assignees/:assignee"}, {"GET", "/repos/:owner/:repo/issues/:number/comments"}, //{"GET", "/repos/:owner/:repo/issues/comments"}, //{"GET", "/repos/:owner/:repo/issues/comments/:id"}, {"POST", "/repos/:owner/:repo/issues/:number/comments"}, //{"PATCH", "/repos/:owner/:repo/issues/comments/:id"}, //{"DELETE", "/repos/:owner/:repo/issues/comments/:id"}, {"GET", "/repos/:owner/:repo/issues/:number/events"}, //{"GET", "/repos/:owner/:repo/issues/events"}, //{"GET", "/repos/:owner/:repo/issues/events/:id"}, {"GET", "/repos/:owner/:repo/labels"}, {"GET", "/repos/:owner/:repo/labels/:name"}, {"POST", "/repos/:owner/:repo/labels"}, //{"PATCH", "/repos/:owner/:repo/labels/:name"}, {"DELETE", "/repos/:owner/:repo/labels/:name"}, {"GET", "/repos/:owner/:repo/issues/:number/labels"}, {"POST", "/repos/:owner/:repo/issues/:number/labels"}, {"DELETE", "/repos/:owner/:repo/issues/:number/labels/:name"}, {"PUT", "/repos/:owner/:repo/issues/:number/labels"}, {"DELETE", "/repos/:owner/:repo/issues/:number/labels"}, {"GET", "/repos/:owner/:repo/milestones/:number/labels"}, {"GET", "/repos/:owner/:repo/milestones"}, {"GET", "/repos/:owner/:repo/milestones/:number"}, {"POST", "/repos/:owner/:repo/milestones"}, //{"PATCH", "/repos/:owner/:repo/milestones/:number"}, {"DELETE", "/repos/:owner/:repo/milestones/:number"}, // Miscellaneous {"GET", "/emojis"}, {"GET", "/gitignore/templates"}, {"GET", "/gitignore/templates/:name"}, {"POST", "/markdown"}, {"POST", "/markdown/raw"}, {"GET", "/meta"}, {"GET", "/rate_limit"}, // Organizations {"GET", "/users/:user/orgs"}, {"GET", "/user/orgs"}, {"GET", "/orgs/:org"}, //{"PATCH", "/orgs/:org"}, {"GET", "/orgs/:org/members"}, {"GET", "/orgs/:org/members/:user"}, {"DELETE", "/orgs/:org/members/:user"}, {"GET", "/orgs/:org/public_members"}, {"GET", "/orgs/:org/public_members/:user"}, {"PUT", "/orgs/:org/public_members/:user"}, {"DELETE", "/orgs/:org/public_members/:user"}, {"GET", "/orgs/:org/teams"}, {"GET", "/teams/:id"}, {"POST", "/orgs/:org/teams"}, //{"PATCH", "/teams/:id"}, {"DELETE", "/teams/:id"}, {"GET", "/teams/:id/members"}, {"GET", "/teams/:id/members/:user"}, {"PUT", "/teams/:id/members/:user"}, {"DELETE", "/teams/:id/members/:user"}, {"GET", "/teams/:id/repos"}, {"GET", "/teams/:id/repos/:owner/:repo"}, {"PUT", "/teams/:id/repos/:owner/:repo"}, {"DELETE", "/teams/:id/repos/:owner/:repo"}, {"GET", "/user/teams"}, // Pull Requests {"GET", "/repos/:owner/:repo/pulls"}, {"GET", "/repos/:owner/:repo/pulls/:number"}, {"POST", "/repos/:owner/:repo/pulls"}, //{"PATCH", "/repos/:owner/:repo/pulls/:number"}, {"GET", "/repos/:owner/:repo/pulls/:number/commits"}, {"GET", "/repos/:owner/:repo/pulls/:number/files"}, {"GET", "/repos/:owner/:repo/pulls/:number/merge"}, {"PUT", "/repos/:owner/:repo/pulls/:number/merge"}, {"GET", "/repos/:owner/:repo/pulls/:number/comments"}, //{"GET", "/repos/:owner/:repo/pulls/comments"}, //{"GET", "/repos/:owner/:repo/pulls/comments/:number"}, {"PUT", "/repos/:owner/:repo/pulls/:number/comments"}, //{"PATCH", "/repos/:owner/:repo/pulls/comments/:number"}, //{"DELETE", "/repos/:owner/:repo/pulls/comments/:number"}, // Repositories {"GET", "/user/repos"}, {"GET", "/users/:user/repos"}, {"GET", "/orgs/:org/repos"}, {"GET", "/repositories"}, {"POST", "/user/repos"}, {"POST", "/orgs/:org/repos"}, {"GET", "/repos/:owner/:repo"}, //{"PATCH", "/repos/:owner/:repo"}, {"GET", "/repos/:owner/:repo/contributors"}, {"GET", "/repos/:owner/:repo/languages"}, {"GET", "/repos/:owner/:repo/teams"}, {"GET", "/repos/:owner/:repo/tags"}, {"GET", "/repos/:owner/:repo/branches"}, {"GET", "/repos/:owner/:repo/branches/:branch"}, {"DELETE", "/repos/:owner/:repo"}, {"GET", "/repos/:owner/:repo/collaborators"}, {"GET", "/repos/:owner/:repo/collaborators/:user"}, {"PUT", "/repos/:owner/:repo/collaborators/:user"}, {"DELETE", "/repos/:owner/:repo/collaborators/:user"}, {"GET", "/repos/:owner/:repo/comments"}, {"GET", "/repos/:owner/:repo/commits/:sha/comments"}, {"POST", "/repos/:owner/:repo/commits/:sha/comments"}, {"GET", "/repos/:owner/:repo/comments/:id"}, //{"PATCH", "/repos/:owner/:repo/comments/:id"}, {"DELETE", "/repos/:owner/:repo/comments/:id"}, {"GET", "/repos/:owner/:repo/commits"}, {"GET", "/repos/:owner/:repo/commits/:sha"}, {"GET", "/repos/:owner/:repo/readme"}, //{"GET", "/repos/:owner/:repo/contents/*path"}, //{"PUT", "/repos/:owner/:repo/contents/*path"}, //{"DELETE", "/repos/:owner/:repo/contents/*path"}, //{"GET", "/repos/:owner/:repo/:archive_format/:ref"}, {"GET", "/repos/:owner/:repo/keys"}, {"GET", "/repos/:owner/:repo/keys/:id"}, {"POST", "/repos/:owner/:repo/keys"}, //{"PATCH", "/repos/:owner/:repo/keys/:id"}, {"DELETE", "/repos/:owner/:repo/keys/:id"}, {"GET", "/repos/:owner/:repo/downloads"}, {"GET", "/repos/:owner/:repo/downloads/:id"}, {"DELETE", "/repos/:owner/:repo/downloads/:id"}, {"GET", "/repos/:owner/:repo/forks"}, {"POST", "/repos/:owner/:repo/forks"}, {"GET", "/repos/:owner/:repo/hooks"}, {"GET", "/repos/:owner/:repo/hooks/:id"}, {"POST", "/repos/:owner/:repo/hooks"}, //{"PATCH", "/repos/:owner/:repo/hooks/:id"}, {"POST", "/repos/:owner/:repo/hooks/:id/tests"}, {"DELETE", "/repos/:owner/:repo/hooks/:id"}, {"POST", "/repos/:owner/:repo/merges"}, {"GET", "/repos/:owner/:repo/releases"}, {"GET", "/repos/:owner/:repo/releases/:id"}, {"POST", "/repos/:owner/:repo/releases"}, //{"PATCH", "/repos/:owner/:repo/releases/:id"}, {"DELETE", "/repos/:owner/:repo/releases/:id"}, {"GET", "/repos/:owner/:repo/releases/:id/assets"}, {"GET", "/repos/:owner/:repo/stats/contributors"}, {"GET", "/repos/:owner/:repo/stats/commit_activity"}, {"GET", "/repos/:owner/:repo/stats/code_frequency"}, {"GET", "/repos/:owner/:repo/stats/participation"}, {"GET", "/repos/:owner/:repo/stats/punch_card"}, {"GET", "/repos/:owner/:repo/statuses/:ref"}, {"POST", "/repos/:owner/:repo/statuses/:ref"}, // Search {"GET", "/search/repositories"}, {"GET", "/search/code"}, {"GET", "/search/issues"}, {"GET", "/search/users"}, {"GET", "/legacy/issues/search/:owner/:repository/:state/:keyword"}, {"GET", "/legacy/repos/search/:keyword"}, {"GET", "/legacy/user/search/:keyword"}, {"GET", "/legacy/user/email/:email"}, // Users {"GET", "/users/:user"}, {"GET", "/user"}, //{"PATCH", "/user"}, {"GET", "/users"}, {"GET", "/user/emails"}, {"POST", "/user/emails"}, {"DELETE", "/user/emails"}, {"GET", "/users/:user/followers"}, {"GET", "/user/followers"}, {"GET", "/users/:user/following"}, {"GET", "/user/following"}, {"GET", "/user/following/:user"}, {"GET", "/users/:user/following/:target_user"}, {"PUT", "/user/following/:user"}, {"DELETE", "/user/following/:user"}, {"GET", "/users/:user/keys"}, {"GET", "/user/keys"}, {"GET", "/user/keys/:id"}, {"POST", "/user/keys"}, //{"PATCH", "/user/keys/:id"}, {"DELETE", "/user/keys/:id"}, } func githubConfigRouter(router *Engine) { for _, route := range githubAPI { router.Handle(route.method, route.path, func(c *Context) { output := make(map[string]string, len(c.Params)+1) output["status"] = "good" for _, param := range c.Params { output[param.Key] = param.Value } c.JSON(200, output) }) } } func TestGithubAPI(t *testing.T) { DefaultWriter = os.Stdout router := Default() githubConfigRouter(router) for _, route := range githubAPI { path, values := exampleFromPath(route.path) w := performRequest(router, route.method, path) // TEST assert.Contains(t, w.Body.String(), "\"status\":\"good\"") for _, value := range values { str := fmt.Sprintf("\"%s\":\"%s\"", value.Key, value.Value) assert.Contains(t, w.Body.String(), str) } } } func exampleFromPath(path string) (string, Params) { output := new(bytes.Buffer) params := make(Params, 0, 6) start := -1 for i, c := range path { if c == ':' { start = i + 1 } if start >= 0 { if c == '/' { value := fmt.Sprint(rand.Intn(100000)) params = append(params, Param{ Key: path[start:i], Value: value, }) output.WriteString(value) output.WriteRune(c) start = -1 } } else { output.WriteRune(c) } } if start >= 0 { value := fmt.Sprint(rand.Intn(100000)) params = append(params, Param{ Key: path[start:], Value: value, }) output.WriteString(value) } return output.String(), params } func BenchmarkGithub(b *testing.B) { router := New() githubConfigRouter(router) runRequest(b, router, "GET", "/legacy/issues/search/:owner/:repository/:state/:keyword") } func BenchmarkParallelGithub(b *testing.B) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) req, _ := http.NewRequest("POST", "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) } func BenchmarkParallelGithubDefault(b *testing.B) { DefaultWriter = os.Stdout router := Default() githubConfigRouter(router) req, _ := http.NewRequest("POST", "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) } gin-1.2/logger.go000066400000000000000000000062221312613627200137440ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "io" "os" "time" "github.com/mattn/go-isatty" ) var ( green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109}) white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109}) yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109}) red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109}) blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109}) magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109}) cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109}) reset = string([]byte{27, 91, 48, 109}) disableColor = false ) func DisableConsoleColor() { disableColor = true } func ErrorLogger() HandlerFunc { return ErrorLoggerT(ErrorTypeAny) } func ErrorLoggerT(typ ErrorType) HandlerFunc { return func(c *Context) { c.Next() errors := c.Errors.ByType(typ) if len(errors) > 0 { c.JSON(-1, errors) } } } // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter // By default gin.DefaultWriter = os.Stdout func Logger() HandlerFunc { return LoggerWithWriter(DefaultWriter) } // LoggerWithWriter instance a Logger middleware with the specified writter buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { isTerm := true if w, ok := out.(*os.File); !ok || (os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd()))) || disableColor { isTerm = false } var skip map[string]struct{} if length := len(notlogged); length > 0 { skip = make(map[string]struct{}, length) for _, path := range notlogged { skip[path] = struct{}{} } } return func(c *Context) { // Start timer start := time.Now() path := c.Request.URL.Path // Process request c.Next() // Log only when path is not being skipped if _, ok := skip[path]; !ok { // Stop timer end := time.Now() latency := end.Sub(start) clientIP := c.ClientIP() method := c.Request.Method statusCode := c.Writer.Status() var statusColor, methodColor string if isTerm { statusColor = colorForStatus(statusCode) methodColor = colorForMethod(method) } comment := c.Errors.ByType(ErrorTypePrivate).String() fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %s %-7s %s\n%s", end.Format("2006/01/02 - 15:04:05"), statusColor, statusCode, reset, latency, clientIP, methodColor, method, reset, path, comment, ) } } } func colorForStatus(code int) string { switch { case code >= 200 && code < 300: return green case code >= 300 && code < 400: return white case code >= 400 && code < 500: return yellow default: return red } } func colorForMethod(method string) string { switch method { case "GET": return blue case "POST": return cyan case "PUT": return yellow case "DELETE": return red case "PATCH": return green case "HEAD": return magenta case "OPTIONS": return white default: return reset } } gin-1.2/logger_test.go000066400000000000000000000124201312613627200150000ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "testing" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestLogger(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer)) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) performRequest(router, "GET", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() performRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() performRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() performRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() performRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() performRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() performRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() performRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestColorForMethod(t *testing.T) { assert.Equal(t, colorForMethod("GET"), string([]byte{27, 91, 57, 55, 59, 52, 52, 109}), "get should be blue") assert.Equal(t, colorForMethod("POST"), string([]byte{27, 91, 57, 55, 59, 52, 54, 109}), "post should be cyan") assert.Equal(t, colorForMethod("PUT"), string([]byte{27, 91, 57, 55, 59, 52, 51, 109}), "put should be yellow") assert.Equal(t, colorForMethod("DELETE"), string([]byte{27, 91, 57, 55, 59, 52, 49, 109}), "delete should be red") assert.Equal(t, colorForMethod("PATCH"), string([]byte{27, 91, 57, 55, 59, 52, 50, 109}), "patch should be green") assert.Equal(t, colorForMethod("HEAD"), string([]byte{27, 91, 57, 55, 59, 52, 53, 109}), "head should be magenta") assert.Equal(t, colorForMethod("OPTIONS"), string([]byte{27, 91, 57, 48, 59, 52, 55, 109}), "options should be white") assert.Equal(t, colorForMethod("TRACE"), string([]byte{27, 91, 48, 109}), "trace is not defined and should be the reset color") } func TestColorForStatus(t *testing.T) { assert.Equal(t, colorForStatus(200), string([]byte{27, 91, 57, 55, 59, 52, 50, 109}), "2xx should be green") assert.Equal(t, colorForStatus(301), string([]byte{27, 91, 57, 48, 59, 52, 55, 109}), "3xx should be white") assert.Equal(t, colorForStatus(404), string([]byte{27, 91, 57, 55, 59, 52, 51, 109}), "4xx should be yellow") assert.Equal(t, colorForStatus(2), string([]byte{27, 91, 57, 55, 59, 52, 49, 109}), "other things should be red") } func TestErrorLogger(t *testing.T) { router := New() router.Use(ErrorLogger()) router.GET("/error", func(c *Context) { c.Error(errors.New("this is an error")) }) router.GET("/abort", func(c *Context) { c.AbortWithError(401, errors.New("no authorized")) }) router.GET("/print", func(c *Context) { c.Error(errors.New("this is an error")) c.String(500, "hola!") }) w := performRequest(router, "GET", "/error") assert.Equal(t, 200, w.Code) assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String()) w = performRequest(router, "GET", "/abort") assert.Equal(t, 401, w.Code) assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String()) w = performRequest(router, "GET", "/print") assert.Equal(t, 500, w.Code) assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String()) } func TestSkippingPaths(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer, "/skipped")) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) performRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() performRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestDisableConsoleColor(t *testing.T) { New() assert.False(t, disableColor) DisableConsoleColor() assert.True(t, disableColor) } gin-1.2/logo.jpg000066400000000000000000000276501312613627200136100ustar00rootroot00000000000000JFIFHHExifMM*JR(iZHH8Photoshop 3.08BIM8BIM%ُ B~ }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzC     C   ?(((((((fú.ӥm%ĮU#E,ē(ihb='I˂ F uPs$q$W~/!V&UV+o=2G KŴfF,'xIq<1G  Gl|#`?~x lu}GwB{Hi|Hei`6phrOmSƾwxgCa #Rq3`yqda--乒K|G2>'86O$Ƶr?;xڙU9Pp4]#I[ieFS\Pʞ3O!p$t:|j]j3J_ _ Xw$6ׂ~x?@O H9M4rx~ܼ%ng8@@;K__#ciAAcV1,cn t<&i4v g4BYf)9rNMsi/F}jfv4pB$rF=^ 4]#>")4v{Yd)NI4xCAwEwNZo^V0sTP{7m<%iMtd<20N@5>)O2O#26gg c;J|-IԚuӛK+@Gd)4ex<`PPOa|^`+id'cB |e㫛þ2ΙOscY=evUʫe 9 f:?'/"_(w P|/Ch-fni#-C_m'1xmZO_ilT*N8 8=}KAxx>tYEʴwЛ(QR$M9RŞ>|/?u-&1gOG`| w[ bL?}^  |K^Jcl{Gx?,>6xO3Ó)e?hx7r?V®}n={xԿi4? wR:3ş'Ꮔo|KxCrieDY\J|h$d]RC/5-^++ 8^{*EYM~z_J=x(ms㕞M  o-k"ˆ |u񿌮u/~9[lrJ i"lmEC"<Uy%LxIĞKt ۏ0+32ɠqOԾYAwK7O*?jiIYy i71Y_2Kr]qcr=-7R ouxbd"7 <;xKAO:4t\AP眜9/~DTieMkͮr%E#x|.Yz O]\>\ڭX3^Iʺ<}(x㴉pQjT?/j: z٣!ZB 9fnx.7|?IExK71o0I"BTxMxox{u$}B/ LF0~m$ @o~^&?4|] ߌOtoMWwPdI2@E'q?g7YGOg~@}bk;w=H쑅Mz ^_D`ZP cx{Ï H%?a0|ӣ2c ~?L66ҵ)ɎCvߔAz<vQFG@{gi{ ~HsV1Q#Ō [WK@Nn ILoᐯ}jj*oumv?Mh$@XׅZ^$:* 3^1#ɵϓ!IjF|}Ụ.V3gVelo.&b w8]k:-<qN4)υL-H"?w2!<to*-.lLUM_(0.8L/8eg''wVq$"8U"|@dzxmHjwo`W7xF? 4A oX5PrWЎCڹ_xLG@eG:x[>f4Eq@nxwQj[Lbǝ2,ld^E_ |+d\}]i =o&77Wӵ?)M jmJ坢`]S' @<ؾ$bեdߤ@iv%Xd{攷=)O6B:?*,x㞈Q@c⽏ '-Nb:dy#@;Lv=Np-2m"UYOgohxºޅzK $SdBÿޭc?|o[F/48n>k泷Vy!GgX9 TkܾLuG[ G\=*xY']ÞbR2~w? \4X﷘ͭȶ0$u"Y-#4Jey핤E9WG`zhVWPC)(UG@1-V4_UhZ S$ʀ72+㞋~%Ω]=k` wDz3Э5 ǨWa}?k_xtukF Y~f*[#o84T?h(>/tkgnM]n2eerDy5v> W:|>mhnlQ/$z(9 W|'%lEG%u!qٜ|Գ Wƿ6~#$tѣ!UUP" su'㎻ŇYm-ɲRZŜsg+Y*)f'h+<G[cX( bPy38}u b1[!8+xԟz썡hMo VX6(Ĺ'c@m߇Þ!A %$_4w2a^@Q@|[m׀xdI=u8ʙ \gOiVz{jwa{q +$nYH Yx-j6xTA/s`-Ư6S_ou{|#`qҀ?oE HTu$ 4G=_VY[Fi۸(@?4]>2|_/_-GZe}_Oh$U%X ed2W=-( h` T-==;^'u6ntѣ|p`vy1bKIIDu?jopPm cE,Ic?}[:X\ݰX-2I&{r(&8W,_gCG蠻ԕR[m$Vu;$a|FNk> e5 sAsjdW1/*Hh(KMG*2=Ao{>gui96Q-]nx z?,eOM367Lrc5@?ì_N7E4~1ڜP)G_]6t?~b? W8EӯܼP➃<|M| '{ RY'o\@׺ERԐz93_ǂ?mMtn!$d,=>P=q?~x/e[x@@ ߕ=붠(?2<7utt5!6 K܌ ﶽῃWZ }I>8眮ѷ@ag- ttQZ:lb>00P>( FRT(،ZO%^]^.f23grĜo? hƱ.;:},dy=_8)(( Bp(k>#i|adxZ/Guw J܉1bOqlϺg7c_;iA4\ep=<ׁS-oM]/7if#Ϫ@^1}ljC{_?"_t%2n~gG#{==,Q64QFHWo[֤]Vfm_p{z>)+ x:F,⻻D9?yd>-=s9=֯'7 <0Vʮ:pItw+UK{/:*,-+ԾW6Z CbL8@UsGq )$NXz85׈ k_ o~W2ٵq;>F2]" T>?}'⯃4x|K!kilӡ$.;2#߂84Q@GG&?=ٞ =ݴ`EUkZ?,]_'Tb((oKѠhGogpox\5\i_n Jފ%1dwG?*֖:紓˻xEiy`xs_h<37(.+ TR3=ܓ@+t.-#Ue B+? %omtKUP󤳍Ed䒅'񓌐S>w|!<XZxw ])L*Ή^Jgn:]1a+ >k{E(K8%WmhnUU]<;Bی%A |E@E\j^;+ǷLY,c@1 : 18> ~Ҟ-6)Ede1{$krJO$}=(= |9uۯŻ <)k+ ϲ[C$MK/pt(G◅W W;N\[#c;];O5֞u[|WEʝBkBf/?þ,&KteӮ\xA:ݣ eFV4/ i^;[/Sh.#:فh K4> GQ0AP;7A\G .m`H.x$^92 h;BF{o9Xs(h洸IU5:Q7Z}dسd |8:힙Ȏ746 C,qPMrw/^ 間iVS^O|y#B77E,$|a4EDž5u:w2E&v;خ]n2qMb{+X[xJyc`Y[#  ;M,g7d{6oay:׉4/u*}wր8//h:փ| >1阏K$G|l+pNWx][W/.`NE*Sw#2ܾ]`>JtƉhG~bFh¥㏍Z/͹._[}0n4C;aT־Ҁ9xHu{xr&^F$1#ugf$k 6G3*]~ۿwh51"h!-R2C|cVE;+9_\8#PP(gmN~$QKZGb3C\CK %گddd2y,hXy)϶;ĺVM#B_Y)8v%^K3$#ߏexVAhwz߆<\nNɖer_nFQH\0MEos1 nI:AǭKEPmCOlnlu&xdYH$U xGE=ɢh%XflFqmҽ{]ZGקc<'!O"1ހ>z3~Ծ'O]z6qw*LuRHȻ 9S?_~4Is]<5za%,"0P}$c P4/5 )=v9Z[[S*DڎI [|EO\455gM{X0ȑ[$K.O'<Iׂu;ķ1ޥjE§p( NHӥzPEPEsItOxR]gL,LE7]wdIݩX>OshEOk$.$GnS{h~zuы˓Tn\,1@NQ@(󏎓M:p&9xS֩= YQ?i]mN$u]:0 {aP+i?"?hRxggi2hv;:(((k_Sź4i}oiOKCiqT9B5֒ꖰ^JdxĈЩſkoISF5i:g :̆8FH\362*L!+q|-cK>eu;iR 808h>TH]d2>3m⋘P=ΞB灅i"8p}ݚ#ñ|tPz%f)3޾cM>HqM4X_wWgg>3@NWM͜Ҏ'O |AqsEx[wr_m'kv "l 28~Q?jv61nP0]BxBu|⿴v٭oSE|Vp|$Д<MX݆'>q@XWVcx">X/h\3Y|WdF^BBׂ=C-?CIkHӜK9=#{o ƒlծ}1Q@#4ϊ?kmE,n}A_C G|Vq>vl͂ʣHѴNӴ;m6Cmk j:UuT"PԴQ@gin-1.2/middleware_test.go000066400000000000000000000115211312613627200156370ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "strings" "testing" "github.com/gin-contrib/sse" "github.com/stretchr/testify/assert" ) func TestMiddlewareGeneralCase(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" }) router.GET("/", func(c *Context) { signature += "D" }) router.NoRoute(func(c *Context) { signature += " X " }) router.NoMethod(func(c *Context) { signature += " XX " }) // RUN w := performRequest(router, "GET", "/") // TEST assert.Equal(t, w.Code, 200) assert.Equal(t, signature, "ACDB") } func TestMiddlewareNoRoute(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() c.Next() c.Next() c.Next() signature += "D" }) router.NoRoute(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoMethod(func(c *Context) { signature += " X " }) // RUN w := performRequest(router, "GET", "/") // TEST assert.Equal(t, w.Code, 404) assert.Equal(t, signature, "ACEGHFDB") } func TestMiddlewareNoMethodEnabled(t *testing.T) { signature := "" router := New() router.HandleMethodNotAllowed = true router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := performRequest(router, "GET", "/") // TEST assert.Equal(t, w.Code, 405) assert.Equal(t, signature, "ACEGHFDB") } func TestMiddlewareNoMethodDisabled(t *testing.T) { signature := "" router := New() router.HandleMethodNotAllowed = false router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := performRequest(router, "GET", "/") // TEST assert.Equal(t, w.Code, 404) assert.Equal(t, signature, "AC X DB") } func TestMiddlewareAbort(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" }) router.Use(func(c *Context) { signature += "C" c.AbortWithStatus(401) c.Next() signature += "D" }) router.GET("/", func(c *Context) { signature += " X " c.Next() signature += " XX " }) // RUN w := performRequest(router, "GET", "/") // TEST assert.Equal(t, w.Code, 401) assert.Equal(t, signature, "ACD") } func TestMiddlewareAbortHandlersChainAndNext(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() c.AbortWithStatus(410) signature += "B" }) router.GET("/", func(c *Context) { signature += "C" c.Next() }) // RUN w := performRequest(router, "GET", "/") // TEST assert.Equal(t, w.Code, 410) assert.Equal(t, signature, "ACB") } // TestFailHandlersChain - ensure that Fail interrupt used middleware in fifo order as // as well as Abort func TestMiddlewareFailHandlersChain(t *testing.T) { // SETUP signature := "" router := New() router.Use(func(context *Context) { signature += "A" context.AbortWithError(500, errors.New("foo")) }) router.Use(func(context *Context) { signature += "B" context.Next() signature += "C" }) // RUN w := performRequest(router, "GET", "/") // TEST assert.Equal(t, w.Code, 500) assert.Equal(t, signature, "A") } func TestMiddlewareWrite(t *testing.T) { router := New() router.Use(func(c *Context) { c.String(400, "hola\n") }) router.Use(func(c *Context) { c.XML(400, H{"foo": "bar"}) }) router.Use(func(c *Context) { c.JSON(400, H{"foo": "bar"}) }) router.GET("/", func(c *Context) { c.JSON(400, H{"foo": "bar"}) }, func(c *Context) { c.Render(400, sse.Event{ Event: "test", Data: "message", }) }) w := performRequest(router, "GET", "/") assert.Equal(t, 400, w.Code) assert.Equal(t, strings.Replace("hola\nbar{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", "", -1), strings.Replace(w.Body.String(), " ", "", -1)) } gin-1.2/mode.go000066400000000000000000000025501312613627200134110ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "io" "os" "github.com/gin-gonic/gin/binding" ) const ENV_GIN_MODE = "GIN_MODE" const ( DebugMode string = "debug" ReleaseMode string = "release" TestMode string = "test" ) const ( debugCode = iota releaseCode testCode ) // DefaultWriter is the default io.Writer used the Gin for debug output and // middleware output like Logger() or Recovery(). // Note that both Logger and Recovery provides custom ways to configure their // output io.Writer. // To support coloring in Windows use: // import "github.com/mattn/go-colorable" // gin.DefaultWriter = colorable.NewColorableStdout() var DefaultWriter io.Writer = os.Stdout var DefaultErrorWriter io.Writer = os.Stderr var ginMode = debugCode var modeName = DebugMode func init() { mode := os.Getenv(ENV_GIN_MODE) if len(mode) == 0 { SetMode(DebugMode) } else { SetMode(mode) } } func SetMode(value string) { switch value { case DebugMode: ginMode = debugCode case ReleaseMode: ginMode = releaseCode case TestMode: ginMode = testCode default: panic("gin mode unknown: " + value) } modeName = value } func DisableBindValidation() { binding.Validator = nil } func Mode() string { return modeName } gin-1.2/mode_test.go000066400000000000000000000012101312613627200144400ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "testing" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestSetMode(t *testing.T) { SetMode(DebugMode) assert.Equal(t, ginMode, debugCode) assert.Equal(t, Mode(), DebugMode) SetMode(ReleaseMode) assert.Equal(t, ginMode, releaseCode) assert.Equal(t, Mode(), ReleaseMode) SetMode(TestMode) assert.Equal(t, ginMode, testCode) assert.Equal(t, Mode(), TestMode) assert.Panics(t, func() { SetMode("unknown") }) } gin-1.2/path.go000066400000000000000000000052241312613627200134220ustar00rootroot00000000000000// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The Go Authors. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE. package gin // CleanPath is the URL version of path.Clean, it returns a canonical URL path // for p, eliminating . and .. elements. // // The following rules are applied iteratively until no further processing can // be done: // 1. Replace multiple slashes with a single slash. // 2. Eliminate each . path name element (the current directory). // 3. Eliminate each inner .. path name element (the parent directory) // along with the non-.. element that precedes it. // 4. Eliminate .. elements that begin a rooted path: // that is, replace "/.." by "/" at the beginning of a path. // // If the result of this process is an empty string, "/" is returned func cleanPath(p string) string { // Turn empty string into "/" if p == "" { return "/" } n := len(p) var buf []byte // Invariants: // reading from path; r is index of next byte to process. // writing to buf; w is index of next byte to write. // path must start with '/' r := 1 w := 1 if p[0] != '/' { r = 0 buf = make([]byte, n+1) buf[0] = '/' } trailing := n > 2 && p[n-1] == '/' // A bit more clunky without a 'lazybuf' like the path package, but the loop // gets completely inlined (bufApp). So in contrast to the path package this // loop has no expensive function calls (except 1x make) for r < n { switch { case p[r] == '/': // empty path element, trailing slash is added after the end r++ case p[r] == '.' && r+1 == n: trailing = true r++ case p[r] == '.' && p[r+1] == '/': // . element r++ case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): // .. element: remove to last / r += 2 if w > 1 { // can backtrack w-- if buf == nil { for w > 1 && p[w] != '/' { w-- } } else { for w > 1 && buf[w] != '/' { w-- } } } default: // real path element. // add slash if needed if w > 1 { bufApp(&buf, p, w, '/') w++ } // copy element for r < n && p[r] != '/' { bufApp(&buf, p, w, p[r]) w++ r++ } } } // re-append trailing slash if trailing && w > 1 { bufApp(&buf, p, w, '/') w++ } if buf == nil { return p[:w] } return string(buf[:w]) } // internal helper to lazily create a buffer if necessary func bufApp(buf *[]byte, s string, w int, c byte) { if *buf == nil { if s[w] == c { return } *buf = make([]byte, len(s)) copy(*buf, s[:w]) } (*buf)[w] = c } gin-1.2/path_test.go000066400000000000000000000037001312613627200144560ustar00rootroot00000000000000// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The Go Authors. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "runtime" "testing" "github.com/stretchr/testify/assert" ) var cleanTests = []struct { path, result string }{ // Already clean {"/", "/"}, {"/abc", "/abc"}, {"/a/b/c", "/a/b/c"}, {"/abc/", "/abc/"}, {"/a/b/c/", "/a/b/c/"}, // missing root {"", "/"}, {"abc", "/abc"}, {"abc/def", "/abc/def"}, {"a/b/c", "/a/b/c"}, // Remove doubled slash {"//", "/"}, {"/abc//", "/abc/"}, {"/abc/def//", "/abc/def/"}, {"/a/b/c//", "/a/b/c/"}, {"/abc//def//ghi", "/abc/def/ghi"}, {"//abc", "/abc"}, {"///abc", "/abc"}, {"//abc//", "/abc/"}, // Remove . elements {".", "/"}, {"./", "/"}, {"/abc/./def", "/abc/def"}, {"/./abc/def", "/abc/def"}, {"/abc/.", "/abc/"}, // Remove .. elements {"..", "/"}, {"../", "/"}, {"../../", "/"}, {"../..", "/"}, {"../../abc", "/abc"}, {"/abc/def/ghi/../jkl", "/abc/def/jkl"}, {"/abc/def/../ghi/../jkl", "/abc/jkl"}, {"/abc/def/..", "/abc"}, {"/abc/def/../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"}, // Combinations {"abc/./../def", "/def"}, {"abc//./../def", "/def"}, {"abc/../../././../def", "/def"}, } func TestPathClean(t *testing.T) { for _, test := range cleanTests { assert.Equal(t, cleanPath(test.path), test.result) assert.Equal(t, cleanPath(test.result), test.result) } } func TestPathCleanMallocs(t *testing.T) { if testing.Short() { t.Skip("skipping malloc count in short mode") } if runtime.GOMAXPROCS(0) > 1 { t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1") return } for _, test := range cleanTests { allocs := testing.AllocsPerRun(100, func() { cleanPath(test.result) }) assert.EqualValues(t, allocs, 0) } } gin-1.2/recovery.go000066400000000000000000000055301312613627200143240ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "io" "io/ioutil" "log" "net/http/httputil" "runtime" ) var ( dunno = []byte("???") centerDot = []byte("·") dot = []byte(".") slash = []byte("/") ) // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. func Recovery() HandlerFunc { return RecoveryWithWriter(DefaultErrorWriter) } func RecoveryWithWriter(out io.Writer) HandlerFunc { var logger *log.Logger if out != nil { logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags) } return func(c *Context) { defer func() { if err := recover(); err != nil { if logger != nil { stack := stack(3) httprequest, _ := httputil.DumpRequest(c.Request, false) logger.Printf("[Recovery] panic recovered:\n%s\n%s\n%s%s", string(httprequest), err, stack, reset) } c.AbortWithStatus(500) } }() c.Next() } } // stack returns a nicely formated stack frame, skipping skip frames func stack(skip int) []byte { buf := new(bytes.Buffer) // the returned data // As we loop, we open files and read them. These variables record the currently // loaded file. var lines [][]byte var lastFile string for i := skip; ; i++ { // Skip the expected number of frames pc, file, line, ok := runtime.Caller(i) if !ok { break } // Print this much at least. If we can't find the source, it won't show. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) if file != lastFile { data, err := ioutil.ReadFile(file) if err != nil { continue } lines = bytes.Split(data, []byte{'\n'}) lastFile = file } fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) } return buf.Bytes() } // source returns a space-trimmed slice of the n'th line. func source(lines [][]byte, n int) []byte { n-- // in stack trace, lines are 1-indexed but our array is 0-indexed if n < 0 || n >= len(lines) { return dunno } return bytes.TrimSpace(lines[n]) } // function returns, if possible, the name of the function containing the PC. func function(pc uintptr) []byte { fn := runtime.FuncForPC(pc) if fn == nil { return dunno } name := []byte(fn.Name()) // The name includes the path name to the package, which is unnecessary // since the file name is already included. Plus, it has center dots. // That is, we see // runtime/debug.*T·ptrmethod // and want // *T.ptrmethod // Also the package path might contains dot (e.g. code.google.com/...), // so first eliminate the path prefix if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 { name = name[lastslash+1:] } if period := bytes.Index(name, dot); period >= 0 { name = name[period+1:] } name = bytes.Replace(name, centerDot, dot, -1) return name } gin-1.2/recovery_test.go000066400000000000000000000023021312613627200153550ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := performRequest(router, "GET", "/recovery") // TEST assert.Equal(t, w.Code, 500) assert.Contains(t, buffer.String(), "GET /recovery") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), "TestPanicInHandler") } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(400) panic("Oupps, Houston, we have a problem") }) // RUN w := performRequest(router, "GET", "/recovery") // TEST assert.Equal(t, w.Code, 400) } gin-1.2/render/000077500000000000000000000000001312613627200134135ustar00rootroot00000000000000gin-1.2/render/data.go000066400000000000000000000010341312613627200146510ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" type Data struct { ContentType string Data []byte } // Render (Data) writes data with custom ContentType func (r Data) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) _, err = w.Write(r.Data) return } func (r Data) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) } gin-1.2/render/html.go000066400000000000000000000033361312613627200147130ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "html/template" "net/http" ) type ( Delims struct { Left string Right string } HTMLRender interface { Instance(string, interface{}) Render } HTMLProduction struct { Template *template.Template Delims Delims } HTMLDebug struct { Files []string Glob string Delims Delims FuncMap template.FuncMap } HTML struct { Template *template.Template Name string Data interface{} } ) var htmlContentType = []string{"text/html; charset=utf-8"} func (r HTMLProduction) Instance(name string, data interface{}) Render { return HTML{ Template: r.Template, Name: name, Data: data, } } func (r HTMLDebug) Instance(name string, data interface{}) Render { return HTML{ Template: r.loadTemplate(), Name: name, Data: data, } } func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} } if len(r.Files) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) } if len(r.Glob) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) } panic("the HTML debug render was created without files or glob pattern") } func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) if len(r.Name) == 0 { return r.Template.Execute(w, r.Data) } return r.Template.ExecuteTemplate(w, r.Name, r.Data) } func (r HTML) WriteContentType(w http.ResponseWriter) { writeContentType(w, htmlContentType) } gin-1.2/render/json.go000066400000000000000000000021531312613627200147140ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "encoding/json" "net/http" ) type ( JSON struct { Data interface{} } IndentedJSON struct { Data interface{} } ) var jsonContentType = []string{"application/json; charset=utf-8"} func (r JSON) Render(w http.ResponseWriter) (err error) { if err = WriteJSON(w, r.Data); err != nil { panic(err) } return } func (r JSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } func WriteJSON(w http.ResponseWriter, obj interface{}) error { writeContentType(w, jsonContentType) jsonBytes, err := json.Marshal(obj) if err != nil { return err } w.Write(jsonBytes) return nil } func (r IndentedJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) jsonBytes, err := json.MarshalIndent(r.Data, "", " ") if err != nil { return err } w.Write(jsonBytes) return nil } func (r IndentedJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } gin-1.2/render/msgpack.go000066400000000000000000000013531312613627200153710ustar00rootroot00000000000000// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "github.com/ugorji/go/codec" ) type MsgPack struct { Data interface{} } var msgpackContentType = []string{"application/msgpack; charset=utf-8"} func (r MsgPack) WriteContentType(w http.ResponseWriter) { writeContentType(w, msgpackContentType) } func (r MsgPack) Render(w http.ResponseWriter) error { return WriteMsgPack(w, r.Data) } func WriteMsgPack(w http.ResponseWriter, obj interface{}) error { writeContentType(w, msgpackContentType) var h codec.Handle = new(codec.MsgpackHandle) return codec.NewEncoder(w, h).Encode(obj) } gin-1.2/render/redirect.go000066400000000000000000000011301312613627200155360ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "fmt" "net/http" ) type Redirect struct { Code int Request *http.Request Location string } func (r Redirect) Render(w http.ResponseWriter) error { if (r.Code < 300 || r.Code > 308) && r.Code != 201 { panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code)) } http.Redirect(w, r.Request, r.Location, r.Code) return nil } func (r Redirect) WriteContentType(http.ResponseWriter) {} gin-1.2/render/render.go000066400000000000000000000014371312613627200152260ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" type Render interface { Render(http.ResponseWriter) error WriteContentType(w http.ResponseWriter) } var ( _ Render = JSON{} _ Render = IndentedJSON{} _ Render = XML{} _ Render = String{} _ Render = Redirect{} _ Render = Data{} _ Render = HTML{} _ HTMLRender = HTMLDebug{} _ HTMLRender = HTMLProduction{} _ Render = YAML{} _ Render = MsgPack{} _ Render = MsgPack{} ) func writeContentType(w http.ResponseWriter, value []string) { header := w.Header() if val := header["Content-Type"]; len(val) == 0 { header["Content-Type"] = value } } gin-1.2/render/render_test.go000066400000000000000000000070611312613627200162640ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "bytes" "encoding/xml" "html/template" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/ugorji/go/codec" ) // TODO unit tests // test errors func TestRenderMsgPack(t *testing.T) { w := httptest.NewRecorder() data := map[string]interface{}{ "foo": "bar", } err := (MsgPack{data}).Render(w) assert.NoError(t, err) h := new(codec.MsgpackHandle) assert.NotNil(t, h) buf := bytes.NewBuffer([]byte{}) assert.NotNil(t, buf) err = codec.NewEncoder(buf, h).Encode(data) assert.NoError(t, err) assert.Equal(t, w.Body.String(), string(buf.Bytes())) assert.Equal(t, w.Header().Get("Content-Type"), "application/msgpack; charset=utf-8") } func TestRenderJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]interface{}{ "foo": "bar", } err := (JSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderIndentedJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]interface{}{ "foo": "bar", "bar": "foo", } err := (IndentedJSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}") assert.Equal(t, w.Header().Get("Content-Type"), "application/json; charset=utf-8") } type xmlmap map[string]interface{} // Allows type H to be used with xml.Marshal func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil { return err } return nil } func TestRenderXML(t *testing.T) { w := httptest.NewRecorder() data := xmlmap{ "foo": "bar", } err := (XML{data}).Render(w) assert.NoError(t, err) assert.Equal(t, w.Body.String(), "bar") assert.Equal(t, w.Header().Get("Content-Type"), "application/xml; charset=utf-8") } func TestRenderRedirect(t *testing.T) { // TODO } func TestRenderData(t *testing.T) { w := httptest.NewRecorder() data := []byte("#!PNG some raw data") err := (Data{ ContentType: "image/png", Data: data, }).Render(w) assert.NoError(t, err) assert.Equal(t, w.Body.String(), "#!PNG some raw data") assert.Equal(t, w.Header().Get("Content-Type"), "image/png") } func TestRenderString(t *testing.T) { w := httptest.NewRecorder() err := (String{ Format: "hola %s %d", Data: []interface{}{"manu", 2}, }).Render(w) assert.NoError(t, err) assert.Equal(t, w.Body.String(), "hola manu 2") assert.Equal(t, w.Header().Get("Content-Type"), "text/plain; charset=utf-8") } func TestRenderHTMLTemplate(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("t").Parse(`Hello {{.name}}`)) htmlRender := HTMLProduction{Template: templ} instance := htmlRender.Instance("t", map[string]interface{}{ "name": "alexandernyquist", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, w.Body.String(), "Hello alexandernyquist") assert.Equal(t, w.Header().Get("Content-Type"), "text/html; charset=utf-8") } gin-1.2/render/text.go000066400000000000000000000013701312613627200147270ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "fmt" "io" "net/http" ) type String struct { Format string Data []interface{} } var plainContentType = []string{"text/plain; charset=utf-8"} func (r String) Render(w http.ResponseWriter) error { WriteString(w, r.Format, r.Data) return nil } func (r String) WriteContentType(w http.ResponseWriter) { writeContentType(w, plainContentType) } func WriteString(w http.ResponseWriter, format string, data []interface{}) { writeContentType(w, plainContentType) if len(data) > 0 { fmt.Fprintf(w, format, data...) } else { io.WriteString(w, format) } } gin-1.2/render/xml.go000066400000000000000000000010341312613627200145400ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "encoding/xml" "net/http" ) type XML struct { Data interface{} } var xmlContentType = []string{"application/xml; charset=utf-8"} func (r XML) Render(w http.ResponseWriter) error { r.WriteContentType(w) return xml.NewEncoder(w).Encode(r.Data) } func (r XML) WriteContentType(w http.ResponseWriter) { writeContentType(w, xmlContentType) } gin-1.2/render/yaml.go000066400000000000000000000011431312613627200147030ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "gopkg.in/yaml.v2" ) type YAML struct { Data interface{} } var yamlContentType = []string{"application/x-yaml; charset=utf-8"} func (r YAML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := yaml.Marshal(r.Data) if err != nil { return err } w.Write(bytes) return nil } func (r YAML) WriteContentType(w http.ResponseWriter) { writeContentType(w, yamlContentType) } gin-1.2/response_writer.go000066400000000000000000000045761312613627200157310ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bufio" "io" "net" "net/http" ) const ( noWritten = -1 defaultStatus = 200 ) type ( ResponseWriter interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // Returns the HTTP response status code of the current request. Status() int // Returns the number of bytes already written into the response http body. // See Written() Size() int // Writes the string into the response body. WriteString(string) (int, error) // Returns true if the response body was already written. Written() bool // Forces to write the http header (status code + headers). WriteHeaderNow() } responseWriter struct { http.ResponseWriter size int status int } ) var _ ResponseWriter = &responseWriter{} func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer w.size = noWritten w.status = defaultStatus } func (w *responseWriter) WriteHeader(code int) { if code > 0 && w.status != code { if w.Written() { debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) } w.status = code } } func (w *responseWriter) WriteHeaderNow() { if !w.Written() { w.size = 0 w.ResponseWriter.WriteHeader(w.status) } } func (w *responseWriter) Write(data []byte) (n int, err error) { w.WriteHeaderNow() n, err = w.ResponseWriter.Write(data) w.size += n return } func (w *responseWriter) WriteString(s string) (n int, err error) { w.WriteHeaderNow() n, err = io.WriteString(w.ResponseWriter, s) w.size += n return } func (w *responseWriter) Status() int { return w.status } func (w *responseWriter) Size() int { return w.size } func (w *responseWriter) Written() bool { return w.size != noWritten } // Implements the http.Hijacker interface func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() } // Implements the http.CloseNotify interface func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Implements the http.Flush interface func (w *responseWriter) Flush() { w.ResponseWriter.(http.Flusher).Flush() } gin-1.2/response_writer_test.go000066400000000000000000000054441312613627200167630ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) // TODO // func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { // func (w *responseWriter) CloseNotify() <-chan bool { // func (w *responseWriter) Flush() { var _ ResponseWriter = &responseWriter{} var _ http.ResponseWriter = &responseWriter{} var _ http.ResponseWriter = ResponseWriter(&responseWriter{}) var _ http.Hijacker = ResponseWriter(&responseWriter{}) var _ http.Flusher = ResponseWriter(&responseWriter{}) var _ http.CloseNotifier = ResponseWriter(&responseWriter{}) func init() { SetMode(TestMode) } func TestResponseWriterReset(t *testing.T) { testWritter := httptest.NewRecorder() writer := &responseWriter{} var w ResponseWriter = writer writer.reset(testWritter) assert.Equal(t, writer.size, -1) assert.Equal(t, writer.status, 200) assert.Equal(t, writer.ResponseWriter, testWritter) assert.Equal(t, w.Size(), -1) assert.Equal(t, w.Status(), 200) assert.False(t, w.Written()) } func TestResponseWriterWriteHeader(t *testing.T) { testWritter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWritter) w := ResponseWriter(writer) w.WriteHeader(300) assert.False(t, w.Written()) assert.Equal(t, w.Status(), 300) assert.NotEqual(t, testWritter.Code, 300) w.WriteHeader(-1) assert.Equal(t, w.Status(), 300) } func TestResponseWriterWriteHeadersNow(t *testing.T) { testWritter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWritter) w := ResponseWriter(writer) w.WriteHeader(300) w.WriteHeaderNow() assert.True(t, w.Written()) assert.Equal(t, w.Size(), 0) assert.Equal(t, testWritter.Code, 300) writer.size = 10 w.WriteHeaderNow() assert.Equal(t, w.Size(), 10) } func TestResponseWriterWrite(t *testing.T) { testWritter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWritter) w := ResponseWriter(writer) n, err := w.Write([]byte("hola")) assert.Equal(t, n, 4) assert.Equal(t, w.Size(), 4) assert.Equal(t, w.Status(), 200) assert.Equal(t, testWritter.Code, 200) assert.Equal(t, testWritter.Body.String(), "hola") assert.NoError(t, err) n, err = w.Write([]byte(" adios")) assert.Equal(t, n, 6) assert.Equal(t, w.Size(), 10) assert.Equal(t, testWritter.Body.String(), "hola adios") assert.NoError(t, err) } func TestResponseWriterHijack(t *testing.T) { testWritter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWritter) w := ResponseWriter(writer) assert.Panics(t, func() { w.Hijack() }) assert.True(t, w.Written()) assert.Panics(t, func() { w.CloseNotify() }) w.Flush() } gin-1.2/routergroup.go000066400000000000000000000170231312613627200150630ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "path" "regexp" "strings" ) type ( IRouter interface { IRoutes Group(string, ...HandlerFunc) *RouterGroup } IRoutes interface { Use(...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes DELETE(string, ...HandlerFunc) IRoutes PATCH(string, ...HandlerFunc) IRoutes PUT(string, ...HandlerFunc) IRoutes OPTIONS(string, ...HandlerFunc) IRoutes HEAD(string, ...HandlerFunc) IRoutes StaticFile(string, string) IRoutes Static(string, string) IRoutes StaticFS(string, http.FileSystem) IRoutes } // RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix // and an array of handlers (middleware) RouterGroup struct { Handlers HandlersChain basePath string engine *Engine root bool } ) var _ IRouter = &RouterGroup{} // Use adds middleware to the group, see example code in github. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() } // Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. // For example, all the routes that use a common middlware for authorization could be grouped. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } } func (group *RouterGroup) BasePath() string { return group.basePath } func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { absolutePath := group.calculateAbsolutePath(relativePath) handlers = group.combineHandlers(handlers) group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() } // Handle registers a new request handle and middleware with the given path and method. // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. // See the example code in github. // // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut // functions can be used. // // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil { panic("http method " + httpMethod + " is not valid") } return group.handle(httpMethod, relativePath, handlers) } // POST is a shortcut for router.Handle("POST", path, handle) func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle("POST", relativePath, handlers) } // GET is a shortcut for router.Handle("GET", path, handle) func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle("GET", relativePath, handlers) } // DELETE is a shortcut for router.Handle("DELETE", path, handle) func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle("DELETE", relativePath, handlers) } // PATCH is a shortcut for router.Handle("PATCH", path, handle) func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle("PATCH", relativePath, handlers) } // PUT is a shortcut for router.Handle("PUT", path, handle) func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle("PUT", relativePath, handlers) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle("OPTIONS", relativePath, handlers) } // HEAD is a shortcut for router.Handle("HEAD", path, handle) func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle("HEAD", relativePath, handlers) } // Any registers a route that matches all the HTTP methods. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { group.handle("GET", relativePath, handlers) group.handle("POST", relativePath, handlers) group.handle("PUT", relativePath, handlers) group.handle("PATCH", relativePath, handlers) group.handle("HEAD", relativePath, handlers) group.handle("OPTIONS", relativePath, handlers) group.handle("DELETE", relativePath, handlers) group.handle("CONNECT", relativePath, handlers) group.handle("TRACE", relativePath, handlers) return group.returnObj() } // StaticFile registers a single route in order to server a single file of the local filesystem. // router.StaticFile("favicon.ico", "./resources/favicon.ico") func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static file") } handler := func(c *Context) { c.File(filepath) } group.GET(relativePath, handler) group.HEAD(relativePath, handler) return group.returnObj() } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // router.Static("/static", "/var/www") func (group *RouterGroup) Static(relativePath, root string) IRoutes { return group.StaticFS(relativePath, Dir(root, false)) } // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. // Gin by default user: gin.Dir() func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static folder") } handler := group.createStaticHandler(relativePath, fs) urlPattern := path.Join(relativePath, "/*filepath") // Register GET and HEAD handlers group.GET(urlPattern, handler) group.HEAD(urlPattern, handler) return group.returnObj() } func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { absolutePath := group.calculateAbsolutePath(relativePath) fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) _, nolisting := fs.(*onlyfilesFS) return func(c *Context) { if nolisting { c.Writer.WriteHeader(404) } fileServer.ServeHTTP(c.Writer, c.Request) } } func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { finalSize := len(group.Handlers) + len(handlers) if finalSize >= int(abortIndex) { panic("too many handlers") } mergedHandlers := make(HandlersChain, finalSize) copy(mergedHandlers, group.Handlers) copy(mergedHandlers[len(group.Handlers):], handlers) return mergedHandlers } func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { return joinPaths(group.basePath, relativePath) } func (group *RouterGroup) returnObj() IRoutes { if group.root { return group.engine } return group } gin-1.2/routergroup_test.go000066400000000000000000000104571312613627200161260ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "testing" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestRouterGroupBasic(t *testing.T) { router := New() group := router.Group("/hola", func(c *Context) {}) group.Use(func(c *Context) {}) assert.Len(t, group.Handlers, 2) assert.Equal(t, group.BasePath(), "/hola") assert.Equal(t, group.engine, router) group2 := group.Group("manu") group2.Use(func(c *Context) {}, func(c *Context) {}) assert.Len(t, group2.Handlers, 4) assert.Equal(t, group2.BasePath(), "/hola/manu") assert.Equal(t, group2.engine, router) } func TestRouterGroupBasicHandle(t *testing.T) { performRequestInGroup(t, "GET") performRequestInGroup(t, "POST") performRequestInGroup(t, "PUT") performRequestInGroup(t, "PATCH") performRequestInGroup(t, "DELETE") performRequestInGroup(t, "HEAD") performRequestInGroup(t, "OPTIONS") } func performRequestInGroup(t *testing.T, method string) { router := New() v1 := router.Group("v1", func(c *Context) {}) assert.Equal(t, v1.BasePath(), "/v1") login := v1.Group("/login/", func(c *Context) {}, func(c *Context) {}) assert.Equal(t, login.BasePath(), "/v1/login/") handler := func(c *Context) { c.String(400, "the method was %s and index %d", c.Request.Method, c.index) } switch method { case "GET": v1.GET("/test", handler) login.GET("/test", handler) case "POST": v1.POST("/test", handler) login.POST("/test", handler) case "PUT": v1.PUT("/test", handler) login.PUT("/test", handler) case "PATCH": v1.PATCH("/test", handler) login.PATCH("/test", handler) case "DELETE": v1.DELETE("/test", handler) login.DELETE("/test", handler) case "HEAD": v1.HEAD("/test", handler) login.HEAD("/test", handler) case "OPTIONS": v1.OPTIONS("/test", handler) login.OPTIONS("/test", handler) default: panic("unknown method") } w := performRequest(router, method, "/v1/login/test") assert.Equal(t, w.Code, 400) assert.Equal(t, w.Body.String(), "the method was "+method+" and index 3") w = performRequest(router, method, "/v1/test") assert.Equal(t, w.Code, 400) assert.Equal(t, w.Body.String(), "the method was "+method+" and index 1") } func TestRouterGroupInvalidStatic(t *testing.T) { router := New() assert.Panics(t, func() { router.Static("/path/:param", "/") }) assert.Panics(t, func() { router.Static("/path/*param", "/") }) } func TestRouterGroupInvalidStaticFile(t *testing.T) { router := New() assert.Panics(t, func() { router.StaticFile("/path/:param", "favicon.ico") }) assert.Panics(t, func() { router.StaticFile("/path/*param", "favicon.ico") }) } func TestRouterGroupTooManyHandlers(t *testing.T) { router := New() handlers1 := make([]HandlerFunc, 40) router.Use(handlers1...) handlers2 := make([]HandlerFunc, 26) assert.Panics(t, func() { router.Use(handlers2...) }) assert.Panics(t, func() { router.GET("/", handlers2...) }) } func TestRouterGroupBadMethod(t *testing.T) { router := New() assert.Panics(t, func() { router.Handle("get", "/") }) assert.Panics(t, func() { router.Handle(" GET", "/") }) assert.Panics(t, func() { router.Handle("GET ", "/") }) assert.Panics(t, func() { router.Handle("", "/") }) assert.Panics(t, func() { router.Handle("PO ST", "/") }) assert.Panics(t, func() { router.Handle("1GET", "/") }) assert.Panics(t, func() { router.Handle("PATCh", "/") }) } func TestRouterGroupPipeline(t *testing.T) { router := New() testRoutesInterface(t, router) v1 := router.Group("/v1") testRoutesInterface(t, v1) } func testRoutesInterface(t *testing.T, r IRoutes) { handler := func(c *Context) {} assert.Equal(t, r, r.Use(handler)) assert.Equal(t, r, r.Handle("GET", "/handler", handler)) assert.Equal(t, r, r.Any("/any", handler)) assert.Equal(t, r, r.GET("/", handler)) assert.Equal(t, r, r.POST("/", handler)) assert.Equal(t, r, r.DELETE("/", handler)) assert.Equal(t, r, r.PATCH("/", handler)) assert.Equal(t, r, r.PUT("/", handler)) assert.Equal(t, r, r.OPTIONS("/", handler)) assert.Equal(t, r, r.HEAD("/", handler)) assert.Equal(t, r, r.StaticFile("/file", ".")) assert.Equal(t, r, r.Static("/static", ".")) assert.Equal(t, r, r.StaticFS("/static2", Dir(".", false))) } gin-1.2/routes_test.go000066400000000000000000000276501312613627200150550ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" ) func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder { req, _ := http.NewRequest(method, path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } func testRouteOK(method string, t *testing.T) { passed := false passedAny := false r := New() r.Any("/test2", func(c *Context) { passedAny = true }) r.Handle(method, "/test", func(c *Context) { passed = true }) w := performRequest(r, method, "/test") assert.True(t, passed) assert.Equal(t, w.Code, http.StatusOK) performRequest(r, method, "/test2") assert.True(t, passedAny) } // TestSingleRouteOK tests that POST route is correctly invoked. func testRouteNotOK(method string, t *testing.T) { passed := false router := New() router.Handle(method, "/test_2", func(c *Context) { passed = true }) w := performRequest(router, method, "/test") assert.False(t, passed) assert.Equal(t, w.Code, http.StatusNotFound) } // TestSingleRouteOK tests that POST route is correctly invoked. func testRouteNotOK2(method string, t *testing.T) { passed := false router := New() router.HandleMethodNotAllowed = true var methodRoute string if method == "POST" { methodRoute = "GET" } else { methodRoute = "POST" } router.Handle(methodRoute, "/test", func(c *Context) { passed = true }) w := performRequest(router, method, "/test") assert.False(t, passed) assert.Equal(t, w.Code, http.StatusMethodNotAllowed) } func TestRouterMethod(t *testing.T) { router := New() router.PUT("/hey2", func(c *Context) { c.String(200, "sup2") }) router.PUT("/hey", func(c *Context) { c.String(200, "called") }) router.PUT("/hey3", func(c *Context) { c.String(200, "sup3") }) w := performRequest(router, "PUT", "/hey") assert.Equal(t, w.Code, 200) assert.Equal(t, w.Body.String(), "called") } func TestRouterGroupRouteOK(t *testing.T) { testRouteOK("GET", t) testRouteOK("POST", t) testRouteOK("PUT", t) testRouteOK("PATCH", t) testRouteOK("HEAD", t) testRouteOK("OPTIONS", t) testRouteOK("DELETE", t) testRouteOK("CONNECT", t) testRouteOK("TRACE", t) } func TestRouteNotOK(t *testing.T) { testRouteNotOK("GET", t) testRouteNotOK("POST", t) testRouteNotOK("PUT", t) testRouteNotOK("PATCH", t) testRouteNotOK("HEAD", t) testRouteNotOK("OPTIONS", t) testRouteNotOK("DELETE", t) testRouteNotOK("CONNECT", t) testRouteNotOK("TRACE", t) } func TestRouteNotOK2(t *testing.T) { testRouteNotOK2("GET", t) testRouteNotOK2("POST", t) testRouteNotOK2("PUT", t) testRouteNotOK2("PATCH", t) testRouteNotOK2("HEAD", t) testRouteNotOK2("OPTIONS", t) testRouteNotOK2("DELETE", t) testRouteNotOK2("CONNECT", t) testRouteNotOK2("TRACE", t) } func TestRouteRedirectTrailingSlash(t *testing.T) { router := New() router.RedirectFixedPath = false router.RedirectTrailingSlash = true router.GET("/path", func(c *Context) {}) router.GET("/path2/", func(c *Context) {}) router.POST("/path3", func(c *Context) {}) router.PUT("/path4/", func(c *Context) {}) w := performRequest(router, "GET", "/path/") assert.Equal(t, w.Header().Get("Location"), "/path") assert.Equal(t, w.Code, 301) w = performRequest(router, "GET", "/path2") assert.Equal(t, w.Header().Get("Location"), "/path2/") assert.Equal(t, w.Code, 301) w = performRequest(router, "POST", "/path3/") assert.Equal(t, w.Header().Get("Location"), "/path3") assert.Equal(t, w.Code, 307) w = performRequest(router, "PUT", "/path4") assert.Equal(t, w.Header().Get("Location"), "/path4/") assert.Equal(t, w.Code, 307) w = performRequest(router, "GET", "/path") assert.Equal(t, w.Code, 200) w = performRequest(router, "GET", "/path2/") assert.Equal(t, w.Code, 200) w = performRequest(router, "POST", "/path3") assert.Equal(t, w.Code, 200) w = performRequest(router, "PUT", "/path4/") assert.Equal(t, w.Code, 200) router.RedirectTrailingSlash = false w = performRequest(router, "GET", "/path/") assert.Equal(t, w.Code, 404) w = performRequest(router, "GET", "/path2") assert.Equal(t, w.Code, 404) w = performRequest(router, "POST", "/path3/") assert.Equal(t, w.Code, 404) w = performRequest(router, "PUT", "/path4") assert.Equal(t, w.Code, 404) } func TestRouteRedirectFixedPath(t *testing.T) { router := New() router.RedirectFixedPath = true router.RedirectTrailingSlash = false router.GET("/path", func(c *Context) {}) router.GET("/Path2", func(c *Context) {}) router.POST("/PATH3", func(c *Context) {}) router.POST("/Path4/", func(c *Context) {}) w := performRequest(router, "GET", "/PATH") assert.Equal(t, w.Header().Get("Location"), "/path") assert.Equal(t, w.Code, 301) w = performRequest(router, "GET", "/path2") assert.Equal(t, w.Header().Get("Location"), "/Path2") assert.Equal(t, w.Code, 301) w = performRequest(router, "POST", "/path3") assert.Equal(t, w.Header().Get("Location"), "/PATH3") assert.Equal(t, w.Code, 307) w = performRequest(router, "POST", "/path4") assert.Equal(t, w.Header().Get("Location"), "/Path4/") assert.Equal(t, w.Code, 307) } // TestContextParamsGet tests that a parameter can be parsed from the URL. func TestRouteParamsByName(t *testing.T) { name := "" lastName := "" wild := "" router := New() router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w := performRequest(router, "GET", "/test/john/smith/is/super/great") assert.Equal(t, w.Code, 200) assert.Equal(t, name, "john") assert.Equal(t, lastName, "smith") assert.Equal(t, wild, "/is/super/great") } // TestHandleStaticFile - ensure the static file handles properly func TestRouteStaticFile(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() f, err := ioutil.TempFile(testRoot, "") if err != nil { t.Error(err) } defer os.Remove(f.Name()) f.WriteString("Gin Web Framework") f.Close() dir, filename := filepath.Split(f.Name()) // SETUP gin router := New() router.Static("/using_static", dir) router.StaticFile("/result", f.Name()) w := performRequest(router, "GET", "/using_static/"+filename) w2 := performRequest(router, "GET", "/result") assert.Equal(t, w, w2) assert.Equal(t, w.Code, 200) assert.Equal(t, w.Body.String(), "Gin Web Framework") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") w3 := performRequest(router, "HEAD", "/using_static/"+filename) w4 := performRequest(router, "HEAD", "/result") assert.Equal(t, w3, w4) assert.Equal(t, w3.Code, 200) } // TestHandleStaticDir - ensure the root/sub dir handles properly func TestRouteStaticListingDir(t *testing.T) { router := New() router.StaticFS("/", Dir("./", true)) w := performRequest(router, "GET", "/") assert.Equal(t, w.Code, 200) assert.Contains(t, w.Body.String(), "gin.go") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8") } // TestHandleHeadToDir - ensure the root/sub dir handles properly func TestRouteStaticNoListing(t *testing.T) { router := New() router.Static("/", "./") w := performRequest(router, "GET", "/") assert.Equal(t, w.Code, 404) assert.NotContains(t, w.Body.String(), "gin.go") } func TestRouterMiddlewareAndStatic(t *testing.T) { router := New() static := router.Group("/", func(c *Context) { c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("X-GIN", "Gin Framework") }) static.Static("/", "./") w := performRequest(router, "GET", "/gin.go") assert.Equal(t, w.Code, 200) assert.Contains(t, w.Body.String(), "package gin") assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") assert.NotEqual(t, w.HeaderMap.Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST") assert.Equal(t, w.HeaderMap.Get("Expires"), "Mon, 02 Jan 2006 15:04:05 MST") assert.Equal(t, w.HeaderMap.Get("x-GIN"), "Gin Framework") } func TestRouteNotAllowedEnabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = true router.POST("/path", func(c *Context) {}) w := performRequest(router, "GET", "/path") assert.Equal(t, w.Code, http.StatusMethodNotAllowed) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = performRequest(router, "GET", "/path") assert.Equal(t, w.Body.String(), "responseText") assert.Equal(t, w.Code, http.StatusTeapot) } func TestRouteNotAllowedDisabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = false router.POST("/path", func(c *Context) {}) w := performRequest(router, "GET", "/path") assert.Equal(t, w.Code, 404) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = performRequest(router, "GET", "/path") assert.Equal(t, w.Body.String(), "404 page not found") assert.Equal(t, w.Code, 404) } func TestRouterNotFound(t *testing.T) { router := New() router.RedirectFixedPath = true router.GET("/path", func(c *Context) {}) router.GET("/dir/", func(c *Context) {}) router.GET("/", func(c *Context) {}) testRoutes := []struct { route string code int header string }{ {"/path/", 301, "map[Location:[/path]]"}, // TSR -/ {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/ {"", 301, "map[Location:[/]]"}, // TSR +/ {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/ {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/ {"/../path", 301, "map[Location:[/path]]"}, // CleanPath {"/nope", 404, ""}, // NotFound } for _, tr := range testRoutes { w := performRequest(router, "GET", tr.route) assert.Equal(t, w.Code, tr.code) if w.Code != 404 { assert.Equal(t, fmt.Sprint(w.Header()), tr.header) } } // Test custom not found handler var notFound bool router.NoRoute(func(c *Context) { c.AbortWithStatus(404) notFound = true }) w := performRequest(router, "GET", "/nope") assert.Equal(t, w.Code, 404) assert.True(t, notFound) // Test other method than GET (want 307 instead of 301) router.PATCH("/path", func(c *Context) {}) w = performRequest(router, "PATCH", "/path/") assert.Equal(t, w.Code, 307) assert.Equal(t, fmt.Sprint(w.Header()), "map[Location:[/path]]") // Test special case where no node for the prefix "/" exists router = New() router.GET("/a", func(c *Context) {}) w = performRequest(router, "GET", "/") assert.Equal(t, w.Code, 404) } func TestRouteRawPath(t *testing.T) { route := New() route.UseRawPath = true route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, c.Param("name"), name) assert.Equal(t, c.Param("num"), num) assert.Equal(t, "Some/Other/Project", name) assert.Equal(t, "222", num) }) w := performRequest(route, "POST", "/project/Some%2FOther%2FProject/build/222") assert.Equal(t, w.Code, 200) } func TestRouteRawPathNoUnescape(t *testing.T) { route := New() route.UseRawPath = true route.UnescapePathValues = false route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, c.Param("name"), name) assert.Equal(t, c.Param("num"), num) assert.Equal(t, "Some%2FOther%2FProject", name) assert.Equal(t, "333", num) }) w := performRequest(route, "POST", "/project/Some%2FOther%2FProject/build/333") assert.Equal(t, w.Code, 200) } gin-1.2/test_helpers.go000066400000000000000000000005441312613627200151670ustar00rootroot00000000000000// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" ) func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { r = New() c = r.allocateContext() c.reset() c.writermem.reset(w) return } gin-1.2/tree.go000066400000000000000000000363021312613627200134260ustar00rootroot00000000000000// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "net/url" "strings" "unicode" ) // Param is a single URL parameter, consisting of a key and a value. type Param struct { Key string Value string } // Params is a Param-slice, as returned by the router. // The slice is ordered, the first URL parameter is also the first slice value. // It is therefore safe to read values by the index. type Params []Param // Get returns the value of the first Param which key matches the given name. // If no matching Param is found, an empty string is returned. func (ps Params) Get(name string) (string, bool) { for _, entry := range ps { if entry.Key == name { return entry.Value, true } } return "", false } // ByName returns the value of the first Param which key matches the given name. // If no matching Param is found, an empty string is returned. func (ps Params) ByName(name string) (va string) { va, _ = ps.Get(name) return } type methodTree struct { method string root *node } type methodTrees []methodTree func (trees methodTrees) get(method string) *node { for _, tree := range trees { if tree.method == method { return tree.root } } return nil } func min(a, b int) int { if a <= b { return a } return b } func countParams(path string) uint8 { var n uint for i := 0; i < len(path); i++ { if path[i] != ':' && path[i] != '*' { continue } n++ } if n >= 255 { return 255 } return uint8(n) } type nodeType uint8 const ( static nodeType = iota // default root param catchAll ) type node struct { path string wildChild bool nType nodeType maxParams uint8 indices string children []*node handlers HandlersChain priority uint32 } // increments priority of the given child and reorders if necessary func (n *node) incrementChildPrio(pos int) int { n.children[pos].priority++ prio := n.children[pos].priority // adjust position (move to front) newPos := pos for newPos > 0 && n.children[newPos-1].priority < prio { // swap node positions tmpN := n.children[newPos-1] n.children[newPos-1] = n.children[newPos] n.children[newPos] = tmpN newPos-- } // build new index char string if newPos != pos { n.indices = n.indices[:newPos] + // unchanged prefix, might be empty n.indices[pos:pos+1] + // the index char we move n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos' } return newPos } // addRoute adds a node with the given handle to the path. // Not concurrency-safe! func (n *node) addRoute(path string, handlers HandlersChain) { fullPath := path n.priority++ numParams := countParams(path) // non-empty tree if len(n.path) > 0 || len(n.children) > 0 { walk: for { // Update maxParams of the current node if numParams > n.maxParams { n.maxParams = numParams } // Find the longest common prefix. // This also implies that the common prefix contains no ':' or '*' // since the existing key can't contain those chars. i := 0 max := min(len(path), len(n.path)) for i < max && path[i] == n.path[i] { i++ } // Split edge if i < len(n.path) { child := node{ path: n.path[i:], wildChild: n.wildChild, indices: n.indices, children: n.children, handlers: n.handlers, priority: n.priority - 1, } // Update maxParams (max of all children) for i := range child.children { if child.children[i].maxParams > child.maxParams { child.maxParams = child.children[i].maxParams } } n.children = []*node{&child} // []byte for proper unicode char conversion, see #65 n.indices = string([]byte{n.path[i]}) n.path = path[:i] n.handlers = nil n.wildChild = false } // Make new node a child of this node if i < len(path) { path = path[i:] if n.wildChild { n = n.children[0] n.priority++ // Update maxParams of the child node if numParams > n.maxParams { n.maxParams = numParams } numParams-- // Check if the wildcard matches if len(path) >= len(n.path) && n.path == path[:len(n.path)] { // check for longer wildcard, e.g. :name and :names if len(n.path) >= len(path) || path[len(n.path)] == '/' { continue walk } } panic("path segment '" + path + "' conflicts with existing wildcard '" + n.path + "' in path '" + fullPath + "'") } c := path[0] // slash after param if n.nType == param && c == '/' && len(n.children) == 1 { n = n.children[0] n.priority++ continue walk } // Check if a child with the next path byte exists for i := 0; i < len(n.indices); i++ { if c == n.indices[i] { i = n.incrementChildPrio(i) n = n.children[i] continue walk } } // Otherwise insert it if c != ':' && c != '*' { // []byte for proper unicode char conversion, see #65 n.indices += string([]byte{c}) child := &node{ maxParams: numParams, } n.children = append(n.children, child) n.incrementChildPrio(len(n.indices) - 1) n = child } n.insertChild(numParams, path, fullPath, handlers) return } else if i == len(path) { // Make node a (in-path) leaf if n.handlers != nil { panic("handlers are already registered for path ''" + fullPath + "'") } n.handlers = handlers } return } } else { // Empty tree n.insertChild(numParams, path, fullPath, handlers) n.nType = root } } func (n *node) insertChild(numParams uint8, path string, fullPath string, handlers HandlersChain) { var offset int // already handled bytes of the path // find prefix until first wildcard (beginning with ':'' or '*'') for i, max := 0, len(path); numParams > 0; i++ { c := path[i] if c != ':' && c != '*' { continue } // find wildcard end (either '/' or path end) end := i + 1 for end < max && path[end] != '/' { switch path[end] { // the wildcard name must not contain ':' and '*' case ':', '*': panic("only one wildcard per path segment is allowed, has: '" + path[i:] + "' in path '" + fullPath + "'") default: end++ } } // check if this Node existing children which would be // unreachable if we insert the wildcard here if len(n.children) > 0 { panic("wildcard route '" + path[i:end] + "' conflicts with existing children in path '" + fullPath + "'") } // check if the wildcard has a name if end-i < 2 { panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") } if c == ':' { // param // split path at the beginning of the wildcard if i > 0 { n.path = path[offset:i] offset = i } child := &node{ nType: param, maxParams: numParams, } n.children = []*node{child} n.wildChild = true n = child n.priority++ numParams-- // if the path doesn't end with the wildcard, then there // will be another non-wildcard subpath starting with '/' if end < max { n.path = path[offset:end] offset = end child := &node{ maxParams: numParams, priority: 1, } n.children = []*node{child} n = child } } else { // catchAll if end != max || numParams > 1 { panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") } if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'") } // currently fixed width 1 for '/' i-- if path[i] != '/' { panic("no / before catch-all in path '" + fullPath + "'") } n.path = path[offset:i] // first node: catchAll node with empty path child := &node{ wildChild: true, nType: catchAll, maxParams: 1, } n.children = []*node{child} n.indices = string(path[i]) n = child n.priority++ // second node: node holding the variable child = &node{ path: path[i:], nType: catchAll, maxParams: 1, handlers: handlers, priority: 1, } n.children = []*node{child} return } } // insert remaining path part and handle to the leaf n.path = path[offset:] n.handlers = handlers } // Returns the handle registered with the given path (key). The values of // wildcards are saved to a map. // If no handle can be found, a TSR (trailing slash redirect) recommendation is // made if a handle exists with an extra (without the) trailing slash for the // given path. func (n *node) getValue(path string, po Params, unescape bool) (handlers HandlersChain, p Params, tsr bool) { p = po walk: // Outer loop for walking the tree for { if len(path) > len(n.path) { if path[:len(n.path)] == n.path { path = path[len(n.path):] // If this node does not have a wildcard (param or catchAll) // child, we can just look up the next child node and continue // to walk down the tree if !n.wildChild { c := path[0] for i := 0; i < len(n.indices); i++ { if c == n.indices[i] { n = n.children[i] continue walk } } // Nothing found. // We can recommend to redirect to the same URL without a // trailing slash if a leaf exists for that path. tsr = (path == "/" && n.handlers != nil) return } // handle wildcard child n = n.children[0] switch n.nType { case param: // find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // save param value if cap(p) < int(n.maxParams) { p = make(Params, 0, n.maxParams) } i := len(p) p = p[:i+1] // expand slice within preallocated capacity p[i].Key = n.path[1:] val := path[:end] if unescape { var err error if p[i].Value, err = url.QueryUnescape(val); err != nil { p[i].Value = val // fallback, in case of error } } else { p[i].Value = val } // we need to go deeper! if end < len(path) { if len(n.children) > 0 { path = path[end:] n = n.children[0] continue walk } // ... but we can't tsr = (len(path) == end+1) return } if handlers = n.handlers; handlers != nil { return } if len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists for TSR recommendation n = n.children[0] tsr = (n.path == "/" && n.handlers != nil) } return case catchAll: // save param value if cap(p) < int(n.maxParams) { p = make(Params, 0, n.maxParams) } i := len(p) p = p[:i+1] // expand slice within preallocated capacity p[i].Key = n.path[2:] if unescape { var err error if p[i].Value, err = url.QueryUnescape(path); err != nil { p[i].Value = path // fallback, in case of error } } else { p[i].Value = path } handlers = n.handlers return default: panic("invalid node type") } } } else if path == n.path { // We should have reached the node containing the handle. // Check if this node has a handle registered. if handlers = n.handlers; handlers != nil { return } if path == "/" && n.wildChild && n.nType != root { tsr = true return } // No handle found. Check if a handle for this path + a // trailing slash exists for trailing slash recommendation for i := 0; i < len(n.indices); i++ { if n.indices[i] == '/' { n = n.children[i] tsr = (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) return } } return } // Nothing found. We can recommend to redirect to the same URL with an // extra trailing slash if a leaf exists for that path tsr = (path == "/") || (len(n.path) == len(path)+1 && n.path[len(path)] == '/' && path == n.path[:len(n.path)-1] && n.handlers != nil) return } } // Makes a case-insensitive lookup of the given path and tries to find a handler. // It can optionally also fix trailing slashes. // It returns the case-corrected path and a bool indicating whether the lookup // was successful. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) { ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory // Outer loop for walking the tree for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) { path = path[len(n.path):] ciPath = append(ciPath, n.path...) if len(path) > 0 { // If this node does not have a wildcard (param or catchAll) child, // we can just look up the next child node and continue to walk down // the tree if !n.wildChild { r := unicode.ToLower(rune(path[0])) for i, index := range n.indices { // must use recursive approach since both index and // ToLower(index) could exist. We must check both. if r == unicode.ToLower(index) { out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash) if found { return append(ciPath, out...), true } } } // Nothing found. We can recommend to redirect to the same URL // without a trailing slash if a leaf exists for that path found = (fixTrailingSlash && path == "/" && n.handlers != nil) return } n = n.children[0] switch n.nType { case param: // find param end (either '/' or path end) k := 0 for k < len(path) && path[k] != '/' { k++ } // add param value to case insensitive path ciPath = append(ciPath, path[:k]...) // we need to go deeper! if k < len(path) { if len(n.children) > 0 { path = path[k:] n = n.children[0] continue } // ... but we can't if fixTrailingSlash && len(path) == k+1 { return ciPath, true } return } if n.handlers != nil { return ciPath, true } else if fixTrailingSlash && len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists n = n.children[0] if n.path == "/" && n.handlers != nil { return append(ciPath, '/'), true } } return case catchAll: return append(ciPath, path...), true default: panic("invalid node type") } } else { // We should have reached the node containing the handle. // Check if this node has a handle registered. if n.handlers != nil { return ciPath, true } // No handle found. // Try to fix the path by adding a trailing slash if fixTrailingSlash { for i := 0; i < len(n.indices); i++ { if n.indices[i] == '/' { n = n.children[i] if (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) { return append(ciPath, '/'), true } return } } } return } } // Nothing found. // Try to fix the path by adding / removing a trailing slash if fixTrailingSlash { if path == "/" { return ciPath, true } if len(path)+1 == len(n.path) && n.path[len(path)] == '/' && strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) && n.handlers != nil { return append(ciPath, n.path...), true } } return } gin-1.2/tree_test.go000066400000000000000000000406441312613627200144710ustar00rootroot00000000000000// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "fmt" "reflect" "strings" "testing" ) func printChildren(n *node, prefix string) { fmt.Printf(" %02d:%02d %s%s[%d] %v %t %d \r\n", n.priority, n.maxParams, prefix, n.path, len(n.children), n.handlers, n.wildChild, n.nType) for l := len(n.path); l > 0; l-- { prefix += " " } for _, child := range n.children { printChildren(child, prefix) } } // Used as a workaround since we can't compare functions or their addressses var fakeHandlerValue string func fakeHandler(val string) HandlersChain { return HandlersChain{func(c *Context) { fakeHandlerValue = val }} } type testRequests []struct { path string nilHandler bool route string ps Params } func checkRequests(t *testing.T, tree *node, requests testRequests, unescapes ...bool) { unescape := false if len(unescapes) >= 1 { unescape = unescapes[0] } for _, request := range requests { handler, ps, _ := tree.getValue(request.path, nil, unescape) if handler == nil { if !request.nilHandler { t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path) } } else if request.nilHandler { t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path) } else { handler[0](nil) if fakeHandlerValue != request.route { t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route) } } if !reflect.DeepEqual(ps, request.ps) { t.Errorf("Params mismatch for route '%s'", request.path) } } } func checkPriorities(t *testing.T, n *node) uint32 { var prio uint32 for i := range n.children { prio += checkPriorities(t, n.children[i]) } if n.handlers != nil { prio++ } if n.priority != prio { t.Errorf( "priority mismatch for node '%s': is %d, should be %d", n.path, n.priority, prio, ) } return prio } func checkMaxParams(t *testing.T, n *node) uint8 { var maxParams uint8 for i := range n.children { params := checkMaxParams(t, n.children[i]) if params > maxParams { maxParams = params } } if n.nType > root && !n.wildChild { maxParams++ } if n.maxParams != maxParams { t.Errorf( "maxParams mismatch for node '%s': is %d, should be %d", n.path, n.maxParams, maxParams, ) } return maxParams } func TestCountParams(t *testing.T) { if countParams("/path/:param1/static/*catch-all") != 2 { t.Fail() } if countParams(strings.Repeat("/:param", 256)) != 255 { t.Fail() } } func TestTreeAddAndGet(t *testing.T) { tree := &node{} routes := [...]string{ "/hi", "/contact", "/co", "/c", "/a", "/ab", "/doc/", "/doc/go_faq.html", "/doc/go1.html", "/α", "/β", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } //printChildren(tree, "") checkRequests(t, tree, testRequests{ {"/a", false, "/a", nil}, {"/", true, "", nil}, {"/hi", false, "/hi", nil}, {"/contact", false, "/contact", nil}, {"/co", false, "/co", nil}, {"/con", true, "", nil}, // key mismatch {"/cona", true, "", nil}, // key mismatch {"/no", true, "", nil}, // no matching child {"/ab", false, "/ab", nil}, {"/α", false, "/α", nil}, {"/β", false, "/β", nil}, }) checkPriorities(t, tree) checkMaxParams(t, tree) } func TestTreeWildcard(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/cmd/:tool/:sub", "/cmd/:tool/", "/src/*filepath", "/search/", "/search/:query", "/user_:name", "/user_:name/about", "/files/:dir/*filepath", "/doc/", "/doc/go_faq.html", "/doc/go1.html", "/info/:user/public", "/info/:user/project/:project", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } //printChildren(tree, "") checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}}, {"/cmd/test", true, "", Params{Param{"tool", "test"}}}, {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}}, {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, {"/search/", false, "/search/", nil}, {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}}, {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}}, {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}}, {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}}, {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}}, }) checkPriorities(t, tree) checkMaxParams(t, tree) } func TestUnescapeParameters(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/cmd/:tool/:sub", "/cmd/:tool/", "/src/*filepath", "/search/:query", "/files/:dir/*filepath", "/info/:user/project/:project", "/info/:user", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } //printChildren(tree, "") unescape := true checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}}, {"/cmd/test", true, "", Params{Param{"tool", "test"}}}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, {"/src/some/file+test.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file test.png"}}}, {"/src/some/file++++%%%%test.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file++++%%%%test.png"}}}, {"/src/some/file%2Ftest.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file/test.png"}}}, {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng in ünìcodé"}}}, {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}}, {"/info/slash%2Fgordon", false, "/info/:user", Params{Param{"user", "slash/gordon"}}}, {"/info/slash%2Fgordon/project/Project%20%231", false, "/info/:user/project/:project", Params{Param{"user", "slash/gordon"}, Param{"project", "Project #1"}}}, {"/info/slash%%%%", false, "/info/:user", Params{Param{"user", "slash%%%%"}}}, {"/info/slash%%%%2Fgordon/project/Project%%%%20%231", false, "/info/:user/project/:project", Params{Param{"user", "slash%%%%2Fgordon"}, Param{"project", "Project%%%%20%231"}}}, }, unescape) checkPriorities(t, tree) checkMaxParams(t, tree) } func catchPanic(testFunc func()) (recv interface{}) { defer func() { recv = recover() }() testFunc() return } type testRoute struct { path string conflict bool } func testRoutes(t *testing.T, routes []testRoute) { tree := &node{} for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route.path, nil) }) if route.conflict { if recv == nil { t.Errorf("no panic for conflicting route '%s'", route.path) } } else if recv != nil { t.Errorf("unexpected panic for route '%s': %v", route.path, recv) } } //printChildren(tree, "") } func TestTreeWildcardConflict(t *testing.T) { routes := []testRoute{ {"/cmd/:tool/:sub", false}, {"/cmd/vet", true}, {"/src/*filepath", false}, {"/src/*filepathx", true}, {"/src/", true}, {"/src1/", false}, {"/src1/*filepath", true}, {"/src2*filepath", true}, {"/search/:query", false}, {"/search/invalid", true}, {"/user_:name", false}, {"/user_x", true}, {"/user_:name", false}, {"/id:id", false}, {"/id/:id", true}, } testRoutes(t, routes) } func TestTreeChildConflict(t *testing.T) { routes := []testRoute{ {"/cmd/vet", false}, {"/cmd/:tool/:sub", true}, {"/src/AUTHORS", false}, {"/src/*filepath", true}, {"/user_x", false}, {"/user_:name", true}, {"/id/:id", false}, {"/id:id", true}, {"/:id", true}, {"/*filepath", true}, } testRoutes(t, routes) } func TestTreeDupliatePath(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/doc/", "/src/*filepath", "/search/:query", "/user_:name", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } // Add again recv = catchPanic(func() { tree.addRoute(route, nil) }) if recv == nil { t.Fatalf("no panic while inserting duplicate route '%s", route) } } //printChildren(tree, "") checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/doc/", false, "/doc/", nil}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}}, }) } func TestEmptyWildcardName(t *testing.T) { tree := &node{} routes := [...]string{ "/user:", "/user:/", "/cmd/:/", "/src/*", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, nil) }) if recv == nil { t.Fatalf("no panic while inserting route with empty wildcard name '%s", route) } } } func TestTreeCatchAllConflict(t *testing.T) { routes := []testRoute{ {"/src/*filepath/x", true}, {"/src2/", false}, {"/src2/*filepath/x", true}, } testRoutes(t, routes) } func TestTreeCatchAllConflictRoot(t *testing.T) { routes := []testRoute{ {"/", false}, {"/*filepath", true}, } testRoutes(t, routes) } func TestTreeDoubleWildcard(t *testing.T) { const panicMsg = "only one wildcard per path segment is allowed" routes := [...]string{ "/:foo:bar", "/:foo:bar/", "/:foo*bar", } for _, route := range routes { tree := &node{} recv := catchPanic(func() { tree.addRoute(route, nil) }) if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) { t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv) } } } /*func TestTreeDuplicateWildcard(t *testing.T) { tree := &node{} routes := [...]string{ "/:id/:name/:id", } for _, route := range routes { ... } }*/ func TestTreeTrailingSlashRedirect(t *testing.T) { tree := &node{} routes := [...]string{ "/hi", "/b/", "/search/:query", "/cmd/:tool/", "/src/*filepath", "/x", "/x/y", "/y/", "/y/z", "/0/:id", "/0/:id/1", "/1/:id/", "/1/:id/2", "/aa", "/a/", "/admin", "/admin/:category", "/admin/:category/:page", "/doc", "/doc/go_faq.html", "/doc/go1.html", "/no/a", "/no/b", "/api/hello/:name", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } } //printChildren(tree, "") tsrRoutes := [...]string{ "/hi/", "/b", "/search/gopher/", "/cmd/vet", "/src", "/x/", "/y", "/0/go/", "/1/go", "/a", "/admin/", "/admin/config/", "/admin/config/permissions/", "/doc/", } for _, route := range tsrRoutes { handler, _, tsr := tree.getValue(route, nil, false) if handler != nil { t.Fatalf("non-nil handler for TSR route '%s", route) } else if !tsr { t.Errorf("expected TSR recommendation for route '%s'", route) } } noTsrRoutes := [...]string{ "/", "/no", "/no/", "/_", "/_/", "/api/world/abc", } for _, route := range noTsrRoutes { handler, _, tsr := tree.getValue(route, nil, false) if handler != nil { t.Fatalf("non-nil handler for No-TSR route '%s", route) } else if tsr { t.Errorf("expected no TSR recommendation for route '%s'", route) } } } func TestTreeRootTrailingSlashRedirect(t *testing.T) { tree := &node{} recv := catchPanic(func() { tree.addRoute("/:test", fakeHandler("/:test")) }) if recv != nil { t.Fatalf("panic inserting test route: %v", recv) } handler, _, tsr := tree.getValue("/", nil, false) if handler != nil { t.Fatalf("non-nil handler") } else if tsr { t.Errorf("expected no TSR recommendation") } } func TestTreeFindCaseInsensitivePath(t *testing.T) { tree := &node{} routes := [...]string{ "/hi", "/b/", "/ABC/", "/search/:query", "/cmd/:tool/", "/src/*filepath", "/x", "/x/y", "/y/", "/y/z", "/0/:id", "/0/:id/1", "/1/:id/", "/1/:id/2", "/aa", "/a/", "/doc", "/doc/go_faq.html", "/doc/go1.html", "/doc/go/away", "/no/a", "/no/b", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } } // Check out == in for all registered routes // With fixTrailingSlash = true for _, route := range routes { out, found := tree.findCaseInsensitivePath(route, true) if !found { t.Errorf("Route '%s' not found!", route) } else if string(out) != route { t.Errorf("Wrong result for route '%s': %s", route, string(out)) } } // With fixTrailingSlash = false for _, route := range routes { out, found := tree.findCaseInsensitivePath(route, false) if !found { t.Errorf("Route '%s' not found!", route) } else if string(out) != route { t.Errorf("Wrong result for route '%s': %s", route, string(out)) } } tests := []struct { in string out string found bool slash bool }{ {"/HI", "/hi", true, false}, {"/HI/", "/hi", true, true}, {"/B", "/b/", true, true}, {"/B/", "/b/", true, false}, {"/abc", "/ABC/", true, true}, {"/abc/", "/ABC/", true, false}, {"/aBc", "/ABC/", true, true}, {"/aBc/", "/ABC/", true, false}, {"/abC", "/ABC/", true, true}, {"/abC/", "/ABC/", true, false}, {"/SEARCH/QUERY", "/search/QUERY", true, false}, {"/SEARCH/QUERY/", "/search/QUERY", true, true}, {"/CMD/TOOL/", "/cmd/TOOL/", true, false}, {"/CMD/TOOL", "/cmd/TOOL/", true, true}, {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false}, {"/x/Y", "/x/y", true, false}, {"/x/Y/", "/x/y", true, true}, {"/X/y", "/x/y", true, false}, {"/X/y/", "/x/y", true, true}, {"/X/Y", "/x/y", true, false}, {"/X/Y/", "/x/y", true, true}, {"/Y/", "/y/", true, false}, {"/Y", "/y/", true, true}, {"/Y/z", "/y/z", true, false}, {"/Y/z/", "/y/z", true, true}, {"/Y/Z", "/y/z", true, false}, {"/Y/Z/", "/y/z", true, true}, {"/y/Z", "/y/z", true, false}, {"/y/Z/", "/y/z", true, true}, {"/Aa", "/aa", true, false}, {"/Aa/", "/aa", true, true}, {"/AA", "/aa", true, false}, {"/AA/", "/aa", true, true}, {"/aA", "/aa", true, false}, {"/aA/", "/aa", true, true}, {"/A/", "/a/", true, false}, {"/A", "/a/", true, true}, {"/DOC", "/doc", true, false}, {"/DOC/", "/doc", true, true}, {"/NO", "", false, true}, {"/DOC/GO", "", false, true}, } // With fixTrailingSlash = true for _, test := range tests { out, found := tree.findCaseInsensitivePath(test.in, true) if found != test.found || (found && (string(out) != test.out)) { t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", test.in, string(out), found, test.out, test.found) return } } // With fixTrailingSlash = false for _, test := range tests { out, found := tree.findCaseInsensitivePath(test.in, false) if test.slash { if found { // test needs a trailingSlash fix. It must not be found! t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out)) } } else { if found != test.found || (found && (string(out) != test.out)) { t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", test.in, string(out), found, test.out, test.found) return } } } } func TestTreeInvalidNodeType(t *testing.T) { const panicMsg = "invalid node type" tree := &node{} tree.addRoute("/", fakeHandler("/")) tree.addRoute("/:page", fakeHandler("/:page")) // set invalid node type tree.children[0].nType = 42 // normal lookup recv := catchPanic(func() { tree.getValue("/test", nil, false) }) if rs, ok := recv.(string); !ok || rs != panicMsg { t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) } // case-insensitive lookup recv = catchPanic(func() { tree.findCaseInsensitivePath("/test", true) }) if rs, ok := recv.(string); !ok || rs != panicMsg { t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) } } gin-1.2/utils.go000066400000000000000000000061421312613627200136260ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "encoding/xml" "net/http" "os" "path" "reflect" "runtime" "strings" ) const BindKey = "_gin-gonic/gin/bindkey" func Bind(val interface{}) HandlerFunc { value := reflect.ValueOf(val) if value.Kind() == reflect.Ptr { panic(`Bind struct can not be a pointer. Example: Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{}) `) } typ := value.Type() return func(c *Context) { obj := reflect.New(typ).Interface() if c.Bind(obj) == nil { c.Set(BindKey, obj) } } } func WrapF(f http.HandlerFunc) HandlerFunc { return func(c *Context) { f(c.Writer, c.Request) } } func WrapH(h http.Handler) HandlerFunc { return func(c *Context) { h.ServeHTTP(c.Writer, c.Request) } } type H map[string]interface{} // MarshalXML allows type H to be used with xml.Marshal func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil { return err } return nil } func assert1(guard bool, text string) { if !guard { panic(text) } } func filterFlags(content string) string { for i, char := range content { if char == ' ' || char == ';' { return content[:i] } } return content } func chooseData(custom, wildcard interface{}) interface{} { if custom == nil { if wildcard == nil { panic("negotiation config is invalid") } return wildcard } return custom } func parseAccept(acceptHeader string) []string { parts := strings.Split(acceptHeader, ",") out := make([]string, 0, len(parts)) for _, part := range parts { index := strings.IndexByte(part, ';') if index >= 0 { part = part[0:index] } part = strings.TrimSpace(part) if len(part) > 0 { out = append(out, part) } } return out } func lastChar(str string) uint8 { size := len(str) if size == 0 { panic("The length of the string can't be 0") } return str[size-1] } func nameOfFunction(f interface{}) string { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } func joinPaths(absolutePath, relativePath string) string { if len(relativePath) == 0 { return absolutePath } finalPath := path.Join(absolutePath, relativePath) appendSlash := lastChar(relativePath) == '/' && lastChar(finalPath) != '/' if appendSlash { return finalPath + "/" } return finalPath } func resolveAddress(addr []string) string { switch len(addr) { case 0: if port := os.Getenv("PORT"); len(port) > 0 { debugPrint("Environment variable PORT=\"%s\"", port) return ":" + port } debugPrint("Environment variable PORT is undefined. Using port :8080 by default") return ":8080" case 1: return addr[0] default: panic("too much parameters") } } gin-1.2/utils_test.go000066400000000000000000000064411312613627200146670ustar00rootroot00000000000000// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } type testStruct struct { T *testing.T } func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) { assert.Equal(t.T, req.Method, "POST") assert.Equal(t.T, req.URL.Path, "/path") w.WriteHeader(500) fmt.Fprint(w, "hello") } func TestWrap(t *testing.T) { router := New() router.POST("/path", WrapH(&testStruct{t})) router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) { assert.Equal(t, req.Method, "GET") assert.Equal(t, req.URL.Path, "/path2") w.WriteHeader(400) fmt.Fprint(w, "hola!") })) w := performRequest(router, "POST", "/path") assert.Equal(t, w.Code, 500) assert.Equal(t, w.Body.String(), "hello") w = performRequest(router, "GET", "/path2") assert.Equal(t, w.Code, 400) assert.Equal(t, w.Body.String(), "hola!") } func TestLastChar(t *testing.T) { assert.Equal(t, lastChar("hola"), uint8('a')) assert.Equal(t, lastChar("adios"), uint8('s')) assert.Panics(t, func() { lastChar("") }) } func TestParseAccept(t *testing.T) { parts := parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8") assert.Len(t, parts, 4) assert.Equal(t, parts[0], "text/html") assert.Equal(t, parts[1], "application/xhtml+xml") assert.Equal(t, parts[2], "application/xml") assert.Equal(t, parts[3], "*/*") } func TestChooseData(t *testing.T) { A := "a" B := "b" assert.Equal(t, chooseData(A, B), A) assert.Equal(t, chooseData(nil, B), B) assert.Panics(t, func() { chooseData(nil, nil) }) } func TestFilterFlags(t *testing.T) { result := filterFlags("text/html ") assert.Equal(t, result, "text/html") result = filterFlags("text/html;") assert.Equal(t, result, "text/html") } func TestFunctionName(t *testing.T) { assert.Regexp(t, `^(.*/vendor/)?github.com/gin-gonic/gin.somefunction$`, nameOfFunction(somefunction)) } func somefunction() { // this empty function is used by TestFunctionName() } func TestJoinPaths(t *testing.T) { assert.Equal(t, joinPaths("", ""), "") assert.Equal(t, joinPaths("", "/"), "/") assert.Equal(t, joinPaths("/a", ""), "/a") assert.Equal(t, joinPaths("/a/", ""), "/a/") assert.Equal(t, joinPaths("/a/", "/"), "/a/") assert.Equal(t, joinPaths("/a", "/"), "/a/") assert.Equal(t, joinPaths("/a", "/hola"), "/a/hola") assert.Equal(t, joinPaths("/a/", "/hola"), "/a/hola") assert.Equal(t, joinPaths("/a/", "/hola/"), "/a/hola/") assert.Equal(t, joinPaths("/a/", "/hola//"), "/a/hola/") } type bindTestStruct struct { Foo string `form:"foo" binding:"required"` Bar int `form:"bar" binding:"min=4"` } func TestBindMiddleware(t *testing.T) { var value *bindTestStruct var called bool router := New() router.GET("/", Bind(bindTestStruct{}), func(c *Context) { called = true value = c.MustGet(BindKey).(*bindTestStruct) }) performRequest(router, "GET", "/?foo=hola&bar=10") assert.True(t, called) assert.Equal(t, value.Foo, "hola") assert.Equal(t, value.Bar, 10) called = false performRequest(router, "GET", "/?foo=hola&bar=1") assert.False(t, called) assert.Panics(t, func() { Bind(&bindTestStruct{}) }) } gin-1.2/vendor/000077500000000000000000000000001312613627200134315ustar00rootroot00000000000000gin-1.2/vendor/vendor.json000066400000000000000000000067031312613627200156270ustar00rootroot00000000000000{ "comment": "v1.2", "ignore": "test", "package": [ { "checksumSHA1": "dvabztWVQX8f6oMLRyv4dLH+TGY=", "comment": "v1.1.0", "path": "github.com/davecgh/go-spew/spew", "revision": "346938d642f2ec3594ed81d874461961cd0faa76", "revisionTime": "2016-10-29T20:57:26Z" }, { "checksumSHA1": "7c3FuEadBInl/4ExSrB7iJMXpe4=", "path": "github.com/dustin/go-broadcast", "revision": "3bdf6d4a7164a50bc19d5f230e2981d87d2584f1", "revisionTime": "2014-06-27T04:00:55Z" }, { "checksumSHA1": "QeKwBtN2df+j+4stw3bQJ6yO4EY=", "path": "github.com/gin-contrib/sse", "revision": "22d885f9ecc78bf4ee5d72b937e4bbcdc58e8cae", "revisionTime": "2017-01-09T09:34:21Z" }, { "checksumSHA1": "FJKrZuFmeLJp8HDeJc6UkIDBPUw=", "path": "github.com/gin-gonic/autotls", "revision": "5b3297bdcee778ff3bbdc99ab7c41e1c2677d22d", "revisionTime": "2017-04-16T09:39:34Z" }, { "checksumSHA1": "qlPUeFabwF4RKAOF1H+yBFU1Veg=", "path": "github.com/golang/protobuf/proto", "revision": "5a0f697c9ed9d68fef0116532c6e05cfeae00e55", "revisionTime": "2017-06-01T23:02:30Z" }, { "checksumSHA1": "9if9IBLsxkarJ804NPWAzgskIAk=", "path": "github.com/manucorporat/stats", "revision": "8f2d6ace262eba462e9beb552382c98be51d807b", "revisionTime": "2015-05-31T20:46:25Z" }, { "checksumSHA1": "U6lX43KDDlNOn+Z0Yyww+ZzHfFo=", "path": "github.com/mattn/go-isatty", "revision": "57fdcb988a5c543893cc61bce354a6e24ab70022", "revisionTime": "2017-03-07T16:30:44Z" }, { "checksumSHA1": "LuFv4/jlrmFNnDb/5SCSEPAM9vU=", "comment": "v1.0.0", "path": "github.com/pmezard/go-difflib/difflib", "revision": "792786c7400a136282c1664665ae0a8db921c6c2", "revisionTime": "2016-01-10T10:55:54Z" }, { "checksumSHA1": "Q2V7Zs3diLmLfmfbiuLpSxETSuY=", "comment": "v1.1.4", "path": "github.com/stretchr/testify/assert", "revision": "976c720a22c8eb4eb6a0b4348ad85ad12491a506", "revisionTime": "2016-09-25T22:06:09Z" }, { "checksumSHA1": "CoxdaTYdPZNJXr8mJfLxye428N0=", "path": "github.com/ugorji/go/codec", "revision": "c88ee250d0221a57af388746f5cf03768c21d6e2", "revisionTime": "2017-02-15T20:11:44Z" }, { "checksumSHA1": "W0j4I7QpxXlChjyhAojZmFjU6Bg=", "path": "golang.org/x/crypto/acme", "revision": "adbae1b6b6fb4b02448a0fc0dbbc9ba2b95b294d", "revisionTime": "2017-06-19T06:03:41Z" }, { "checksumSHA1": "TrKJW+flz7JulXU3sqnBJjGzgQc=", "path": "golang.org/x/crypto/acme/autocert", "revision": "adbae1b6b6fb4b02448a0fc0dbbc9ba2b95b294d", "revisionTime": "2017-06-19T06:03:41Z" }, { "checksumSHA1": "9jjO5GjLa0XF/nfWihF02RoH4qc=", "comment": "release-branch.go1.7", "path": "golang.org/x/net/context", "revision": "d4c55e66d8c3a2f3382d264b08e3e3454a66355a", "revisionTime": "2016-10-18T08:54:36Z" }, { "checksumSHA1": "TVEkpH3gq84iQ39I4R+mlDwjuVI=", "path": "golang.org/x/sys/unix", "revision": "99f16d856c9836c42d24e7ab64ea72916925fa97", "revisionTime": "2017-03-08T15:04:45Z" }, { "checksumSHA1": "39V1idWER42Lmcmg2Uy40wMzOlo=", "comment": "v8.18.1", "path": "gopkg.in/go-playground/validator.v8", "revision": "5f57d2222ad794d0dffb07e664ea05e2ee07d60c", "revisionTime": "2016-07-18T13:41:25Z" }, { "checksumSHA1": "12GqsW8PiRPnezDDy0v4brZrndM=", "comment": "v2", "path": "gopkg.in/yaml.v2", "revision": "a5b47d31c556af34a302ce5d659e6fea44d90de0", "revisionTime": "2016-09-28T15:37:09Z" } ], "rootPath": "github.com/gin-gonic/gin" } gin-1.2/wercker.yml000066400000000000000000000000241312613627200143150ustar00rootroot00000000000000box: wercker/default