diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index f287c265..0ede2a05 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -33,7 +33,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@v7 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/gin.yml b/.github/workflows/gin.yml index 8ece7f1d..d0f42d09 100644 --- a/.github/workflows/gin.yml +++ b/.github/workflows/gin.yml @@ -16,24 +16,27 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v6 + uses: actions/setup-go@v7 with: go-version: "^1" - name: Setup golangci-lint uses: golangci/golangci-lint-action@v9 with: - version: v2.6 + version: v2.11 args: --verbose test: needs: lint + permissions: + contents: read + id-token: write strategy: matrix: os: [ubuntu-latest, macos-latest] - go: ["1.24", "1.25"] + go: ["1.26", "1.27"] test-tags: [ "", @@ -55,17 +58,17 @@ jobs: GOPROXY: https://proxy.golang.org steps: - name: Set up Go ${{ matrix.go }} - uses: actions/setup-go@v6 + uses: actions/setup-go@v7 with: go-version: ${{ matrix.go }} cache: false - name: Checkout Code - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: ref: ${{ github.ref }} - - uses: actions/cache@v5 + - uses: actions/cache@v6 with: path: | ${{ matrix.go-build }} @@ -78,6 +81,7 @@ jobs: run: make test - name: Upload coverage to Codecov - uses: codecov/codecov-action@v5 + uses: codecov/codecov-action@v7 with: + use_oidc: true flags: ${{ matrix.os }},go-${{ matrix.go }},${{ matrix.test-tags }} diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 0098b952..6dd36ff1 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -13,15 +13,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v6 + uses: actions/setup-go@v7 with: go-version: "^1" - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v6 + uses: goreleaser/goreleaser-action@v7 with: # either 'goreleaser' (default) or 'goreleaser-pro' distribution: goreleaser diff --git a/.github/workflows/trivy-scan.yml b/.github/workflows/trivy-scan.yml index b86aed7f..751d0106 100644 --- a/.github/workflows/trivy-scan.yml +++ b/.github/workflows/trivy-scan.yml @@ -9,7 +9,7 @@ on: - master schedule: # Run daily at 00:00 UTC - - cron: '0 0 * * *' + - cron: "0 0 * * *" workflow_dispatch: # Allow manual trigger permissions: @@ -22,35 +22,35 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Run Trivy vulnerability scanner (source code) - uses: aquasecurity/trivy-action@0.33.1 + uses: aquasecurity/trivy-action@v0.36.0 with: - scan-type: 'fs' - scan-ref: '.' - scanners: 'vuln,secret,misconfig' - format: 'sarif' - output: 'trivy-results.sarif' - severity: 'CRITICAL,HIGH,MEDIUM' + scan-type: "fs" + scan-ref: "." + scanners: "vuln,secret,misconfig" + format: "sarif" + output: "trivy-results.sarif" + severity: "CRITICAL,HIGH,MEDIUM" ignore-unfixed: true - name: Upload Trivy results to GitHub Security tab uses: github/codeql-action/upload-sarif@v4 if: always() with: - sarif_file: 'trivy-results.sarif' + sarif_file: "trivy-results.sarif" - name: Run Trivy scanner (table output for logs) - uses: aquasecurity/trivy-action@0.33.1 + uses: aquasecurity/trivy-action@v0.36.0 if: always() with: - scan-type: 'fs' - scan-ref: '.' - scanners: 'vuln,secret,misconfig' - format: 'table' - severity: 'CRITICAL,HIGH,MEDIUM' + scan-type: "fs" + scan-ref: "." + scanners: "vuln,secret,misconfig" + format: "table" + severity: "CRITICAL,HIGH,MEDIUM" ignore-unfixed: true - exit-code: '1' + exit-code: "1" diff --git a/AUTHORS.md b/AUTHORS.md deleted file mode 100644 index b4773ef3..00000000 --- a/AUTHORS.md +++ /dev/null @@ -1,406 +0,0 @@ -List of all the awesome people working to make Gin the best Web Framework in Go. - -## gin 1.x series authors - -**Gin Core Team:** Bo-Yi Wu (@appleboy), thinkerou (@thinkerou), Javier Provecho (@javierprovecho) - -## gin 0.x series authors - -**Maintainers:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) - ------- - -People and companies, who have contributed, in alphabetical order. - -- 178inaba <178inaba@users.noreply.github.com> -- A. F -- ABHISHEK SONI -- Abhishek Chanda -- Abner Chen -- AcoNCodes -- Adam Dratwinski -- Adam Mckaig -- Adam Zielinski -- Adonis -- Alan Wang -- Albin Gilles -- Aleksandr Didenko -- Alessandro (Ale) Segala <43508+ItalyPaleAle@users.noreply.github.com> -- Alex -- Alexander -- Alexander Lokhman -- Alexander Melentyev <55826637+alexander-melentyev@users.noreply.github.com> -- Alexander Nyquist -- Allen Ren -- AllinGo -- Ammar Bandukwala -- An Xiao (Luffy) -- Andre Dublin <81dublin@gmail.com> -- Andrew Szeto -- Andrey Abramov -- Andrey Nering -- Andrey Smirnov -- Andrii Bubis -- André Bazaglia -- Andy Pan -- Antoine GIRARD -- Anup Kumar Panwar <1anuppanwar@gmail.com> -- Aravinth Sundaram -- Artem -- Ashwani -- Aurelien Regat-Barrel -- Austin Heap -- Barnabus -- Bo-Yi Wu -- Boris Borshevsky -- Boyi Wu -- BradyBromley <51128276+BradyBromley@users.noreply.github.com> -- Brendan Fosberry -- Brian Wigginton -- Carlos Eduardo -- Chad Russell -- Charles -- Christian Muehlhaeuser -- Christian Persson -- Christopher Harrington -- Damon Zhao -- Dan Markham -- Dang Nguyen -- Daniel Krom -- Daniel M. Lambea -- Danieliu -- David Irvine -- David Zhang -- Davor Kapsa -- DeathKing -- Dennis Cho <47404603+forest747@users.noreply.github.com> -- Dmitry Dorogin -- Dmitry Kutakov -- Dmitry Sedykh -- Don2Quixote <35610661+Don2Quixote@users.noreply.github.com> -- Donn Pebe -- Dustin Decker -- Eason Lin -- Edward Betts -- Egor Seredin <4819888+agmt@users.noreply.github.com> -- Emmanuel Goh -- Equim -- Eren A. Akyol -- Eric_Lee -- Erik Bender -- Ethan Kan -- Evgeny Persienko -- Faisal Alam -- Fareed Dudhia -- Filip Figiel -- Florian Polster -- Frank Bille -- Franz Bettag -- Ganlv -- Gaozhen Ying -- George Gabolaev -- George Kirilenko -- Georges Varouchas -- Gordon Tyler -- Harindu Perera -- Helios <674876158@qq.com> -- Henry Kwan -- Henry Yee -- Himanshu Mishra -- Hiroyuki Tanaka -- Ibraheem Ahmed -- Ignacio Galindo -- Igor H. Vieira -- Ildar1111 <54001462+Ildar1111@users.noreply.github.com> -- Iskander (Alex) Sharipov -- Ismail Gjevori -- Ivan Chen -- JINNOUCHI Yasushi -- James Pettyjohn -- Jamie Stackhouse -- Jason Lee -- Javier Provecho -- Javier Provecho -- Javier Provecho -- Javier Provecho Fernandez -- Javier Provecho Fernandez -- Jean-Christophe Lebreton -- Jeff -- Jeremy Loy -- Jim Filippou -- Jimmy Pettersson -- John Bampton -- Johnny Dallas -- Johnny Dallas -- Jonathan (JC) Chen -- Josep Jesus Bigorra Algaba <42377845+averageflow@users.noreply.github.com> -- Josh Horowitz -- Joshua Loper -- Julien Schmidt -- Jun Kimura -- Justin Beckwith -- Justin Israel -- Justin Mayhew -- Jérôme Laforge -- Kacper Bąk <56700396+53jk1@users.noreply.github.com> -- Kamron Batman -- Kane Rogers -- Kaushik Neelichetty -- Keiji Yoshida -- Kel Cecil -- Kevin Mulvey -- Kevin Zhu -- Kirill Motkov -- Klemen Sever -- Kristoffer A. Iversen -- Krzysztof Szafrański -- Kumar McMillan -- Kyle Mcgill -- Lanco <35420416+lancoLiu@users.noreply.github.com> -- Levi Olson -- Lin Kao-Yuan -- Linus Unnebäck -- Lucas Clemente -- Ludwig Valda Vasquez -- Luis GG -- MW Lim -- Maksimov Sergey -- Manjusaka -- Manu MA -- Manu MA -- Manu Mtz-Almeida -- Manu Mtz.-Almeida -- Manuel Alonso -- Mara Kim -- Mario Kostelac -- Martin Karlsch -- Matt Newberry -- Matt Williams -- Matthieu MOREL -- Max Hilbrunner -- Maxime Soulé -- MetalBreaker -- Michael Puncel -- MichaelDeSteven <51652084+MichaelDeSteven@users.noreply.github.com> -- Mike <38686456+icy4ever@users.noreply.github.com> -- Mike Stipicevic -- Miki Tebeka -- Miles -- Mirza Ceric -- Mykyta Semenistyi -- Naoki Takano -- Ngalim Siregar -- Ni Hao -- Nick Gerakines -- Nikifor Seryakov -- Notealot <714804968@qq.com> -- Olivier Mengué -- Olivier Robardet -- Pablo Moncada -- Pablo Moncada -- Panmax <967168@qq.com> -- Peperoncino <2wua4nlyi@gmail.com> -- Philipp Meinen -- Pierre Massat -- Qt -- Quentin ROYER -- README Bot <35302948+codetriage-readme-bot@users.noreply.github.com> -- Rafal Zajac -- Rahul Datta Roy -- Rajiv Kilaparti -- Raphael Gavache -- Ray Rodriguez -- Regner Blok-Andersen -- Remco -- Rex Lee(李俊) -- Richard Lee -- Riverside -- Robert Wilkinson -- Rogier Lommers -- Rohan Pai -- Romain Beuque -- Roman Belyakovsky -- Roman Zaynetdinov <627197+zaynetro@users.noreply.github.com> -- Roman Zaynetdinov -- Ronald Petty -- Ross Wolf <31489089+rw-access@users.noreply.github.com> -- Roy Lou -- Rubi <14269809+codenoid@users.noreply.github.com> -- Ryan <46182144+ryanker@users.noreply.github.com> -- Ryan J. Yoder -- SRK.Lyu -- Sai -- Samuel Abreu -- Santhosh Kumar -- Sasha Melentyev -- Sasha Myasoedov -- Segev Finer -- Sergey Egorov -- Sergey Fedchenko -- Sergey Gonimar -- Sergey Ponomarev -- Serica <943914044@qq.com> -- Shamus Taylor -- Shilin Wang -- Shuo -- Skuli Oskarsson -- Snawoot -- Sridhar Ratnakumar -- Steeve Chailloux -- Sudhir Mishra -- Suhas Karanth -- TaeJun Park -- Tatsuya Hoshino -- Tevic -- Tevin Jeffrey -- The Gitter Badger -- Thibault Jamet -- Thomas Boerger -- Thomas Schaffer -- Tommy Chu -- Tudor Roman -- Uwe Dauernheim -- Valentine Oragbakosi -- Vas N -- Vasilyuk Vasiliy -- Victor Castell -- Vince Yuan -- Vyacheslav Dubinin -- Waynerv -- Weilin Shi <934587911@qq.com> -- Xudong Cai -- Yasuhiro Matsumoto -- Yehezkiel Syamsuhadi -- Yoshiki Nakagawa -- Yoshiyuki Kinjo -- Yue Yang -- ZYunH -- Zach Newburgh -- Zasda Yusuf Mikail -- ZhangYunHao -- ZhiFeng Hu -- Zhu Xi -- a2tt -- ahuigo <1781999+ahuigo@users.noreply.github.com> -- ali -- aljun -- andrea -- andriikushch -- anoty -- awkj -- axiaoxin <254606826@qq.com> -- bbiao -- bestgopher <84328409@qq.com> -- betahu -- bigwheel -- bn4t <17193640+bn4t@users.noreply.github.com> -- bullgare -- chainhelen -- chenyang929 -- chriswhelix -- collinmsn <4130944@qq.com> -- cssivision -- danielalves -- delphinus -- dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> -- dickeyxxx -- edebernis -- error10 -- esplo -- eudore <30709860+eudore@users.noreply.github.com> -- ffhelicopter <32922889+ffhelicopter@users.noreply.github.com> -- filikos <11477309+filikos@users.noreply.github.com> -- forging2012 -- goqihoo -- grapeVine -- guonaihong -- heige -- heige -- hellojukay -- henrylee2cn -- htobenothing -- iamhesir <78344375+iamhesir@users.noreply.github.com> -- ijaa -- ishanray -- ishanray -- itcloudy <272685110@qq.com> -- jarodsong6 -- jasonrhansen -- jincheng9 -- joeADSP <75027008+joeADSP@users.noreply.github.com> -- junfengye -- kaiiak -- kebo -- keke <19yamashita15@gmail.com> -- kishor kunal raj <68464660+kishorkunal-raj@users.noreply.github.com> -- kyledinh -- lantw44 -- likakuli <1154584512@qq.com> -- linfangrong -- linzi <873804682@qq.com> -- llgoer -- long-road <13412081338@163.com> -- mbesancon -- mehdy -- metal A-wing -- micanzhang -- minarc -- mllu -- mopemoepe -- msoedov -- mstmdev -- novaeye -- olebedev -- phithon -- pjgg -- qm012 <67568757+qm012@users.noreply.github.com> -- raymonder jin -- rns -- root@andrea:~# -- sekky0905 <20237968+sekky0905@users.noreply.github.com> -- senhtry -- shadrus -- silasb -- solos -- songjiayang -- sope -- srt180 <30768686+srt180@users.noreply.github.com> -- stackerzzq -- sunshineplan -- syssam -- techjanitor -- techjanitor -- thinkerou -- thinkgo <49174849+thinkgos@users.noreply.github.com> -- tsirolnik -- tyltr <31768692+tylitianrui@users.noreply.github.com> -- vinhha96 -- voidman -- vz -- wei -- weibaohui -- whirosan -- willnewrelic -- wssccc -- wuhuizuo -- xyb -- y-yagi -- yiranzai -- youzeliang -- yugu -- yuyabe -- zebozhuang -- zero11-0203 <93071220+zero11-0203@users.noreply.github.com> -- zesani <7sin@outlook.co.th> -- zhanweidu -- zhing -- ziheng -- zzjin -- 森 優太 <59682979+uta-mori@users.noreply.github.com> -- 杰哥 <858806258@qq.com> -- 涛叔 -- 市民233 -- 尹宝强 -- 梦溪笔谈 -- 飞雪无情 -- 寻寻觅觅的Gopher diff --git a/BENCHMARKS.md b/BENCHMARKS.md index c11ee99a..111e04ad 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -1,666 +1,291 @@ +# Gin Benchmark Report -# Benchmark System - -**VM HOST:** Travis -**Machine:** Ubuntu 16.04.6 LTS x64 -**Date:** May 04th, 2020 -**Version:** Gin v1.6.3 -**Go Version:** 1.14.2 linux/amd64 +**Machine:** Apple M4 Pro +**OS:** macOS (Darwin 25.3.0), arm64 +**Date:** March 15th, 2026 +**Gin Version:** v1.12.0 +**Go Version:** 1.25.8 darwin/arm64 **Source:** [Go HTTP Router Benchmark](https://github.com/gin-gonic/go-http-routing-benchmark) -**Result:** [See the gist](https://gist.github.com/appleboy/b5f2ecfaf50824ae9c64dcfb9165ae5e) or [Travis result](https://travis-ci.org/github/gin-gonic/go-http-routing-benchmark/jobs/682947061) -## Static Routes: 157 +--- -```sh -Gin: 34936 Bytes +## Table of Contents -HttpServeMux: 14512 Bytes -Ace: 30680 Bytes -Aero: 34536 Bytes -Bear: 30456 Bytes -Beego: 98456 Bytes -Bone: 40224 Bytes -Chi: 83608 Bytes -Denco: 10216 Bytes -Echo: 80328 Bytes -GocraftWeb: 55288 Bytes -Goji: 29744 Bytes -Gojiv2: 105840 Bytes -GoJsonRest: 137496 Bytes -GoRestful: 816936 Bytes -GorillaMux: 585632 Bytes -GowwwRouter: 24968 Bytes -HttpRouter: 21712 Bytes -HttpTreeMux: 73448 Bytes -Kocha: 115472 Bytes -LARS: 30640 Bytes -Macaron: 38592 Bytes -Martini: 310864 Bytes -Pat: 19696 Bytes -Possum: 89920 Bytes -R2router: 23712 Bytes -Rivet: 24608 Bytes -Tango: 28264 Bytes -TigerTonic: 78768 Bytes -Traffic: 538976 Bytes -Vulcan: 369960 Bytes -``` +- [Summary](#summary) +- [Memory Consumption](#memory-consumption) +- [Benchmark Results](#benchmark-results) + - [GitHub API (203 routes)](#github-api-203-routes) + - [Google+ API (13 routes)](#google-api-13-routes) + - [Parse API (26 routes)](#parse-api-26-routes) + - [Static Routes (157 routes)](#static-routes-157-routes) +- [Micro Benchmarks](#micro-benchmarks) + - [Single Param](#single-param) + - [5 Params](#5-params) + - [20 Params](#20-params) + - [Param Write](#param-write) -## GithubAPI Routes: 203 +--- -```sh -Gin: 58512 Bytes +## Summary -Ace: 48688 Bytes -Aero: 318568 Bytes -Bear: 84248 Bytes -Beego: 150936 Bytes -Bone: 100976 Bytes -Chi: 95112 Bytes -Denco: 36736 Bytes -Echo: 100296 Bytes -GocraftWeb: 95432 Bytes -Goji: 49680 Bytes -Gojiv2: 104704 Bytes -GoJsonRest: 141976 Bytes -GoRestful: 1241656 Bytes -GorillaMux: 1322784 Bytes -GowwwRouter: 80008 Bytes -HttpRouter: 37144 Bytes -HttpTreeMux: 78800 Bytes -Kocha: 785120 Bytes -LARS: 48600 Bytes -Macaron: 92784 Bytes -Martini: 485264 Bytes -Pat: 21200 Bytes -Possum: 85312 Bytes -R2router: 47104 Bytes -Rivet: 42840 Bytes -Tango: 54840 Bytes -TigerTonic: 95264 Bytes -Traffic: 921744 Bytes -Vulcan: 425992 Bytes -``` +The table below ranks all routers by **GitHub API throughput** (203 routes, all methods), which best represents real-world routing workloads. _Lower ns/op is better._ -## GPlusAPI Routes: 13 +| Rank | Router | ns/op | B/op | allocs/op | Zero-alloc | +| :--: | :------------ | --------: | --------: | --------: | :----------------: | +| 1 | **Gin** | 9,944 | 0 | 0 | :white_check_mark: | +| 2 | **BunRouter** | 10,281 | 0 | 0 | :white_check_mark: | +| 3 | **Echo** | 11,072 | 0 | 0 | :white_check_mark: | +| 4 | HttpRouter | 15,059 | 13,792 | 167 | | +| 5 | HttpTreeMux | 49,302 | 65,856 | 671 | | +| 6 | Chi | 94,376 | 130,817 | 740 | | +| 7 | Beego | 101,941 | 71,456 | 609 | | +| 8 | Fiber | 109,148 | 0 | 0 | :white_check_mark: | +| 9 | Macaron | 121,785 | 147,784 | 1,624 | | +| 10 | Goji v2 | 242,849 | 313,744 | 3,712 | | +| 11 | GoRestful | 885,678 | 1,006,744 | 3,009 | | +| 12 | GorillaMux | 1,316,844 | 225,667 | 1,588 | | -```sh -Gin: 4384 Bytes +**Key takeaways:** -Ace: 3712 Bytes -Aero: 26056 Bytes -Bear: 7112 Bytes -Beego: 10272 Bytes -Bone: 6688 Bytes -Chi: 8024 Bytes -Denco: 3264 Bytes -Echo: 9688 Bytes -GocraftWeb: 7496 Bytes -Goji: 3152 Bytes -Gojiv2: 7376 Bytes -GoJsonRest: 11400 Bytes -GoRestful: 74328 Bytes -GorillaMux: 66208 Bytes -GowwwRouter: 5744 Bytes -HttpRouter: 2808 Bytes -HttpTreeMux: 7440 Bytes -Kocha: 128880 Bytes -LARS: 3656 Bytes -Macaron: 8656 Bytes -Martini: 23920 Bytes -Pat: 1856 Bytes -Possum: 7248 Bytes -R2router: 3928 Bytes -Rivet: 3064 Bytes -Tango: 5168 Bytes -TigerTonic: 9408 Bytes -Traffic: 46400 Bytes -Vulcan: 25544 Bytes -``` +- **Gin**, **BunRouter**, and **Echo** form the top tier — all achieve zero heap allocations and route the full GitHub API in ~10 us. +- **HttpRouter** remains extremely fast but incurs 1 alloc per parameterized route (167 allocs for 203 routes). +- **Fiber** also achieves zero allocations, but its fasthttp-based benchmark infrastructure adds per-iteration reset overhead — do not compare its absolute ns/op directly with net/http routers. +- **GorillaMux** and **GoRestful** are feature-rich but orders of magnitude slower, making them less suitable for latency-sensitive applications. -## ParseAPI Routes: 26 +> **Fiber caveat:** Fiber benchmarks use `fasthttp.RequestCtx` with per-iteration Reset, which adds constant overhead not present in net/http benchmarks. Fiber-vs-Fiber comparisons are valid; cross-framework comparisons should be interpreted with care. -```sh -Gin: 7776 Bytes +--- -Ace: 6704 Bytes -Aero: 28488 Bytes -Bear: 12320 Bytes -Beego: 19280 Bytes -Bone: 11440 Bytes -Chi: 9744 Bytes -Denco: 4192 Bytes -Echo: 11664 Bytes -GocraftWeb: 12800 Bytes -Goji: 5680 Bytes -Gojiv2: 14464 Bytes -GoJsonRest: 14072 Bytes -GoRestful: 116264 Bytes -GorillaMux: 105880 Bytes -GowwwRouter: 9344 Bytes -HttpRouter: 5072 Bytes -HttpTreeMux: 7848 Bytes -Kocha: 181712 Bytes -LARS: 6632 Bytes -Macaron: 13648 Bytes -Martini: 45888 Bytes -Pat: 2560 Bytes -Possum: 9200 Bytes -R2router: 7056 Bytes -Rivet: 5680 Bytes -Tango: 8920 Bytes -TigerTonic: 9840 Bytes -Traffic: 79096 Bytes -Vulcan: 44504 Bytes -``` +## Memory Consumption -## Static Routes +Memory required for loading the routing structure (lower is better). Sorted by bytes ascending. -```sh -BenchmarkGin_StaticAll 62169 19319 ns/op 0 B/op 0 allocs/op +### Static Routes: 157 -BenchmarkAce_StaticAll 65428 18313 ns/op 0 B/op 0 allocs/op -BenchmarkAero_StaticAll 121132 9632 ns/op 0 B/op 0 allocs/op -BenchmarkHttpServeMux_StaticAll 52626 22758 ns/op 0 B/op 0 allocs/op -BenchmarkBeego_StaticAll 9962 179058 ns/op 55264 B/op 471 allocs/op -BenchmarkBear_StaticAll 14894 80966 ns/op 20272 B/op 469 allocs/op -BenchmarkBone_StaticAll 18718 64065 ns/op 0 B/op 0 allocs/op -BenchmarkChi_StaticAll 10000 149827 ns/op 67824 B/op 471 allocs/op -BenchmarkDenco_StaticAll 211393 5680 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_StaticAll 49341 24343 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_StaticAll 10000 126209 ns/op 46312 B/op 785 allocs/op -BenchmarkGoji_StaticAll 27956 43174 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_StaticAll 3430 370718 ns/op 205984 B/op 1570 allocs/op -BenchmarkGoJsonRest_StaticAll 9134 188888 ns/op 51653 B/op 1727 allocs/op -BenchmarkGoRestful_StaticAll 706 1703330 ns/op 613280 B/op 2053 allocs/op -BenchmarkGorillaMux_StaticAll 1268 924083 ns/op 153233 B/op 1413 allocs/op -BenchmarkGowwwRouter_StaticAll 63374 18935 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_StaticAll 109938 10902 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_StaticAll 109166 10861 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_StaticAll 92258 12992 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_StaticAll 65200 18387 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_StaticAll 5671 291501 ns/op 115553 B/op 1256 allocs/op -BenchmarkMartini_StaticAll 807 1460498 ns/op 125444 B/op 1717 allocs/op -BenchmarkPat_StaticAll 513 2342396 ns/op 602832 B/op 12559 allocs/op -BenchmarkPossum_StaticAll 10000 128270 ns/op 65312 B/op 471 allocs/op -BenchmarkR2router_StaticAll 16726 71760 ns/op 22608 B/op 628 allocs/op -BenchmarkRivet_StaticAll 41722 28723 ns/op 0 B/op 0 allocs/op -BenchmarkTango_StaticAll 7606 205082 ns/op 39209 B/op 1256 allocs/op -BenchmarkTigerTonic_StaticAll 26247 45806 ns/op 7376 B/op 157 allocs/op -BenchmarkTraffic_StaticAll 550 2284518 ns/op 754864 B/op 14601 allocs/op -BenchmarkVulcan_StaticAll 10000 131343 ns/op 15386 B/op 471 allocs/op -``` +| Router | Bytes | +| :------------- | ---------: | +| **HttpRouter** | **21,680** | +| **Gin** | **34,408** | +| **Macaron** | **36,976** | +| BunRouter | 51,232 | +| Fiber | 59,248 | +| HttpServeMux | 71,728 | +| HttpTreeMux | 73,448 | +| Chi | 83,160 | +| Echo | 91,976 | +| Beego | 98,824 | +| Goji v2 | 117,952 | +| GorillaMux | 599,496 | +| GoRestful | 819,704 | + +### GitHub API Routes: 203 + +| Router | Bytes | +| :-------------- | ---------: | +| **HttpRouter** | **37,072** | +| **Gin** | **58,840** | +| **HttpTreeMux** | **78,800** | +| Macaron | 90,632 | +| BunRouter | 93,776 | +| Chi | 94,888 | +| Echo | 117,784 | +| Goji v2 | 118,640 | +| Beego | 150,840 | +| Fiber | 163,832 | +| GoRestful | 1,270,848 | +| GorillaMux | 1,319,696 | + +### Google+ API Routes: 13 + +| Router | Bytes | +| :------------- | --------: | +| **HttpRouter** | **2,776** | +| **Gin** | **4,576** | +| **BunRouter** | **7,360** | +| HttpTreeMux | 7,440 | +| Chi | 8,008 | +| Goji v2 | 8,096 | +| Macaron | 8,672 | +| Beego | 10,256 | +| Fiber | 10,840 | +| Echo | 10,968 | +| GorillaMux | 68,000 | +| GoRestful | 72,536 | + +### Parse API Routes: 26 + +| Router | Bytes | +| :-------------- | --------: | +| **HttpRouter** | **5,024** | +| **Gin** | **7,896** | +| **HttpTreeMux** | **7,848** | +| BunRouter | 9,336 | +| Chi | 9,656 | +| Echo | 13,816 | +| Macaron | 13,704 | +| Fiber | 15,352 | +| Goji v2 | 16,064 | +| Beego | 19,256 | +| GorillaMux | 105,384 | +| GoRestful | 121,200 | + +--- + +## Benchmark Results + +### GitHub API (203 routes) + +Routing all 203 GitHub API endpoints per operation. + +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :------------ | --------: | --------: | --------: | +| 1 | **Gin** | 9,944 | 0 | 0 | +| 2 | **BunRouter** | 10,281 | 0 | 0 | +| 3 | **Echo** | 11,072 | 0 | 0 | +| 4 | HttpRouter | 15,059 | 13,792 | 167 | +| 5 | HttpTreeMux | 49,302 | 65,856 | 671 | +| 6 | Chi | 94,376 | 130,817 | 740 | +| 7 | Beego | 101,941 | 71,456 | 609 | +| 8 | Fiber | 109,148 | 0 | 0 | +| 9 | Macaron | 121,785 | 147,784 | 1,624 | +| 10 | Goji v2 | 242,849 | 313,744 | 3,712 | +| 11 | GoRestful | 885,678 | 1,006,744 | 3,009 | +| 12 | GorillaMux | 1,316,844 | 225,667 | 1,588 | + +### Google+ API (13 routes) + +Routing all 13 Google+ API endpoints per operation. + +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :------------ | -----: | -----: | --------: | +| 1 | **BunRouter** | 348.5 | 0 | 0 | +| 2 | **Gin** | 429.7 | 0 | 0 | +| 3 | **Echo** | 451.1 | 0 | 0 | +| 4 | HttpRouter | 668.6 | 640 | 11 | +| 5 | HttpTreeMux | 2,428 | 4,032 | 38 | +| 6 | Fiber | 2,506 | 0 | 0 | +| 7 | Chi | 5,333 | 8,480 | 48 | +| 8 | Beego | 5,927 | 4,576 | 39 | +| 9 | Macaron | 7,294 | 9,464 | 104 | +| 10 | Goji v2 | 8,000 | 15,120 | 115 | +| 11 | GorillaMux | 14,707 | 14,448 | 102 | +| 12 | GoRestful | 24,189 | 60,720 | 193 | + +### Parse API (26 routes) + +Routing all 26 Parse API endpoints per operation. + +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :------------ | -----: | ------: | --------: | +| 1 | **BunRouter** | 588.2 | 0 | 0 | +| 2 | **Gin** | 712.1 | 0 | 0 | +| 3 | **Echo** | 742.1 | 0 | 0 | +| 4 | HttpRouter | 948.5 | 640 | 16 | +| 5 | HttpTreeMux | 3,372 | 5,728 | 51 | +| 6 | Fiber | 4,250 | 0 | 0 | +| 7 | Chi | 8,863 | 14,944 | 84 | +| 8 | Beego | 10,541 | 9,152 | 78 | +| 9 | Macaron | 13,635 | 18,928 | 208 | +| 10 | Goji v2 | 13,264 | 29,456 | 199 | +| 11 | GorillaMux | 25,886 | 26,960 | 198 | +| 12 | GoRestful | 54,780 | 131,728 | 380 | + +### Static Routes (157 routes) + +Routing all 157 static routes per operation. Includes http.ServeMux as baseline. + +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :-------------- | ------: | ------: | --------: | +| 1 | **HttpRouter** | 4,177 | 0 | 0 | +| 2 | **HttpTreeMux** | 5,363 | 0 | 0 | +| 3 | **Gin** | 5,528 | 0 | 0 | +| 4 | BunRouter | 5,997 | 0 | 0 | +| 5 | Echo | 6,897 | 0 | 0 | +| — | HttpServeMux | 18,172 | 0 | 0 | +| 6 | Fiber | 29,310 | 0 | 0 | +| 7 | Chi | 41,317 | 57,776 | 314 | +| 8 | Beego | 68,255 | 55,264 | 471 | +| 9 | Macaron | 81,824 | 114,296 | 1,256 | +| 10 | Goji v2 | 84,459 | 175,840 | 1,099 | +| 11 | GorillaMux | 302,825 | 133,137 | 1,099 | +| 12 | GoRestful | 436,510 | 677,824 | 2,193 | + +--- ## Micro Benchmarks -```sh -BenchmarkGin_Param 18785022 63.9 ns/op 0 B/op 0 allocs/op +### Single Param -BenchmarkAce_Param 14689765 81.5 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Param 23094770 51.2 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Param 1417045 845 ns/op 456 B/op 5 allocs/op -BenchmarkBeego_Param 1000000 1080 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Param 1000000 1463 ns/op 816 B/op 6 allocs/op -BenchmarkChi_Param 1378756 885 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Param 8557899 143 ns/op 32 B/op 1 allocs/op -BenchmarkEcho_Param 16433347 75.5 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Param 1000000 1218 ns/op 648 B/op 8 allocs/op -BenchmarkGoji_Param 1921248 617 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_Param 561848 2156 ns/op 1328 B/op 11 allocs/op -BenchmarkGoJsonRest_Param 1000000 1358 ns/op 649 B/op 13 allocs/op -BenchmarkGoRestful_Param 224857 5307 ns/op 4192 B/op 14 allocs/op -BenchmarkGorillaMux_Param 498313 2459 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_Param 1864354 654 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Param 26269074 47.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Param 2109829 557 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_Param 5050216 243 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_Param 19811712 59.9 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Param 662746 2329 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_Param 279902 4260 ns/op 1072 B/op 10 allocs/op -BenchmarkPat_Param 1000000 1382 ns/op 536 B/op 11 allocs/op -BenchmarkPossum_Param 1000000 1014 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Param 1712559 707 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_Param 6648086 182 ns/op 48 B/op 1 allocs/op -BenchmarkTango_Param 1221504 994 ns/op 248 B/op 8 allocs/op -BenchmarkTigerTonic_Param 891661 2261 ns/op 776 B/op 16 allocs/op -BenchmarkTraffic_Param 350059 3598 ns/op 1856 B/op 21 allocs/op -BenchmarkVulcan_Param 2517823 472 ns/op 98 B/op 3 allocs/op -BenchmarkAce_Param5 9214365 130 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Param5 15369013 77.9 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Param5 1000000 1113 ns/op 501 B/op 5 allocs/op -BenchmarkBeego_Param5 1000000 1269 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Param5 986820 1873 ns/op 864 B/op 6 allocs/op -BenchmarkChi_Param5 1000000 1156 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Param5 3036331 400 ns/op 160 B/op 1 allocs/op -BenchmarkEcho_Param5 6447133 186 ns/op 0 B/op 0 allocs/op -BenchmarkGin_Param5 10786068 110 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Param5 844820 1944 ns/op 920 B/op 11 allocs/op -BenchmarkGoji_Param5 1474965 827 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_Param5 442820 2516 ns/op 1392 B/op 11 allocs/op -BenchmarkGoJsonRest_Param5 507555 2711 ns/op 1097 B/op 16 allocs/op -BenchmarkGoRestful_Param5 216481 6093 ns/op 4288 B/op 14 allocs/op -BenchmarkGorillaMux_Param5 314402 3628 ns/op 1344 B/op 10 allocs/op -BenchmarkGowwwRouter_Param5 1624660 733 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Param5 13167324 92.0 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Param5 1000000 1295 ns/op 576 B/op 6 allocs/op -BenchmarkKocha_Param5 1000000 1138 ns/op 440 B/op 10 allocs/op -BenchmarkLARS_Param5 11580613 105 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Param5 473596 2755 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_Param5 230756 5111 ns/op 1232 B/op 11 allocs/op -BenchmarkPat_Param5 469190 3370 ns/op 888 B/op 29 allocs/op -BenchmarkPossum_Param5 1000000 1002 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Param5 1422129 844 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_Param5 2263789 539 ns/op 240 B/op 1 allocs/op -BenchmarkTango_Param5 1000000 1256 ns/op 360 B/op 8 allocs/op -BenchmarkTigerTonic_Param5 175500 7492 ns/op 2279 B/op 39 allocs/op -BenchmarkTraffic_Param5 233631 5816 ns/op 2208 B/op 27 allocs/op -BenchmarkVulcan_Param5 1923416 629 ns/op 98 B/op 3 allocs/op -BenchmarkAce_Param20 4321266 281 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Param20 31501641 35.2 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Param20 335204 3489 ns/op 1665 B/op 5 allocs/op -BenchmarkBeego_Param20 503674 2860 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Param20 298922 4741 ns/op 2031 B/op 6 allocs/op -BenchmarkChi_Param20 878181 1957 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Param20 1000000 1360 ns/op 640 B/op 1 allocs/op -BenchmarkEcho_Param20 2104946 580 ns/op 0 B/op 0 allocs/op -BenchmarkGin_Param20 4167204 290 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Param20 173064 7514 ns/op 3796 B/op 15 allocs/op -BenchmarkGoji_Param20 458778 2651 ns/op 1247 B/op 2 allocs/op -BenchmarkGojiv2_Param20 364862 3178 ns/op 1632 B/op 11 allocs/op -BenchmarkGoJsonRest_Param20 125514 9760 ns/op 4485 B/op 20 allocs/op -BenchmarkGoRestful_Param20 101217 11964 ns/op 6715 B/op 18 allocs/op -BenchmarkGorillaMux_Param20 147654 8132 ns/op 3452 B/op 12 allocs/op -BenchmarkGowwwRouter_Param20 1000000 1225 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Param20 4920895 247 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Param20 173202 6605 ns/op 3196 B/op 10 allocs/op -BenchmarkKocha_Param20 345988 3620 ns/op 1808 B/op 27 allocs/op -BenchmarkLARS_Param20 4592326 262 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Param20 166492 7286 ns/op 2924 B/op 12 allocs/op -BenchmarkMartini_Param20 122162 10653 ns/op 3595 B/op 13 allocs/op -BenchmarkPat_Param20 78630 15239 ns/op 4424 B/op 93 allocs/op -BenchmarkPossum_Param20 1000000 1008 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Param20 294981 4587 ns/op 2284 B/op 7 allocs/op -BenchmarkRivet_Param20 691798 2090 ns/op 1024 B/op 1 allocs/op -BenchmarkTango_Param20 842440 2505 ns/op 856 B/op 8 allocs/op -BenchmarkTigerTonic_Param20 38614 31509 ns/op 9870 B/op 119 allocs/op -BenchmarkTraffic_Param20 57633 21107 ns/op 7853 B/op 47 allocs/op -BenchmarkVulcan_Param20 1000000 1178 ns/op 98 B/op 3 allocs/op -BenchmarkAce_ParamWrite 7330743 180 ns/op 8 B/op 1 allocs/op -BenchmarkAero_ParamWrite 13833598 86.7 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParamWrite 1363321 867 ns/op 456 B/op 5 allocs/op -BenchmarkBeego_ParamWrite 1000000 1104 ns/op 360 B/op 4 allocs/op -BenchmarkBone_ParamWrite 1000000 1475 ns/op 816 B/op 6 allocs/op -BenchmarkChi_ParamWrite 1320590 892 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_ParamWrite 7093605 172 ns/op 32 B/op 1 allocs/op -BenchmarkEcho_ParamWrite 8434424 161 ns/op 8 B/op 1 allocs/op -BenchmarkGin_ParamWrite 10377034 118 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParamWrite 1000000 1266 ns/op 656 B/op 9 allocs/op -BenchmarkGoji_ParamWrite 1874168 654 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_ParamWrite 459032 2352 ns/op 1360 B/op 13 allocs/op -BenchmarkGoJsonRest_ParamWrite 499434 2145 ns/op 1128 B/op 18 allocs/op -BenchmarkGoRestful_ParamWrite 241087 5470 ns/op 4200 B/op 15 allocs/op -BenchmarkGorillaMux_ParamWrite 425686 2522 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_ParamWrite 922172 1778 ns/op 976 B/op 8 allocs/op -BenchmarkHttpRouter_ParamWrite 15392049 77.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParamWrite 1973385 597 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_ParamWrite 4262500 281 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_ParamWrite 10764410 113 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParamWrite 486769 2726 ns/op 1176 B/op 14 allocs/op -BenchmarkMartini_ParamWrite 264804 4842 ns/op 1176 B/op 14 allocs/op -BenchmarkPat_ParamWrite 735116 2047 ns/op 960 B/op 15 allocs/op -BenchmarkPossum_ParamWrite 1000000 1004 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_ParamWrite 1592136 768 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_ParamWrite 3582051 339 ns/op 112 B/op 2 allocs/op -BenchmarkTango_ParamWrite 2237337 534 ns/op 136 B/op 4 allocs/op -BenchmarkTigerTonic_ParamWrite 439608 3136 ns/op 1216 B/op 21 allocs/op -BenchmarkTraffic_ParamWrite 306979 4328 ns/op 2280 B/op 25 allocs/op -BenchmarkVulcan_ParamWrite 2529973 472 ns/op 98 B/op 3 allocs/op -``` +Route: `/user/:name` — Request: `GET /user/gordon` -## GitHub +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :------------ | ----: | ----: | --------: | +| 1 | **BunRouter** | 12.22 | 0 | 0 | +| 2 | **Echo** | 17.75 | 0 | 0 | +| 3 | **Gin** | 23.31 | 0 | 0 | +| 4 | HttpRouter | 31.88 | 32 | 1 | +| 5 | Fiber | 114.4 | 0 | 0 | +| 6 | HttpTreeMux | 165.0 | 352 | 3 | +| 7 | Chi | 332.2 | 704 | 4 | +| 8 | Beego | 348.8 | 352 | 3 | +| 9 | Goji v2 | 494.3 | 1,136 | 8 | +| 10 | GorillaMux | 630.6 | 1,152 | 8 | +| 11 | Macaron | 708.0 | 1,064 | 10 | +| 12 | GoRestful | 1,394 | 4,600 | 15 | -```sh -BenchmarkGin_GithubStatic 15629472 76.7 ns/op 0 B/op 0 allocs/op +### 5 Params -BenchmarkAce_GithubStatic 15542612 75.9 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GithubStatic 24777151 48.5 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GithubStatic 2788894 435 ns/op 120 B/op 3 allocs/op -BenchmarkBeego_GithubStatic 1000000 1064 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GithubStatic 93507 12838 ns/op 2880 B/op 60 allocs/op -BenchmarkChi_GithubStatic 1387743 860 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GithubStatic 39384996 30.4 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_GithubStatic 12076382 99.1 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GithubStatic 1596495 756 ns/op 296 B/op 5 allocs/op -BenchmarkGoji_GithubStatic 6364876 189 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_GithubStatic 550202 2098 ns/op 1312 B/op 10 allocs/op -BenchmarkGoRestful_GithubStatic 102183 12552 ns/op 4256 B/op 13 allocs/op -BenchmarkGoJsonRest_GithubStatic 1000000 1029 ns/op 329 B/op 11 allocs/op -BenchmarkGorillaMux_GithubStatic 255552 5190 ns/op 976 B/op 9 allocs/op -BenchmarkGowwwRouter_GithubStatic 15531916 77.1 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_GithubStatic 27920724 43.1 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GithubStatic 21448953 55.8 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_GithubStatic 21405310 56.0 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_GithubStatic 13625156 89.0 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GithubStatic 1000000 1747 ns/op 736 B/op 8 allocs/op -BenchmarkMartini_GithubStatic 187186 7326 ns/op 768 B/op 9 allocs/op -BenchmarkPat_GithubStatic 109143 11563 ns/op 3648 B/op 76 allocs/op -BenchmarkPossum_GithubStatic 1575898 770 ns/op 416 B/op 3 allocs/op -BenchmarkR2router_GithubStatic 3046231 404 ns/op 144 B/op 4 allocs/op -BenchmarkRivet_GithubStatic 11484826 105 ns/op 0 B/op 0 allocs/op -BenchmarkTango_GithubStatic 1000000 1153 ns/op 248 B/op 8 allocs/op -BenchmarkTigerTonic_GithubStatic 4929780 249 ns/op 48 B/op 1 allocs/op -BenchmarkTraffic_GithubStatic 106351 11819 ns/op 4664 B/op 90 allocs/op -BenchmarkVulcan_GithubStatic 1613271 722 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GithubParam 8386032 143 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GithubParam 11816200 102 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GithubParam 1000000 1012 ns/op 496 B/op 5 allocs/op -BenchmarkBeego_GithubParam 1000000 1157 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GithubParam 184653 6912 ns/op 1888 B/op 19 allocs/op -BenchmarkChi_GithubParam 1000000 1102 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GithubParam 3484798 352 ns/op 128 B/op 1 allocs/op -BenchmarkEcho_GithubParam 6337380 189 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GithubParam 9132032 131 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GithubParam 1000000 1446 ns/op 712 B/op 9 allocs/op -BenchmarkGoji_GithubParam 1248640 977 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_GithubParam 383233 2784 ns/op 1408 B/op 13 allocs/op -BenchmarkGoJsonRest_GithubParam 1000000 1991 ns/op 713 B/op 14 allocs/op -BenchmarkGoRestful_GithubParam 76414 16015 ns/op 4352 B/op 16 allocs/op -BenchmarkGorillaMux_GithubParam 150026 7663 ns/op 1296 B/op 10 allocs/op -BenchmarkGowwwRouter_GithubParam 1592044 751 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_GithubParam 10420628 115 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GithubParam 1403755 835 ns/op 384 B/op 4 allocs/op -BenchmarkKocha_GithubParam 2286170 533 ns/op 128 B/op 5 allocs/op -BenchmarkLARS_GithubParam 9540374 129 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GithubParam 533154 2742 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_GithubParam 119397 9638 ns/op 1152 B/op 11 allocs/op -BenchmarkPat_GithubParam 150675 8858 ns/op 2408 B/op 48 allocs/op -BenchmarkPossum_GithubParam 1000000 1001 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_GithubParam 1602886 761 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_GithubParam 2986579 409 ns/op 96 B/op 1 allocs/op -BenchmarkTango_GithubParam 1000000 1356 ns/op 344 B/op 8 allocs/op -BenchmarkTigerTonic_GithubParam 388899 3429 ns/op 1176 B/op 22 allocs/op -BenchmarkTraffic_GithubParam 123160 9734 ns/op 2816 B/op 40 allocs/op -BenchmarkVulcan_GithubParam 1000000 1138 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GithubAll 40543 29670 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GithubAll 57632 20648 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GithubAll 9234 216179 ns/op 86448 B/op 943 allocs/op -BenchmarkBeego_GithubAll 7407 243496 ns/op 71456 B/op 609 allocs/op -BenchmarkBone_GithubAll 420 2922835 ns/op 720160 B/op 8620 allocs/op -BenchmarkChi_GithubAll 7620 238331 ns/op 87696 B/op 609 allocs/op -BenchmarkDenco_GithubAll 18355 64494 ns/op 20224 B/op 167 allocs/op -BenchmarkEcho_GithubAll 31251 38479 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GithubAll 43550 27364 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GithubAll 4117 300062 ns/op 131656 B/op 1686 allocs/op -BenchmarkGoji_GithubAll 3274 416158 ns/op 56112 B/op 334 allocs/op -BenchmarkGojiv2_GithubAll 1402 870518 ns/op 352720 B/op 4321 allocs/op -BenchmarkGoJsonRest_GithubAll 2976 401507 ns/op 134371 B/op 2737 allocs/op -BenchmarkGoRestful_GithubAll 410 2913158 ns/op 910144 B/op 2938 allocs/op -BenchmarkGorillaMux_GithubAll 346 3384987 ns/op 251650 B/op 1994 allocs/op -BenchmarkGowwwRouter_GithubAll 10000 143025 ns/op 72144 B/op 501 allocs/op -BenchmarkHttpRouter_GithubAll 55938 21360 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GithubAll 10000 153944 ns/op 65856 B/op 671 allocs/op -BenchmarkKocha_GithubAll 10000 106315 ns/op 23304 B/op 843 allocs/op -BenchmarkLARS_GithubAll 47779 25084 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GithubAll 3266 371907 ns/op 149409 B/op 1624 allocs/op -BenchmarkMartini_GithubAll 331 3444706 ns/op 226551 B/op 2325 allocs/op -BenchmarkPat_GithubAll 273 4381818 ns/op 1483152 B/op 26963 allocs/op -BenchmarkPossum_GithubAll 10000 164367 ns/op 84448 B/op 609 allocs/op -BenchmarkR2router_GithubAll 10000 160220 ns/op 77328 B/op 979 allocs/op -BenchmarkRivet_GithubAll 14625 82453 ns/op 16272 B/op 167 allocs/op -BenchmarkTango_GithubAll 6255 279611 ns/op 63826 B/op 1618 allocs/op -BenchmarkTigerTonic_GithubAll 2008 687874 ns/op 193856 B/op 4474 allocs/op -BenchmarkTraffic_GithubAll 355 3478508 ns/op 820744 B/op 14114 allocs/op -BenchmarkVulcan_GithubAll 6885 193333 ns/op 19894 B/op 609 allocs/op -``` +Route: `/:a/:b/:c/:d/:e` — Request: `GET /test/test/test/test/test` -## Google+ +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :------------ | ----: | ----: | --------: | +| 1 | **BunRouter** | 41.86 | 0 | 0 | +| 2 | **Echo** | 43.76 | 0 | 0 | +| 3 | **Gin** | 44.20 | 0 | 0 | +| 4 | HttpRouter | 83.74 | 160 | 1 | +| 5 | Fiber | 271.6 | 0 | 0 | +| 6 | HttpTreeMux | 358.8 | 576 | 6 | +| 7 | Chi | 453.7 | 704 | 4 | +| 8 | Beego | 480.3 | 352 | 3 | +| 9 | Goji v2 | 532.4 | 1,200 | 8 | +| 10 | Macaron | 799.7 | 1,064 | 10 | +| 11 | GorillaMux | 972.6 | 1,216 | 8 | +| 12 | GoRestful | 1,579 | 4,712 | 15 | -```sh -BenchmarkGin_GPlusStatic 19247326 62.2 ns/op 0 B/op 0 allocs/op +### 20 Params -BenchmarkAce_GPlusStatic 20235060 59.2 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlusStatic 31978935 37.6 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlusStatic 3516523 341 ns/op 104 B/op 3 allocs/op -BenchmarkBeego_GPlusStatic 1212036 991 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GPlusStatic 6736242 183 ns/op 32 B/op 1 allocs/op -BenchmarkChi_GPlusStatic 1490640 814 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GPlusStatic 55006856 21.8 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_GPlusStatic 17688258 67.9 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlusStatic 1829181 666 ns/op 280 B/op 5 allocs/op -BenchmarkGoji_GPlusStatic 9147451 130 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_GPlusStatic 594015 2063 ns/op 1312 B/op 10 allocs/op -BenchmarkGoJsonRest_GPlusStatic 1264906 950 ns/op 329 B/op 11 allocs/op -BenchmarkGoRestful_GPlusStatic 231558 5341 ns/op 3872 B/op 13 allocs/op -BenchmarkGorillaMux_GPlusStatic 908418 1809 ns/op 976 B/op 9 allocs/op -BenchmarkGowwwRouter_GPlusStatic 40684604 29.5 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_GPlusStatic 46742804 25.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlusStatic 32567161 36.9 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_GPlusStatic 33800060 35.3 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_GPlusStatic 20431858 60.0 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlusStatic 1000000 1745 ns/op 736 B/op 8 allocs/op -BenchmarkMartini_GPlusStatic 442248 3619 ns/op 768 B/op 9 allocs/op -BenchmarkPat_GPlusStatic 4328004 292 ns/op 96 B/op 2 allocs/op -BenchmarkPossum_GPlusStatic 1570753 763 ns/op 416 B/op 3 allocs/op -BenchmarkR2router_GPlusStatic 3339474 355 ns/op 144 B/op 4 allocs/op -BenchmarkRivet_GPlusStatic 18570961 64.7 ns/op 0 B/op 0 allocs/op -BenchmarkTango_GPlusStatic 1388702 860 ns/op 200 B/op 8 allocs/op -BenchmarkTigerTonic_GPlusStatic 7803543 159 ns/op 32 B/op 1 allocs/op -BenchmarkTraffic_GPlusStatic 878605 2171 ns/op 1112 B/op 16 allocs/op -BenchmarkVulcan_GPlusStatic 2742446 437 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GPlusParam 11626975 105 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlusParam 16914322 71.6 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlusParam 1405173 832 ns/op 480 B/op 5 allocs/op -BenchmarkBeego_GPlusParam 1000000 1075 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GPlusParam 1000000 1557 ns/op 816 B/op 6 allocs/op -BenchmarkChi_GPlusParam 1347926 894 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GPlusParam 5513000 212 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_GPlusParam 11884383 101 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GPlusParam 12898952 93.1 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlusParam 1000000 1194 ns/op 648 B/op 8 allocs/op -BenchmarkGoji_GPlusParam 1857229 645 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_GPlusParam 520939 2322 ns/op 1328 B/op 11 allocs/op -BenchmarkGoJsonRest_GPlusParam 1000000 1536 ns/op 649 B/op 13 allocs/op -BenchmarkGoRestful_GPlusParam 205449 5800 ns/op 4192 B/op 14 allocs/op -BenchmarkGorillaMux_GPlusParam 395310 3188 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_GPlusParam 1851798 667 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_GPlusParam 18420789 65.2 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlusParam 1878463 629 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_GPlusParam 4495610 273 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_GPlusParam 14615976 83.2 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlusParam 584145 2549 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_GPlusParam 250501 4583 ns/op 1072 B/op 10 allocs/op -BenchmarkPat_GPlusParam 1000000 1645 ns/op 576 B/op 11 allocs/op -BenchmarkPossum_GPlusParam 1000000 1008 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_GPlusParam 1708191 688 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_GPlusParam 5795014 211 ns/op 48 B/op 1 allocs/op -BenchmarkTango_GPlusParam 1000000 1091 ns/op 264 B/op 8 allocs/op -BenchmarkTigerTonic_GPlusParam 760221 2489 ns/op 856 B/op 16 allocs/op -BenchmarkTraffic_GPlusParam 309774 4039 ns/op 1872 B/op 21 allocs/op -BenchmarkVulcan_GPlusParam 1935730 623 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GPlus2Params 9158314 134 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlus2Params 11300517 107 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlus2Params 1239238 961 ns/op 496 B/op 5 allocs/op -BenchmarkBeego_GPlus2Params 1000000 1202 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GPlus2Params 335576 3725 ns/op 1168 B/op 10 allocs/op -BenchmarkChi_GPlus2Params 1000000 1014 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GPlus2Params 4394598 280 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_GPlus2Params 7851861 154 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GPlus2Params 9958588 120 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlus2Params 1000000 1433 ns/op 712 B/op 9 allocs/op -BenchmarkGoji_GPlus2Params 1325134 909 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_GPlus2Params 405955 2870 ns/op 1408 B/op 14 allocs/op -BenchmarkGoJsonRest_GPlus2Params 977038 1987 ns/op 713 B/op 14 allocs/op -BenchmarkGoRestful_GPlus2Params 205018 6142 ns/op 4384 B/op 16 allocs/op -BenchmarkGorillaMux_GPlus2Params 205641 6015 ns/op 1296 B/op 10 allocs/op -BenchmarkGowwwRouter_GPlus2Params 1748542 684 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_GPlus2Params 14047102 87.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlus2Params 1418673 828 ns/op 384 B/op 4 allocs/op -BenchmarkKocha_GPlus2Params 2334562 520 ns/op 128 B/op 5 allocs/op -BenchmarkLARS_GPlus2Params 11954094 101 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlus2Params 491552 2890 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_GPlus2Params 120532 9545 ns/op 1200 B/op 13 allocs/op -BenchmarkPat_GPlus2Params 194739 6766 ns/op 2168 B/op 33 allocs/op -BenchmarkPossum_GPlus2Params 1201224 1009 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_GPlus2Params 1575535 756 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_GPlus2Params 3698930 325 ns/op 96 B/op 1 allocs/op -BenchmarkTango_GPlus2Params 1000000 1212 ns/op 344 B/op 8 allocs/op -BenchmarkTigerTonic_GPlus2Params 349350 3660 ns/op 1200 B/op 22 allocs/op -BenchmarkTraffic_GPlus2Params 169714 7862 ns/op 2248 B/op 28 allocs/op -BenchmarkVulcan_GPlus2Params 1222288 974 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GPlusAll 845606 1398 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlusAll 1000000 1009 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlusAll 103830 11386 ns/op 5488 B/op 61 allocs/op -BenchmarkBeego_GPlusAll 82653 14784 ns/op 4576 B/op 39 allocs/op -BenchmarkBone_GPlusAll 36601 33123 ns/op 11744 B/op 109 allocs/op -BenchmarkChi_GPlusAll 95264 12831 ns/op 5616 B/op 39 allocs/op -BenchmarkDenco_GPlusAll 567681 2950 ns/op 672 B/op 11 allocs/op -BenchmarkEcho_GPlusAll 720366 1665 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GPlusAll 1000000 1185 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlusAll 71575 16365 ns/op 8040 B/op 103 allocs/op -BenchmarkGoji_GPlusAll 136352 9191 ns/op 3696 B/op 22 allocs/op -BenchmarkGojiv2_GPlusAll 38006 31802 ns/op 17616 B/op 154 allocs/op -BenchmarkGoJsonRest_GPlusAll 57238 21561 ns/op 8117 B/op 170 allocs/op -BenchmarkGoRestful_GPlusAll 15147 79276 ns/op 55520 B/op 192 allocs/op -BenchmarkGorillaMux_GPlusAll 24446 48410 ns/op 16112 B/op 128 allocs/op -BenchmarkGowwwRouter_GPlusAll 150112 7770 ns/op 4752 B/op 33 allocs/op -BenchmarkHttpRouter_GPlusAll 1367820 878 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlusAll 166628 8004 ns/op 4032 B/op 38 allocs/op -BenchmarkKocha_GPlusAll 265694 4570 ns/op 976 B/op 43 allocs/op -BenchmarkLARS_GPlusAll 1000000 1068 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlusAll 54564 23305 ns/op 9568 B/op 104 allocs/op -BenchmarkMartini_GPlusAll 16274 73845 ns/op 14016 B/op 145 allocs/op -BenchmarkPat_GPlusAll 27181 44478 ns/op 15264 B/op 271 allocs/op -BenchmarkPossum_GPlusAll 122587 10277 ns/op 5408 B/op 39 allocs/op -BenchmarkR2router_GPlusAll 130137 9297 ns/op 5040 B/op 63 allocs/op -BenchmarkRivet_GPlusAll 532438 3323 ns/op 768 B/op 11 allocs/op -BenchmarkTango_GPlusAll 86054 14531 ns/op 3656 B/op 104 allocs/op -BenchmarkTigerTonic_GPlusAll 33936 35356 ns/op 11600 B/op 242 allocs/op -BenchmarkTraffic_GPlusAll 17833 68181 ns/op 26248 B/op 341 allocs/op -BenchmarkVulcan_GPlusAll 120109 9861 ns/op 1274 B/op 39 allocs/op -``` +Route: `/:a/:b/.../:t` (20 segments) — Request: `GET /a/b/.../t` -## Parse.com +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :------------ | ----: | ----: | --------: | +| 1 | **Gin** | 121.7 | 0 | 0 | +| 2 | **Echo** | 127.5 | 0 | 0 | +| 3 | **BunRouter** | 211.4 | 0 | 0 | +| 4 | HttpRouter | 290.2 | 704 | 1 | +| 5 | Fiber | 466.1 | 0 | 0 | +| 6 | Goji v2 | 745.3 | 1,440 | 8 | +| 7 | Beego | 1,099 | 352 | 3 | +| 8 | Chi | 1,805 | 2,504 | 9 | +| 9 | HttpTreeMux | 1,857 | 3,144 | 13 | +| 10 | Macaron | 2,058 | 2,864 | 15 | +| 11 | GorillaMux | 2,223 | 3,272 | 13 | +| 12 | GoRestful | 3,337 | 7,008 | 20 | -```sh -BenchmarkGin_ParseStatic 18877833 63.5 ns/op 0 B/op 0 allocs/op +### Param Write -BenchmarkAce_ParseStatic 19663731 60.8 ns/op 0 B/op 0 allocs/op -BenchmarkAero_ParseStatic 28967341 41.5 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParseStatic 3006984 402 ns/op 120 B/op 3 allocs/op -BenchmarkBeego_ParseStatic 1000000 1031 ns/op 352 B/op 3 allocs/op -BenchmarkBone_ParseStatic 1782482 675 ns/op 144 B/op 3 allocs/op -BenchmarkChi_ParseStatic 1453261 819 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_ParseStatic 45023595 26.5 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_ParseStatic 17330470 69.3 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParseStatic 1644006 731 ns/op 296 B/op 5 allocs/op -BenchmarkGoji_ParseStatic 7026930 170 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_ParseStatic 517618 2037 ns/op 1312 B/op 10 allocs/op -BenchmarkGoJsonRest_ParseStatic 1227080 975 ns/op 329 B/op 11 allocs/op -BenchmarkGoRestful_ParseStatic 192458 6659 ns/op 4256 B/op 13 allocs/op -BenchmarkGorillaMux_ParseStatic 744062 2109 ns/op 976 B/op 9 allocs/op -BenchmarkGowwwRouter_ParseStatic 37781062 31.8 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_ParseStatic 45311223 26.5 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParseStatic 21383475 56.1 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_ParseStatic 29953290 40.1 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_ParseStatic 20036196 62.7 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParseStatic 1000000 1740 ns/op 736 B/op 8 allocs/op -BenchmarkMartini_ParseStatic 404156 3801 ns/op 768 B/op 9 allocs/op -BenchmarkPat_ParseStatic 1547180 772 ns/op 240 B/op 5 allocs/op -BenchmarkPossum_ParseStatic 1608991 757 ns/op 416 B/op 3 allocs/op -BenchmarkR2router_ParseStatic 3177936 385 ns/op 144 B/op 4 allocs/op -BenchmarkRivet_ParseStatic 17783205 67.4 ns/op 0 B/op 0 allocs/op -BenchmarkTango_ParseStatic 1210777 990 ns/op 248 B/op 8 allocs/op -BenchmarkTigerTonic_ParseStatic 5316440 231 ns/op 48 B/op 1 allocs/op -BenchmarkTraffic_ParseStatic 496050 2539 ns/op 1256 B/op 19 allocs/op -BenchmarkVulcan_ParseStatic 2462798 488 ns/op 98 B/op 3 allocs/op -BenchmarkAce_ParseParam 13393669 89.6 ns/op 0 B/op 0 allocs/op -BenchmarkAero_ParseParam 19836619 60.4 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParseParam 1405954 864 ns/op 467 B/op 5 allocs/op -BenchmarkBeego_ParseParam 1000000 1065 ns/op 352 B/op 3 allocs/op -BenchmarkBone_ParseParam 1000000 1698 ns/op 896 B/op 7 allocs/op -BenchmarkChi_ParseParam 1356037 873 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_ParseParam 6241392 204 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_ParseParam 14088100 85.1 ns/op 0 B/op 0 allocs/op -BenchmarkGin_ParseParam 17426064 68.9 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParseParam 1000000 1254 ns/op 664 B/op 8 allocs/op -BenchmarkGoji_ParseParam 1682574 713 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_ParseParam 502224 2333 ns/op 1360 B/op 12 allocs/op -BenchmarkGoJsonRest_ParseParam 1000000 1401 ns/op 649 B/op 13 allocs/op -BenchmarkGoRestful_ParseParam 182623 7097 ns/op 4576 B/op 14 allocs/op -BenchmarkGorillaMux_ParseParam 482332 2477 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_ParseParam 1834873 657 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_ParseParam 23593393 51.0 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParseParam 2100160 574 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_ParseParam 4837220 252 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_ParseParam 18411192 66.2 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParseParam 571870 2398 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_ParseParam 286262 4268 ns/op 1072 B/op 10 allocs/op -BenchmarkPat_ParseParam 692906 2157 ns/op 992 B/op 15 allocs/op -BenchmarkPossum_ParseParam 1000000 1011 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_ParseParam 1722735 697 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_ParseParam 6058054 203 ns/op 48 B/op 1 allocs/op -BenchmarkTango_ParseParam 1000000 1061 ns/op 280 B/op 8 allocs/op -BenchmarkTigerTonic_ParseParam 890275 2277 ns/op 784 B/op 15 allocs/op -BenchmarkTraffic_ParseParam 351322 3543 ns/op 1896 B/op 21 allocs/op -BenchmarkVulcan_ParseParam 2076544 572 ns/op 98 B/op 3 allocs/op -BenchmarkAce_Parse2Params 11718074 101 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Parse2Params 16264988 73.4 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Parse2Params 1238322 973 ns/op 496 B/op 5 allocs/op -BenchmarkBeego_Parse2Params 1000000 1120 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Parse2Params 1000000 1632 ns/op 848 B/op 6 allocs/op -BenchmarkChi_Parse2Params 1239477 955 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Parse2Params 4944133 245 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_Parse2Params 10518286 114 ns/op 0 B/op 0 allocs/op -BenchmarkGin_Parse2Params 14505195 82.7 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Parse2Params 1000000 1437 ns/op 712 B/op 9 allocs/op -BenchmarkGoji_Parse2Params 1689883 707 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_Parse2Params 502334 2308 ns/op 1344 B/op 11 allocs/op -BenchmarkGoJsonRest_Parse2Params 1000000 1771 ns/op 713 B/op 14 allocs/op -BenchmarkGoRestful_Parse2Params 159092 7583 ns/op 4928 B/op 14 allocs/op -BenchmarkGorillaMux_Parse2Params 417548 2980 ns/op 1296 B/op 10 allocs/op -BenchmarkGowwwRouter_Parse2Params 1751737 686 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Parse2Params 18089204 66.3 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Parse2Params 1556986 777 ns/op 384 B/op 4 allocs/op -BenchmarkKocha_Parse2Params 2493082 485 ns/op 128 B/op 5 allocs/op -BenchmarkLARS_Parse2Params 15350108 78.5 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Parse2Params 530974 2605 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_Parse2Params 247069 4673 ns/op 1152 B/op 11 allocs/op -BenchmarkPat_Parse2Params 816295 2126 ns/op 752 B/op 16 allocs/op -BenchmarkPossum_Parse2Params 1000000 1002 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Parse2Params 1569771 733 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_Parse2Params 4080546 295 ns/op 96 B/op 1 allocs/op -BenchmarkTango_Parse2Params 1000000 1121 ns/op 312 B/op 8 allocs/op -BenchmarkTigerTonic_Parse2Params 399556 3470 ns/op 1168 B/op 22 allocs/op -BenchmarkTraffic_Parse2Params 314194 4159 ns/op 1944 B/op 22 allocs/op -BenchmarkVulcan_Parse2Params 1827559 664 ns/op 98 B/op 3 allocs/op -BenchmarkAce_ParseAll 478395 2503 ns/op 0 B/op 0 allocs/op -BenchmarkAero_ParseAll 715392 1658 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParseAll 59191 20124 ns/op 8928 B/op 110 allocs/op -BenchmarkBeego_ParseAll 45507 27266 ns/op 9152 B/op 78 allocs/op -BenchmarkBone_ParseAll 29328 41459 ns/op 16208 B/op 147 allocs/op -BenchmarkChi_ParseAll 48531 25053 ns/op 11232 B/op 78 allocs/op -BenchmarkDenco_ParseAll 325532 4284 ns/op 928 B/op 16 allocs/op -BenchmarkEcho_ParseAll 433771 2759 ns/op 0 B/op 0 allocs/op -BenchmarkGin_ParseAll 576316 2082 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParseAll 41500 29692 ns/op 13728 B/op 181 allocs/op -BenchmarkGoji_ParseAll 80833 15563 ns/op 5376 B/op 32 allocs/op -BenchmarkGojiv2_ParseAll 19836 60335 ns/op 34448 B/op 277 allocs/op -BenchmarkGoJsonRest_ParseAll 32210 38027 ns/op 13866 B/op 321 allocs/op -BenchmarkGoRestful_ParseAll 6644 190842 ns/op 117600 B/op 354 allocs/op -BenchmarkGorillaMux_ParseAll 12634 95894 ns/op 30288 B/op 250 allocs/op -BenchmarkGowwwRouter_ParseAll 98152 12159 ns/op 6912 B/op 48 allocs/op -BenchmarkHttpRouter_ParseAll 933208 1273 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParseAll 107191 11554 ns/op 5728 B/op 51 allocs/op -BenchmarkKocha_ParseAll 184862 6225 ns/op 1112 B/op 54 allocs/op -BenchmarkLARS_ParseAll 644546 1858 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParseAll 26145 46484 ns/op 19136 B/op 208 allocs/op -BenchmarkMartini_ParseAll 10000 121838 ns/op 25072 B/op 253 allocs/op -BenchmarkPat_ParseAll 25417 47196 ns/op 15216 B/op 308 allocs/op -BenchmarkPossum_ParseAll 58550 20735 ns/op 10816 B/op 78 allocs/op -BenchmarkR2router_ParseAll 72732 16584 ns/op 8352 B/op 120 allocs/op -BenchmarkRivet_ParseAll 281365 4968 ns/op 912 B/op 16 allocs/op -BenchmarkTango_ParseAll 42831 28668 ns/op 7168 B/op 208 allocs/op -BenchmarkTigerTonic_ParseAll 23774 49972 ns/op 16048 B/op 332 allocs/op -BenchmarkTraffic_ParseAll 10000 104679 ns/op 45520 B/op 605 allocs/op -BenchmarkVulcan_ParseAll 64810 18108 ns/op 2548 B/op 78 allocs/op -``` +Route: `/user/:name` with response write — Request: `GET /user/gordon` + +| Rank | Router | ns/op | B/op | allocs/op | +| :--: | :------------ | ----: | ----: | --------: | +| 1 | **BunRouter** | 25.86 | 0 | 0 | +| 2 | **Gin** | 27.65 | 0 | 0 | +| 3 | HttpRouter | 37.40 | 32 | 1 | +| 4 | Echo | 47.94 | 8 | 1 | +| 5 | Fiber | 125.7 | 0 | 0 | +| 6 | HttpTreeMux | 180.4 | 352 | 3 | +| 7 | Chi | 348.3 | 704 | 4 | +| 8 | Beego | 386.1 | 360 | 4 | +| 9 | Goji v2 | 516.9 | 1,168 | 10 | +| 10 | GorillaMux | 665.5 | 1,152 | 8 | +| 11 | Macaron | 784.3 | 1,112 | 13 | +| 12 | GoRestful | 1,534 | 4,608 | 16 | diff --git a/CHANGELOG.md b/CHANGELOG.md index 9451db39..95bc2f84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,74 +1,123 @@ # Gin ChangeLog +## Gin v1.12.0 + +### Features + +- feat(render): add bson protocol ([#4145](https://github.com/gin-gonic/gin/pull/4145)) +- feat(context): add GetError and GetErrorSlice methods for error retrieval ([#4502](https://github.com/gin-gonic/gin/pull/4502)) +- feat(binding): add support for encoding.UnmarshalText in uri/query binding ([#4203](https://github.com/gin-gonic/gin/pull/4203)) +- feat(gin): add option to use escaped path ([#4420](https://github.com/gin-gonic/gin/pull/4420)) +- feat(context): add Protocol Buffers support to content negotiation ([#4423](https://github.com/gin-gonic/gin/pull/4423)) +- feat(context): implemented Delete method ([#38e7651](https://github.com/gin-gonic/gin/commit/38e7651)) +- feat(logger): color latency ([#4146](https://github.com/gin-gonic/gin/pull/4146)) + +### Enhancements + +- perf(tree): reduce allocations in findCaseInsensitivePath ([#4417](https://github.com/gin-gonic/gin/pull/4417)) +- perf(recovery): optimize line reading in stack function ([#4466](https://github.com/gin-gonic/gin/pull/4466)) +- perf(path): replace regex with custom functions in redirectTrailingSlash ([#4414](https://github.com/gin-gonic/gin/pull/4414)) +- perf(tree): optimize path parsing using strings.Count ([#4246](https://github.com/gin-gonic/gin/pull/4246)) +- chore(logger): allow skipping query string output ([#4547](https://github.com/gin-gonic/gin/pull/4547)) +- chore(context): always trust xff headers from unix socket ([#3359](https://github.com/gin-gonic/gin/pull/3359)) +- chore(response): prevent Flush() panic when the underlying ResponseWriter does not implement `http.Flusher` ([#4479](https://github.com/gin-gonic/gin/pull/4479)) +- refactor(recovery): smart error comparison ([#4142](https://github.com/gin-gonic/gin/pull/4142)) +- refactor(context): replace hardcoded localhost IPs with constants ([#4481](https://github.com/gin-gonic/gin/pull/4481)) +- refactor(utils): move util functions to utils.go ([#4467](https://github.com/gin-gonic/gin/pull/4467)) +- refactor(binding): use maps.Copy for cleaner map handling ([#4352](https://github.com/gin-gonic/gin/pull/4352)) +- refactor(context): using maps.Clone ([#4333](https://github.com/gin-gonic/gin/pull/4333)) +- refactor(ginS): use sync.OnceValue to simplify engine function ([#4314](https://github.com/gin-gonic/gin/pull/4314)) +- refactor: replace magic numbers with named constants in bodyAllowedForStatus ([#4529](https://github.com/gin-gonic/gin/pull/4529)) +- refactor: for loop can be modernized using range over int ([#4392](https://github.com/gin-gonic/gin/pull/4392)) + +### Bug Fixes + +- fix(tree): panic in findCaseInsensitivePathRec with RedirectFixedPath ([#4535](https://github.com/gin-gonic/gin/pull/4535)) +- fix(render): write content length in Data.Render ([#4206](https://github.com/gin-gonic/gin/pull/4206)) +- fix(context): ClientIP handling for multiple X-Forwarded-For header values ([#4472](https://github.com/gin-gonic/gin/pull/4472)) +- fix(binding): empty value error ([#2169](https://github.com/gin-gonic/gin/pull/2169)) +- fix(recover): suppress http.ErrAbortHandler in recover ([#4336](https://github.com/gin-gonic/gin/pull/4336)) +- fix(gin): literal colon routes not working with engine.Handler() ([#4415](https://github.com/gin-gonic/gin/pull/4415)) +- fix(gin): close os.File in RunFd to prevent resource leak ([#4422](https://github.com/gin-gonic/gin/pull/4422)) +- fix(response): refine hijack behavior for response lifecycle ([#4373](https://github.com/gin-gonic/gin/pull/4373)) +- fix(binding): improve empty slice/array handling in form binding ([#4380](https://github.com/gin-gonic/gin/pull/4380)) +- fix(debug): version mismatch ([#4403](https://github.com/gin-gonic/gin/pull/4403)) +- fix: correct typos, improve documentation clarity, and remove dead code ([#4511](https://github.com/gin-gonic/gin/pull/4511)) + +### Build process updates / CI + +- ci: update Go version support to 1.25+ across CI and docs ([#4550](https://github.com/gin-gonic/gin/pull/4550)) +- chore(binding): upgrade bson dependency to mongo-driver v2 ([#4549](https://github.com/gin-gonic/gin/pull/4549)) + ## Gin v1.11.0 ### Features -* feat(gin): Experimental support for HTTP/3 using quic-go/quic-go ([#3210](https://github.com/gin-gonic/gin/pull/3210)) -* feat(form): add array collection format in form binding ([#3986](https://github.com/gin-gonic/gin/pull/3986)), add custom string slice for form tag unmarshal ([#3970](https://github.com/gin-gonic/gin/pull/3970)) -* feat(binding): add BindPlain ([#3904](https://github.com/gin-gonic/gin/pull/3904)) -* feat(fs): Export, test and document OnlyFilesFS ([#3939](https://github.com/gin-gonic/gin/pull/3939)) -* feat(binding): add support for unixMilli and unixMicro ([#4190](https://github.com/gin-gonic/gin/pull/4190)) -* feat(form): Support default values for collections in form binding ([#4048](https://github.com/gin-gonic/gin/pull/4048)) -* feat(context): GetXxx added support for more go native types ([#3633](https://github.com/gin-gonic/gin/pull/3633)) +- feat(gin): Experimental support for HTTP/3 using quic-go/quic-go ([#3210](https://github.com/gin-gonic/gin/pull/3210)) +- feat(form): add array collection format in form binding ([#3986](https://github.com/gin-gonic/gin/pull/3986)), add custom string slice for form tag unmarshal ([#3970](https://github.com/gin-gonic/gin/pull/3970)) +- feat(binding): add BindPlain ([#3904](https://github.com/gin-gonic/gin/pull/3904)) +- feat(fs): Export, test and document OnlyFilesFS ([#3939](https://github.com/gin-gonic/gin/pull/3939)) +- feat(binding): add support for unixMilli and unixMicro ([#4190](https://github.com/gin-gonic/gin/pull/4190)) +- feat(form): Support default values for collections in form binding ([#4048](https://github.com/gin-gonic/gin/pull/4048)) +- feat(context): GetXxx added support for more go native types ([#3633](https://github.com/gin-gonic/gin/pull/3633)) ### Enhancements -* perf(context): optimize getMapFromFormData performance ([#4339](https://github.com/gin-gonic/gin/pull/4339)) -* refactor(tree): replace string(/) with "/" in node.insertChild ([#4354](https://github.com/gin-gonic/gin/pull/4354)) -* refactor(render): remove headers parameter from writeHeader ([#4353](https://github.com/gin-gonic/gin/pull/4353)) -* refactor(context): simplify "GetType()" functions ([#4080](https://github.com/gin-gonic/gin/pull/4080)) -* refactor(slice): simplify SliceValidationError Error method ([#3910](https://github.com/gin-gonic/gin/pull/3910)) -* refactor(context):Avoid using filepath.Dir twice in SaveUploadedFile ([#4181](https://github.com/gin-gonic/gin/pull/4181)) -* refactor(context): refactor context handling and improve test robustness ([#4066](https://github.com/gin-gonic/gin/pull/4066)) -* refactor(binding): use strings.Cut to replace strings.Index ([#3522](https://github.com/gin-gonic/gin/pull/3522)) -* refactor(context): add an optional permission parameter to SaveUploadedFile ([#4068](https://github.com/gin-gonic/gin/pull/4068)) -* refactor(context): verify URL is Non-nil in initQueryCache() ([#3969](https://github.com/gin-gonic/gin/pull/3969)) -* refactor(context): YAML judgment logic in Negotiate ([#3966](https://github.com/gin-gonic/gin/pull/3966)) -* tree: replace the self-defined 'min' to official one ([#3975](https://github.com/gin-gonic/gin/pull/3975)) -* context: Remove redundant filepath.Dir usage ([#4181](https://github.com/gin-gonic/gin/pull/4181)) +- perf(context): optimize getMapFromFormData performance ([#4339](https://github.com/gin-gonic/gin/pull/4339)) +- refactor(tree): replace string(/) with "/" in node.insertChild ([#4354](https://github.com/gin-gonic/gin/pull/4354)) +- refactor(render): remove headers parameter from writeHeader ([#4353](https://github.com/gin-gonic/gin/pull/4353)) +- refactor(context): simplify "GetType()" functions ([#4080](https://github.com/gin-gonic/gin/pull/4080)) +- refactor(slice): simplify SliceValidationError Error method ([#3910](https://github.com/gin-gonic/gin/pull/3910)) +- refactor(context):Avoid using filepath.Dir twice in SaveUploadedFile ([#4181](https://github.com/gin-gonic/gin/pull/4181)) +- refactor(context): refactor context handling and improve test robustness ([#4066](https://github.com/gin-gonic/gin/pull/4066)) +- refactor(binding): use strings.Cut to replace strings.Index ([#3522](https://github.com/gin-gonic/gin/pull/3522)) +- refactor(context): add an optional permission parameter to SaveUploadedFile ([#4068](https://github.com/gin-gonic/gin/pull/4068)) +- refactor(context): verify URL is Non-nil in initQueryCache() ([#3969](https://github.com/gin-gonic/gin/pull/3969)) +- refactor(context): YAML judgment logic in Negotiate ([#3966](https://github.com/gin-gonic/gin/pull/3966)) +- tree: replace the self-defined 'min' to official one ([#3975](https://github.com/gin-gonic/gin/pull/3975)) +- context: Remove redundant filepath.Dir usage ([#4181](https://github.com/gin-gonic/gin/pull/4181)) ### Bug Fixes -* fix: prevent middleware re-entry issue in HandleContext ([#3987](https://github.com/gin-gonic/gin/pull/3987)) -* fix(binding): prevent duplicate decoding and add validation in decodeToml ([#4193](https://github.com/gin-gonic/gin/pull/4193)) -* fix(gin): Do not panic when handling method not allowed on empty tree ([#4003](https://github.com/gin-gonic/gin/pull/4003)) -* fix(gin): data race warning for gin mode ([#1580](https://github.com/gin-gonic/gin/pull/1580)) -* fix(context): verify URL is Non-nil in initQueryCache() ([#3969](https://github.com/gin-gonic/gin/pull/3969)) -* fix(context): YAML judgment logic in Negotiate ([#3966](https://github.com/gin-gonic/gin/pull/3966)) -* fix(context): check handler is nil ([#3413](https://github.com/gin-gonic/gin/pull/3413)) -* fix(readme): fix broken link to English documentation ([#4222](https://github.com/gin-gonic/gin/pull/4222)) -* fix(tree): Keep panic infos consistent when wildcard type build faild ([#4077](https://github.com/gin-gonic/gin/pull/4077)) +- fix: prevent middleware re-entry issue in HandleContext ([#3987](https://github.com/gin-gonic/gin/pull/3987)) +- fix(binding): prevent duplicate decoding and add validation in decodeToml ([#4193](https://github.com/gin-gonic/gin/pull/4193)) +- fix(gin): Do not panic when handling method not allowed on empty tree ([#4003](https://github.com/gin-gonic/gin/pull/4003)) +- fix(gin): data race warning for gin mode ([#1580](https://github.com/gin-gonic/gin/pull/1580)) +- fix(context): verify URL is Non-nil in initQueryCache() ([#3969](https://github.com/gin-gonic/gin/pull/3969)) +- fix(context): YAML judgment logic in Negotiate ([#3966](https://github.com/gin-gonic/gin/pull/3966)) +- fix(context): check handler is nil ([#3413](https://github.com/gin-gonic/gin/pull/3413)) +- fix(readme): fix broken link to English documentation ([#4222](https://github.com/gin-gonic/gin/pull/4222)) +- fix(tree): Keep panic infos consistent when wildcard type build faild ([#4077](https://github.com/gin-gonic/gin/pull/4077)) ### Build process updates / CI -* ci: integrate Trivy vulnerability scanning into CI workflow ([#4359](https://github.com/gin-gonic/gin/pull/4359)) -* ci: support Go 1.25 in CI/CD ([#4341](https://github.com/gin-gonic/gin/pull/4341)) -* build(deps): upgrade github.com/bytedance/sonic from v1.13.2 to v1.14.0 ([#4342](https://github.com/gin-gonic/gin/pull/4342)) -* ci: add Go version 1.24 to GitHub Actions ([#4154](https://github.com/gin-gonic/gin/pull/4154)) -* build: update Gin minimum Go version to 1.21 ([#3960](https://github.com/gin-gonic/gin/pull/3960)) -* ci(lint): enable new linters (testifylint, usestdlibvars, perfsprint, etc.) ([#4010](https://github.com/gin-gonic/gin/pull/4010), [#4091](https://github.com/gin-gonic/gin/pull/4091), [#4090](https://github.com/gin-gonic/gin/pull/4090)) -* ci(lint): update workflows and improve test request consistency ([#4126](https://github.com/gin-gonic/gin/pull/4126)) +- ci: integrate Trivy vulnerability scanning into CI workflow ([#4359](https://github.com/gin-gonic/gin/pull/4359)) +- ci: support Go 1.25 in CI/CD ([#4341](https://github.com/gin-gonic/gin/pull/4341)) +- build(deps): upgrade github.com/bytedance/sonic from v1.13.2 to v1.14.0 ([#4342](https://github.com/gin-gonic/gin/pull/4342)) +- ci: add Go version 1.24 to GitHub Actions ([#4154](https://github.com/gin-gonic/gin/pull/4154)) +- build: update Gin minimum Go version to 1.21 ([#3960](https://github.com/gin-gonic/gin/pull/3960)) +- ci(lint): enable new linters (testifylint, usestdlibvars, perfsprint, etc.) ([#4010](https://github.com/gin-gonic/gin/pull/4010), [#4091](https://github.com/gin-gonic/gin/pull/4091), [#4090](https://github.com/gin-gonic/gin/pull/4090)) +- ci(lint): update workflows and improve test request consistency ([#4126](https://github.com/gin-gonic/gin/pull/4126)) ### Dependency updates -* chore(deps): bump google.golang.org/protobuf from 1.36.6 to 1.36.9 ([#4346](https://github.com/gin-gonic/gin/pull/4346), [#4356](https://github.com/gin-gonic/gin/pull/4356)) -* chore(deps): bump github.com/stretchr/testify from 1.10.0 to 1.11.1 ([#4347](https://github.com/gin-gonic/gin/pull/4347)) -* chore(deps): bump actions/setup-go from 5 to 6 ([#4351](https://github.com/gin-gonic/gin/pull/4351)) -* chore(deps): bump github.com/quic-go/quic-go from 0.53.0 to 0.54.0 ([#4328](https://github.com/gin-gonic/gin/pull/4328)) -* chore(deps): bump golang.org/x/net from 0.33.0 to 0.38.0 ([#4178](https://github.com/gin-gonic/gin/pull/4178), [#4221](https://github.com/gin-gonic/gin/pull/4221)) -* chore(deps): bump github.com/go-playground/validator/v10 from 10.20.0 to 10.22.1 ([#4052](https://github.com/gin-gonic/gin/pull/4052)) +- chore(deps): bump google.golang.org/protobuf from 1.36.6 to 1.36.9 ([#4346](https://github.com/gin-gonic/gin/pull/4346), [#4356](https://github.com/gin-gonic/gin/pull/4356)) +- chore(deps): bump github.com/stretchr/testify from 1.10.0 to 1.11.1 ([#4347](https://github.com/gin-gonic/gin/pull/4347)) +- chore(deps): bump actions/setup-go from 5 to 6 ([#4351](https://github.com/gin-gonic/gin/pull/4351)) +- chore(deps): bump github.com/quic-go/quic-go from 0.53.0 to 0.54.0 ([#4328](https://github.com/gin-gonic/gin/pull/4328)) +- chore(deps): bump golang.org/x/net from 0.33.0 to 0.38.0 ([#4178](https://github.com/gin-gonic/gin/pull/4178), [#4221](https://github.com/gin-gonic/gin/pull/4221)) +- chore(deps): bump github.com/go-playground/validator/v10 from 10.20.0 to 10.22.1 ([#4052](https://github.com/gin-gonic/gin/pull/4052)) ### Documentation updates -* docs(changelog): update release notes for Gin v1.10.1 ([#4360](https://github.com/gin-gonic/gin/pull/4360)) -* docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md ([#4207](https://github.com/gin-gonic/gin/pull/4207)) -* docs: update documentation and release notes for Gin v1.10.0 ([#3953](https://github.com/gin-gonic/gin/pull/3953)) -* docs: fix typo in Gin Quick Start ([#3997](https://github.com/gin-gonic/gin/pull/3997)) -* docs: fix comment and link issues ([#4205](https://github.com/gin-gonic/gin/pull/4205), [#3938](https://github.com/gin-gonic/gin/pull/3938)) -* docs: fix route group example code ([#4020](https://github.com/gin-gonic/gin/pull/4020)) -* docs(readme): add Portuguese documentation ([#4078](https://github.com/gin-gonic/gin/pull/4078)) -* docs(context): fix some function names in comment ([#4079](https://github.com/gin-gonic/gin/pull/4079)) +- docs(changelog): update release notes for Gin v1.10.1 ([#4360](https://github.com/gin-gonic/gin/pull/4360)) +- docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md ([#4207](https://github.com/gin-gonic/gin/pull/4207)) +- docs: update documentation and release notes for Gin v1.10.0 ([#3953](https://github.com/gin-gonic/gin/pull/3953)) +- docs: fix typo in Gin Quick Start ([#3997](https://github.com/gin-gonic/gin/pull/3997)) +- docs: fix comment and link issues ([#4205](https://github.com/gin-gonic/gin/pull/4205), [#3938](https://github.com/gin-gonic/gin/pull/3938)) +- docs: fix route group example code ([#4020](https://github.com/gin-gonic/gin/pull/4020)) +- docs(readme): add Portuguese documentation ([#4078](https://github.com/gin-gonic/gin/pull/4078)) +- docs(context): fix some function names in comment ([#4079](https://github.com/gin-gonic/gin/pull/4079)) --- @@ -76,377 +125,377 @@ ### Features -* refactor: strengthen HTTPS security and improve code organization -* feat(binding): Support custom BindUnmarshaler for binding. (#3933) +- refactor: strengthen HTTPS security and improve code organization +- feat(binding): Support custom BindUnmarshaler for binding. (#3933) ### Enhancements -* chore(deps): bump github.com/bytedance/sonic from 1.11.3 to 1.11.6 (#3940) -* chore(deps): bump golangci/golangci-lint-action from 4 to 5 (#3941) -* chore: update external dependencies to latest versions (#3950) -* chore: update various Go dependencies to latest versions (#3901) -* chore: refactor configuration files for better readability (#3951) -* chore: update changelog categories and improve documentation (#3917) -* feat: update version constant to v1.10.0 (#3952) +- chore(deps): bump github.com/bytedance/sonic from 1.11.3 to 1.11.6 (#3940) +- chore(deps): bump golangci/golangci-lint-action from 4 to 5 (#3941) +- chore: update external dependencies to latest versions (#3950) +- chore: update various Go dependencies to latest versions (#3901) +- chore: refactor configuration files for better readability (#3951) +- chore: update changelog categories and improve documentation (#3917) +- feat: update version constant to v1.10.0 (#3952) ### Build process updates -* ci(release): refactor changelog regex patterns and exclusions (#3914) -* ci(Makefile): vet command add .PHONY (#3915) +- ci(release): refactor changelog regex patterns and exclusions (#3914) +- ci(Makefile): vet command add .PHONY (#3915) ## Gin v1.10.0 ### Features -* feat(auth): add proxy-server authentication (#3877) (@EndlessParadox1) -* feat(bind): ShouldBindBodyWith shortcut and change doc (#3871) (@RedCrazyGhost) -* feat(binding): Support custom BindUnmarshaler for binding. (#3933) (@dkkb) -* feat(binding): support override default binding implement (#3514) (@ssfyn) -* feat(engine): Added `OptionFunc` and `With` (#3572) (@flc1125) -* feat(logger): ability to skip logs based on user-defined logic (#3593) (@palvaneh) +- feat(auth): add proxy-server authentication (#3877) (@EndlessParadox1) +- feat(bind): ShouldBindBodyWith shortcut and change doc (#3871) (@RedCrazyGhost) +- feat(binding): Support custom BindUnmarshaler for binding. (#3933) (@dkkb) +- feat(binding): support override default binding implement (#3514) (@ssfyn) +- feat(engine): Added `OptionFunc` and `With` (#3572) (@flc1125) +- feat(logger): ability to skip logs based on user-defined logic (#3593) (@palvaneh) ### Bug fixes -* Revert "fix(uri): query binding bug (#3236)" (#3899) (@appleboy) -* fix(binding): binding error while not upload file (#3819) (#3820) (@clearcodecn) -* fix(binding): dereference pointer to struct (#3199) (@echovl) -* fix(context): make context Value method adhere to Go standards (#3897) (@FarmerChillax) -* fix(engine): fix unit test (#3878) (@flc1125) -* fix(header): Allow header according to RFC 7231 (HTTP 405) (#3759) (@Crocmagnon) -* fix(route): Add fullPath in context copy (#3784) (@KarthikReddyPuli) -* fix(router): catch-all conflicting wildcard (#3812) (@FirePing32) -* fix(sec): upgrade golang.org/x/crypto to 0.17.0 (#3832) (@chncaption) -* fix(tree): correctly expand the capacity of params (#3502) (@georgijd-form3) -* fix(uri): query binding bug (#3236) (@illiafox) -* fix: Add pointer support for url query params (#3659) (#3666) (@omkar-foss) -* fix: protect Context.Keys map when call Copy method (#3873) (@kingcanfish) +- Revert "fix(uri): query binding bug (#3236)" (#3899) (@appleboy) +- fix(binding): binding error while not upload file (#3819) (#3820) (@clearcodecn) +- fix(binding): dereference pointer to struct (#3199) (@echovl) +- fix(context): make context Value method adhere to Go standards (#3897) (@FarmerChillax) +- fix(engine): fix unit test (#3878) (@flc1125) +- fix(header): Allow header according to RFC 7231 (HTTP 405) (#3759) (@Crocmagnon) +- fix(route): Add fullPath in context copy (#3784) (@KarthikReddyPuli) +- fix(router): catch-all conflicting wildcard (#3812) (@FirePing32) +- fix(sec): upgrade golang.org/x/crypto to 0.17.0 (#3832) (@chncaption) +- fix(tree): correctly expand the capacity of params (#3502) (@georgijd-form3) +- fix(uri): query binding bug (#3236) (@illiafox) +- fix: Add pointer support for url query params (#3659) (#3666) (@omkar-foss) +- fix: protect Context.Keys map when call Copy method (#3873) (@kingcanfish) ### Enhancements -* chore(CI): update release args (#3595) (@qloog) -* chore(IP): add TrustedPlatform constant for Fly.io. (#3839) (@ab) -* chore(debug): add ability to override the debugPrint statement (#2337) (@josegonzalez) -* chore(deps): update dependencies to latest versions (#3835) (@appleboy) -* chore(header): Add support for RFC 9512: application/yaml (#3851) (@vincentbernat) -* chore(http): use white color for HTTP 1XX (#3741) (@viralparmarme) -* chore(optimize): the ShouldBindUri method of the Context struct (#3911) (@1911860538) -* chore(perf): Optimize the Copy method of the Context struct (#3859) (@1911860538) -* chore(refactor): modify interface check way (#3855) (@demoManito) -* chore(request): check reader if it's nil before reading (#3419) (@noahyao1024) -* chore(security): upgrade Protobuf for CVE-2024-24786 (#3893) (@Fotkurz) -* chore: refactor CI and update dependencies (#3848) (@appleboy) -* chore: refactor configuration files for better readability (#3951) (@appleboy) -* chore: update GitHub Actions configuration (#3792) (@appleboy) -* chore: update changelog categories and improve documentation (#3917) (@appleboy) -* chore: update dependencies to latest versions (#3694) (@appleboy) -* chore: update external dependencies to latest versions (#3950) (@appleboy) -* chore: update various Go dependencies to latest versions (#3901) (@appleboy) +- chore(CI): update release args (#3595) (@qloog) +- chore(IP): add TrustedPlatform constant for Fly.io. (#3839) (@ab) +- chore(debug): add ability to override the debugPrint statement (#2337) (@josegonzalez) +- chore(deps): update dependencies to latest versions (#3835) (@appleboy) +- chore(header): Add support for RFC 9512: application/yaml (#3851) (@vincentbernat) +- chore(http): use white color for HTTP 1XX (#3741) (@viralparmarme) +- chore(optimize): the ShouldBindUri method of the Context struct (#3911) (@1911860538) +- chore(perf): Optimize the Copy method of the Context struct (#3859) (@1911860538) +- chore(refactor): modify interface check way (#3855) (@demoManito) +- chore(request): check reader if it's nil before reading (#3419) (@noahyao1024) +- chore(security): upgrade Protobuf for CVE-2024-24786 (#3893) (@Fotkurz) +- chore: refactor CI and update dependencies (#3848) (@appleboy) +- chore: refactor configuration files for better readability (#3951) (@appleboy) +- chore: update GitHub Actions configuration (#3792) (@appleboy) +- chore: update changelog categories and improve documentation (#3917) (@appleboy) +- chore: update dependencies to latest versions (#3694) (@appleboy) +- chore: update external dependencies to latest versions (#3950) (@appleboy) +- chore: update various Go dependencies to latest versions (#3901) (@appleboy) ### Build process updates -* build(codecov): Added a codecov configuration (#3891) (@flc1125) -* ci(Makefile): vet command add .PHONY (#3915) (@imalasong) -* ci(lint): update tooling and workflows for consistency (#3834) (@appleboy) -* ci(release): refactor changelog regex patterns and exclusions (#3914) (@appleboy) -* ci(testing): add go1.22 version (#3842) (@appleboy) +- build(codecov): Added a codecov configuration (#3891) (@flc1125) +- ci(Makefile): vet command add .PHONY (#3915) (@imalasong) +- ci(lint): update tooling and workflows for consistency (#3834) (@appleboy) +- ci(release): refactor changelog regex patterns and exclusions (#3914) (@appleboy) +- ci(testing): add go1.22 version (#3842) (@appleboy) ### Documentation updates -* docs(context): Added deprecation comments to BindWith (#3880) (@flc1125) -* docs(middleware): comments to function `BasicAuthForProxy` (#3881) (@EndlessParadox1) -* docs: Add document to constant `AuthProxyUserKey` and `BasicAuthForProxy`. (#3887) (@EndlessParadox1) -* docs: fix typo in comment (#3868) (@testwill) -* docs: fix typo in function documentation (#3872) (@TotomiEcio) -* docs: remove redundant comments (#3765) (@WeiTheShinobi) -* feat: update version constant to v1.10.0 (#3952) (@appleboy) +- docs(context): Added deprecation comments to BindWith (#3880) (@flc1125) +- docs(middleware): comments to function `BasicAuthForProxy` (#3881) (@EndlessParadox1) +- docs: Add document to constant `AuthProxyUserKey` and `BasicAuthForProxy`. (#3887) (@EndlessParadox1) +- docs: fix typo in comment (#3868) (@testwill) +- docs: fix typo in function documentation (#3872) (@TotomiEcio) +- docs: remove redundant comments (#3765) (@WeiTheShinobi) +- feat: update version constant to v1.10.0 (#3952) (@appleboy) ### Others -* Upgrade golang.org/x/net -> v0.13.0 (#3684) (@cpcf) -* test(git): gitignore add develop tools (#3370) (@demoManito) -* test(http): use constant instead of numeric literal (#3863) (@testwill) -* test(path): Optimize unit test execution results (#3883) (@flc1125) -* test(render): increased unit tests coverage (#3691) (@araujo88) +- Upgrade golang.org/x/net -> v0.13.0 (#3684) (@cpcf) +- test(git): gitignore add develop tools (#3370) (@demoManito) +- test(http): use constant instead of numeric literal (#3863) (@testwill) +- test(path): Optimize unit test execution results (#3883) (@flc1125) +- test(render): increased unit tests coverage (#3691) (@araujo88) ## Gin v1.9.1 ### BUG FIXES -* fix Request.Context() checks [#3512](https://github.com/gin-gonic/gin/pull/3512) +- fix Request.Context() checks [#3512](https://github.com/gin-gonic/gin/pull/3512) ### SECURITY -* fix lack of escaping of filename in Content-Disposition [#3556](https://github.com/gin-gonic/gin/pull/3556) +- fix lack of escaping of filename in Content-Disposition [#3556](https://github.com/gin-gonic/gin/pull/3556) ### ENHANCEMENTS -* refactor: use bytes.ReplaceAll directly [#3455](https://github.com/gin-gonic/gin/pull/3455) -* convert strings and slices using the officially recommended way [#3344](https://github.com/gin-gonic/gin/pull/3344) -* improve render code coverage [#3525](https://github.com/gin-gonic/gin/pull/3525) +- refactor: use bytes.ReplaceAll directly [#3455](https://github.com/gin-gonic/gin/pull/3455) +- convert strings and slices using the officially recommended way [#3344](https://github.com/gin-gonic/gin/pull/3344) +- improve render code coverage [#3525](https://github.com/gin-gonic/gin/pull/3525) ### DOCS -* docs: changed documentation link for trusted proxies [#3575](https://github.com/gin-gonic/gin/pull/3575) -* chore: improve linting, testing, and GitHub Actions setup [#3583](https://github.com/gin-gonic/gin/pull/3583) +- docs: changed documentation link for trusted proxies [#3575](https://github.com/gin-gonic/gin/pull/3575) +- chore: improve linting, testing, and GitHub Actions setup [#3583](https://github.com/gin-gonic/gin/pull/3583) ## Gin v1.9.0 ### BREAK CHANGES -* Stop useless panicking in context and render [#2150](https://github.com/gin-gonic/gin/pull/2150) +- Stop useless panicking in context and render [#2150](https://github.com/gin-gonic/gin/pull/2150) ### BUG FIXES -* fix(router): tree bug where loop index is not decremented. [#3460](https://github.com/gin-gonic/gin/pull/3460) -* fix(context): panic on NegotiateFormat - index out of range [#3397](https://github.com/gin-gonic/gin/pull/3397) -* Add escape logic for header [#3500](https://github.com/gin-gonic/gin/pull/3500) and [#3503](https://github.com/gin-gonic/gin/pull/3503) +- fix(router): tree bug where loop index is not decremented. [#3460](https://github.com/gin-gonic/gin/pull/3460) +- fix(context): panic on NegotiateFormat - index out of range [#3397](https://github.com/gin-gonic/gin/pull/3397) +- Add escape logic for header [#3500](https://github.com/gin-gonic/gin/pull/3500) and [#3503](https://github.com/gin-gonic/gin/pull/3503) ### SECURITY -* Fix the GO-2022-0969 and GO-2022-0288 vulnerabilities [#3333](https://github.com/gin-gonic/gin/pull/3333) -* fix(security): vulnerability GO-2023-1571 [#3505](https://github.com/gin-gonic/gin/pull/3505) +- Fix the GO-2022-0969 and GO-2022-0288 vulnerabilities [#3333](https://github.com/gin-gonic/gin/pull/3333) +- fix(security): vulnerability GO-2023-1571 [#3505](https://github.com/gin-gonic/gin/pull/3505) ### ENHANCEMENTS -* feat: add sonic json support [#3184](https://github.com/gin-gonic/gin/pull/3184) -* chore(file): Creates a directory named path [#3316](https://github.com/gin-gonic/gin/pull/3316) -* fix: modify interface check way [#3327](https://github.com/gin-gonic/gin/pull/3327) -* remove deprecated of package io/ioutil [#3395](https://github.com/gin-gonic/gin/pull/3395) -* refactor: avoid calling strings.ToLower twice [#3343](https://github.com/gin-gonic/gin/pull/3433) -* console logger HTTP status code bug fixed [#3453](https://github.com/gin-gonic/gin/pull/3453) -* chore(yaml): upgrade dependency to v3 version [#3456](https://github.com/gin-gonic/gin/pull/3456) -* chore(router): match method added to routergroup for multiple HTTP methods supporting [#3464](https://github.com/gin-gonic/gin/pull/3464) -* chore(http): add support for go1.20 http.rwUnwrapper to gin.responseWriter [#3489](https://github.com/gin-gonic/gin/pull/3489) +- feat: add sonic json support [#3184](https://github.com/gin-gonic/gin/pull/3184) +- chore(file): Creates a directory named path [#3316](https://github.com/gin-gonic/gin/pull/3316) +- fix: modify interface check way [#3327](https://github.com/gin-gonic/gin/pull/3327) +- remove deprecated of package io/ioutil [#3395](https://github.com/gin-gonic/gin/pull/3395) +- refactor: avoid calling strings.ToLower twice [#3343](https://github.com/gin-gonic/gin/pull/3433) +- console logger HTTP status code bug fixed [#3453](https://github.com/gin-gonic/gin/pull/3453) +- chore(yaml): upgrade dependency to v3 version [#3456](https://github.com/gin-gonic/gin/pull/3456) +- chore(router): match method added to routergroup for multiple HTTP methods supporting [#3464](https://github.com/gin-gonic/gin/pull/3464) +- chore(http): add support for go1.20 http.rwUnwrapper to gin.responseWriter [#3489](https://github.com/gin-gonic/gin/pull/3489) ### DOCS -* docs: update markdown format [#3260](https://github.com/gin-gonic/gin/pull/3260) -* docs(readme): Add the TOML rendering example [#3400](https://github.com/gin-gonic/gin/pull/3400) -* docs(readme): move more example to docs/doc.md [#3449](https://github.com/gin-gonic/gin/pull/3449) -* docs: update markdown format [#3446](https://github.com/gin-gonic/gin/pull/3446) +- docs: update markdown format [#3260](https://github.com/gin-gonic/gin/pull/3260) +- docs(readme): Add the TOML rendering example [#3400](https://github.com/gin-gonic/gin/pull/3400) +- docs(readme): move more example to docs/doc.md [#3449](https://github.com/gin-gonic/gin/pull/3449) +- docs: update markdown format [#3446](https://github.com/gin-gonic/gin/pull/3446) ## Gin v1.8.2 ### BUG FIXES -* fix(route): redirectSlash bug ([#3227]((https://github.com/gin-gonic/gin/pull/3227))) -* fix(engine): missing route params for CreateTestContext ([#2778]((https://github.com/gin-gonic/gin/pull/2778))) ([#2803]((https://github.com/gin-gonic/gin/pull/2803))) +- fix(route): redirectSlash bug ([#3227](<(https://github.com/gin-gonic/gin/pull/3227)>)) +- fix(engine): missing route params for CreateTestContext ([#2778](<(https://github.com/gin-gonic/gin/pull/2778)>)) ([#2803](<(https://github.com/gin-gonic/gin/pull/2803)>)) ### SECURITY -* Fix the GO-2022-1144 vulnerability ([#3432]((https://github.com/gin-gonic/gin/pull/3432))) +- Fix the GO-2022-1144 vulnerability ([#3432](<(https://github.com/gin-gonic/gin/pull/3432)>)) ## Gin v1.8.1 ### ENHANCEMENTS -* feat(context): add ContextWithFallback feature flag [#3172](https://github.com/gin-gonic/gin/pull/3172) +- feat(context): add ContextWithFallback feature flag [#3172](https://github.com/gin-gonic/gin/pull/3172) ## Gin v1.8.0 ### BREAK CHANGES -* TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967). Please replace `RemoteIP() (net.IP, bool)` with `RemoteIP() net.IP` -* gin.Context with fallback value from gin.Context.Request.Context() [#2751](https://github.com/gin-gonic/gin/pull/2751) +- TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967). Please replace `RemoteIP() (net.IP, bool)` with `RemoteIP() net.IP` +- gin.Context with fallback value from gin.Context.Request.Context() [#2751](https://github.com/gin-gonic/gin/pull/2751) ### BUG FIXES -* Fixed SetOutput() panics on go 1.17 [#2861](https://github.com/gin-gonic/gin/pull/2861) -* Fix: wrong when wildcard follows named param [#2983](https://github.com/gin-gonic/gin/pull/2983) -* Fix: missing sameSite when do context.reset() [#3123](https://github.com/gin-gonic/gin/pull/3123) +- Fixed SetOutput() panics on go 1.17 [#2861](https://github.com/gin-gonic/gin/pull/2861) +- Fix: wrong when wildcard follows named param [#2983](https://github.com/gin-gonic/gin/pull/2983) +- Fix: missing sameSite when do context.reset() [#3123](https://github.com/gin-gonic/gin/pull/3123) ### ENHANCEMENTS -* Use Header() instead of deprecated HeaderMap [#2694](https://github.com/gin-gonic/gin/pull/2694) -* RouterGroup.Handle regular match optimization of http method [#2685](https://github.com/gin-gonic/gin/pull/2685) -* Add support go-json, another drop-in json replacement [#2680](https://github.com/gin-gonic/gin/pull/2680) -* Use errors.New to replace fmt.Errorf will much better [#2707](https://github.com/gin-gonic/gin/pull/2707) -* Use Duration.Truncate for truncating precision [#2711](https://github.com/gin-gonic/gin/pull/2711) -* Get client IP when using Cloudflare [#2723](https://github.com/gin-gonic/gin/pull/2723) -* Optimize code adjust [#2700](https://github.com/gin-gonic/gin/pull/2700/files) -* Optimize code and reduce code cyclomatic complexity [#2737](https://github.com/gin-gonic/gin/pull/2737) -* Improve sliceValidateError.Error performance [#2765](https://github.com/gin-gonic/gin/pull/2765) -* Support custom struct tag [#2720](https://github.com/gin-gonic/gin/pull/2720) -* Improve router group tests [#2787](https://github.com/gin-gonic/gin/pull/2787) -* Fallback Context.Deadline() Context.Done() Context.Err() to Context.Request.Context() [#2769](https://github.com/gin-gonic/gin/pull/2769) -* Some codes optimize [#2830](https://github.com/gin-gonic/gin/pull/2830) [#2834](https://github.com/gin-gonic/gin/pull/2834) [#2838](https://github.com/gin-gonic/gin/pull/2838) [#2837](https://github.com/gin-gonic/gin/pull/2837) [#2788](https://github.com/gin-gonic/gin/pull/2788) [#2848](https://github.com/gin-gonic/gin/pull/2848) [#2851](https://github.com/gin-gonic/gin/pull/2851) [#2701](https://github.com/gin-gonic/gin/pull/2701) -* TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967) -* Test(route): expose performRequest func [#3012](https://github.com/gin-gonic/gin/pull/3012) -* Support h2c with prior knowledge [#1398](https://github.com/gin-gonic/gin/pull/1398) -* Feat attachment filename support utf8 [#3071](https://github.com/gin-gonic/gin/pull/3071) -* Feat: add StaticFileFS [#2749](https://github.com/gin-gonic/gin/pull/2749) -* Feat(context): return GIN Context from Value method [#2825](https://github.com/gin-gonic/gin/pull/2825) -* Feat: automatically SetMode to TestMode when run go test [#3139](https://github.com/gin-gonic/gin/pull/3139) -* Add TOML bining for gin [#3081](https://github.com/gin-gonic/gin/pull/3081) -* IPv6 add default trusted proxies [#3033](https://github.com/gin-gonic/gin/pull/3033) +- Use Header() instead of deprecated HeaderMap [#2694](https://github.com/gin-gonic/gin/pull/2694) +- RouterGroup.Handle regular match optimization of http method [#2685](https://github.com/gin-gonic/gin/pull/2685) +- Add support go-json, another drop-in json replacement [#2680](https://github.com/gin-gonic/gin/pull/2680) +- Use errors.New to replace fmt.Errorf will much better [#2707](https://github.com/gin-gonic/gin/pull/2707) +- Use Duration.Truncate for truncating precision [#2711](https://github.com/gin-gonic/gin/pull/2711) +- Get client IP when using Cloudflare [#2723](https://github.com/gin-gonic/gin/pull/2723) +- Optimize code adjust [#2700](https://github.com/gin-gonic/gin/pull/2700/files) +- Optimize code and reduce code cyclomatic complexity [#2737](https://github.com/gin-gonic/gin/pull/2737) +- Improve sliceValidateError.Error performance [#2765](https://github.com/gin-gonic/gin/pull/2765) +- Support custom struct tag [#2720](https://github.com/gin-gonic/gin/pull/2720) +- Improve router group tests [#2787](https://github.com/gin-gonic/gin/pull/2787) +- Fallback Context.Deadline() Context.Done() Context.Err() to Context.Request.Context() [#2769](https://github.com/gin-gonic/gin/pull/2769) +- Some codes optimize [#2830](https://github.com/gin-gonic/gin/pull/2830) [#2834](https://github.com/gin-gonic/gin/pull/2834) [#2838](https://github.com/gin-gonic/gin/pull/2838) [#2837](https://github.com/gin-gonic/gin/pull/2837) [#2788](https://github.com/gin-gonic/gin/pull/2788) [#2848](https://github.com/gin-gonic/gin/pull/2848) [#2851](https://github.com/gin-gonic/gin/pull/2851) [#2701](https://github.com/gin-gonic/gin/pull/2701) +- TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967) +- Test(route): expose performRequest func [#3012](https://github.com/gin-gonic/gin/pull/3012) +- Support h2c with prior knowledge [#1398](https://github.com/gin-gonic/gin/pull/1398) +- Feat attachment filename support utf8 [#3071](https://github.com/gin-gonic/gin/pull/3071) +- Feat: add StaticFileFS [#2749](https://github.com/gin-gonic/gin/pull/2749) +- Feat(context): return GIN Context from Value method [#2825](https://github.com/gin-gonic/gin/pull/2825) +- Feat: automatically SetMode to TestMode when run go test [#3139](https://github.com/gin-gonic/gin/pull/3139) +- Add TOML bining for gin [#3081](https://github.com/gin-gonic/gin/pull/3081) +- IPv6 add default trusted proxies [#3033](https://github.com/gin-gonic/gin/pull/3033) ### DOCS -* Add note about nomsgpack tag to the readme [#2703](https://github.com/gin-gonic/gin/pull/2703) +- Add note about nomsgpack tag to the readme [#2703](https://github.com/gin-gonic/gin/pull/2703) ## Gin v1.7.7 ### BUG FIXES -* Fixed X-Forwarded-For unsafe handling of CVE-2020-28483 [#2844](https://github.com/gin-gonic/gin/pull/2844), closed issue [#2862](https://github.com/gin-gonic/gin/issues/2862). -* Tree: updated the code logic for `latestNode` [#2897](https://github.com/gin-gonic/gin/pull/2897), closed issue [#2894](https://github.com/gin-gonic/gin/issues/2894) [#2878](https://github.com/gin-gonic/gin/issues/2878). -* Tree: fixed the misplacement of adding slashes [#2847](https://github.com/gin-gonic/gin/pull/2847), closed issue [#2843](https://github.com/gin-gonic/gin/issues/2843). -* Tree: fixed tsr with mixed static and wildcard paths [#2924](https://github.com/gin-gonic/gin/pull/2924), closed issue [#2918](https://github.com/gin-gonic/gin/issues/2918). +- Fixed X-Forwarded-For unsafe handling of CVE-2020-28483 [#2844](https://github.com/gin-gonic/gin/pull/2844), closed issue [#2862](https://github.com/gin-gonic/gin/issues/2862). +- Tree: updated the code logic for `latestNode` [#2897](https://github.com/gin-gonic/gin/pull/2897), closed issue [#2894](https://github.com/gin-gonic/gin/issues/2894) [#2878](https://github.com/gin-gonic/gin/issues/2878). +- Tree: fixed the misplacement of adding slashes [#2847](https://github.com/gin-gonic/gin/pull/2847), closed issue [#2843](https://github.com/gin-gonic/gin/issues/2843). +- Tree: fixed tsr with mixed static and wildcard paths [#2924](https://github.com/gin-gonic/gin/pull/2924), closed issue [#2918](https://github.com/gin-gonic/gin/issues/2918). ### ENHANCEMENTS -* TrustedProxies: make it backward-compatible [#2887](https://github.com/gin-gonic/gin/pull/2887), closed issue [#2819](https://github.com/gin-gonic/gin/issues/2819). -* TrustedPlatform: provide custom options for another CDN services [#2906](https://github.com/gin-gonic/gin/pull/2906). +- TrustedProxies: make it backward-compatible [#2887](https://github.com/gin-gonic/gin/pull/2887), closed issue [#2819](https://github.com/gin-gonic/gin/issues/2819). +- TrustedPlatform: provide custom options for another CDN services [#2906](https://github.com/gin-gonic/gin/pull/2906). ### DOCS -* NoMethod: added usage annotation ([#2832](https://github.com/gin-gonic/gin/pull/2832#issuecomment-929954463)). +- NoMethod: added usage annotation ([#2832](https://github.com/gin-gonic/gin/pull/2832#issuecomment-929954463)). ## Gin v1.7.6 ### BUG FIXES -* bump new release to fix v1.7.5 release error by using v1.7.4 codes. +- bump new release to fix v1.7.5 release error by using v1.7.4 codes. ## Gin v1.7.4 ### BUG FIXES -* bump new release to fix checksum mismatch +- bump new release to fix checksum mismatch ## Gin v1.7.3 ### BUG FIXES -* fix level 1 router match [#2767](https://github.com/gin-gonic/gin/issues/2767), [#2796](https://github.com/gin-gonic/gin/issues/2796) +- fix level 1 router match [#2767](https://github.com/gin-gonic/gin/issues/2767), [#2796](https://github.com/gin-gonic/gin/issues/2796) ## Gin v1.7.2 ### BUG FIXES -* Fix conflict between param and exact path [#2706](https://github.com/gin-gonic/gin/issues/2706). Close issue [#2682](https://github.com/gin-gonic/gin/issues/2682) [#2696](https://github.com/gin-gonic/gin/issues/2696). +- Fix conflict between param and exact path [#2706](https://github.com/gin-gonic/gin/issues/2706). Close issue [#2682](https://github.com/gin-gonic/gin/issues/2682) [#2696](https://github.com/gin-gonic/gin/issues/2696). ## Gin v1.7.1 ### BUG FIXES -* fix: data race with trustedCIDRs from [#2674](https://github.com/gin-gonic/gin/issues/2674)([#2675](https://github.com/gin-gonic/gin/pull/2675)) +- fix: data race with trustedCIDRs from [#2674](https://github.com/gin-gonic/gin/issues/2674)([#2675](https://github.com/gin-gonic/gin/pull/2675)) ## Gin v1.7.0 ### BUG FIXES -* fix compile error from [#2572](https://github.com/gin-gonic/gin/pull/2572) ([#2600](https://github.com/gin-gonic/gin/pull/2600)) -* fix: print headers without Authorization header on broken pipe ([#2528](https://github.com/gin-gonic/gin/pull/2528)) -* fix(tree): reassign fullpath when register new node ([#2366](https://github.com/gin-gonic/gin/pull/2366)) +- fix compile error from [#2572](https://github.com/gin-gonic/gin/pull/2572) ([#2600](https://github.com/gin-gonic/gin/pull/2600)) +- fix: print headers without Authorization header on broken pipe ([#2528](https://github.com/gin-gonic/gin/pull/2528)) +- fix(tree): reassign fullpath when register new node ([#2366](https://github.com/gin-gonic/gin/pull/2366)) ### ENHANCEMENTS -* Support params and exact routes without creating conflicts ([#2663](https://github.com/gin-gonic/gin/pull/2663)) -* chore: improve render string performance ([#2365](https://github.com/gin-gonic/gin/pull/2365)) -* Sync route tree to httprouter latest code ([#2368](https://github.com/gin-gonic/gin/pull/2368)) -* chore: rename getQueryCache/getFormCache to initQueryCache/initFormCa ([#2375](https://github.com/gin-gonic/gin/pull/2375)) -* chore(performance): improve countParams ([#2378](https://github.com/gin-gonic/gin/pull/2378)) -* Remove some functions that have the same effect as the bytes package ([#2387](https://github.com/gin-gonic/gin/pull/2387)) -* update:SetMode function ([#2321](https://github.com/gin-gonic/gin/pull/2321)) -* remove an unused type SecureJSONPrefix ([#2391](https://github.com/gin-gonic/gin/pull/2391)) -* Add a redirect sample for POST method ([#2389](https://github.com/gin-gonic/gin/pull/2389)) -* Add CustomRecovery builtin middleware ([#2322](https://github.com/gin-gonic/gin/pull/2322)) -* binding: avoid 2038 problem on 32-bit architectures ([#2450](https://github.com/gin-gonic/gin/pull/2450)) -* Prevent panic in Context.GetQuery() when there is no Request ([#2412](https://github.com/gin-gonic/gin/pull/2412)) -* Add GetUint and GetUint64 method on gin.context ([#2487](https://github.com/gin-gonic/gin/pull/2487)) -* update content-disposition header to MIME-style ([#2512](https://github.com/gin-gonic/gin/pull/2512)) -* reduce allocs and improve the render `WriteString` ([#2508](https://github.com/gin-gonic/gin/pull/2508)) -* implement ".Unwrap() error" on Error type ([#2525](https://github.com/gin-gonic/gin/pull/2525)) ([#2526](https://github.com/gin-gonic/gin/pull/2526)) -* Allow bind with a map[string]string ([#2484](https://github.com/gin-gonic/gin/pull/2484)) -* chore: update tree ([#2371](https://github.com/gin-gonic/gin/pull/2371)) -* Support binding for slice/array obj [Rewrite] ([#2302](https://github.com/gin-gonic/gin/pull/2302)) -* basic auth: fix timing oracle ([#2609](https://github.com/gin-gonic/gin/pull/2609)) -* Add mixed param and non-param paths (port of httprouter[#329](https://github.com/gin-gonic/gin/pull/329)) ([#2663](https://github.com/gin-gonic/gin/pull/2663)) -* feat(engine): add trustedproxies and remoteIP ([#2632](https://github.com/gin-gonic/gin/pull/2632)) +- Support params and exact routes without creating conflicts ([#2663](https://github.com/gin-gonic/gin/pull/2663)) +- chore: improve render string performance ([#2365](https://github.com/gin-gonic/gin/pull/2365)) +- Sync route tree to httprouter latest code ([#2368](https://github.com/gin-gonic/gin/pull/2368)) +- chore: rename getQueryCache/getFormCache to initQueryCache/initFormCa ([#2375](https://github.com/gin-gonic/gin/pull/2375)) +- chore(performance): improve countParams ([#2378](https://github.com/gin-gonic/gin/pull/2378)) +- Remove some functions that have the same effect as the bytes package ([#2387](https://github.com/gin-gonic/gin/pull/2387)) +- update:SetMode function ([#2321](https://github.com/gin-gonic/gin/pull/2321)) +- remove an unused type SecureJSONPrefix ([#2391](https://github.com/gin-gonic/gin/pull/2391)) +- Add a redirect sample for POST method ([#2389](https://github.com/gin-gonic/gin/pull/2389)) +- Add CustomRecovery builtin middleware ([#2322](https://github.com/gin-gonic/gin/pull/2322)) +- binding: avoid 2038 problem on 32-bit architectures ([#2450](https://github.com/gin-gonic/gin/pull/2450)) +- Prevent panic in Context.GetQuery() when there is no Request ([#2412](https://github.com/gin-gonic/gin/pull/2412)) +- Add GetUint and GetUint64 method on gin.context ([#2487](https://github.com/gin-gonic/gin/pull/2487)) +- update content-disposition header to MIME-style ([#2512](https://github.com/gin-gonic/gin/pull/2512)) +- reduce allocs and improve the render `WriteString` ([#2508](https://github.com/gin-gonic/gin/pull/2508)) +- implement ".Unwrap() error" on Error type ([#2525](https://github.com/gin-gonic/gin/pull/2525)) ([#2526](https://github.com/gin-gonic/gin/pull/2526)) +- Allow bind with a map[string]string ([#2484](https://github.com/gin-gonic/gin/pull/2484)) +- chore: update tree ([#2371](https://github.com/gin-gonic/gin/pull/2371)) +- Support binding for slice/array obj [Rewrite] ([#2302](https://github.com/gin-gonic/gin/pull/2302)) +- basic auth: fix timing oracle ([#2609](https://github.com/gin-gonic/gin/pull/2609)) +- Add mixed param and non-param paths (port of httprouter[#329](https://github.com/gin-gonic/gin/pull/329)) ([#2663](https://github.com/gin-gonic/gin/pull/2663)) +- feat(engine): add trustedproxies and remoteIP ([#2632](https://github.com/gin-gonic/gin/pull/2632)) ## Gin v1.6.3 ### ENHANCEMENTS - * Improve performance: Change `*sync.RWMutex` to `sync.RWMutex` in context. [#2351](https://github.com/gin-gonic/gin/pull/2351) +- Improve performance: Change `*sync.RWMutex` to `sync.RWMutex` in context. [#2351](https://github.com/gin-gonic/gin/pull/2351) ## Gin v1.6.2 ### BUG FIXES - * fix missing initial sync.RWMutex [#2305](https://github.com/gin-gonic/gin/pull/2305) +- fix missing initial sync.RWMutex [#2305](https://github.com/gin-gonic/gin/pull/2305) ### ENHANCEMENTS - * Add set samesite in cookie. [#2306](https://github.com/gin-gonic/gin/pull/2306) +- Add set samesite in cookie. [#2306](https://github.com/gin-gonic/gin/pull/2306) ## Gin v1.6.1 ### BUG FIXES - * Revert "fix accept incoming network connections" [#2294](https://github.com/gin-gonic/gin/pull/2294) +- Revert "fix accept incoming network connections" [#2294](https://github.com/gin-gonic/gin/pull/2294) ## Gin v1.6.0 ### BREAKING - * chore(performance): Improve performance for adding RemoveExtraSlash flag [#2159](https://github.com/gin-gonic/gin/pull/2159) - * drop support govendor [#2148](https://github.com/gin-gonic/gin/pull/2148) - * Added support for SameSite cookie flag [#1615](https://github.com/gin-gonic/gin/pull/1615) +- chore(performance): Improve performance for adding RemoveExtraSlash flag [#2159](https://github.com/gin-gonic/gin/pull/2159) +- drop support govendor [#2148](https://github.com/gin-gonic/gin/pull/2148) +- Added support for SameSite cookie flag [#1615](https://github.com/gin-gonic/gin/pull/1615) ### FEATURES - * add yaml negotiation [#2220](https://github.com/gin-gonic/gin/pull/2220) - * FileFromFS [#2112](https://github.com/gin-gonic/gin/pull/2112) +- add yaml negotiation [#2220](https://github.com/gin-gonic/gin/pull/2220) +- FileFromFS [#2112](https://github.com/gin-gonic/gin/pull/2112) ### BUG FIXES - * Unix Socket Handling [#2280](https://github.com/gin-gonic/gin/pull/2280) - * Use json marshall in context json to fix breaking new line issue. Fixes #2209 [#2228](https://github.com/gin-gonic/gin/pull/2228) - * fix accept incoming network connections [#2216](https://github.com/gin-gonic/gin/pull/2216) - * Fixed a bug in the calculation of the maximum number of parameters [#2166](https://github.com/gin-gonic/gin/pull/2166) - * [FIX] allow empty headers on DataFromReader [#2121](https://github.com/gin-gonic/gin/pull/2121) - * Add mutex for protect Context.Keys map [#1391](https://github.com/gin-gonic/gin/pull/1391) +- Unix Socket Handling [#2280](https://github.com/gin-gonic/gin/pull/2280) +- Use json marshall in context json to fix breaking new line issue. Fixes #2209 [#2228](https://github.com/gin-gonic/gin/pull/2228) +- fix accept incoming network connections [#2216](https://github.com/gin-gonic/gin/pull/2216) +- Fixed a bug in the calculation of the maximum number of parameters [#2166](https://github.com/gin-gonic/gin/pull/2166) +- [FIX] allow empty headers on DataFromReader [#2121](https://github.com/gin-gonic/gin/pull/2121) +- Add mutex for protect Context.Keys map [#1391](https://github.com/gin-gonic/gin/pull/1391) ### ENHANCEMENTS - * Add mitigation for log injection [#2277](https://github.com/gin-gonic/gin/pull/2277) - * tree: range over nodes values [#2229](https://github.com/gin-gonic/gin/pull/2229) - * tree: remove duplicate assignment [#2222](https://github.com/gin-gonic/gin/pull/2222) - * chore: upgrade go-isatty and json-iterator/go [#2215](https://github.com/gin-gonic/gin/pull/2215) - * path: sync code with httprouter [#2212](https://github.com/gin-gonic/gin/pull/2212) - * Use zero-copy approach to convert types between string and byte slice [#2206](https://github.com/gin-gonic/gin/pull/2206) - * Reuse bytes when cleaning the URL paths [#2179](https://github.com/gin-gonic/gin/pull/2179) - * tree: remove one else statement [#2177](https://github.com/gin-gonic/gin/pull/2177) - * tree: sync httprouter update (#2173) (#2172) [#2171](https://github.com/gin-gonic/gin/pull/2171) - * tree: sync part httprouter codes and reduce if/else [#2163](https://github.com/gin-gonic/gin/pull/2163) - * use http method constant [#2155](https://github.com/gin-gonic/gin/pull/2155) - * upgrade go-validator to v10 [#2149](https://github.com/gin-gonic/gin/pull/2149) - * Refactor redirect request in gin.go [#1970](https://github.com/gin-gonic/gin/pull/1970) - * Add build tag nomsgpack [#1852](https://github.com/gin-gonic/gin/pull/1852) +- Add mitigation for log injection [#2277](https://github.com/gin-gonic/gin/pull/2277) +- tree: range over nodes values [#2229](https://github.com/gin-gonic/gin/pull/2229) +- tree: remove duplicate assignment [#2222](https://github.com/gin-gonic/gin/pull/2222) +- chore: upgrade go-isatty and json-iterator/go [#2215](https://github.com/gin-gonic/gin/pull/2215) +- path: sync code with httprouter [#2212](https://github.com/gin-gonic/gin/pull/2212) +- Use zero-copy approach to convert types between string and byte slice [#2206](https://github.com/gin-gonic/gin/pull/2206) +- Reuse bytes when cleaning the URL paths [#2179](https://github.com/gin-gonic/gin/pull/2179) +- tree: remove one else statement [#2177](https://github.com/gin-gonic/gin/pull/2177) +- tree: sync httprouter update (#2173) (#2172) [#2171](https://github.com/gin-gonic/gin/pull/2171) +- tree: sync part httprouter codes and reduce if/else [#2163](https://github.com/gin-gonic/gin/pull/2163) +- use http method constant [#2155](https://github.com/gin-gonic/gin/pull/2155) +- upgrade go-validator to v10 [#2149](https://github.com/gin-gonic/gin/pull/2149) +- Refactor redirect request in gin.go [#1970](https://github.com/gin-gonic/gin/pull/1970) +- Add build tag nomsgpack [#1852](https://github.com/gin-gonic/gin/pull/1852) ### DOCS - * docs(path): improve comments [#2223](https://github.com/gin-gonic/gin/pull/2223) - * Renew README to fit the modification of SetCookie method [#2217](https://github.com/gin-gonic/gin/pull/2217) - * Fix spelling [#2202](https://github.com/gin-gonic/gin/pull/2202) - * Remove broken link from README. [#2198](https://github.com/gin-gonic/gin/pull/2198) - * Update docs on Context.Done(), Context.Deadline() and Context.Err() [#2196](https://github.com/gin-gonic/gin/pull/2196) - * Update validator to v10 [#2190](https://github.com/gin-gonic/gin/pull/2190) - * upgrade go-validator to v10 for README [#2189](https://github.com/gin-gonic/gin/pull/2189) - * Update to currently output [#2188](https://github.com/gin-gonic/gin/pull/2188) - * Fix "Custom Validators" example [#2186](https://github.com/gin-gonic/gin/pull/2186) - * Add project to README [#2165](https://github.com/gin-gonic/gin/pull/2165) - * docs(benchmarks): for gin v1.5 [#2153](https://github.com/gin-gonic/gin/pull/2153) - * Changed wording for clarity in README.md [#2122](https://github.com/gin-gonic/gin/pull/2122) +- docs(path): improve comments [#2223](https://github.com/gin-gonic/gin/pull/2223) +- Renew README to fit the modification of SetCookie method [#2217](https://github.com/gin-gonic/gin/pull/2217) +- Fix spelling [#2202](https://github.com/gin-gonic/gin/pull/2202) +- Remove broken link from README. [#2198](https://github.com/gin-gonic/gin/pull/2198) +- Update docs on Context.Done(), Context.Deadline() and Context.Err() [#2196](https://github.com/gin-gonic/gin/pull/2196) +- Update validator to v10 [#2190](https://github.com/gin-gonic/gin/pull/2190) +- upgrade go-validator to v10 for README [#2189](https://github.com/gin-gonic/gin/pull/2189) +- Update to currently output [#2188](https://github.com/gin-gonic/gin/pull/2188) +- Fix "Custom Validators" example [#2186](https://github.com/gin-gonic/gin/pull/2186) +- Add project to README [#2165](https://github.com/gin-gonic/gin/pull/2165) +- docs(benchmarks): for gin v1.5 [#2153](https://github.com/gin-gonic/gin/pull/2153) +- Changed wording for clarity in README.md [#2122](https://github.com/gin-gonic/gin/pull/2122) ### MISC - * ci support go1.14 [#2262](https://github.com/gin-gonic/gin/pull/2262) - * chore: upgrade depend version [#2231](https://github.com/gin-gonic/gin/pull/2231) - * Drop support go1.10 [#2147](https://github.com/gin-gonic/gin/pull/2147) - * fix comment in `mode.go` [#2129](https://github.com/gin-gonic/gin/pull/2129) +- ci support go1.14 [#2262](https://github.com/gin-gonic/gin/pull/2262) +- chore: upgrade depend version [#2231](https://github.com/gin-gonic/gin/pull/2231) +- Drop support go1.10 [#2147](https://github.com/gin-gonic/gin/pull/2147) +- fix comment in `mode.go` [#2129](https://github.com/gin-gonic/gin/pull/2129) ## Gin v1.5.0 @@ -485,14 +534,14 @@ ### Gin v1.4.0 -- [NEW] Support for [Go Modules](https://github.com/golang/go/wiki/Modules) [#1569](https://github.com/gin-gonic/gin/pull/1569) +- [NEW] Support for [Go Modules](https://github.com/golang/go/wiki/Modules) [#1569](https://github.com/gin-gonic/gin/pull/1569) - [NEW] Refactor of form mapping multipart request [#1829](https://github.com/gin-gonic/gin/pull/1829) - [FIX] Truncate Latency precision in long running request [#1830](https://github.com/gin-gonic/gin/pull/1830) - [FIX] IsTerm flag should not be affected by DisableConsoleColor method. [#1802](https://github.com/gin-gonic/gin/pull/1802) - [NEW] Supporting file binding [#1264](https://github.com/gin-gonic/gin/pull/1264) - [NEW] Add support for mapping arrays [#1797](https://github.com/gin-gonic/gin/pull/1797) - [FIX] Readme updates [#1793](https://github.com/gin-gonic/gin/pull/1793) [#1788](https://github.com/gin-gonic/gin/pull/1788) [1789](https://github.com/gin-gonic/gin/pull/1789) -- [FIX] StaticFS: Fixed Logging two log lines on 404. [#1805](https://github.com/gin-gonic/gin/pull/1805), [#1804](https://github.com/gin-gonic/gin/pull/1804) +- [FIX] StaticFS: Fixed Logging two log lines on 404. [#1805](https://github.com/gin-gonic/gin/pull/1805), [#1804](https://github.com/gin-gonic/gin/pull/1804) - [NEW] Make context.Keys available as LogFormatterParams [#1779](https://github.com/gin-gonic/gin/pull/1779) - [NEW] Use internal/json for Marshal/Unmarshal [#1791](https://github.com/gin-gonic/gin/pull/1791) - [NEW] Support mapping time.Duration [#1794](https://github.com/gin-gonic/gin/pull/1794) @@ -524,7 +573,7 @@ - [NEW] RunFd method to run http.Server through a file descriptor [#1609](https://github.com/gin-gonic/gin/pull/1609) - [NEW] Yaml binding support [#1618](https://github.com/gin-gonic/gin/pull/1618) - [FIX] Pass MaxMultipartMemory when FormFile is called [#1600](https://github.com/gin-gonic/gin/pull/1600) -- [FIX] LoadHTML* tests [#1559](https://github.com/gin-gonic/gin/pull/1559) +- [FIX] LoadHTML\* tests [#1559](https://github.com/gin-gonic/gin/pull/1559) - [FIX] Removed use of sync.pool from HandleContext [#1565](https://github.com/gin-gonic/gin/pull/1565) - [FIX] Format output log to os.Stderr [#1571](https://github.com/gin-gonic/gin/pull/1571) - [FIX] Make logger use a yellow background and a darkgray text for legibility [#1570](https://github.com/gin-gonic/gin/pull/1570) @@ -539,7 +588,6 @@ - [FIX] Add BindXML and ShouldBindXML [#1485](https://github.com/gin-gonic/gin/pull/1485) - [NEW] Upgrade dependency libraries [#1491](https://github.com/gin-gonic/gin/pull/1491) - ## Gin v1.3.0 - [NEW] Add [`func (*Context) QueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.QueryMap), [`func (*Context) GetQueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetQueryMap), [`func (*Context) PostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.PostFormMap) and [`func (*Context) GetPostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetPostFormMap) to support `type map[string]string` as query string or form parameters, see [#1383](https://github.com/gin-gonic/gin/pull/1383) @@ -637,7 +685,6 @@ - [FIX] Error implements the json.Marshaller interface - [FIX] MIT license in every file - ## Gin 1.0rc1 (May 22, 2015) - [PERFORMANCE] Zero allocation router @@ -681,7 +728,6 @@ - [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 @@ -691,14 +737,12 @@ - [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 @@ -707,7 +751,6 @@ - [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. @@ -725,8 +768,8 @@ - [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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9703d6b4..3b05a160 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,6 +36,6 @@ Please ensure your pull request meets the following requirements: - All tests pass in available continuous integration systems (e.g., GitHub Actions). - Add or modify tests to cover your code changes. - If your pull request introduces a new feature, document it in [`docs/doc.md`](docs/doc.md), not in the README. -- Follow the checklist in the [Pull Request Template](.github/PULL_REQUEST_TEMPLATE.md:1). +- Follow the checklist in the [Pull Request Template](.github/PULL_REQUEST_TEMPLATE.md). Thank you for contributing! diff --git a/LICENSE b/LICENSE index 1ff7f370..49770f0c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014 Manuel Martínez-Almeida +Copyright (c) 2014-present 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 diff --git a/Makefile b/Makefile index 1a7de86b..3c2da3b1 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ GO_VERSION=$(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2) PACKAGES ?= $(shell $(GO) list ./...) VETPACKAGES ?= $(shell $(GO) list ./... | grep -v /examples/) GOFILES := $(shell find . -name "*.go") -TESTFOLDER := $(shell $(GO) list ./... | grep -E 'gin$$|binding$$|render$$' | grep -v examples) +TESTFOLDER := $(shell $(GO) list ./... | grep -E 'gin$$|ginS$$|binding$$|render$$' | grep -v examples) TESTTAGS ?= "" .PHONY: test @@ -12,7 +12,11 @@ TESTTAGS ?= "" test: echo "mode: count" > coverage.out for d in $(TESTFOLDER); do \ - $(GO) test $(TESTTAGS) -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \ + if [ -n "$(TESTTAGS)" ]; then \ + $(GO) test $(TESTTAGS) -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \ + else \ + $(GO) test -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \ + fi; \ cat tmp.out; \ if grep -q "^--- FAIL" tmp.out; then \ rm tmp.out; \ diff --git a/README.md b/README.md index 1b9ab808..10e627fc 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,9 @@ [![Open Source Helpers](https://www.codetriage.com/gin-gonic/gin/badges/users.svg)](https://www.codetriage.com/gin-gonic/gin) [![Release](https://img.shields.io/github/release/gin-gonic/gin.svg?style=flat-square)](https://github.com/gin-gonic/gin/releases) -## 📰 [Announcing Gin 1.11.0!](https://gin-gonic.com/en/blog/news/gin-1-11-0-release-announcement/) +## 📰 Gin 1.12.0 is now available! -Read about the latest features and improvements in Gin 1.11.0 on our official blog. +We're excited to announce the release of **[Gin 1.12.0](https://gin-gonic.com/en/blog/news/gin-1-12-0-release-announcement/)**! This release brings new features, performance improvements, and important bug fixes. Check out the [release announcement](https://gin-gonic.com/en/blog/news/gin-1-12-0-release-announcement/) on our official blog for the full details. --- @@ -44,7 +44,7 @@ Gin combines the simplicity of Express.js-style routing with Go's performance ch ### Prerequisites -- **Go version**: Gin requires [Go](https://go.dev/) version [1.24](https://go.dev/doc/devel/release#go1.24.0) or above +- **Go version**: Gin requires [Go](https://go.dev/) version [1.26](https://go.dev/doc/devel/release#go1.26.0) or above - **Basic Go knowledge**: Familiarity with Go syntax and package management is helpful ### Installation @@ -209,7 +209,7 @@ Gin powers many high-traffic applications and services in production: ## 🤝 Contributing -Gin is the work of hundreds of contributors from around the world. We welcome and appreciate your contributions! +Gin is the work of hundreds of contributors from around the world. We welcome and appreciate your contributions! See the full list of [contributors](https://github.com/gin-gonic/gin/graphs/contributors). ### How to Contribute diff --git a/binding/binding.go b/binding/binding.go index 702d0e82..eced0ae2 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -23,6 +23,7 @@ const ( MIMEYAML = "application/x-yaml" MIMEYAML2 = "application/yaml" MIMETOML = "application/toml" + MIMEBSON = "application/bson" ) // Binding describes the interface which needs to be implemented for binding the @@ -86,6 +87,7 @@ var ( Header Binding = headerBinding{} Plain BindingBody = plainBinding{} TOML BindingBody = tomlBinding{} + BSON BindingBody = bsonBinding{} ) // Default returns the appropriate Binding instance based on the HTTP method @@ -110,6 +112,8 @@ func Default(method, contentType string) Binding { return TOML case MIMEMultipartPOSTForm: return FormMultipart + case MIMEBSON: + return BSON default: // case MIMEPOSTForm: return Form } diff --git a/binding/binding_nomsgpack.go b/binding/binding_nomsgpack.go index c8e61310..ae364d79 100644 --- a/binding/binding_nomsgpack.go +++ b/binding/binding_nomsgpack.go @@ -21,6 +21,7 @@ const ( MIMEYAML = "application/x-yaml" MIMEYAML2 = "application/yaml" MIMETOML = "application/toml" + MIMEBSON = "application/bson" ) // Binding describes the interface which needs to be implemented for binding the @@ -82,6 +83,7 @@ var ( Header = headerBinding{} TOML = tomlBinding{} Plain = plainBinding{} + BSON BindingBody = bsonBinding{} ) // Default returns the appropriate Binding instance based on the HTTP method @@ -104,6 +106,8 @@ func Default(method, contentType string) Binding { return FormMultipart case MIMETOML: return TOML + case MIMEBSON: + return BSON default: // case MIMEPOSTForm: return Form } diff --git a/binding/binding_test.go b/binding/binding_test.go index 07619ebf..f90488cd 100644 --- a/binding/binding_test.go +++ b/binding/binding_test.go @@ -21,6 +21,7 @@ import ( "github.com/gin-gonic/gin/testdata/protoexample" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.mongodb.org/mongo-driver/v2/bson" "google.golang.org/protobuf/proto" ) @@ -172,6 +173,9 @@ func TestBindingDefault(t *testing.T) { assert.Equal(t, TOML, Default(http.MethodPost, MIMETOML)) assert.Equal(t, TOML, Default(http.MethodPut, MIMETOML)) + + assert.Equal(t, BSON, Default(http.MethodPost, MIMEBSON)) + assert.Equal(t, BSON, Default(http.MethodPut, MIMEBSON)) } func TestBindingJSONNilBody(t *testing.T) { @@ -731,6 +735,18 @@ func TestBindingProtoBufFail(t *testing.T) { string(data), string(data[1:])) } +func TestBindingBSON(t *testing.T) { + var obj FooStruct + obj.Foo = "bar" + data, _ := bson.Marshal(&obj) + testBodyBinding(t, + BSON, "bson", + "/", "/", + string(data), + // note: for badbody, we remove first byte to make it invalid + string(data[1:])) +} + func TestValidationFails(t *testing.T) { var obj FooStruct req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`) diff --git a/binding/bson.go b/binding/bson.go new file mode 100644 index 00000000..464890f0 --- /dev/null +++ b/binding/bson.go @@ -0,0 +1,30 @@ +// Copyright 2025 Gin Core Team. 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" + "net/http" + + "go.mongodb.org/mongo-driver/v2/bson" +) + +type bsonBinding struct{} + +func (bsonBinding) Name() string { + return "bson" +} + +func (b bsonBinding) Bind(req *http.Request, obj any) error { + buf, err := io.ReadAll(req.Body) + if err == nil { + err = b.BindBody(buf, obj) + } + return err +} + +func (bsonBinding) BindBody(body []byte, obj any) error { + return bson.Unmarshal(body, obj) +} diff --git a/binding/default_validator.go b/binding/default_validator.go index 8203bcaa..f27d437b 100644 --- a/binding/default_validator.go +++ b/binding/default_validator.go @@ -32,7 +32,10 @@ func (err SliceValidationError) Error() string { if b.Len() > 0 { b.WriteString("\n") } - b.WriteString("[" + strconv.Itoa(i) + "]: " + err[i].Error()) + b.WriteString("[") + b.WriteString(strconv.Itoa(i)) + b.WriteString("]: ") + b.WriteString(err[i].Error()) } } return b.String() diff --git a/codecov.yml b/codecov.yml index 47782e50..f78e4295 100644 --- a/codecov.yml +++ b/codecov.yml @@ -1,6 +1,7 @@ -coverage: +codecov: require_ci_to_pass: true +coverage: status: project: default: diff --git a/context.go b/context.go index c7bc61fe..582d00f2 100644 --- a/context.go +++ b/context.go @@ -40,6 +40,7 @@ const ( MIMEYAML2 = binding.MIMEYAML2 MIMETOML = binding.MIMETOML MIMEPROTOBUF = binding.MIMEPROTOBUF + MIMEBSON = binding.MIMEBSON ) // BodyBytesKey indicates a default body bytes key. @@ -131,15 +132,24 @@ func (c *Context) Copy() *Context { cp.handlers = nil cp.fullPath = c.fullPath - cKeys := c.Keys c.mu.RLock() - cp.Keys = maps.Clone(cKeys) + cp.Keys = maps.Clone(c.Keys) c.mu.RUnlock() cParams := c.Params cp.Params = make([]Param, len(cParams)) copy(cp.Params, cParams) + if c.Errors != nil { + cp.Errors = make(errorMsgs, len(c.Errors)) + copy(cp.Errors, c.Errors) + } + + if c.Accepted != nil { + cp.Accepted = make([]string, len(c.Accepted)) + copy(cp.Accepted, c.Accepted) + } + return &cp } @@ -618,8 +628,8 @@ func (c *Context) DefaultPostForm(key, defaultValue string) string { // 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 +// 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 @@ -715,6 +725,11 @@ func (c *Context) MultipartForm() (*multipart.Form, error) { } // SaveUploadedFile uploads the form file to specific dst. +// An optional perm argument specifies the permission bits used when creating +// the destination directory. If not provided, the default is 0750. The exact +// permission is enforced only on the destination directory and only when it is +// newly created by this call; pre-existing directories (e.g. /tmp) are not +// modified. func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm ...fs.FileMode) error { src, err := file.Open() if err != nil { @@ -727,11 +742,19 @@ func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm mode = perm[0] } dir := filepath.Dir(dst) + // Record whether the destination directory exists before MkdirAll, so we + // only chmod a directory we just created. Chmod'ing a pre-existing directory + // the process does not own (e.g. /tmp) fails with "operation not permitted" + // (#4622). A non-ErrNotExist stat error also skips chmod and lets MkdirAll + // surface the underlying failure. + _, statErr := os.Stat(dir) if err = os.MkdirAll(dir, mode); err != nil { return err } - if err = os.Chmod(dir, mode); err != nil { - return err + if errors.Is(statErr, os.ErrNotExist) { + if err = os.Chmod(dir, mode); err != nil { + return err + } } out, err := os.Create(dst) @@ -750,8 +773,8 @@ func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm // "application/json" --> JSON binding // "application/xml" --> XML binding // -// 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. +// It parses the request's body based on the Content-Type (e.g., JSON or XML). +// It decodes the payload into the struct specified as a pointer. // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid. func (c *Context) Bind(obj any) error { b := binding.Default(c.Request.Method, c.ContentType()) @@ -763,7 +786,7 @@ func (c *Context) BindJSON(obj any) error { return c.MustBindWith(obj, binding.JSON) } -// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML). +// BindXML is a shortcut for c.MustBindWith(obj, binding.XML). func (c *Context) BindXML(obj any) error { return c.MustBindWith(obj, binding.XML) } @@ -831,8 +854,8 @@ func (c *Context) MustBindWith(obj any, b binding.Binding) error { // "application/json" --> JSON binding // "application/xml" --> XML binding // -// 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. +// It parses the request's body based on the Content-Type (e.g., JSON or XML). +// It decodes the payload into the struct specified as a pointer. // Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid. func (c *Context) ShouldBind(obj any) error { b := binding.Default(c.Request.Method, c.ContentType()) @@ -1046,6 +1069,33 @@ func (c *Context) IsWebsocket() bool { return false } +// Scheme returns the HTTP scheme of the request ("http" or "https"). +// When running behind reverse proxies or load balancers `Request.URL.Scheme` is usually empty. +// the original scheme is commonly forwarded via headers such as X-Forwarded-Proto. +// Reference: +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Proto +func (c *Context) Scheme() string { + if c.Request.TLS != nil { + return "https" + } + if scheme := c.requestHeader("X-Forwarded-Proto"); scheme != "" { + return scheme + } + if scheme := c.requestHeader("X-Forwarded-Protocol"); scheme != "" { + return scheme + } + if ssl := c.requestHeader("X-Forwarded-Ssl"); ssl == "on" { + return "https" + } + if scheme := c.requestHeader("X-Url-Scheme"); scheme != "" { + return scheme + } + if scheme := c.Request.URL.Scheme; scheme != "" { + return scheme + } + return "http" +} + func (c *Context) requestHeader(key string) string { return c.Request.Header.Get(key) } @@ -1055,9 +1105,10 @@ func (c *Context) requestHeader(key string) string { /************************************/ // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function. +// Uses http.StatusContinue constant for better code clarity. func bodyAllowedForStatus(status int) bool { switch { - case status >= 100 && status <= 199: + case status >= http.StatusContinue && status < http.StatusOK: return false case status == http.StatusNoContent: return false @@ -1167,6 +1218,11 @@ func (c *Context) Render(code int, r render.Render) { // 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 any) { + if c.engine.HTMLRender == nil { + c.Render(code, render.HTML{}) + return + } + instance := c.engine.HTMLRender.Instance(name, obj) c.Render(code, instance) } @@ -1180,7 +1236,7 @@ func (c *Context) IndentedJSON(code int, obj any) { } // SecureJSON serializes the given struct as Secure JSON into the response body. -// Default prepends "while(1)," to response body if the given struct is array values. +// Default prepends "while(1);" to response body if the given struct is array values. // It also sets the Content-Type as "application/json". func (c *Context) SecureJSON(code int, obj any) { c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj}) @@ -1222,6 +1278,12 @@ func (c *Context) XML(code int, obj any) { c.Render(code, render.XML{Data: obj}) } +// PDF writes the given PDF binary data into the response body. +// It also sets the Content-Type as "application/pdf". +func (c *Context) PDF(code int, data []byte) { + c.Render(code, render.PDF{Data: data}) +} + // YAML serializes the given struct as YAML into the response body. func (c *Context) YAML(code int, obj any) { c.Render(code, render.YAML{Data: obj}) @@ -1237,6 +1299,11 @@ func (c *Context) ProtoBuf(code int, obj any) { c.Render(code, render.ProtoBuf{Data: obj}) } +// BSON serializes the given struct as BSON into the response body. +func (c *Context) BSON(code int, obj any) { + c.Render(code, render.BSON{Data: obj}) +} + // String writes the given string into the response body. func (c *Context) String(code int, format string, values ...any) { c.Render(code, render.String{Format: format, Data: values}) @@ -1344,6 +1411,7 @@ type Negotiate struct { Data any TOMLData any PROTOBUFData any + BSONData any } // Negotiate calls different Render according to acceptable Accept format. @@ -1373,6 +1441,10 @@ func (c *Context) Negotiate(code int, config Negotiate) { data := chooseData(config.PROTOBUFData, config.Data) c.ProtoBuf(code, data) + case binding.MIMEBSON: + data := chooseData(config.BSONData, config.Data) + c.BSON(code, data) + default: c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) //nolint: errcheck } diff --git a/context_test.go b/context_test.go index cb534884..b82e04d5 100644 --- a/context_test.go +++ b/context_test.go @@ -7,6 +7,7 @@ package gin import ( "bytes" "context" + "crypto/tls" "errors" "fmt" "html/template" @@ -32,6 +33,7 @@ import ( testdata "github.com/gin-gonic/gin/testdata/protoexample" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.mongodb.org/mongo-driver/v2/bson" "google.golang.org/protobuf/proto" ) @@ -246,13 +248,11 @@ func TestSaveUploadedFileWithPermission(t *testing.T) { require.NoError(t, err) assert.Equal(t, "permission_test", f.Filename) var mode fs.FileMode = 0o755 - require.NoError(t, c.SaveUploadedFile(f, "permission_test", mode)) - t.Cleanup(func() { - assert.NoError(t, os.Remove("permission_test")) - }) - info, err := os.Stat(filepath.Dir("permission_test")) + dst := filepath.Join(t.TempDir(), "subdir", "permission_test") + require.NoError(t, c.SaveUploadedFile(f, dst, mode)) + info, err := os.Stat(filepath.Dir(dst)) require.NoError(t, err) - assert.Equal(t, info.Mode().Perm(), mode) + assert.Equal(t, mode, info.Mode().Perm()) } func TestSaveUploadedFileWithPermissionFailed(t *testing.T) { @@ -270,7 +270,52 @@ func TestSaveUploadedFileWithPermissionFailed(t *testing.T) { require.NoError(t, err) assert.Equal(t, "permission_test", f.Filename) var mode fs.FileMode = 0o644 - require.Error(t, c.SaveUploadedFile(f, "test/permission_test", mode)) + dst := filepath.Join(t.TempDir(), "test", "permission_test") + require.Error(t, c.SaveUploadedFile(f, dst, mode)) +} + +// TestSaveUploadedFileToExistingDir is a regression test for issue #4622. +// SaveUploadedFile must not call os.Chmod on a directory that already exists, +// because the process may not own it (e.g. /tmp on Linux/macOS), where chmod +// fails with "operation not permitted". This asserts the behavioral contract +// directly — a pre-existing directory's permissions are left unchanged — so it +// catches the regression on every platform, including environments (root/CI, +// user-owned $TMPDIR) where chmod on the temp dir would otherwise succeed. +func TestSaveUploadedFileToExistingDir(t *testing.T) { + buf := new(bytes.Buffer) + mw := multipart.NewWriter(buf) + w, err := mw.CreateFormFile("file", "existing_dir_test") + require.NoError(t, err) + _, err = w.Write([]byte("existing_dir_test")) + require.NoError(t, err) + mw.Close() + + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) + c.Request.Header.Set("Content-Type", mw.FormDataContentType()) + f, err := c.FormFile("file") + require.NoError(t, err) + + // A pre-existing directory owned by this process, set to a known mode. + dir := t.TempDir() + require.NoError(t, os.Chmod(dir, 0o700)) + + // Pass a perm that differs from the directory's current mode. The fix must + // not apply it to the pre-existing directory; the old code chmod'd it + // unconditionally, which also failed outright on unowned dirs like /tmp. + dst := filepath.Join(dir, "existing_dir_test.txt") + require.NoError(t, c.SaveUploadedFile(f, dst, 0o755)) + + // The pre-existing directory's permissions must be unchanged. + info, err := os.Stat(dir) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), info.Mode().Perm(), + "permissions of a pre-existing directory must not be modified") + + // The file must still be written with the correct content. + content, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, "existing_dir_test", string(content)) } func TestContextReset(t *testing.T) { @@ -664,6 +709,30 @@ func TestContextGetStringMapStringSlice(t *testing.T) { assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"]) } +func TestCopyConcurrentWithSet(t *testing.T) { + c := &Context{} + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + c.Set(i, i) + } + }() + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + cp := c.Copy() + for k, v := range cp.Keys { + if k != v { + t.Errorf("copied key %v = %v, want %v", k, v, k) + } + } + } + }() + wg.Wait() +} + func TestContextCopy(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.index = 2 @@ -687,6 +756,50 @@ func TestContextCopy(t *testing.T) { assert.Equal(t, cp.fullPath, c.fullPath) } +func TestContextCopyCopiesErrors(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + _ = c.Error(errors.New("first error")) + _ = c.Error(errors.New("second error")) + + cp := c.Copy() + + // copied context has the same errors + assert.Len(t, cp.Errors, 2) + assert.Equal(t, c.Errors[0].Error(), cp.Errors[0].Error()) + assert.Equal(t, c.Errors[1].Error(), cp.Errors[1].Error()) + + // mutations on the copy do not affect the original + _ = cp.Error(errors.New("third error")) + assert.Len(t, c.Errors, 2) + assert.Len(t, cp.Errors, 3) +} + +func TestContextCopyCopiesAccepted(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.SetAccepted("application/json", "text/html") + + cp := c.Copy() + + assert.Equal(t, c.Accepted, cp.Accepted) + + // mutations on the copy do not affect the original + cp.SetAccepted("text/plain") + assert.Equal(t, []string{"application/json", "text/html"}, c.Accepted) + assert.Equal(t, []string{"text/plain"}, cp.Accepted) +} + +func TestContextCopyNilErrorsAndAccepted(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + + cp := c.Copy() + + assert.Nil(t, cp.Errors) + assert.Nil(t, cp.Accepted) +} + func TestContextHandlerName(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest} @@ -1030,6 +1143,7 @@ func TestContextGetCookie(t *testing.T) { } func TestContextBodyAllowedForStatus(t *testing.T) { + assert.False(t, bodyAllowedForStatus(http.StatusContinue)) assert.False(t, bodyAllowedForStatus(http.StatusProcessing)) assert.False(t, bodyAllowedForStatus(http.StatusNoContent)) assert.False(t, bodyAllowedForStatus(http.StatusNotModified)) @@ -1255,6 +1369,82 @@ func TestContextRenderHTML(t *testing.T) { assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } +func TestContextRenderHTMLWithoutRenderer(t *testing.T) { + tests := []struct { + name string + method string + status int + wantErrors []string + wantAborted bool + wantNextCalled bool + }{ + { + name: "body allowed", + method: http.MethodGet, + status: http.StatusAccepted, + wantErrors: []string{"html renderer is not configured"}, + wantAborted: true, + }, + { + name: "no content", + method: http.MethodGet, + status: http.StatusNoContent, + wantNextCalled: true, + }, + { + name: "not modified", + method: http.MethodGet, + status: http.StatusNotModified, + wantNextCalled: true, + }, + { + name: "head", + method: http.MethodHead, + status: http.StatusOK, + wantErrors: []string{"html renderer is not configured"}, + wantAborted: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := httptest.NewRecorder() + router := New() + var contextErrors []string + var contextAborted bool + nextHandlerCalled := false + + handlers := []HandlerFunc{ + func(c *Context) { + c.HTML(tt.status, "index.tmpl", H{"title": "Main website"}) + contextErrors = c.Errors.Errors() + contextAborted = c.IsAborted() + }, + func(_ *Context) { + nextHandlerCalled = true + }, + } + if tt.method == http.MethodHead { + router.HEAD("/", handlers...) + } else { + router.GET("/", handlers...) + } + + req := httptest.NewRequest(tt.method, "/", nil) + require.NotPanics(t, func() { + router.ServeHTTP(w, req) + }) + + assert.Equal(t, tt.status, w.Code) + assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) + assert.Equal(t, tt.wantErrors, contextErrors) + assert.Equal(t, tt.wantAborted, contextAborted) + assert.Equal(t, tt.wantNextCalled, nextHandlerCalled) + assert.Empty(t, w.Body.String()) + }) + } +} + func TestContextRenderHTML2(t *testing.T) { w := httptest.NewRecorder() c, router := CreateTestContext(w) @@ -1318,6 +1508,33 @@ func TestContextRenderNoContentXML(t *testing.T) { assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) } +// TestContextRenderPDF tests that the response is serialized as PDF +// and Content-Type is set to application/pdf +func TestContextRenderPDF(t *testing.T) { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + + data := []byte("%Test pdf content") + c.PDF(http.StatusCreated, data) + + assert.Equal(t, http.StatusCreated, w.Code) + assert.Equal(t, data, w.Body.Bytes()) + assert.Equal(t, "application/pdf", w.Header().Get("Content-Type")) +} + +// Tests that no PDF is rendered if code is 204 +func TestContextRenderNoContentPDF(t *testing.T) { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + + data := []byte("%Test pdf content") + c.PDF(http.StatusNoContent, data) + + assert.Equal(t, http.StatusNoContent, w.Code) + assert.Empty(t, w.Body.Bytes()) + assert.Equal(t, "application/pdf", w.Header().Get("Content-Type")) +} + // TestContextRenderString tests that the response is returned // with Content-Type set to text/plain func TestContextRenderString(t *testing.T) { @@ -1701,6 +1918,23 @@ func TestContextNegotiationWithPROTOBUF(t *testing.T) { assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type")) } +func TestContextNegotiationWithBSON(t *testing.T) { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + c.Request, _ = http.NewRequest(http.MethodPost, "", nil) + + c.Negotiate(http.StatusOK, Negotiate{ + Offered: []string{MIMEBSON, MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2}, + Data: H{"foo": "bar"}, + }) + + bData, _ := bson.Marshal(H{"foo": "bar"}) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, string(bData), w.Body.String()) + assert.Equal(t, "application/bson", w.Header().Get("Content-Type")) +} + func TestContextNegotiationNotSupport(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) @@ -2909,6 +3143,65 @@ func TestWebsocketsRequired(t *testing.T) { assert.False(t, c.IsWebsocket()) } +func TestContextScheme(t *testing.T) { + // TLS connection takes highest priority. + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.TLS = &tls.ConnectionState{} + assert.Equal(t, "https", c.Scheme()) + + // X-Forwarded-Proto header. + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.Header.Set("X-Forwarded-Proto", "https") + assert.Equal(t, "https", c.Scheme()) + + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.Header.Set("X-Forwarded-Proto", "http") + assert.Equal(t, "http", c.Scheme()) + + // X-Forwarded-Protocol header. + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.Header.Set("X-Forwarded-Protocol", "https") + assert.Equal(t, "https", c.Scheme()) + + // X-Forwarded-Ssl: on header. + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.Header.Set("X-Forwarded-Ssl", "on") + assert.Equal(t, "https", c.Scheme()) + + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.Header.Set("X-Forwarded-Ssl", "off") + assert.Equal(t, "http", c.Scheme()) + + // X-Url-Scheme header. + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.Header.Set("X-Url-Scheme", "https") + assert.Equal(t, "https", c.Scheme()) + + // Request.URL.Scheme fallback. + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "https://example.com/", nil) + assert.Equal(t, "https", c.Scheme()) + + // Default fallback: plain http. + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + assert.Equal(t, "http", c.Scheme()) + + // TLS takes priority over X-Forwarded-Proto. + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.Request.TLS = &tls.ConnectionState{} + c.Request.Header.Set("X-Forwarded-Proto", "http") + assert.Equal(t, "https", c.Scheme()) +} + func TestGetRequestHeaderValue(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodGet, "/chat", nil) @@ -2929,6 +3222,16 @@ func TestContextGetRawData(t *testing.T) { assert.Equal(t, "Fetch binary post data", string(data)) } +func TestContextGetRawDataNilBody(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodPost, "/", nil) + + data, err := c.GetRawData() + assert.Nil(t, data) + require.Error(t, err) + assert.Equal(t, "cannot read nil body", err.Error()) +} + func TestContextRenderDataFromReader(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) @@ -3517,6 +3820,24 @@ func TestContextSetCookieData(t *testing.T) { setCookie := c.Writer.Header().Get("Set-Cookie") assert.Contains(t, setCookie, "SameSite=None") }) + + // Test that SameSiteDefaultMode inherits from context's sameSite + t.Run("SameSiteDefaultMode inherits context sameSite", func(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.SetSameSite(http.SameSiteStrictMode) + cookie := &http.Cookie{ + Name: "user", + Value: "gin", + Path: "/", + Domain: "localhost", + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteDefaultMode, + } + c.SetCookieData(cookie) + setCookie := c.Writer.Header().Get("Set-Cookie") + assert.Contains(t, setCookie, "SameSite=Strict") + }) } func TestGetMapFromFormData(t *testing.T) { diff --git a/debug.go b/debug.go index 1cfa3721..753c1285 100644 --- a/debug.go +++ b/debug.go @@ -13,7 +13,7 @@ import ( "sync/atomic" ) -const ginSupportMinGoVer = 24 +const ginSupportMinGoVer = 25 var runtimeVersion = runtime.Version() @@ -80,7 +80,7 @@ func getMinVer(v string) (uint64, error) { func debugPrintWARNINGDefault() { if v, e := getMinVer(runtimeVersion); e == nil && v < ginSupportMinGoVer { - debugPrint(`[WARNING] Now Gin requires Go 1.24+. + debugPrint(`[WARNING] Now Gin requires Go 1.25+. `) } diff --git a/debug_test.go b/debug_test.go index dab02133..bf115ceb 100644 --- a/debug_test.go +++ b/debug_test.go @@ -121,7 +121,7 @@ func TestDebugPrintWARNINGDefaultWithUnsupportedVersion(t *testing.T) { debugPrintWARNINGDefault() SetMode(TestMode) }) - assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.24+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) + assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.25+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } func TestDebugPrintWARNINGNew(t *testing.T) { diff --git a/docs/doc.md b/docs/doc.md index 449c8d02..01edf52c 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -4,9 +4,10 @@ - [Build Tags](#build-tags) - [Build with json replacement](#build-with-json-replacement) - - [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature) -- [API Examples](#api-examples) + - [Build without MsgPack rendering feature](#build-without-msgpack-rendering-feature) +- [Routing](#routing) - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options) + - [Using the QUERY method](#using-the-query-method) - [Parameters in path](#parameters-in-path) - [Querystring parameters](#querystring-parameters) - [Multipart/Urlencoded Form](#multiparturlencoded-form) @@ -16,23 +17,37 @@ - [Single file](#single-file) - [Multiple files](#multiple-files) - [Grouping routes](#grouping-routes) + - [Redirects](#redirects) +- [Middleware](#middleware) - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default) - [Using middleware](#using-middleware) + - [Custom Middleware](#custom-middleware) - [Custom Recovery behavior](#custom-recovery-behavior) + - [Using BasicAuth() middleware](#using-basicauth-middleware) + - [Goroutines inside a middleware](#goroutines-inside-a-middleware) +- [Logging](#logging) - [How to write log file](#how-to-write-log-file) - [Custom Log Format](#custom-log-format) + - [Skip logging](#skip-logging) - [Controlling Log output coloring](#controlling-log-output-coloring) + - [Avoid logging query strings](#avoid-logging-query-strings) + - [Define format for the log of routes](#define-format-for-the-log-of-routes) +- [Request Binding & Validation](#request-binding--validation) - [Model binding and validation](#model-binding-and-validation) - [Custom Validators](#custom-validators) - [Only Bind Query String](#only-bind-query-string) - [Bind Query String or Post Data](#bind-query-string-or-post-data) - [Bind default value if none provided](#bind-default-value-if-none-provided) - - [Collection format for arrays](#collection-format-for-arrays) + - [Collection format for arrays](#collection-format-for-arrays) - [Bind Uri](#bind-uri) - [Bind custom unmarshaler](#bind-custom-unmarshaler) - [Bind Header](#bind-header) - [Bind HTML checkboxes](#bind-html-checkboxes) - [Multipart/Urlencoded binding](#multiparturlencoded-binding) + - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct) + - [Try to bind body into different structs](#try-to-bind-body-into-different-structs) + - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag) +- [Response Rendering](#response-rendering) - [XML, JSON, YAML, TOML and ProtoBuf rendering](#xml-json-yaml-toml-and-protobuf-rendering) - [SecureJSON](#securejson) - [JSONP](#jsonp) @@ -46,27 +61,22 @@ - [Custom Delimiters](#custom-delimiters) - [Custom Template Funcs](#custom-template-funcs) - [Multitemplate](#multitemplate) - - [Redirects](#redirects) - - [Custom Middleware](#custom-middleware) - - [Using BasicAuth() middleware](#using-basicauth-middleware) - - [Goroutines inside a middleware](#goroutines-inside-a-middleware) + - [Build a single binary with templates](#build-a-single-binary-with-templates) +- [Server Configuration](#server-configuration) - [Custom HTTP configuration](#custom-http-configuration) + - [Custom json codec at runtime](#custom-json-codec-at-runtime) - [Support Let's Encrypt](#support-lets-encrypt) - [Run multiple service using Gin](#run-multiple-service-using-gin) - [Graceful shutdown or restart](#graceful-shutdown-or-restart) - [Third-party packages](#third-party-packages) - [Manually](#manually) - - [Build a single binary with templates](#build-a-single-binary-with-templates) - - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct) - - [Try to bind body into different structs](#try-to-bind-body-into-different-structs) - - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag) - [http2 server push](#http2-server-push) - - [Define format for the log of routes](#define-format-for-the-log-of-routes) - [Set and get a cookie](#set-and-get-a-cookie) - - [Custom json codec at runtime](#custom-json-codec-at-runtime) -- [Don't trust all proxies](#dont-trust-all-proxies) + - [Don't trust all proxies](#dont-trust-all-proxies) - [Testing](#testing) +You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples). + ## Build tags ### Build with json replacement @@ -88,7 +98,7 @@ go build -tags=go_json . [sonic](https://github.com/bytedance/sonic) ```sh -$ go build -tags=sonic . +go build -tags=sonic . ``` ### Build without `MsgPack` rendering feature @@ -101,9 +111,9 @@ go build -tags=nomsgpack . This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852). -## API Examples +## Routing -You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples). +> Learn how to define routes, handle parameters, and organize endpoints. ### Using GET, POST, PUT, PATCH, DELETE and OPTIONS @@ -128,6 +138,46 @@ func main() { } ``` +### Using the QUERY method + +`QUERY` is the safe and idempotent method defined by [RFC 10008](https://www.rfc-editor.org/info/rfc10008/). It carries its query in the request body, so you can send a query that is too large or too structured for a URL without turning it into a `POST`. + +```go +func main() { + router := gin.Default() + + router.QUERY("/search", func(c *gin.Context) { + var query struct { + Term string `json:"term"` + } + if err := c.ShouldBindJSON(&query); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"term": query.Term}) + }) + + router.Run() +} +``` + +Use the `gin.MethodQuery` constant wherever an HTTP method name is expected, for example when building a request in a test: + +```go +req := httptest.NewRequest(gin.MethodQuery, "/search", body) +``` + +Keep in mind: + +- `router.Any` also registers `QUERY` alongside standard HTTP methods. Handlers registered with `Any` should respect QUERY's safe and idempotent semantics when processing that method. +- `QUERY` is not part of the `gin.IRoutes` interface. `*gin.Engine` and `*gin.RouterGroup` expose it directly; if you only hold an `IRoutes` value, assert to `gin.IQueryRoutes` first. + +```go +if q, ok := routes.(gin.IQueryRoutes); ok { + q.QUERY("/search", searching) +} +``` + ### Parameters in path ```go @@ -360,6 +410,40 @@ func main() { } ``` +### Redirects + +Issuing a HTTP redirect is easy. Both internal and external locations are supported. + +```go +r.GET("/test", func(c *gin.Context) { + c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") +}) +``` + +Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444) + +```go +r.POST("/test", func(c *gin.Context) { + c.Redirect(http.StatusFound, "/foo") +}) +``` + +Issuing a Router redirect, use `HandleContext` like below. + +```go +r.GET("/test", func(c *gin.Context) { + c.Request.URL.Path = "/test2" + r.HandleContext(c) +}) +r.GET("/test2", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"hello": "world"}) +}) +``` + +## Middleware + +> Configure middleware for request processing, authentication, and error recovery. + ### Blank Gin without middleware by default Use @@ -416,6 +500,46 @@ func main() { } ``` +### 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") +} +``` + ### Custom Recovery behavior ```go @@ -450,6 +574,82 @@ func main() { } ``` +### 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 new Goroutines 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") +} +``` + +## Logging + +> Control log output, formatting, and filtering. + ### How to write log file ```go @@ -469,7 +669,7 @@ func main() { c.String(http.StatusOK, "pong") }) -   router.Run(":8080") + router.Run(":8080") } ``` @@ -592,6 +792,68 @@ func main() { } ``` +### Avoid logging query strings + +```go +func main() { + router := gin.New() + + // SkipQueryString indicates that the logger should not log the query string. + // For example, /path?q=1 will be logged as /path + loggerConfig := gin.LoggerConfig{SkipQueryString: true} + + router.Use(gin.LoggerWithConfig(loggerConfig)) +} +``` + +### Define format for the log of routes + +The default log of routes is: + +```sh +[GIN-debug] POST /foo --> main.main.func1 (3 handlers) +[GIN-debug] GET /bar --> main.main.func2 (3 handlers) +[GIN-debug] GET /status --> main.main.func3 (3 handlers) +``` + +If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`. +In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs. + +```go +import ( + "log" + "net/http" + + "github.com/gin-gonic/gin" +) + +func main() { + r := gin.Default() + gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { + log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) + } + + r.POST("/foo", func(c *gin.Context) { + c.JSON(http.StatusOK, "foo") + }) + + r.GET("/bar", func(c *gin.Context) { + c.JSON(http.StatusOK, "bar") + }) + + r.GET("/status", func(c *gin.Context) { + c.JSON(http.StatusOK, "ok") + }) + + // Listen and Server in http://0.0.0.0:8080 + r.Run() +} +``` + +## Request Binding & Validation + +> Bind and validate request data from query strings, forms, JSON, and more. + ### Model binding and validation To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML, TOML and standard form values (foo=bar&boo=baz). @@ -868,7 +1130,6 @@ Test it with: curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012" ``` - ### Bind default value if none provided If the server should bind a default value to a field when the client does not provide one, specify the default value using the `default` key within the `form` tag: @@ -877,44 +1138,44 @@ If the server should bind a default value to a field when the client does not pr package main import ( - "net/http" + "net/http" - "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" ) type Person struct { - Name string `form:"name,default=William"` - Age int `form:"age,default=10"` - Friends []string `form:"friends,default=Will;Bill"` - Addresses [2]string `form:"addresses,default=foo bar" collection_format:"ssv"` - LapTimes []int `form:"lap_times,default=1;2;3" collection_format:"csv"` + Name string `form:"name,default=William"` + Age int `form:"age,default=10"` + Friends []string `form:"friends,default=Will;Bill"` + Addresses [2]string `form:"addresses,default=foo bar" collection_format:"ssv"` + LapTimes []int `form:"lap_times,default=1;2;3" collection_format:"csv"` } func main() { - g := gin.Default() - g.POST("/person", func(c *gin.Context) { - var req Person - if err := c.ShouldBindQuery(&req); err != nil { - c.JSON(http.StatusBadRequest, err) - return - } - c.JSON(http.StatusOK, req) - }) - _ = g.Run("localhost:8080") + g := gin.Default() + g.POST("/person", func(c *gin.Context) { + var req Person + if err := c.ShouldBindQuery(&req); err != nil { + c.JSON(http.StatusBadRequest, err) + return + } + c.JSON(http.StatusOK, req) + }) + _ = g.Run("localhost:8080") } ``` -``` +```sh curl -X POST http://localhost:8080/person -{"Name":"William","Age":10,"Friends":["Will","Bill"],"Colors":["red","blue"],"LapTimes":[1,2,3]} +{"Name":"William","Age":10,"Friends":["Will","Bill"],"Addresses":["foo","bar"],"LapTimes":[1,2,3]} ``` NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply: + - Since commas are used to delimit tag options, they are not supported within a default value and will result in undefined behavior - For the collection formats "multi" and "csv", a semicolon should be used in place of a comma to delimit default values - Since semicolons are used to delimit default values for "multi" and "csv", they are not supported within a default value for "multi" and "csv" - #### Collection format for arrays | Format | Description | Example | @@ -929,29 +1190,29 @@ NOTE: For default [collection values](#collection-format-for-arrays), the follow package main import ( - "log" - "time" - "github.com/gin-gonic/gin" + "log" + "time" + "github.com/gin-gonic/gin" ) type Person struct { - Name string `form:"name"` - Addresses []string `form:"addresses" collection_format:"csv"` - Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` - CreateTime time.Time `form:"createTime" time_format:"unixNano"` - UnixTime time.Time `form:"unixTime" time_format:"unix"` + Name string `form:"name"` + Addresses []string `form:"addresses" collection_format:"csv"` + Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` + CreateTime time.Time `form:"createTime" time_format:"unixNano"` + UnixTime time.Time `form:"unixTime" time_format:"unix"` } func main() { - route := gin.Default() - route.GET("/testing", startPage) - route.Run(":8085") + 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/master/binding/binding.go#L48 + 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/master/binding/binding.go#L48 if c.ShouldBind(&person) == nil { log.Println(person.Name) log.Println(person.Addresses) @@ -959,13 +1220,14 @@ func startPage(c *gin.Context) { log.Println(person.CreateTime) log.Println(person.UnixTime) } - c.String(200, "Success") + c.String(200, "Success") } ``` Test it with: + ```sh -$ curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" +curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" ``` ### Bind Uri @@ -1050,12 +1312,15 @@ Test it with: ```sh curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02' ``` + Result + ```sh {"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]} ``` Note: + - If `parser=encoding.TextUnmarshaler` is specified for a type that does **not** implement `encoding.TextUnmarshaler`, gin will ignore it and proceed with its default binding logic. - If `parser=encoding.TextUnmarshaler` is specified for a type and that type's implementation of `encoding.TextUnmarshaler` returns an error, gin will stop binding and return the error to the client. @@ -1102,12 +1367,15 @@ Test it with: ```sh curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02' ``` + Result + ```sh {"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]} ``` Note: + - If a type implements both `encoding.TextUnmarshaler` and `BindUnmarshaler`, gin will use `BindUnmarshaler` by default unless you specify `parser=encoding.TextUnmarshaler` in the binding tag. - If a type returns an error from its implementation of `BindUnmarshaler`, gin will stop binding and return the error to the client. @@ -1179,21 +1447,21 @@ form.html ```html
-

Check some colors

- - - - - - - +

Check some colors

+ + + + + + +
``` result: ```json -{"color":["red","green","blue"]} +{ "color": ["red", "green", "blue"] } ``` ### Multipart/Urlencoded binding @@ -1240,6 +1508,202 @@ Test it with: curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile ``` +### Bind form-data request with custom struct + +The follow example using custom struct: + +```go +type StructA struct { + FieldA string `form:"field_a"` +} + +type StructB struct { + NestedStruct StructA + FieldB string `form:"field_b"` +} + +type StructC struct { + NestedStructPointer *StructA + FieldC string `form:"field_c"` +} + +type StructD struct { + NestedAnonyStruct struct { + FieldX string `form:"field_x"` + } + FieldD string `form:"field_d"` +} + +func GetDataB(c *gin.Context) { + var b StructB + c.Bind(&b) + c.JSON(http.StatusOK, gin.H{ + "a": b.NestedStruct, + "b": b.FieldB, + }) +} + +func GetDataC(c *gin.Context) { + var b StructC + c.Bind(&b) + c.JSON(http.StatusOK, gin.H{ + "a": b.NestedStructPointer, + "c": b.FieldC, + }) +} + +func GetDataD(c *gin.Context) { + var b StructD + c.Bind(&b) + c.JSON(http.StatusOK, gin.H{ + "x": b.NestedAnonyStruct, + "d": b.FieldD, + }) +} + +func main() { + r := gin.Default() + r.GET("/getb", GetDataB) + r.GET("/getc", GetDataC) + r.GET("/getd", GetDataD) + + r.Run() +} +``` + +Using the command `curl` command result: + +```sh +$ curl "http://localhost:8080/getb?field_a=hello&field_b=world" +{"a":{"FieldA":"hello"},"b":"world"} +$ curl "http://localhost:8080/getc?field_a=hello&field_c=world" +{"a":{"FieldA":"hello"},"c":"world"} +$ curl "http://localhost:8080/getd?field_x=hello&field_d=world" +{"d":"world","x":{"FieldX":"hello"}} +``` + +### Try to bind body into different structs + +The normal methods for binding request body consumes `c.Request.Body` and they +cannot be called multiple times. + +```go +type formA struct { + Foo string `json:"foo" xml:"foo" binding:"required"` +} + +type formB struct { + Bar string `json:"bar" xml:"bar" binding:"required"` +} + +func SomeHandler(c *gin.Context) { + objA := formA{} + objB := formB{} + // Calling c.ShouldBind consumes c.Request.Body and it cannot be reused. + if errA := c.ShouldBind(&objA); errA == nil { + c.String(http.StatusOK, `the body should be formA`) + // Always an error is occurred by this because c.Request.Body is EOF now. + } else if errB := c.ShouldBind(&objB); errB == nil { + c.String(http.StatusOK, `the body should be formB`) + } else { + ... + } +} +``` + +For this, you can use `c.ShouldBindBodyWith` or shortcuts. + +- `c.ShouldBindBodyWithJSON` is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON). +- `c.ShouldBindBodyWithXML` is a shortcut for c.ShouldBindBodyWith(obj, binding.XML). +- `c.ShouldBindBodyWithYAML` is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML). +- `c.ShouldBindBodyWithTOML` is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML). + +```go +func SomeHandler(c *gin.Context) { + objA := formA{} + objB := formB{} + // This reads c.Request.Body and stores the result into the context. + if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil { + c.String(http.StatusOK, `the body should be formA`) + // At this time, it reuses body stored in the context. + } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { + c.String(http.StatusOK, `the body should be formB JSON`) + // And it can accepts other formats + } else if errB2 := c.ShouldBindBodyWithXML(&objB); errB2 == nil { + c.String(http.StatusOK, `the body should be formB XML`) + } else { + ... + } +} +``` + +1. `c.ShouldBindBodyWith` stores body into the context before binding. This has + a slight impact to performance, so you should not use this method if you are + enough to call binding at once. +2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`, + `ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`, + can be called by `c.ShouldBind()` multiple times without any damage to + performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)). + +### Bind form-data request with custom struct and custom tag + +```go +const ( + customerTag = "url" + defaultMemory = 32 << 20 +) + +type customerBinding struct {} + +func (customerBinding) Name() string { + return "form" +} + +func (customerBinding) Bind(req *http.Request, obj any) error { + if err := req.ParseForm(); err != nil { + return err + } + if err := req.ParseMultipartForm(defaultMemory); err != nil { + if err != http.ErrNotMultipart { + return err + } + } + if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil { + return err + } + return validate(obj) +} + +func validate(obj any) error { + if binding.Validator == nil { + return nil + } + return binding.Validator.ValidateStruct(obj) +} + +// Now we can do this!!! +// FormA is an external type that we can't modify it's tag +type FormA struct { + FieldA string `url:"field_a"` +} + +func ListHandler(s *Service) func(ctx *gin.Context) { + return func(ctx *gin.Context) { + var urlBinding = customerBinding{} + var opt FormA + err := ctx.MustBindWith(&opt, urlBinding) + if err != nil { + ... + } + ... + } +} +``` + +## Response Rendering + +> Render responses in various formats including JSON, XML, HTML, and more. + ### XML, JSON, YAML, TOML and ProtoBuf rendering ```go @@ -1298,7 +1762,7 @@ func main() { #### SecureJSON -Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values. +Using SecureJSON to prevent json hijacking. Default prepends `"while(1);"` to response body if the given struct is array values. ```go func main() { @@ -1484,9 +1948,7 @@ templates/index.tmpl ```html -

- {{ .title }} -

+

{{ .title }}

``` @@ -1514,10 +1976,9 @@ templates/posts/index.tmpl ```html {{ define "posts/index.tmpl" }} -

- {{ .title }} -

-

Using posts/index.tmpl

+ +

{{ .title }}

+

Using posts/index.tmpl

{{ end }} ``` @@ -1526,10 +1987,9 @@ templates/users/index.tmpl ```html {{ define "users/index.tmpl" }} -

- {{ .title }} -

-

Using users/index.tmpl

+ +

{{ .title }}

+

Using users/index.tmpl

{{ end }} ``` @@ -1615,147 +2075,62 @@ Date: 2017/07/01 Gin allows only one html.Template by default. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`. -### Redirects +### Build a single binary with templates -Issuing a HTTP redirect is easy. Both internal and external locations are supported. +You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package. ```go -r.GET("/test", func(c *gin.Context) { - c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") -}) -``` +package main -Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444) +import ( + "embed" + "html/template" + "net/http" -```go -r.POST("/test", func(c *gin.Context) { - c.Redirect(http.StatusFound, "/foo") -}) -``` + "github.com/gin-gonic/gin" +) -Issuing a Router redirect, use `HandleContext` like below. - -``` go -r.GET("/test", func(c *gin.Context) { - c.Request.URL.Path = "/test2" - r.HandleContext(c) -}) -r.GET("/test2", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"hello": "world"}) -}) -``` - -### 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) - } -} +//go:embed assets/* templates/* +var f embed.FS func main() { - r := gin.New() - r.Use(Logger()) + router := gin.Default() + templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl")) + router.SetHTMLTemplate(templ) - r.GET("/test", func(c *gin.Context) { - example := c.MustGet("example").(string) + // example: /public/assets/images/example.png + router.StaticFS("/public", http.FS(f)) - // it would print: "12345" - log.Println(example) + router.GET("/", func(c *gin.Context) { + c.HTML(http.StatusOK, "index.tmpl", gin.H{ + "title": "Main website", + }) }) - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") + router.GET("/foo", func(c *gin.Context) { + c.HTML(http.StatusOK, "bar.tmpl", gin.H{ + "title": "Foo website", + }) + }) + + router.GET("favicon.ico", func(c *gin.Context) { + file, _ := f.ReadFile("assets/favicon.ico") + c.Data( + http.StatusOK, + "image/x-icon", + file, + ) + }) + + router.Run(":8080") } ``` -### Using BasicAuth() middleware +See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory. -```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"}, -} +## Server Configuration -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 new Goroutines 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") -} -``` +> Configure HTTP servers, TLS, proxies, and runtime settings. ### Custom HTTP configuration @@ -1785,6 +2160,65 @@ func main() { } ``` +### Custom json codec at runtime + +Gin support custom json serialization and deserialization logic without using compile tags. + +1. Define a custom struct implements the `json.Core` interface. + +2. Before your engine starts, assign values to `json.API` using the custom struct. + +```go +package main + +import ( + "io" + + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/codec/json" + jsoniter "github.com/json-iterator/go" +) + +var customConfig = jsoniter.Config{ + EscapeHTML: true, + SortMapKeys: true, + ValidateJsonRawMessage: true, +}.Froze() + +// implement api.JsonApi +type customJsonApi struct { +} + +func (j customJsonApi) Marshal(v any) ([]byte, error) { + return customConfig.Marshal(v) +} + +func (j customJsonApi) Unmarshal(data []byte, v any) error { + return customConfig.Unmarshal(data, v) +} + +func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) { + return customConfig.MarshalIndent(v, prefix, indent) +} + +func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder { + return customConfig.NewEncoder(writer) +} + +func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder { + return customConfig.NewDecoder(reader) +} + +func main() { + //Replace the default json api + json.API = customJsonApi{} + + //Start your gin engine + router := gin.Default() + router.Run(":8080") +} +``` + ### Support Let's Encrypt example for 1-line LetsEncrypt HTTPS servers. @@ -1950,9 +2384,9 @@ endless.ListenAndServe(":4242", router) Alternatives: -* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers. -* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server. -* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. +- [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers. +- [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server. +- [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. #### Manually @@ -1965,6 +2399,7 @@ package main import ( "context" + "errors" "log" "net/http" "os" @@ -1997,7 +2432,7 @@ func main() { // Wait for interrupt signal to gracefully shutdown the server with // a timeout of 5 seconds. - quit := make(chan os.Signal) + quit := make(chan os.Signal, 1) // kill (no param) default send syscall.SIGTERM // kill -2 is syscall.SIGINT // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it @@ -2018,251 +2453,6 @@ func main() { } ``` -### Build a single binary with templates - -You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package. - -```go -package main - -import ( - "embed" - "html/template" - "net/http" - - "github.com/gin-gonic/gin" -) - -//go:embed assets/* templates/* -var f embed.FS - -func main() { - router := gin.Default() - templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl")) - router.SetHTMLTemplate(templ) - - // example: /public/assets/images/example.png - router.StaticFS("/public", http.FS(f)) - - router.GET("/", func(c *gin.Context) { - c.HTML(http.StatusOK, "index.tmpl", gin.H{ - "title": "Main website", - }) - }) - - router.GET("/foo", func(c *gin.Context) { - c.HTML(http.StatusOK, "bar.tmpl", gin.H{ - "title": "Foo website", - }) - }) - - router.GET("favicon.ico", func(c *gin.Context) { - file, _ := f.ReadFile("assets/favicon.ico") - c.Data( - http.StatusOK, - "image/x-icon", - file, - ) - }) - - router.Run(":8080") -} -``` - -See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory. - -### Bind form-data request with custom struct - -The follow example using custom struct: - -```go -type StructA struct { - FieldA string `form:"field_a"` -} - -type StructB struct { - NestedStruct StructA - FieldB string `form:"field_b"` -} - -type StructC struct { - NestedStructPointer *StructA - FieldC string `form:"field_c"` -} - -type StructD struct { - NestedAnonyStruct struct { - FieldX string `form:"field_x"` - } - FieldD string `form:"field_d"` -} - -func GetDataB(c *gin.Context) { - var b StructB - c.Bind(&b) - c.JSON(http.StatusOK, gin.H{ - "a": b.NestedStruct, - "b": b.FieldB, - }) -} - -func GetDataC(c *gin.Context) { - var b StructC - c.Bind(&b) - c.JSON(http.StatusOK, gin.H{ - "a": b.NestedStructPointer, - "c": b.FieldC, - }) -} - -func GetDataD(c *gin.Context) { - var b StructD - c.Bind(&b) - c.JSON(http.StatusOK, gin.H{ - "x": b.NestedAnonyStruct, - "d": b.FieldD, - }) -} - -func main() { - r := gin.Default() - r.GET("/getb", GetDataB) - r.GET("/getc", GetDataC) - r.GET("/getd", GetDataD) - - r.Run() -} -``` - -Using the command `curl` command result: - -```sh -$ curl "http://localhost:8080/getb?field_a=hello&field_b=world" -{"a":{"FieldA":"hello"},"b":"world"} -$ curl "http://localhost:8080/getc?field_a=hello&field_c=world" -{"a":{"FieldA":"hello"},"c":"world"} -$ curl "http://localhost:8080/getd?field_x=hello&field_d=world" -{"d":"world","x":{"FieldX":"hello"}} -``` - -### Try to bind body into different structs - -The normal methods for binding request body consumes `c.Request.Body` and they -cannot be called multiple times. - -```go -type formA struct { - Foo string `json:"foo" xml:"foo" binding:"required"` -} - -type formB struct { - Bar string `json:"bar" xml:"bar" binding:"required"` -} - -func SomeHandler(c *gin.Context) { - objA := formA{} - objB := formB{} - // Calling c.ShouldBind consumes c.Request.Body and it cannot be reused. - if errA := c.ShouldBind(&objA); errA == nil { - c.String(http.StatusOK, `the body should be formA`) - // Always an error is occurred by this because c.Request.Body is EOF now. - } else if errB := c.ShouldBind(&objB); errB == nil { - c.String(http.StatusOK, `the body should be formB`) - } else { - ... - } -} -``` - -For this, you can use `c.ShouldBindBodyWith` or shortcuts. - -- `c.ShouldBindBodyWithJSON` is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON). -- `c.ShouldBindBodyWithXML` is a shortcut for c.ShouldBindBodyWith(obj, binding.XML). -- `c.ShouldBindBodyWithYAML` is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML). -- `c.ShouldBindBodyWithTOML` is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML). - -```go -func SomeHandler(c *gin.Context) { - objA := formA{} - objB := formB{} - // This reads c.Request.Body and stores the result into the context. - if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil { - c.String(http.StatusOK, `the body should be formA`) - // At this time, it reuses body stored in the context. - } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { - c.String(http.StatusOK, `the body should be formB JSON`) - // And it can accepts other formats - } else if errB2 := c.ShouldBindBodyWithXML(&objB); errB2 == nil { - c.String(http.StatusOK, `the body should be formB XML`) - } else { - ... - } -} -``` - -1. `c.ShouldBindBodyWith` stores body into the context before binding. This has -a slight impact to performance, so you should not use this method if you are -enough to call binding at once. -2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`, -`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`, -can be called by `c.ShouldBind()` multiple times without any damage to -performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)). - -### Bind form-data request with custom struct and custom tag - -```go -const ( - customerTag = "url" - defaultMemory = 32 << 20 -) - -type customerBinding struct {} - -func (customerBinding) Name() string { - return "form" -} - -func (customerBinding) Bind(req *http.Request, obj any) error { - if err := req.ParseForm(); err != nil { - return err - } - if err := req.ParseMultipartForm(defaultMemory); err != nil { - if err != http.ErrNotMultipart { - return err - } - } - if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil { - return err - } - return validate(obj) -} - -func validate(obj any) error { - if binding.Validator == nil { - return nil - } - return binding.Validator.ValidateStruct(obj) -} - -// Now we can do this!!! -// FormA is an external type that we can't modify it's tag -type FormA struct { - FieldA string `url:"field_a"` -} - -func ListHandler(s *Service) func(ctx *gin.Context) { - return func(ctx *gin.Context) { - var urlBinding = customerBinding{} - var opt FormA - err := ctx.MustBindWith(&opt, urlBinding) - if err != nil { - ... - } - ... - } -} -``` - ### http2 server push http.Pusher is supported only **go1.8+**. See the [golang blog](https://go.dev/blog/h2push) for detail information. @@ -2312,50 +2502,6 @@ func main() { } ``` -### Define format for the log of routes - -The default log of routes is: - -```sh -[GIN-debug] POST /foo --> main.main.func1 (3 handlers) -[GIN-debug] GET /bar --> main.main.func2 (3 handlers) -[GIN-debug] GET /status --> main.main.func3 (3 handlers) -``` - -If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`. -In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs. - -```go -import ( - "log" - "net/http" - - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { - log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) - } - - r.POST("/foo", func(c *gin.Context) { - c.JSON(http.StatusOK, "foo") - }) - - r.GET("/bar", func(c *gin.Context) { - c.JSON(http.StatusOK, "bar") - }) - - r.GET("/status", func(c *gin.Context) { - c.JSON(http.StatusOK, "ok") - }) - - // Listen and Server in http://0.0.0.0:8080 - r.Run() -} -``` - ### Set and get a cookie ```go @@ -2436,66 +2582,7 @@ func main() { } ``` -### Custom json codec at runtime - -Gin support custom json serialization and deserialization logic without using compile tags. - -1. Define a custom struct implements the `json.Core` interface. - -2. Before your engine starts, assign values to `json.API` using the custom struct. - -```go -package main - -import ( - "io" - - "github.com/gin-gonic/gin" - "github.com/gin-gonic/gin/codec/json" - jsoniter "github.com/json-iterator/go" -) - -var customConfig = jsoniter.Config{ - EscapeHTML: true, - SortMapKeys: true, - ValidateJsonRawMessage: true, -}.Froze() - -// implement api.JsonApi -type customJsonApi struct { -} - -func (j customJsonApi) Marshal(v any) ([]byte, error) { - return customConfig.Marshal(v) -} - -func (j customJsonApi) Unmarshal(data []byte, v any) error { - return customConfig.Unmarshal(data, v) -} - -func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) { - return customConfig.MarshalIndent(v, prefix, indent) -} - -func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder { - return customConfig.NewEncoder(writer) -} - -func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder { - return customConfig.NewDecoder(reader) -} - -func main() { - //Replace the default json api - json.API = customJsonApi{} - - //Start your gin engine - router := gin.Default() - router.Run(":8080") -} -``` - -## Don't trust all proxies +### Don't trust all proxies Gin lets you specify which headers to hold the real client IP (if any), as well as specifying which proxies (or direct clients) you trust to diff --git a/errors.go b/errors.go index 829e9d2c..c0d907b9 100644 --- a/errors.go +++ b/errors.go @@ -26,8 +26,6 @@ const ( ErrorTypePublic ErrorType = 1 << 1 // ErrorTypeAny indicates any other error. ErrorTypeAny ErrorType = 1<<64 - 1 - // ErrorTypeNu indicates any other error. - ErrorTypeNu = 2 ) // Error represents a error's specification. diff --git a/gin.go b/gin.go index 2e033bf3..a1607275 100644 --- a/gin.go +++ b/gin.go @@ -13,6 +13,7 @@ import ( "path" "strings" "sync" + "time" "github.com/gin-gonic/gin/internal/bytesconv" filesystem "github.com/gin-gonic/gin/internal/fs" @@ -29,6 +30,12 @@ const ( backslash = "\\" ) +// defaultReadHeaderTimeout is the default ReadHeaderTimeout applied to the +// http.Server created by Run, RunTLS and RunListener. It protects against +// slowloris-style resource exhaustion when the caller does not configure a +// custom http.Server. +const defaultReadHeaderTimeout = 10 * time.Second + var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") @@ -166,6 +173,12 @@ type Engine struct { // method call. MaxMultipartMemory int64 + // ReadHeaderTimeout is the maximum duration allowed for reading the request + // headers by the http.Server created through Run, RunTLS and RunListener. + // If zero or negative, a default of 10 seconds is used. Set to a positive + // value to customize, or use a custom http.Server directly to disable it. + ReadHeaderTimeout time.Duration + // UseH2C enable h2c support. UseH2C bool @@ -219,6 +232,7 @@ func New(opts ...OptionFunc) *Engine { RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, + ReadHeaderTimeout: defaultReadHeaderTimeout, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", @@ -255,6 +269,15 @@ func (engine *Engine) allocateContext(maxParams uint16) *Context { return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } +// getReadHeaderTimeout returns the configured ReadHeaderTimeout, or the +// default if it is zero or negative. +func (engine *Engine) getReadHeaderTimeout() time.Duration { + if engine.ReadHeaderTimeout <= 0 { + return defaultReadHeaderTimeout + } + return engine.ReadHeaderTimeout +} + // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} @@ -537,6 +560,9 @@ func parseIP(ip string) net.IP { // 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. +// The created http.Server is configured with a default ReadHeaderTimeout of 10 seconds +// (configurable via Engine.ReadHeaderTimeout) to mitigate slowloris attacks. +// For full control over timeouts, create a custom http.Server and use ServeHTTP. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() @@ -548,8 +574,9 @@ func (engine *Engine) Run(addr ...string) (err error) { address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) server := &http.Server{ // #nosec G112 - Addr: address, - Handler: engine.Handler(), + Addr: address, + Handler: engine.Handler(), + ReadHeaderTimeout: engine.getReadHeaderTimeout(), } err = server.ListenAndServe() return @@ -568,8 +595,9 @@ func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { } server := &http.Server{ // #nosec G112 - Addr: addr, - Handler: engine.Handler(), + Addr: addr, + Handler: engine.Handler(), + ReadHeaderTimeout: engine.getReadHeaderTimeout(), } err = server.ListenAndServeTLS(certFile, keyFile) return @@ -652,7 +680,8 @@ func (engine *Engine) RunListener(listener net.Listener) (err error) { } server := &http.Server{ // #nosec G112 - Handler: engine.Handler(), + Handler: engine.Handler(), + ReadHeaderTimeout: engine.getReadHeaderTimeout(), } err = server.Serve(listener) return diff --git a/ginS/gins.go b/ginS/gins.go index 7918ce3a..5a82ab09 100644 --- a/ginS/gins.go +++ b/ginS/gins.go @@ -67,6 +67,11 @@ func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().GET(relativePath, handlers...) } +// QUERY is a shortcut for router.Handle("QUERY", path, handle) +func QUERY(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { + return engine().QUERY(relativePath, handlers...) +} + // DELETE is a shortcut for router.Handle("DELETE", path, handle) func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().DELETE(relativePath, handlers...) diff --git a/ginS/gins_test.go b/ginS/gins_test.go index ffde85d2..d7f0d624 100644 --- a/ginS/gins_test.go +++ b/ginS/gins_test.go @@ -31,6 +31,19 @@ func TestGET(t *testing.T) { assert.Equal(t, "test", w.Body.String()) } +func TestQUERY(t *testing.T) { + QUERY("/query", func(c *gin.Context) { + c.String(http.StatusOK, "query") + }) + + req := httptest.NewRequest(gin.MethodQuery, "/query", nil) + w := httptest.NewRecorder() + engine().ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "query", w.Body.String()) +} + func TestPOST(t *testing.T) { POST("/post", func(c *gin.Context) { c.String(http.StatusCreated, "created") diff --git a/gin_integration_test.go b/gin_integration_test.go index 720b140f..da408d9c 100644 --- a/gin_integration_test.go +++ b/gin_integration_test.go @@ -25,6 +25,7 @@ import ( "github.com/stretchr/testify/require" ) +// testRequest sends a request and validates its response. // params[0]=url example:http://127.0.0.1:8080/index (cannot be empty) // params[1]=response status (custom compare status) default:"200 OK" // params[2]=response body (custom compare content) default:"it worked" diff --git a/gin_test.go b/gin_test.go index 43c9494d..71a817a7 100644 --- a/gin_test.go +++ b/gin_test.go @@ -743,6 +743,78 @@ func TestEngineHandleContextPreventsMiddlewareReEntry(t *testing.T) { assert.Equal(t, int64(1), handlerCounterV2) } +func TestEngineHandleContextNoRouteWithGroupMiddleware(t *testing.T) { + // Scenario from issue #1848: + // - Engine with no global middleware (gin.New()) + // - A group with middleware + // - A route in that group + // - NoRoute handler that redirects via HandleContext + // The group middleware should run exactly once per HandleContext call, + // not accumulate across redirects. + + var middlewareCount, handlerCount int64 + + r := New() + grp := r.Group("", func(c *Context) { + atomic.AddInt64(&middlewareCount, 1) + c.Next() + }) + grp.GET("/target", func(c *Context) { + atomic.AddInt64(&handlerCount, 1) + c.String(http.StatusOK, "ok") + }) + + r.NoRoute(func(c *Context) { + c.Request.URL.Path = "/target" + r.HandleContext(c) + }) + + // Access a non-existent route to trigger NoRoute -> HandleContext + w := PerformRequest(r, "GET", "/nonexistent") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "ok", w.Body.String()) + // Middleware and handler should each run exactly once + assert.Equal(t, int64(1), atomic.LoadInt64(&middlewareCount)) + assert.Equal(t, int64(1), atomic.LoadInt64(&handlerCount)) +} + +func TestEngineHandleContextNoRouteWithEngineMiddleware(t *testing.T) { + // When engine middleware exists and NoRoute redirects via HandleContext, + // verify the handlers run the expected number of times. + + var engineMwCount, groupMwCount, handlerCount int64 + + r := New() + r.Use(func(c *Context) { + atomic.AddInt64(&engineMwCount, 1) + c.Next() + }) + + grp := r.Group("", func(c *Context) { + atomic.AddInt64(&groupMwCount, 1) + c.Next() + }) + grp.GET("/target", func(c *Context) { + atomic.AddInt64(&handlerCount, 1) + c.String(http.StatusOK, "ok") + }) + + r.NoRoute(func(c *Context) { + c.Request.URL.Path = "/target" + r.HandleContext(c) + }) + + w := PerformRequest(r, "GET", "/nonexistent") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "ok", w.Body.String()) + // Handler and group middleware should each run once (from HandleContext) + assert.Equal(t, int64(1), atomic.LoadInt64(&handlerCount)) + assert.Equal(t, int64(1), atomic.LoadInt64(&groupMwCount)) + // Engine middleware runs twice: once for the NoRoute chain, once for the HandleContext chain + // This is expected behavior since HandleContext re-enters the full handler chain + assert.Equal(t, int64(2), atomic.LoadInt64(&engineMwCount)) +} + func TestEngineHandleContextUseEscapedPathPercentEncoded(t *testing.T) { r := New() r.UseEscapedPath = true @@ -952,6 +1024,26 @@ func TestWithOptionFunc(t *testing.T) { assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"}) } +func TestReadHeaderTimeoutDefault(t *testing.T) { + engine := New() + assert.Equal(t, defaultReadHeaderTimeout, engine.ReadHeaderTimeout) + assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout()) +} + +func TestReadHeaderTimeoutCustom(t *testing.T) { + engine := New(func(e *Engine) { + e.ReadHeaderTimeout = 30 * time.Second + }) + assert.Equal(t, 30*time.Second, engine.ReadHeaderTimeout) + assert.Equal(t, 30*time.Second, engine.getReadHeaderTimeout()) +} + +func TestReadHeaderTimeoutZeroFallsBackToDefault(t *testing.T) { + engine := New() + engine.ReadHeaderTimeout = 0 + assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout()) +} + type Birthday string func (b *Birthday) UnmarshalParam(param string) error { @@ -1084,3 +1176,22 @@ func TestUpdateRouteTreesCalledOnce(t *testing.T) { assert.Equal(t, "ok", w.Body.String()) } } + +func TestRouterQueryMethod(t *testing.T) { + router := New() + router.QUERY("/test", func(c *Context) { + c.String(http.StatusOK, "query ok") + }) + + w := httptest.NewRecorder() + req, _ := http.NewRequest("QUERY", "/test", nil) + router.ServeHTTP(w, req) + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "query ok", w.Body.String()) + + // Other methods should not match + w2 := httptest.NewRecorder() + req2, _ := http.NewRequest(http.MethodGet, "/test", nil) + router.ServeHTTP(w2, req2) + assert.Equal(t, http.StatusNotFound, w2.Code) +} diff --git a/go.mod b/go.mod index b755e40d..99a8d5bb 100644 --- a/go.mod +++ b/go.mod @@ -1,42 +1,41 @@ module github.com/gin-gonic/gin -go 1.24.0 +go 1.26.0 require ( - github.com/bytedance/sonic v1.14.2 + github.com/bytedance/sonic v1.15.0 github.com/gin-contrib/sse v1.1.0 - github.com/go-playground/validator/v10 v10.28.0 - github.com/goccy/go-json v0.10.2 - github.com/goccy/go-yaml v1.19.1 + github.com/go-playground/validator/v10 v10.30.3 + github.com/goccy/go-json v0.10.6 + github.com/goccy/go-yaml v1.19.2 github.com/json-iterator/go v1.1.12 github.com/mattn/go-isatty v0.0.20 github.com/modern-go/reflect2 v1.0.2 github.com/pelletier/go-toml/v2 v2.2.4 - github.com/quic-go/quic-go v0.57.1 - github.com/stretchr/testify v1.11.1 + github.com/quic-go/quic-go v0.60.0 + github.com/stretchr/testify v1.12.1 github.com/ugorji/go/codec v1.3.1 - golang.org/x/net v0.47.0 - google.golang.org/protobuf v1.36.10 + go.mongodb.org/mongo-driver/v2 v2.5.0 + golang.org/x/net v0.57.0 + google.golang.org/protobuf v1.36.11 ) require ( github.com/bytedance/gopkg v0.1.3 // indirect - github.com/bytedance/sonic/loader v0.4.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/gabriel-vasile/mimetype v1.4.10 // indirect + github.com/gabriel-vasile/mimetype v1.4.13 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect - github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect - github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - golang.org/x/arch v0.20.0 // indirect - golang.org/x/crypto v0.45.0 // indirect - golang.org/x/sys v0.38.0 // indirect - golang.org/x/text v0.31.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect + go.uber.org/mock v0.6.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/arch v0.25.0 // indirect + golang.org/x/crypto v0.56.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect ) diff --git a/go.sum b/go.sum index 06442efb..dc6ef902 100644 --- a/go.sum +++ b/go.sum @@ -1,17 +1,16 @@ github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= -github.com/bytedance/sonic v1.14.2 h1:k1twIoe97C1DtYUo+fZQy865IuHia4PR5RPiuGPPIIE= -github.com/bytedance/sonic v1.14.2/go.mod h1:T80iDELeHiHKSc0C9tubFygiuXoGzrkjKzX2quAx980= -github.com/bytedance/sonic/loader v0.4.0 h1:olZ7lEqcxtZygCK9EKYKADnpQoYkRQxaeY2NYzevs+o= -github.com/bytedance/sonic/loader v0.4.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= -github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM= +github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= @@ -20,12 +19,12 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= -github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= -github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= -github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/goccy/go-yaml v1.19.1 h1:3rG3+v8pkhRqoQ/88NYNMHYVGYztCOCIZ7UQhu7H+NE= -github.com/goccy/go-yaml v1.19.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8= +github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc= +github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= +github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -33,28 +32,24 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0= +github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= -github.com/quic-go/quic-go v0.57.1 h1:25KAAR9QR8KZrCZRThWMKVAwGoiHIrNbT72ULHTuI10= -github.com/quic-go/quic-go v0.57.1/go.mod h1:ly4QBAjHA2VhdnxhojRsCUOeJwKYg+taDlos92xb1+s= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0= +github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -64,32 +59,31 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= -go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= -go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= -golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= -golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE= +golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8= +golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y= +golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/logger.go b/logger.go index 6441f7ea..cf92553a 100644 --- a/logger.go +++ b/logger.go @@ -48,6 +48,11 @@ type LoggerConfig struct { // Optional. SkipPaths []string + // SkipQueryString indicates that query strings should not be written + // for cases such as when API keys are passed via query strings. + // Optional. Default value is false. + SkipQueryString bool + // Skip is a Skipper that indicates which logs should not be written. // Optional. Skip Skipper @@ -298,7 +303,7 @@ func LoggerWithConfig(conf LoggerConfig) HandlerFunc { param.BodySize = c.Writer.Size() - if raw != "" { + if raw != "" && !conf.SkipQueryString { path = path + "?" + raw } diff --git a/logger_test.go b/logger_test.go index 53d0df95..395d97e6 100644 --- a/logger_test.go +++ b/logger_test.go @@ -318,20 +318,21 @@ func TestColorForStatus(t *testing.T) { } func TestColorForLatency(t *testing.T) { - colorForLantency := func(latency time.Duration) string { + colorForLatency := func(latency time.Duration) string { p := LogFormatterParams{ Latency: latency, } return p.LatencyColor() } - assert.Equal(t, white, colorForLantency(time.Duration(0)), "0 should be white") - assert.Equal(t, white, colorForLantency(time.Millisecond*20), "20ms should be white") - assert.Equal(t, green, colorForLantency(time.Millisecond*150), "150ms should be green") - assert.Equal(t, cyan, colorForLantency(time.Millisecond*250), "250ms should be cyan") - assert.Equal(t, yellow, colorForLantency(time.Millisecond*600), "600ms should be yellow") - assert.Equal(t, magenta, colorForLantency(time.Millisecond*1500), "1.5s should be magenta") - assert.Equal(t, red, colorForLantency(time.Second*3), "other things should be red") + assert.Equal(t, white, colorForLatency(time.Duration(0)), "0 should be white") + assert.Equal(t, white, colorForLatency(time.Millisecond*20), "20ms should be white") + assert.Equal(t, green, colorForLatency(time.Millisecond*150), "150ms should be green") + assert.Equal(t, cyan, colorForLatency(time.Millisecond*250), "250ms should be cyan") + assert.Equal(t, blue, colorForLatency(time.Millisecond*400), "400ms should be blue") + assert.Equal(t, yellow, colorForLatency(time.Millisecond*600), "600ms should be yellow") + assert.Equal(t, magenta, colorForLatency(time.Millisecond*1500), "1.5s should be magenta") + assert.Equal(t, red, colorForLatency(time.Second*3), "other things should be red") } func TestResetColor(t *testing.T) { @@ -471,3 +472,17 @@ func TestForceConsoleColor(t *testing.T) { // reset console color mode. consoleColorMode = autoColor } + +func TestLoggerWithConfigSkipQueryString(t *testing.T) { + buffer := new(strings.Builder) + router := New() + router.Use(LoggerWithConfig(LoggerConfig{ + Output: buffer, + SkipQueryString: true, + })) + router.GET("/logged", func(c *Context) { c.Status(http.StatusOK) }) + + PerformRequest(router, "GET", "/logged?a=21") + assert.Contains(t, buffer.String(), "200") + assert.NotContains(t, buffer.String(), "a=21") +} diff --git a/path.go b/path.go index 3b67caa9..672213d1 100644 --- a/path.go +++ b/path.go @@ -55,7 +55,7 @@ func cleanPath(p string) string { // A bit more clunky without a 'lazybuf' like the path package, but the loop // gets completely inlined (bufApp calls). - // loop has no expensive function calls (except 1x make) // So in contrast to the path package this loop has no expensive function + // So in contrast to the path package this loop has no expensive function // calls (except make, if needed). for r < n { diff --git a/recovery.go b/recovery.go index bbf1d565..2124fe5f 100644 --- a/recovery.go +++ b/recovery.go @@ -106,7 +106,12 @@ func secureRequestDump(r *http.Request) string { return strings.Join(lines, "\r\n") } -func defaultHandleRecovery(c *Context, _ any) { +func defaultHandleRecovery(c *Context, err any) { + e, ok := err.(error) + if !ok { + e = fmt.Errorf("%v", err) + } + c.Error(e) //nolint: errcheck c.AbortWithStatus(http.StatusInternalServerError) } diff --git a/recovery_test.go b/recovery_test.go index 0faa3280..e5211790 100644 --- a/recovery_test.go +++ b/recovery_test.go @@ -5,6 +5,7 @@ package gin import ( + "errors" "net" "net/http" "os" @@ -22,7 +23,7 @@ func TestPanicClean(t *testing.T) { router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) - panic("Oupps, Houston, we have a problem") + panic("Oops, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery", @@ -52,14 +53,14 @@ func TestPanicInHandler(t *testing.T) { router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { - panic("Oupps, Houston, we have a problem") + panic("Oops, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") - assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") + assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") @@ -80,7 +81,7 @@ func TestPanicWithAbort(t *testing.T) { router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) - panic("Oupps, Houston, we have a problem") + panic("Oops, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") @@ -152,6 +153,49 @@ func TestPanicWithAbortHandler(t *testing.T) { assert.NotContains(t, out, "panic recovered") } +func TestPanicInHandlerRecordsError(t *testing.T) { + tests := []struct { + name string + recoveredErr any + expectedErr string + }{ + { + name: "string panic", + recoveredErr: "Oops, Houston, we have a problem", + expectedErr: "Oops, Houston, we have a problem", + }, + { + name: "error panic", + recoveredErr: errors.New("recovered error"), + expectedErr: "recovered error", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + router := New() + + var recoveredErrors errorMsgs + router.Use(func(c *Context) { + c.Next() + recoveredErrors = c.Errors + }) + router.Use(RecoveryWithWriter(nil)) + router.GET("/recovery", func(_ *Context) { + panic(tt.recoveredErr) + }) + + w := PerformRequest(router, http.MethodGet, "/recovery") + + assert.Equal(t, http.StatusInternalServerError, w.Code) + if assert.Len(t, recoveredErrors, 1) { + assert.EqualError(t, recoveredErrors[0], tt.expectedErr) + assert.Equal(t, ErrorTypePrivate, recoveredErrors[0].Type) + } + }) + } +} + func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) @@ -162,14 +206,14 @@ func TestCustomRecoveryWithWriter(t *testing.T) { } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { - panic("Oupps, Houston, we have a problem") + panic("Oops, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") - assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") + assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") @@ -181,7 +225,7 @@ func TestCustomRecoveryWithWriter(t *testing.T) { assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") - assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) + assert.Equal(t, strings.Repeat("Oops, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } @@ -197,14 +241,14 @@ func TestCustomRecovery(t *testing.T) { } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { - panic("Oupps, Houston, we have a problem") + panic("Oops, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") - assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") + assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") @@ -216,7 +260,7 @@ func TestCustomRecovery(t *testing.T) { assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") - assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) + assert.Equal(t, strings.Repeat("Oops, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } @@ -232,14 +276,14 @@ func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { - panic("Oupps, Houston, we have a problem") + panic("Oops, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") - assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") + assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") @@ -251,7 +295,7 @@ func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") - assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) + assert.Equal(t, strings.Repeat("Oops, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } diff --git a/render/bson.go b/render/bson.go new file mode 100644 index 00000000..07f02333 --- /dev/null +++ b/render/bson.go @@ -0,0 +1,34 @@ +// Copyright 2025 Gin Core Team. 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" + + "go.mongodb.org/mongo-driver/v2/bson" +) + +// BSON contains the given interface object. +type BSON struct { + Data any +} + +var bsonContentType = []string{"application/bson"} + +// Render (BSON) marshals the given interface object and writes data with custom ContentType. +func (r BSON) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + + bytes, err := bson.Marshal(&r.Data) + if err == nil { + _, err = w.Write(bytes) + } + return err +} + +// WriteContentType (BSONBuf) writes BSONBuf ContentType. +func (r BSON) WriteContentType(w http.ResponseWriter) { + writeContentType(w, bsonContentType) +} diff --git a/render/data.go b/render/data.go index a653ea30..2c0ad5e3 100644 --- a/render/data.go +++ b/render/data.go @@ -4,7 +4,10 @@ package render -import "net/http" +import ( + "net/http" + "strconv" +) // Data contains ContentType and bytes data. type Data struct { @@ -15,6 +18,9 @@ type Data struct { // Render (Data) writes data with custom ContentType. func (r Data) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) + if len(r.Data) > 0 { + w.Header().Set("Content-Length", strconv.Itoa(len(r.Data))) + } _, err = w.Write(r.Data) return } diff --git a/render/html.go b/render/html.go index 965d84c6..36c8f079 100644 --- a/render/html.go +++ b/render/html.go @@ -5,6 +5,7 @@ package render import ( + "errors" "html/template" "net/http" @@ -50,6 +51,8 @@ type HTML struct { var htmlContentType = []string{"text/html; charset=utf-8"} +var errHTMLRendererNotConfigured = errors.New("html renderer is not configured") + // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ @@ -88,6 +91,9 @@ func (r HTMLDebug) loadTemplate() *template.Template { // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) + if r.Template == nil { + return errHTMLRendererNotConfigured + } if r.Name == "" { return r.Template.Execute(w, r.Data) diff --git a/render/pdf.go b/render/pdf.go new file mode 100644 index 00000000..04dcc1f5 --- /dev/null +++ b/render/pdf.go @@ -0,0 +1,26 @@ +// Copyright 2026 Gin Core Team. 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" + +// PDF contains the given PDF binary data. +type PDF struct { + Data []byte +} + +var pdfContentType = []string{"application/pdf"} + +// Render (PDF) writes PDF data with custom ContentType. +func (r PDF) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + _, err := w.Write(r.Data) + return err +} + +// WriteContentType (PDF) writes PDF ContentType for response. +func (r PDF) WriteContentType(w http.ResponseWriter) { + writeContentType(w, pdfContentType) +} diff --git a/render/render.go b/render/render.go index 4bdcfa23..28bc0f5d 100644 --- a/render/render.go +++ b/render/render.go @@ -31,6 +31,7 @@ var ( _ Render = (*AsciiJSON)(nil) _ Render = (*ProtoBuf)(nil) _ Render = (*TOML)(nil) + _ Render = (*PDF)(nil) ) func writeContentType(w http.ResponseWriter, value []string) { diff --git a/render/render_msgpack_test.go b/render/render_msgpack_test.go index 579897cc..48b23870 100644 --- a/render/render_msgpack_test.go +++ b/render/render_msgpack_test.go @@ -7,7 +7,7 @@ package render import ( - "bytes" + "errors" "net/http/httptest" "testing" @@ -16,9 +16,6 @@ import ( "github.com/ugorji/go/codec" ) -// TODO unit tests -// test errors - func TestRenderMsgPack(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ @@ -32,13 +29,52 @@ func TestRenderMsgPack(t *testing.T) { require.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) - + var decoded map[string]any + var mh codec.MsgpackHandle + mh.RawToString = true + err = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded) require.NoError(t, err) - assert.Equal(t, w.Body.String(), buf.String()) + assert.Equal(t, data, decoded) assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) } + +func TestWriteMsgPack(t *testing.T) { + w := httptest.NewRecorder() + data := map[string]any{ + "foo": "bar", + "num": 42, + } + + err := WriteMsgPack(w, data) + require.NoError(t, err) + + assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) + + var decoded map[string]any + var mh codec.MsgpackHandle + mh.RawToString = true + err = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded) + require.NoError(t, err) + assert.Len(t, decoded, 2) + assert.Equal(t, "bar", decoded["foo"]) + assert.EqualValues(t, 42, decoded["num"]) +} + +type failWriter struct { + *httptest.ResponseRecorder +} + +func (w *failWriter) Write(data []byte) (int, error) { + return 0, errors.New("write error") +} + +func TestRenderMsgPackError(t *testing.T) { + w := httptest.NewRecorder() + data := map[string]any{ + "foo": "bar", + } + + err := (MsgPack{data}).Render(&failWriter{w}) + require.Error(t, err) + assert.Contains(t, err.Error(), "write error") +} diff --git a/render/render_test.go b/render/render_test.go index d9ae2067..a3f90a3f 100644 --- a/render/render_test.go +++ b/render/render_test.go @@ -8,6 +8,7 @@ import ( "encoding/xml" "errors" "html/template" + "io" "net" "net/http" "net/http/httptest" @@ -15,16 +16,13 @@ import ( "strings" "testing" - "github.com/gin-gonic/gin/codec/json" testdata "github.com/gin-gonic/gin/testdata/protoexample" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.mongodb.org/mongo-driver/v2/bson" "google.golang.org/protobuf/proto" ) -// TODO unit tests -// test errors - func TestRenderJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ @@ -139,19 +137,44 @@ func TestRenderJsonpJSON(t *testing.T) { } type errorWriter struct { - bufString string + bufString string + ErrThreshold int // 1-based threshold. If 1, errors on the 1st Write call. + writeCount int *httptest.ResponseRecorder } var _ http.ResponseWriter = (*errorWriter)(nil) +func (w *errorWriter) Header() http.Header { + if w.ResponseRecorder == nil { + w.ResponseRecorder = httptest.NewRecorder() + } + return w.ResponseRecorder.Header() +} + +func (w *errorWriter) WriteHeader(statusCode int) { + if w.ResponseRecorder == nil { + w.ResponseRecorder = httptest.NewRecorder() + } + w.ResponseRecorder.WriteHeader(statusCode) +} + func (w *errorWriter) Write(buf []byte) (int, error) { - if string(buf) == w.bufString { - return 0, errors.New(`write "` + w.bufString + `" error`) + w.writeCount++ + if (w.bufString != "" && string(buf) == w.bufString) || (w.ErrThreshold > 0 && w.writeCount >= w.ErrThreshold) { + return 0, errors.New(`write error`) + } + if w.ResponseRecorder == nil { + w.ResponseRecorder = httptest.NewRecorder() } return w.ResponseRecorder.Write(buf) } +func (w *errorWriter) reset() { + w.writeCount = 0 + w.ResponseRecorder = httptest.NewRecorder() +} + func TestRenderJsonpJSONError(t *testing.T) { ew := &errorWriter{ ResponseRecorder: httptest.NewRecorder(), @@ -164,23 +187,33 @@ func TestRenderJsonpJSONError(t *testing.T) { }, } - cb := template.JSEscapeString(jsonpJSON.Callback) - ew.bufString = cb - err := jsonpJSON.Render(ew) // error was returned while writing callback - assert.Equal(t, `write "`+cb+`" error`, err.Error()) + // error was returned while writing callback + ew.reset() + ew.ErrThreshold = 1 + err := jsonpJSON.Render(ew) + require.Error(t, err) + assert.Equal(t, "write error", err.Error()) - ew.bufString = `(` + // error was returned while writing "(" + ew.reset() + ew.ErrThreshold = 2 err = jsonpJSON.Render(ew) - assert.Equal(t, `write "`+`(`+`" error`, err.Error()) + require.Error(t, err) + assert.Equal(t, "write error", err.Error()) - data, _ := json.API.Marshal(jsonpJSON.Data) // error was returned while writing data - ew.bufString = string(data) + // error was returned while writing data + ew.reset() + ew.ErrThreshold = 3 err = jsonpJSON.Render(ew) - assert.Equal(t, `write "`+string(data)+`" error`, err.Error()) + require.Error(t, err) + assert.Equal(t, "write error", err.Error()) - ew.bufString = `);` + // error was returned while writing ");" + ew.reset() + ew.ErrThreshold = 4 err = jsonpJSON.Render(ew) - assert.Equal(t, `write "`+`);`+`" error`, err.Error()) + require.Error(t, err) + assert.Equal(t, "write error", err.Error()) } func TestRenderJsonpJSONError2(t *testing.T) { @@ -250,7 +283,7 @@ func TestRenderPureJSON(t *testing.T) { type xmlmap map[string]any -// Allows type H to be used with xml.Marshal +// MarshalXML allows xmlmap to be used with xml.Marshal. func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", @@ -298,7 +331,7 @@ b: type fail struct{} -// Hook MarshalYAML +// MarshalYAML returns an error for YAML rendering failure tests. func (ft *fail) MarshalYAML() (any, error) { return nil, errors.New("fail") } @@ -359,6 +392,55 @@ func TestRenderProtoBufFail(t *testing.T) { require.Error(t, err) } +func TestRenderBSON(t *testing.T) { + w := httptest.NewRecorder() + reps := []int64{int64(1), int64(2)} + type mystruct struct { + Label string + Reps []int64 + } + + data := &mystruct{ + Label: "test", + Reps: reps, + } + + (BSON{data}).WriteContentType(w) + bsonData, err := bson.Marshal(data) + require.NoError(t, err) + assert.Equal(t, "application/bson", w.Header().Get("Content-Type")) + + err = (BSON{data}).Render(w) + + require.NoError(t, err) + assert.Equal(t, bsonData, w.Body.Bytes()) + assert.Equal(t, "application/bson", w.Header().Get("Content-Type")) +} + +func TestRenderBSONError(t *testing.T) { + w := httptest.NewRecorder() + data := make(chan int) + + err := (BSON{data}).Render(w) + require.Error(t, err) +} + +func TestRenderBSONWriteError(t *testing.T) { + type testStruct struct { + Value string + } + data := &testStruct{Value: "test"} + + ew := &errorWriter{ + ErrThreshold: 1, + ResponseRecorder: httptest.NewRecorder(), + } + + err := (BSON{data}).Render(ew) + require.Error(t, err) + assert.Equal(t, "write error", err.Error()) +} + func TestRenderXML(t *testing.T) { w := httptest.NewRecorder() data := xmlmap{ @@ -375,6 +457,31 @@ func TestRenderXML(t *testing.T) { assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) } +func TestRenderXMLError(t *testing.T) { + w := httptest.NewRecorder() + data := make(chan int) + + err := (XML{data}).Render(w) + require.Error(t, err) + assert.Contains(t, err.Error(), "xml: unsupported type: chan int") +} + +func TestRenderPDF(t *testing.T) { + w := httptest.NewRecorder() + data := []byte("%Test pdf content") + + pdf := PDF{data} + + pdf.WriteContentType(w) + assert.Equal(t, "application/pdf", w.Header().Get("Content-Type")) + + err := pdf.Render(w) + require.NoError(t, err) + + assert.Equal(t, data, w.Body.Bytes()) + assert.Equal(t, "application/pdf", w.Header().Get("Content-Type")) +} + func TestRenderRedirect(t *testing.T) { req, err := http.NewRequest(http.MethodGet, "/test-redirect", nil) require.NoError(t, err) @@ -427,6 +534,52 @@ func TestRenderData(t *testing.T) { require.NoError(t, err) assert.Equal(t, "#!PNG some raw data", w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) + assert.Equal(t, "19", w.Header().Get("Content-Length")) +} + +func TestRenderDataContentLength(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + size, err := strconv.Atoi(r.URL.Query().Get("size")) + assert.NoError(t, err) + + data := Data{ + ContentType: "application/octet-stream", + Data: make([]byte, size), + } + assert.NoError(t, data.Render(w)) + })) + t.Cleanup(srv.Close) + + for _, size := range []int{0, 1, 100, 100_000} { + t.Run(strconv.Itoa(size), func(t *testing.T) { + resp, err := http.Get(srv.URL + "?size=" + strconv.Itoa(size)) + require.NoError(t, err) + defer resp.Body.Close() + + assert.Equal(t, "application/octet-stream", resp.Header.Get("Content-Type")) + assert.Equal(t, strconv.Itoa(size), resp.Header.Get("Content-Length")) + + actual, err := io.Copy(io.Discard, resp.Body) + require.NoError(t, err) + assert.EqualValues(t, size, actual) + }) + } +} + +func TestRenderDataError(t *testing.T) { + ew := &errorWriter{ + ErrThreshold: 1, + ResponseRecorder: httptest.NewRecorder(), + } + data := []byte("#!PNG some raw data") + + err := (Data{ + ContentType: "image/png", + Data: data, + }).Render(ew) + + require.Error(t, err) + assert.Equal(t, "write error", err.Error()) } func TestRenderString(t *testing.T) { @@ -477,6 +630,16 @@ func TestRenderHTMLTemplate(t *testing.T) { assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } +func TestRenderHTMLWithoutTemplate(t *testing.T) { + w := httptest.NewRecorder() + + err := (HTML{}).Render(w) + + require.EqualError(t, err, "html renderer is not configured") + assert.Empty(t, w.Body.String()) + assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) +} + func TestRenderHTMLTemplateEmptyName(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("").Parse(`Hello {{.name}}`)) @@ -568,6 +731,32 @@ func TestRenderHTMLDebugPanics(t *testing.T) { assert.Panics(t, func() { htmlRender.Instance("", nil) }) } +func TestRenderHTMLTemplateError(t *testing.T) { + w := httptest.NewRecorder() + templ := template.Must(template.New("t").Parse(`Hello {{if .name}}{{.name.DoesNotExist}}{{end}}`)) + + htmlRender := HTMLProduction{Template: templ} + instance := htmlRender.Instance("t", map[string]any{ + "name": "alexandernyquist", + }) + + err := instance.Render(w) + require.Error(t, err) +} + +func TestRenderHTMLTemplateExecuteError(t *testing.T) { + w := httptest.NewRecorder() + templ := template.Must(template.New("t").Parse(`Hello {{.name.invalid}}`)) + + htmlRender := HTMLProduction{Template: templ} + instance := htmlRender.Instance("t", map[string]any{ + "name": "alexandernyquist", + }) + + err := instance.Render(w) + require.Error(t, err) +} + func TestRenderReader(t *testing.T) { w := httptest.NewRecorder() @@ -619,10 +808,10 @@ func TestRenderWriteError(t *testing.T) { prefix := "my-prefix:" r := SecureJSON{Data: data, Prefix: prefix} ew := &errorWriter{ - bufString: prefix, + ErrThreshold: 1, ResponseRecorder: httptest.NewRecorder(), } err := r.Render(ew) require.Error(t, err) - assert.Equal(t, `write "my-prefix:" error`, err.Error()) + assert.Equal(t, "write error", err.Error()) } diff --git a/response_writer.go b/response_writer.go index 142a7cc5..80c5f53d 100644 --- a/response_writer.go +++ b/response_writer.go @@ -117,15 +117,22 @@ func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size > 0 { return nil, nil, errHijackAlreadyWritten } + hijacker, ok := w.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, http.ErrNotSupported + } if w.size < 0 { w.size = 0 } - return w.ResponseWriter.(http.Hijacker).Hijack() + return hijacker.Hijack() } // CloseNotify implements the http.CloseNotifier interface. func (w *responseWriter) CloseNotify() <-chan bool { - return w.ResponseWriter.(http.CloseNotifier).CloseNotify() + if cn, ok := w.ResponseWriter.(http.CloseNotifier); ok { + return cn.CloseNotify() + } + return nil } // Flush implements the http.Flusher interface. diff --git a/response_writer_test.go b/response_writer_test.go index 255559a7..47856bd3 100644 --- a/response_writer_test.go +++ b/response_writer_test.go @@ -15,10 +15,33 @@ import ( "github.com/stretchr/testify/require" ) -// TODO -// func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { -// func (w *responseWriter) CloseNotify() <-chan bool { -// func (w *responseWriter) Flush() { +// TestResponseWriterFlushWithFlusher verifies Flush() calls the underlying Flusher. +func TestResponseWriterFlushWithFlusher(t *testing.T) { + testWriter := httptest.NewRecorder() + writer := &responseWriter{ResponseWriter: testWriter} + writer.Flush() + assert.True(t, testWriter.Flushed) +} + +// TestResponseWriterFlushWithNonFlusher verifies Flush() is a no-op +// when the underlying ResponseWriter does not implement http.Flusher. +// Guards against the panic reported in https://github.com/gin-gonic/gin/issues/4460 +func TestResponseWriterFlushWithNonFlusher(t *testing.T) { + nonFlusher := &nonFlusherWriter{header: http.Header{}} + writer := &responseWriter{ResponseWriter: nonFlusher} + require.NotPanics(t, func() { + writer.Flush() + }) +} + +// nonFlusherWriter is a minimal http.ResponseWriter that does NOT implement http.Flusher. +type nonFlusherWriter struct { + header http.Header +} + +func (w *nonFlusherWriter) Header() http.Header { return w.header } +func (w *nonFlusherWriter) Write(b []byte) (int, error) { return len(b), nil } +func (w *nonFlusherWriter) WriteHeader(code int) {} var ( _ ResponseWriter = &responseWriter{} @@ -124,15 +147,18 @@ func TestResponseWriterHijack(t *testing.T) { writer.reset(testWriter) w := ResponseWriter(writer) - assert.Panics(t, func() { - _, _, err := w.Hijack() - require.NoError(t, err) - }) - assert.True(t, w.Written()) + // httptest.ResponseRecorder doesn't implement http.Hijacker; return + // http.ErrNotSupported instead of panicking (#4638). On unsupported the + // writer state stays untouched so the handler can still emit a normal + // HTTP response as a fallback. + conn, buf, err := w.Hijack() + assert.Nil(t, conn) + assert.Nil(t, buf) + require.ErrorIs(t, err, http.ErrNotSupported) + assert.False(t, w.Written()) - assert.Panics(t, func() { - w.CloseNotify() - }) + // CloseNotify on a non-CloseNotifier returns nil instead of panicking. + assert.Nil(t, w.CloseNotify()) w.Flush() } @@ -205,7 +231,8 @@ func TestResponseWriterHijackAfterWrite(t *testing.T) { } } -// Test: WebSocket compatibility - allow hijack after WriteHeaderNow(), but block after body data. +// TestResponseWriterHijackAfterWriteHeaderNow verifies that hijacking is allowed after +// WriteHeaderNow but blocked after body data is written. func TestResponseWriterHijackAfterWriteHeaderNow(t *testing.T) { tests := []struct { name string diff --git a/routergroup.go b/routergroup.go index b2540ec1..47eeee58 100644 --- a/routergroup.go +++ b/routergroup.go @@ -11,6 +11,11 @@ import ( "strings" ) +// MethodQuery is the HTTP QUERY method defined by RFC 10008. It is declared +// here because the standard library does not provide http.MethodQuery yet. +// Once it does, this constant keeps the same value and stays valid. +const MethodQuery = "QUERY" + var ( // regEnLetter matches english letters for http method name regEnLetter = regexp.MustCompile("^[A-Z]+$") @@ -19,7 +24,7 @@ var ( anyMethods = []string{ http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect, - http.MethodTrace, + http.MethodTrace, MethodQuery, } ) @@ -50,6 +55,22 @@ type IRoutes interface { StaticFS(string, http.FileSystem) IRoutes } +// IQueryRoutes defines the router handle interface for the HTTP QUERY method. +// +// It is deliberately kept out of IRoutes: adding a method to IRoutes would +// break every type outside of Gin that implements it, such as test doubles and +// wrappers. Type assert when you only hold an IRoutes value: +// +// if q, ok := routes.(gin.IQueryRoutes); ok { +// q.QUERY("/search", handler) +// } +// +// *gin.RouterGroup and *gin.Engine satisfy this interface, so the assertion is +// only needed when the concrete type has been erased. +type IQueryRoutes interface { + QUERY(string, ...HandlerFunc) IRoutes +} + // RouterGroup is used internally to configure router, a RouterGroup is associated with // a prefix and an array of handlers (middleware). type RouterGroup struct { @@ -59,7 +80,10 @@ type RouterGroup struct { root bool } -var _ IRouter = (*RouterGroup)(nil) +var ( + _ IRouter = (*RouterGroup)(nil) + _ IQueryRoutes = (*RouterGroup)(nil) +) // Use adds middleware to the group, see example code in GitHub. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { @@ -100,6 +124,8 @@ func (group *RouterGroup) handle(httpMethod, relativePath string, handlers Handl // 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). +// +// It panics if httpMethod is not a valid HTTP method (uppercase ASCII letters only). func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { if matched := regEnLetter.MatchString(httpMethod); !matched { panic("http method " + httpMethod + " is not valid") @@ -142,8 +168,17 @@ func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRo return group.handle(http.MethodHead, relativePath, handlers) } +// QUERY is a shortcut for router.Handle("QUERY", path, handlers). +// +// QUERY is the safe and idempotent method defined by RFC 10008 that carries its +// query in the request body. The body is read like any other body, for example +// with c.ShouldBindJSON. +func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(MethodQuery, relativePath, handlers) +} + // Any registers a route that matches all the HTTP methods. -// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. +// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE, QUERY. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range anyMethods { group.handle(method, relativePath, handlers) @@ -169,7 +204,7 @@ func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { }) } -// StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.. +// StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead. // router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false}) // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes { @@ -200,6 +235,7 @@ func (group *RouterGroup) Static(relativePath, root string) IRoutes { // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. // Gin by default uses: gin.Dir() +// It panics if relativePath contains URL parameters (: or *). 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") diff --git a/routergroup_test.go b/routergroup_test.go index 182c5589..c3859a35 100644 --- a/routergroup_test.go +++ b/routergroup_test.go @@ -42,6 +42,7 @@ func TestRouterGroupBasicHandle(t *testing.T) { performRequestInGroup(t, http.MethodDelete) performRequestInGroup(t, http.MethodHead) performRequestInGroup(t, http.MethodOptions) + performRequestInGroup(t, MethodQuery) } func performRequestInGroup(t *testing.T, method string) { @@ -78,6 +79,9 @@ func performRequestInGroup(t *testing.T, method string) { case http.MethodOptions: v1.OPTIONS("/test", handler) login.OPTIONS("/test", handler) + case MethodQuery: + v1.QUERY("/test", handler) + login.QUERY("/test", handler) default: panic("unknown method") } @@ -217,3 +221,25 @@ func TestRouterGroupCombineHandlersEmptySliceNotNil(t *testing.T) { assert.NotNil(t, result, "result should not be nil even with empty handlers") assert.Empty(t, result, "empty handlers should return empty chain") } + +func TestRouterGroupAny(t *testing.T) { + router := New() + router.Any("/any", func(c *Context) { + c.String(http.StatusOK, c.Request.Method) + }) + + v1 := router.Group("/v1") + v1.Any("/any", func(c *Context) { + c.String(http.StatusOK, "v1:"+c.Request.Method) + }) + + for _, method := range anyMethods { + w := PerformRequest(router, method, "/any") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, method, w.Body.String()) + + w = PerformRequest(router, method, "/v1/any") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "v1:"+method, w.Body.String()) + } +} diff --git a/routes_test.go b/routes_test.go index 1cae3fce..a032a2b7 100644 --- a/routes_test.go +++ b/routes_test.go @@ -10,6 +10,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -51,7 +52,7 @@ func testRouteOK(method string, t *testing.T) { assert.True(t, passedAny) } -// TestSingleRouteOK tests that POST route is correctly invoked. +// testRouteNotOK tests that a request with the wrong method returns a not found response. func testRouteNotOK(method string, t *testing.T) { passed := false router := New() @@ -65,7 +66,7 @@ func testRouteNotOK(method string, t *testing.T) { assert.Equal(t, http.StatusNotFound, w.Code) } -// TestSingleRouteOK tests that POST route is correctly invoked. +// testRouteNotOK2 tests that a request with the wrong method returns a method not allowed response. func testRouteNotOK2(method string, t *testing.T) { passed := false router := New() @@ -86,6 +87,59 @@ func testRouteNotOK2(method string, t *testing.T) { assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } +// TestRouteQuery tests that a QUERY route is invoked and can read the request +// body, which is the whole point of the method (RFC 10008). +func TestRouteQuery(t *testing.T) { + type search struct { + Term string `json:"term"` + } + + router := New() + router.QUERY("/search", func(c *Context) { + var body search + require.NoError(t, c.ShouldBindJSON(&body)) + c.String(http.StatusOK, body.Term) + }) + + req := httptest.NewRequest(MethodQuery, "/search", strings.NewReader(`{"term":"gin"}`)) + req.Header.Set("Content-Type", MIMEJSON) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "gin", w.Body.String()) +} + +// TestRouteQueryRegisteredByAny documents that Any registers QUERY. +func TestRouteQueryRegisteredByAny(t *testing.T) { + router := New() + router.Any("/test", func(c *Context) { + c.Status(http.StatusOK) + }) + + w := PerformRequest(router, MethodQuery, "/test") + + assert.Equal(t, http.StatusOK, w.Code) +} + +// TestQueryRoutesInterface tests that a router reached through IRoutes can +// still register a QUERY route via the IQueryRoutes assertion. +func TestQueryRoutesInterface(t *testing.T) { + router := New() + + var routes IRoutes = router.Group("/v1") + queryRoutes, ok := routes.(IQueryRoutes) + require.True(t, ok) + + queryRoutes.QUERY("/search", func(c *Context) { + c.Status(http.StatusOK) + }) + + w := PerformRequest(router, MethodQuery, "/v1/search") + + assert.Equal(t, http.StatusOK, w.Code) +} + func TestRouterMethod(t *testing.T) { router := New() router.PUT("/hey2", func(c *Context) { @@ -116,6 +170,7 @@ func TestRouterGroupRouteOK(t *testing.T) { testRouteOK(http.MethodDelete, t) testRouteOK(http.MethodConnect, t) testRouteOK(http.MethodTrace, t) + testRouteOK(MethodQuery, t) } func TestRouteNotOK(t *testing.T) { @@ -128,6 +183,7 @@ func TestRouteNotOK(t *testing.T) { testRouteNotOK(http.MethodDelete, t) testRouteNotOK(http.MethodConnect, t) testRouteNotOK(http.MethodTrace, t) + testRouteNotOK(MethodQuery, t) } func TestRouteNotOK2(t *testing.T) { @@ -140,6 +196,7 @@ func TestRouteNotOK2(t *testing.T) { testRouteNotOK2(http.MethodDelete, t) testRouteNotOK2(http.MethodConnect, t) testRouteNotOK2(http.MethodTrace, t) + testRouteNotOK2(MethodQuery, t) } func TestRouteRedirectTrailingSlash(t *testing.T) { @@ -273,7 +330,7 @@ func TestRouteRedirectFixedPath(t *testing.T) { assert.Equal(t, http.StatusTemporaryRedirect, w.Code) } -// TestContextParamsGet tests that a parameter can be parsed from the URL. +// TestRouteParamsByName tests that route parameters can be parsed by name. func TestRouteParamsByName(t *testing.T) { name := "" lastName := "" @@ -305,7 +362,7 @@ func TestRouteParamsByName(t *testing.T) { assert.Equal(t, "/is/super/great", wild) } -// TestContextParamsGet tests that a parameter can be parsed from the URL even with extra slashes. +// TestRouteParamsByNameWithExtraSlash tests that route parameters can be parsed by name even with extra slashes. func TestRouteParamsByNameWithExtraSlash(t *testing.T) { name := "" lastName := "" @@ -377,7 +434,7 @@ func TestRouteParamsNotEmpty(t *testing.T) { assert.Equal(t, "/is/super/great", wild) } -// TestHandleStaticFile - ensure the static file handles properly +// TestRouteStaticFile tests that a static file is served correctly. func TestRouteStaticFile(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() @@ -412,7 +469,7 @@ func TestRouteStaticFile(t *testing.T) { assert.Equal(t, http.StatusOK, w3.Code) } -// TestHandleStaticFile - ensure the static file handles properly +// TestRouteStaticFileFS tests that a static file from an http.FileSystem is served correctly. func TestRouteStaticFileFS(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() @@ -446,7 +503,7 @@ func TestRouteStaticFileFS(t *testing.T) { assert.Equal(t, http.StatusOK, w3.Code) } -// TestHandleStaticDir - ensure the root/sub dir handles properly +// TestRouteStaticListingDir tests that static directory listing is enabled when configured. func TestRouteStaticListingDir(t *testing.T) { router := New() router.StaticFS("/", Dir("./", true)) @@ -458,7 +515,7 @@ func TestRouteStaticListingDir(t *testing.T) { assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } -// TestHandleHeadToDir - ensure the root/sub dir handles properly +// TestRouteStaticNoListing tests that static directory listing is disabled by default. func TestRouteStaticNoListing(t *testing.T) { router := New() router.Static("/", "./") @@ -656,7 +713,7 @@ func TestRouterStaticFSFileNotFound(t *testing.T) { }) } -// Reproduction test for the bug of issue #1805 +// TestMiddlewareCalledOnceByRouterStaticFSNotFound reproduces the bug reported in issue #1805. func TestMiddlewareCalledOnceByRouterStaticFSNotFound(t *testing.T) { router := New() @@ -789,3 +846,124 @@ func TestEngineHandleMethodNotAllowedCornerCase(t *testing.T) { w := PerformRequest(r, http.MethodGet, "/base/v1/user/groups") assert.Equal(t, http.StatusNotFound, w.Code) } + +func TestLateRouteRegistrationSkippedNodes(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + router.GET("/a", func(c *Context) { c.Status(http.StatusOK) }) + + w := PerformRequest(router, http.MethodGet, "/a") + if w.Code != http.StatusOK { + t.Fatalf("warmup status = %d, want 200", w.Code) + } + + h := func(c *Context) {} + router.GET("/x/y/z/w", h) + router.GET("/x/y/:id/w", h) + router.GET("/x/:id/z/w", h) + router.GET("/:id/y/z/w", h) + + req := httptest.NewRequest(http.MethodPost, "/x/y/z/w/extra", nil) + w = httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404", w.Code) + } +} + +// TestIssue4818_skippedNodesOverflow_Panic reproduces the panic from issue #4818: +// with HandleMethodNotAllowed enabled, getValue is called once per method tree +// reusing the same c.skippedNodes stack without resetting it, so residue +// accumulates until the reslice exceeds the capacity (engine.maxSections). +// The request must not panic and must fall through to the normal 404 path +// (the path genuinely matches no route, so 405 is not applicable here). +func TestIssue4818_skippedNodesOverflow_Panic(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + + h := func(c *Context) {} + router.OPTIONS("/:p0/:p1/a/:p2", h) + router.GET("/:p0/:p1/a/:p2", h) + router.PATCH("/b/:p0/:p1/c", h) + router.DELETE("/b/:p0/:p1/d/:p3", h) + router.GET("/b/:p0/:p1/e/f", h) + router.POST("/b/:p0/:p1/g/:p4/h", h) + router.OPTIONS("/b/:p0/:p1/g/:p4/h", h) + router.DELETE("/b/cache", h) + router.GET("/b/clients/:p1/g", h) + router.POST("/b/clients/:p1/g", h) + router.PATCH("/b/clients/:p1/g/:p4", h) + router.OPTIONS("/b/clients/:p1/g/:p4", h) + + req := httptest.NewRequest(http.MethodPost, "/b/clients/42", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + // Must not panic; path matches no route, so 404 is the correct outcome. + if w.Code != http.StatusNotFound { + t.Fatalf("expected 404, got %d (a panic would have aborted the test)", w.Code) + } +} + +// TestIssue4818_MethodNotAllowedStillWorks verifies the HandleMethodNotAllowed +// loop still produces a correct 405 with an Allow header after the fix, i.e. +// the reset does not break the loop across multiple method trees. +func TestIssue4818_MethodNotAllowedStillWorks(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + + h := func(c *Context) {} + router.OPTIONS("/:p0/:p1/a/:p2", h) + router.GET("/:p0/:p1/a/:p2", h) + router.PATCH("/b/:p0/:p1/c", h) + router.DELETE("/b/:p0/:p1/d/:p3", h) + router.GET("/b/:p0/:p1/e/f", h) + router.POST("/b/:p0/:p1/g/:p4/h", h) + router.OPTIONS("/b/:p0/:p1/g/:p4/h", h) + router.DELETE("/b/cache", h) + router.GET("/b/clients/:p1/g", h) + router.POST("/b/clients/:p1/g", h) + router.PATCH("/b/clients/:p1/g/:p4", h) + router.OPTIONS("/b/clients/:p1/g/:p4", h) + + // PATCH /b/clients/42/g is registered under GET but not under PATCH + // -> HandleMethodNotAllowed should yield 405 with an Allow header. + req := httptest.NewRequest(http.MethodPatch, "/b/clients/42/g", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusMethodNotAllowed { + t.Fatalf("expected 405, got %d", w.Code) + } + allow := w.Header().Get("Allow") + if allow == "" { + t.Fatal("expected Allow header to be set for 405") + } +} + +// TestIssue4818_MethodNotAllowedManyTrees stresses the loop across many +// method trees to make sure the skipped-nodes accumulator can never overflow. +func TestIssue4818_MethodNotAllowedManyTrees(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + + h := func(c *Context) {} + for _, m := range []string{ + http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, + http.MethodPatch, http.MethodOptions, http.MethodHead, http.MethodConnect, + http.MethodTrace, + } { + router.Handle(m, "/:p0/:p1/a/:p2", h) + router.Handle(m, "/s/:p0/:p1/:p2/:p3/:p4/:p5/d", h) + } + // GET route so that a POST to a GET-only path yields 405 + router.GET("/only-get", h) + + req := httptest.NewRequest(http.MethodPost, "/only-get", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusMethodNotAllowed { + t.Fatalf("expected 405, got %d", w.Code) + } +} diff --git a/test_helpers.go b/test_helpers.go index 20d20032..146be8f3 100644 --- a/test_helpers.go +++ b/test_helpers.go @@ -49,10 +49,7 @@ func waitForServerReady(url string, maxAttempts int) error { } // Exponential backoff: 10ms, 20ms, 40ms, 80ms, 160ms... - backoff := time.Duration(10*(1< 500*time.Millisecond { - backoff = 500 * time.Millisecond - } + backoff := min(time.Duration(10*(1< 0 { + rb = shiftNRuneBytes(rb, npLen) + + if rb[0] != 0 { + idxc := rb[0] + for i, c := range []byte(n.indices) { + if c == idxc { + if out := n.children[i].findCaseInsensitivePathRec( + path, ciPath, rb, fixTrailingSlash, + ); out != nil { + return out + } + break + } + } + } else { + var rv rune + var off int + for max_ := min(npLen, 3); off < max_; off++ { + if i := npLen - off; utf8.RuneStart(oldPath[i]) { + rv, _ = utf8.DecodeRuneInString(oldPath[i:]) + break + } + } + + lo := unicode.ToLower(rv) + utf8.EncodeRune(rb[:], lo) + rb = shiftNRuneBytes(rb, off) + + idxc := rb[0] + for i, c := range []byte(n.indices) { + if c == idxc { + if out := n.children[i].findCaseInsensitivePathRec( + path, ciPath, rb, fixTrailingSlash, + ); out != nil { + return out + } + break + } + } + + if up := unicode.ToUpper(rv); up != lo { + utf8.EncodeRune(rb[:], up) + rb = shiftNRuneBytes(rb, off) + + idxc := rb[0] + for i, c := range []byte(n.indices) { + if c == idxc { + if out := n.children[i].findCaseInsensitivePathRec( + path, ciPath, rb, fixTrailingSlash, + ); out != nil { + return out + } + break + } + } + } + } + } + + // Fall back to wildcard child, which is always at the end of the array + n = n.children[len(n.children)-1] switch n.nType { case param: // Find param end (either '/' or path end) diff --git a/tree_test.go b/tree_test.go index b580007d..23339af4 100644 --- a/tree_test.go +++ b/tree_test.go @@ -1018,3 +1018,96 @@ func TestWildcardInvalidSlash(t *testing.T) { } } } + +func TestTreeFindCaseInsensitivePathWithMultipleChildrenAndWildcard(t *testing.T) { + tree := &node{} + + // Setup routes that create a node with both static children and a wildcard child. + // This configuration previously caused a panic ("invalid node type") in + // findCaseInsensitivePathRec because it accessed children[0] instead of the + // wildcard child (which is always at the end of the children array). + // See: https://github.com/gin-gonic/gin/issues/2959 + routes := [...]string{ + "/aa/aa", + "/:bb/aa", + } + + for _, route := range routes { + recv := catchPanic(func() { + tree.addRoute(route, fakeHandler(route)) + }) + if recv != nil { + t.Fatalf("panic inserting route '%s': %v", route, recv) + } + } + + // These lookups previously panicked with "invalid node type" because + // findCaseInsensitivePathRec picked children[0] (a static node) instead + // of the wildcard child at the end of the array. + out, found := tree.findCaseInsensitivePath("/aa", true) + if found { + t.Errorf("Expected no match for '/aa', but got: %s", string(out)) + } + + out, found = tree.findCaseInsensitivePath("/aa/aa/aa/aa", true) + if found { + t.Errorf("Expected no match for '/aa/aa/aa/aa', but got: %s", string(out)) + } + + // Case-insensitive lookup should match the static route /aa/aa + out, found = tree.findCaseInsensitivePath("/AA/AA", true) + if !found { + t.Error("Route '/AA/AA' not found via case-insensitive lookup") + } else if string(out) != "/aa/aa" { + t.Errorf("Wrong result for '/AA/AA': expected '/aa/aa', got: %s", string(out)) + } +} + +func TestTreeFindCaseInsensitivePathWildcardParamAndStaticChild(t *testing.T) { + tree := &node{} + + // Another variant: param route + static route under same prefix + routes := [...]string{ + "/prefix/:id", + "/prefix/xxx", + } + + for _, route := range routes { + recv := catchPanic(func() { + tree.addRoute(route, fakeHandler(route)) + }) + if recv != nil { + t.Fatalf("panic inserting route '%s': %v", route, recv) + } + } + + // Should NOT panic even for paths that don't match any route + out, found := tree.findCaseInsensitivePath("/prefix/a/b/c", true) + if found { + t.Errorf("Expected no match for '/prefix/a/b/c', but got: %s", string(out)) + } + + // Exact match should still work + out, found = tree.findCaseInsensitivePath("/prefix/xxx", true) + if !found { + t.Error("Route '/prefix/xxx' not found") + } else if string(out) != "/prefix/xxx" { + t.Errorf("Wrong result for '/prefix/xxx': %s", string(out)) + } + + // Case-insensitive match should work + out, found = tree.findCaseInsensitivePath("/PREFIX/XXX", true) + if !found { + t.Error("Route '/PREFIX/XXX' not found via case-insensitive lookup") + } else if string(out) != "/prefix/xxx" { + t.Errorf("Wrong result for '/PREFIX/XXX': expected '/prefix/xxx', got: %s", string(out)) + } + + // Param route should still match + out, found = tree.findCaseInsensitivePath("/prefix/something", true) + if !found { + t.Error("Route '/prefix/something' not found via param match") + } else if string(out) != "/prefix/something" { + t.Errorf("Wrong result for '/prefix/something': %s", string(out)) + } +} diff --git a/utils.go b/utils.go index 2fecce46..e8b86fcc 100644 --- a/utils.go +++ b/utils.go @@ -26,6 +26,7 @@ const localhostIP = "127.0.0.1" const localhostIPv6 = "::1" // Bind is a helper function for given interface object and returns a Gin middleware. +// It panics if val is a pointer; pass the struct value directly (e.g., gin.Bind(Struct{}) not gin.Bind(&Struct{})). func Bind(val any) HandlerFunc { value := reflect.ValueOf(val) if value.Kind() == reflect.Ptr { @@ -160,7 +161,8 @@ func resolveAddress(addr []string) string { } } -// https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters +// isASCII reports whether s contains only ASCII characters. +// See https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters. func isASCII(s string) bool { for i := range len(s) { if s[i] > unicode.MaxASCII { diff --git a/utils_test.go b/utils_test.go index 893ebc88..e1f2c332 100644 --- a/utils_test.go +++ b/utils_test.go @@ -13,6 +13,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func init() { @@ -145,6 +146,17 @@ func TestMarshalXMLforH(t *testing.T) { assert.Error(t, e) } +func TestMarshalXMLforHSuccess(t *testing.T) { + h := H{ + "key1": "value1", + "key2": 123, + } + data, err := xml.Marshal(h) + require.NoError(t, err) + assert.Contains(t, string(data), "value1") + assert.Contains(t, string(data), "123") +} + func TestIsASCII(t *testing.T) { assert.True(t, isASCII("test")) assert.False(t, isASCII("🧡💛💚💙💜")) diff --git a/version.go b/version.go index 8049058c..5b54e68a 100644 --- a/version.go +++ b/version.go @@ -5,4 +5,4 @@ package gin // Version is the current gin framework's version. -const Version = "v1.11.0" +const Version = "v1.12.0"