ybelkada HF Staff commited on
Commit
3de7685
·
verified ·
1 Parent(s): b4b0aeb

Harbor format: 871 coding_baseline tasks (part 21)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/.github/FUNDING.yml +12 -0
  2. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/.gitignore +3 -0
  3. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/CHANGELOG.md +341 -0
  4. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/CONTRIBUTING.md +31 -0
  5. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/LICENSE +20 -0
  6. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/Makefile +22 -0
  7. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/README.md +505 -0
  8. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/SECURITY.md +5 -0
  9. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/README.md +24 -0
  10. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/chi.svg +6 -0
  11. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/custom-handler/main.go +35 -0
  12. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/custom-method/main.go +33 -0
  13. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/fileserver/data/notes.txt +1 -0
  14. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/fileserver/main.go +65 -0
  15. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/graceful/main.go +82 -0
  16. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/hello-world/main.go +21 -0
  17. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/limits/main.go +92 -0
  18. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/logging/main.go +9 -0
  19. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/go.mod +9 -0
  20. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/go.sum +8 -0
  21. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/main.go +520 -0
  22. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/routes.json +260 -0
  23. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/routes.md +159 -0
  24. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/router-walk/main.go +42 -0
  25. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/todos-resource/main.go +30 -0
  26. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/todos-resource/todos.go +53 -0
  27. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/todos-resource/users.go +48 -0
  28. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/data/article.go +9 -0
  29. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/data/errors.go +28 -0
  30. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/go.mod +10 -0
  31. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/go.sum +6 -0
  32. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/main.go +154 -0
  33. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/presenter/v1/article.go +22 -0
  34. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/presenter/v2/article.go +30 -0
  35. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/presenter/v3/article.go +39 -0
  36. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/chain.go +49 -0
  37. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/chi.go +137 -0
  38. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/context.go +165 -0
  39. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/go.mod +5 -0
  40. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/basic_auth.go +33 -0
  41. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/clean_path.go +28 -0
  42. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/compress.go +392 -0
  43. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/content_charset.go +50 -0
  44. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/content_encoding.go +34 -0
  45. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/content_type.go +45 -0
  46. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/get_head.go +39 -0
  47. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/heartbeat.go +26 -0
  48. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/logger.go +172 -0
  49. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/maybe.go +18 -0
  50. tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/middleware.go +23 -0
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/.github/FUNDING.yml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: [pkieltyka] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4
+ patreon: # Replace with a single Patreon username
5
+ open_collective: # Replace with a single Open Collective username
6
+ ko_fi: # Replace with a single Ko-fi username
7
+ tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8
+ community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9
+ liberapay: # Replace with a single Liberapay username
10
+ issuehunt: # Replace with a single IssueHunt username
11
+ otechie: # Replace with a single Otechie username
12
+ custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .idea
2
+ *.sw?
3
+ .vscode
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/CHANGELOG.md ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ ## v5.0.12 (2024-02-16)
4
+
5
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.11...v5.0.12
6
+
7
+
8
+ ## v5.0.11 (2023-12-19)
9
+
10
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.10...v5.0.11
11
+
12
+
13
+ ## v5.0.10 (2023-07-13)
14
+
15
+ - Fixed small edge case in tests of v5.0.9 for older Go versions
16
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.9...v5.0.10
17
+
18
+
19
+ ## v5.0.9 (2023-07-13)
20
+
21
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.8...v5.0.9
22
+
23
+
24
+ ## v5.0.8 (2022-12-07)
25
+
26
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.7...v5.0.8
27
+
28
+
29
+ ## v5.0.7 (2021-11-18)
30
+
31
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.6...v5.0.7
32
+
33
+
34
+ ## v5.0.6 (2021-11-15)
35
+
36
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.5...v5.0.6
37
+
38
+
39
+ ## v5.0.5 (2021-10-27)
40
+
41
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.4...v5.0.5
42
+
43
+
44
+ ## v5.0.4 (2021-08-29)
45
+
46
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.3...v5.0.4
47
+
48
+
49
+ ## v5.0.3 (2021-04-29)
50
+
51
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.2...v5.0.3
52
+
53
+
54
+ ## v5.0.2 (2021-03-25)
55
+
56
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.1...v5.0.2
57
+
58
+
59
+ ## v5.0.1 (2021-03-10)
60
+
61
+ - Small improvements
62
+ - History of changes: see https://github.com/go-chi/chi/compare/v5.0.0...v5.0.1
63
+
64
+
65
+ ## v5.0.0 (2021-02-27)
66
+
67
+ - chi v5, `github.com/go-chi/chi/v5` introduces the adoption of Go's SIV to adhere to the current state-of-the-tools in Go.
68
+ - chi v1.5.x did not work out as planned, as the Go tooling is too powerful and chi's adoption is too wide.
69
+ The most responsible thing to do for everyone's benefit is to just release v5 with SIV, so I present to you all,
70
+ chi v5 at `github.com/go-chi/chi/v5`. I hope someday the developer experience and ergonomics I've been seeking
71
+ will still come to fruition in some form, see https://github.com/golang/go/issues/44550
72
+ - History of changes: see https://github.com/go-chi/chi/compare/v1.5.4...v5.0.0
73
+
74
+
75
+ ## v1.5.4 (2021-02-27)
76
+
77
+ - Undo prior retraction in v1.5.3 as we prepare for v5.0.0 release
78
+ - History of changes: see https://github.com/go-chi/chi/compare/v1.5.3...v1.5.4
79
+
80
+
81
+ ## v1.5.3 (2021-02-21)
82
+
83
+ - Update go.mod to go 1.16 with new retract directive marking all versions without prior go.mod support
84
+ - History of changes: see https://github.com/go-chi/chi/compare/v1.5.2...v1.5.3
85
+
86
+
87
+ ## v1.5.2 (2021-02-10)
88
+
89
+ - Reverting allocation optimization as a precaution as go test -race fails.
90
+ - Minor improvements, see history below
91
+ - History of changes: see https://github.com/go-chi/chi/compare/v1.5.1...v1.5.2
92
+
93
+
94
+ ## v1.5.1 (2020-12-06)
95
+
96
+ - Performance improvement: removing 1 allocation by foregoing context.WithValue, thank you @bouk for
97
+ your contribution (https://github.com/go-chi/chi/pull/555). Note: new benchmarks posted in README.
98
+ - `middleware.CleanPath`: new middleware that clean's request path of double slashes
99
+ - deprecate & remove `chi.ServerBaseContext` in favour of stdlib `http.Server#BaseContext`
100
+ - plus other tiny improvements, see full commit history below
101
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.1.2...v1.5.1
102
+
103
+
104
+ ## v1.5.0 (2020-11-12) - now with go.mod support
105
+
106
+ `chi` dates back to 2016 with it's original implementation as one of the first routers to adopt the newly introduced
107
+ context.Context api to the stdlib -- set out to design a router that is faster, more modular and simpler than anything
108
+ else out there -- while not introducing any custom handler types or dependencies. Today, `chi` still has zero dependencies,
109
+ and in many ways is future proofed from changes, given it's minimal nature. Between versions, chi's iterations have been very
110
+ incremental, with the architecture and api being the same today as it was originally designed in 2016. For this reason it
111
+ makes chi a pretty easy project to maintain, as well thanks to the many amazing community contributions over the years
112
+ to who all help make chi better (total of 86 contributors to date -- thanks all!).
113
+
114
+ Chi has been a labour of love, art and engineering, with the goals to offer beautiful ergonomics, flexibility, performance
115
+ and simplicity when building HTTP services with Go. I've strived to keep the router very minimal in surface area / code size,
116
+ and always improving the code wherever possible -- and as of today the `chi` package is just 1082 lines of code (not counting
117
+ middlewares, which are all optional). As well, I don't have the exact metrics, but from my analysis and email exchanges from
118
+ companies and developers, chi is used by thousands of projects around the world -- thank you all as there is no better form of
119
+ joy for me than to have art I had started be helpful and enjoyed by others. And of course I use chi in all of my own projects too :)
120
+
121
+ For me, the aesthetics of chi's code and usage are very important. With the introduction of Go's module support
122
+ (which I'm a big fan of), chi's past versioning scheme choice to v2, v3 and v4 would mean I'd require the import path
123
+ of "github.com/go-chi/chi/v4", leading to the lengthy discussion at https://github.com/go-chi/chi/issues/462.
124
+ Haha, to some, you may be scratching your head why I've spent > 1 year stalling to adopt "/vXX" convention in the import
125
+ path -- which isn't horrible in general -- but for chi, I'm unable to accept it as I strive for perfection in it's API design,
126
+ aesthetics and simplicity. It just doesn't feel good to me given chi's simple nature -- I do not foresee a "v5" or "v6",
127
+ and upgrading between versions in the future will also be just incremental.
128
+
129
+ I do understand versioning is a part of the API design as well, which is why the solution for a while has been to "do nothing",
130
+ as Go supports both old and new import paths with/out go.mod. However, now that Go module support has had time to iron out kinks and
131
+ is adopted everywhere, it's time for chi to get with the times. Luckily, I've discovered a path forward that will make me happy,
132
+ while also not breaking anyone's app who adopted a prior versioning from tags in v2/v3/v4. I've made an experimental release of
133
+ v1.5.0 with go.mod silently, and tested it with new and old projects, to ensure the developer experience is preserved, and it's
134
+ largely unnoticed. Fortunately, Go's toolchain will check the tags of a repo and consider the "latest" tag the one with go.mod.
135
+ However, you can still request a specific older tag such as v4.1.2, and everything will "just work". But new users can just
136
+ `go get github.com/go-chi/chi` or `go get github.com/go-chi/chi@latest` and they will get the latest version which contains
137
+ go.mod support, which is v1.5.0+. `chi` will not change very much over the years, just like it hasn't changed much from 4 years ago.
138
+ Therefore, we will stay on v1.x from here on, starting from v1.5.0. Any breaking changes will bump a "minor" release and
139
+ backwards-compatible improvements/fixes will bump a "tiny" release.
140
+
141
+ For existing projects who want to upgrade to the latest go.mod version, run: `go get -u github.com/go-chi/chi@v1.5.0`,
142
+ which will get you on the go.mod version line (as Go's mod cache may still remember v4.x). Brand new systems can run
143
+ `go get -u github.com/go-chi/chi` or `go get -u github.com/go-chi/chi@latest` to install chi, which will install v1.5.0+
144
+ built with go.mod support.
145
+
146
+ My apologies to the developers who will disagree with the decisions above, but, hope you'll try it and see it's a very
147
+ minor request which is backwards compatible and won't break your existing installations.
148
+
149
+ Cheers all, happy coding!
150
+
151
+
152
+ ---
153
+
154
+
155
+ ## v4.1.2 (2020-06-02)
156
+
157
+ - fix that handles MethodNotAllowed with path variables, thank you @caseyhadden for your contribution
158
+ - fix to replace nested wildcards correctly in RoutePattern, thank you @@unmultimedio for your contribution
159
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.1.1...v4.1.2
160
+
161
+
162
+ ## v4.1.1 (2020-04-16)
163
+
164
+ - fix for issue https://github.com/go-chi/chi/issues/411 which allows for overlapping regexp
165
+ route to the correct handler through a recursive tree search, thanks to @Jahaja for the PR/fix!
166
+ - new middleware.RouteHeaders as a simple router for request headers with wildcard support
167
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.1.0...v4.1.1
168
+
169
+
170
+ ## v4.1.0 (2020-04-1)
171
+
172
+ - middleware.LogEntry: Write method on interface now passes the response header
173
+ and an extra interface type useful for custom logger implementations.
174
+ - middleware.WrapResponseWriter: minor fix
175
+ - middleware.Recoverer: a bit prettier
176
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.0.4...v4.1.0
177
+
178
+ ## v4.0.4 (2020-03-24)
179
+
180
+ - middleware.Recoverer: new pretty stack trace printing (https://github.com/go-chi/chi/pull/496)
181
+ - a few minor improvements and fixes
182
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.0.3...v4.0.4
183
+
184
+
185
+ ## v4.0.3 (2020-01-09)
186
+
187
+ - core: fix regexp routing to include default value when param is not matched
188
+ - middleware: rewrite of middleware.Compress
189
+ - middleware: suppress http.ErrAbortHandler in middleware.Recoverer
190
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.0.2...v4.0.3
191
+
192
+
193
+ ## v4.0.2 (2019-02-26)
194
+
195
+ - Minor fixes
196
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.0.1...v4.0.2
197
+
198
+
199
+ ## v4.0.1 (2019-01-21)
200
+
201
+ - Fixes issue with compress middleware: #382 #385
202
+ - History of changes: see https://github.com/go-chi/chi/compare/v4.0.0...v4.0.1
203
+
204
+
205
+ ## v4.0.0 (2019-01-10)
206
+
207
+ - chi v4 requires Go 1.10.3+ (or Go 1.9.7+) - we have deprecated support for Go 1.7 and 1.8
208
+ - router: respond with 404 on router with no routes (#362)
209
+ - router: additional check to ensure wildcard is at the end of a url pattern (#333)
210
+ - middleware: deprecate use of http.CloseNotifier (#347)
211
+ - middleware: fix RedirectSlashes to include query params on redirect (#334)
212
+ - History of changes: see https://github.com/go-chi/chi/compare/v3.3.4...v4.0.0
213
+
214
+
215
+ ## v3.3.4 (2019-01-07)
216
+
217
+ - Minor middleware improvements. No changes to core library/router. Moving v3 into its
218
+ - own branch as a version of chi for Go 1.7, 1.8, 1.9, 1.10, 1.11
219
+ - History of changes: see https://github.com/go-chi/chi/compare/v3.3.3...v3.3.4
220
+
221
+
222
+ ## v3.3.3 (2018-08-27)
223
+
224
+ - Minor release
225
+ - See https://github.com/go-chi/chi/compare/v3.3.2...v3.3.3
226
+
227
+
228
+ ## v3.3.2 (2017-12-22)
229
+
230
+ - Support to route trailing slashes on mounted sub-routers (#281)
231
+ - middleware: new `ContentCharset` to check matching charsets. Thank you
232
+ @csucu for your community contribution!
233
+
234
+
235
+ ## v3.3.1 (2017-11-20)
236
+
237
+ - middleware: new `AllowContentType` handler for explicit whitelist of accepted request Content-Types
238
+ - middleware: new `SetHeader` handler for short-hand middleware to set a response header key/value
239
+ - Minor bug fixes
240
+
241
+
242
+ ## v3.3.0 (2017-10-10)
243
+
244
+ - New chi.RegisterMethod(method) to add support for custom HTTP methods, see _examples/custom-method for usage
245
+ - Deprecated LINK and UNLINK methods from the default list, please use `chi.RegisterMethod("LINK")` and `chi.RegisterMethod("UNLINK")` in an `init()` function
246
+
247
+
248
+ ## v3.2.1 (2017-08-31)
249
+
250
+ - Add new `Match(rctx *Context, method, path string) bool` method to `Routes` interface
251
+ and `Mux`. Match searches the mux's routing tree for a handler that matches the method/path
252
+ - Add new `RouteMethod` to `*Context`
253
+ - Add new `Routes` pointer to `*Context`
254
+ - Add new `middleware.GetHead` to route missing HEAD requests to GET handler
255
+ - Updated benchmarks (see README)
256
+
257
+
258
+ ## v3.1.5 (2017-08-02)
259
+
260
+ - Setup golint and go vet for the project
261
+ - As per golint, we've redefined `func ServerBaseContext(h http.Handler, baseCtx context.Context) http.Handler`
262
+ to `func ServerBaseContext(baseCtx context.Context, h http.Handler) http.Handler`
263
+
264
+
265
+ ## v3.1.0 (2017-07-10)
266
+
267
+ - Fix a few minor issues after v3 release
268
+ - Move `docgen` sub-pkg to https://github.com/go-chi/docgen
269
+ - Move `render` sub-pkg to https://github.com/go-chi/render
270
+ - Add new `URLFormat` handler to chi/middleware sub-pkg to make working with url mime
271
+ suffixes easier, ie. parsing `/articles/1.json` and `/articles/1.xml`. See comments in
272
+ https://github.com/go-chi/chi/blob/master/middleware/url_format.go for example usage.
273
+
274
+
275
+ ## v3.0.0 (2017-06-21)
276
+
277
+ - Major update to chi library with many exciting updates, but also some *breaking changes*
278
+ - URL parameter syntax changed from `/:id` to `/{id}` for even more flexible routing, such as
279
+ `/articles/{month}-{day}-{year}-{slug}`, `/articles/{id}`, and `/articles/{id}.{ext}` on the
280
+ same router
281
+ - Support for regexp for routing patterns, in the form of `/{paramKey:regExp}` for example:
282
+ `r.Get("/articles/{name:[a-z]+}", h)` and `chi.URLParam(r, "name")`
283
+ - Add `Method` and `MethodFunc` to `chi.Router` to allow routing definitions such as
284
+ `r.Method("GET", "/", h)` which provides a cleaner interface for custom handlers like
285
+ in `_examples/custom-handler`
286
+ - Deprecating `mux#FileServer` helper function. Instead, we encourage users to create their
287
+ own using file handler with the stdlib, see `_examples/fileserver` for an example
288
+ - Add support for LINK/UNLINK http methods via `r.Method()` and `r.MethodFunc()`
289
+ - Moved the chi project to its own organization, to allow chi-related community packages to
290
+ be easily discovered and supported, at: https://github.com/go-chi
291
+ - *NOTE:* please update your import paths to `"github.com/go-chi/chi"`
292
+ - *NOTE:* chi v2 is still available at https://github.com/go-chi/chi/tree/v2
293
+
294
+
295
+ ## v2.1.0 (2017-03-30)
296
+
297
+ - Minor improvements and update to the chi core library
298
+ - Introduced a brand new `chi/render` sub-package to complete the story of building
299
+ APIs to offer a pattern for managing well-defined request / response payloads. Please
300
+ check out the updated `_examples/rest` example for how it works.
301
+ - Added `MethodNotAllowed(h http.HandlerFunc)` to chi.Router interface
302
+
303
+
304
+ ## v2.0.0 (2017-01-06)
305
+
306
+ - After many months of v2 being in an RC state with many companies and users running it in
307
+ production, the inclusion of some improvements to the middlewares, we are very pleased to
308
+ announce v2.0.0 of chi.
309
+
310
+
311
+ ## v2.0.0-rc1 (2016-07-26)
312
+
313
+ - Huge update! chi v2 is a large refactor targeting Go 1.7+. As of Go 1.7, the popular
314
+ community `"net/context"` package has been included in the standard library as `"context"` and
315
+ utilized by `"net/http"` and `http.Request` to managing deadlines, cancelation signals and other
316
+ request-scoped values. We're very excited about the new context addition and are proud to
317
+ introduce chi v2, a minimal and powerful routing package for building large HTTP services,
318
+ with zero external dependencies. Chi focuses on idiomatic design and encourages the use of
319
+ stdlib HTTP handlers and middlewares.
320
+ - chi v2 deprecates its `chi.Handler` interface and requires `http.Handler` or `http.HandlerFunc`
321
+ - chi v2 stores URL routing parameters and patterns in the standard request context: `r.Context()`
322
+ - chi v2 lower-level routing context is accessible by `chi.RouteContext(r.Context()) *chi.Context`,
323
+ which provides direct access to URL routing parameters, the routing path and the matching
324
+ routing patterns.
325
+ - Users upgrading from chi v1 to v2, need to:
326
+ 1. Update the old chi.Handler signature, `func(ctx context.Context, w http.ResponseWriter, r *http.Request)` to
327
+ the standard http.Handler: `func(w http.ResponseWriter, r *http.Request)`
328
+ 2. Use `chi.URLParam(r *http.Request, paramKey string) string`
329
+ or `URLParamFromCtx(ctx context.Context, paramKey string) string` to access a url parameter value
330
+
331
+
332
+ ## v1.0.0 (2016-07-01)
333
+
334
+ - Released chi v1 stable https://github.com/go-chi/chi/tree/v1.0.0 for Go 1.6 and older.
335
+
336
+
337
+ ## v0.9.0 (2016-03-31)
338
+
339
+ - Reuse context objects via sync.Pool for zero-allocation routing [#33](https://github.com/go-chi/chi/pull/33)
340
+ - BREAKING NOTE: due to subtle API changes, previously `chi.URLParams(ctx)["id"]` used to access url parameters
341
+ has changed to: `chi.URLParam(ctx, "id")`
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing
2
+
3
+ ## Prerequisites
4
+
5
+ 1. [Install Go][go-install].
6
+ 2. Download the sources and switch the working directory:
7
+
8
+ ```bash
9
+ go get -u -d github.com/go-chi/chi
10
+ cd $GOPATH/src/github.com/go-chi/chi
11
+ ```
12
+
13
+ ## Submitting a Pull Request
14
+
15
+ A typical workflow is:
16
+
17
+ 1. [Fork the repository.][fork]
18
+ 2. [Create a topic branch.][branch]
19
+ 3. Add tests for your change.
20
+ 4. Run `go test`. If your tests pass, return to the step 3.
21
+ 5. Implement the change and ensure the steps from the previous step pass.
22
+ 6. Run `goimports -w .`, to ensure the new code conforms to Go formatting guideline.
23
+ 7. [Add, commit and push your changes.][git-help]
24
+ 8. [Submit a pull request.][pull-req]
25
+
26
+ [go-install]: https://golang.org/doc/install
27
+ [fork]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo
28
+ [branch]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-branches
29
+ [git-help]: https://docs.github.com/en
30
+ [pull-req]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests
31
+
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka), Google Inc.
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/Makefile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: all
2
+ all:
3
+ @echo "**********************************************************"
4
+ @echo "** chi build tool **"
5
+ @echo "**********************************************************"
6
+
7
+
8
+ .PHONY: test
9
+ test:
10
+ go clean -testcache && $(MAKE) test-router && $(MAKE) test-middleware
11
+
12
+ .PHONY: test-router
13
+ test-router:
14
+ go test -race -v .
15
+
16
+ .PHONY: test-middleware
17
+ test-middleware:
18
+ go test -race -v ./middleware
19
+
20
+ .PHONY: docs
21
+ docs:
22
+ npx docsify-cli serve ./docs
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/README.md ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # <img alt="chi" src="https://cdn.rawgit.com/go-chi/chi/master/_examples/chi.svg" width="220" />
2
+
3
+
4
+ [![GoDoc Widget]][GoDoc]
5
+
6
+ `chi` is a lightweight, idiomatic and composable router for building Go HTTP services. It's
7
+ especially good at helping you write large REST API services that are kept maintainable as your
8
+ project grows and changes. `chi` is built on the new `context` package introduced in Go 1.7 to
9
+ handle signaling, cancelation and request-scoped values across a handler chain.
10
+
11
+ The focus of the project has been to seek out an elegant and comfortable design for writing
12
+ REST API servers, written during the development of the Pressly API service that powers our
13
+ public API service, which in turn powers all of our client-side applications.
14
+
15
+ The key considerations of chi's design are: project structure, maintainability, standard http
16
+ handlers (stdlib-only), developer productivity, and deconstructing a large system into many small
17
+ parts. The core router `github.com/go-chi/chi` is quite small (less than 1000 LOC), but we've also
18
+ included some useful/optional subpackages: [middleware](/middleware), [render](https://github.com/go-chi/render)
19
+ and [docgen](https://github.com/go-chi/docgen). We hope you enjoy it too!
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ go get -u github.com/go-chi/chi/v5
25
+ ```
26
+
27
+
28
+ ## Features
29
+
30
+ * **Lightweight** - cloc'd in ~1000 LOC for the chi router
31
+ * **Fast** - yes, see [benchmarks](#benchmarks)
32
+ * **100% compatible with net/http** - use any http or middleware pkg in the ecosystem that is also compatible with `net/http`
33
+ * **Designed for modular/composable APIs** - middlewares, inline middlewares, route groups and sub-router mounting
34
+ * **Context control** - built on new `context` package, providing value chaining, cancellations and timeouts
35
+ * **Robust** - in production at Pressly, Cloudflare, Heroku, 99Designs, and many others (see [discussion](https://github.com/go-chi/chi/issues/91))
36
+ * **Doc generation** - `docgen` auto-generates routing documentation from your source to JSON or Markdown
37
+ * **Go.mod support** - as of v5, go.mod support (see [CHANGELOG](https://github.com/go-chi/chi/blob/master/CHANGELOG.md))
38
+ * **No external dependencies** - plain ol' Go stdlib + net/http
39
+
40
+
41
+ ## Examples
42
+
43
+ See [_examples/](https://github.com/go-chi/chi/blob/master/_examples/) for a variety of examples.
44
+
45
+
46
+ **As easy as:**
47
+
48
+ ```go
49
+ package main
50
+
51
+ import (
52
+ "net/http"
53
+
54
+ "github.com/go-chi/chi/v5"
55
+ "github.com/go-chi/chi/v5/middleware"
56
+ )
57
+
58
+ func main() {
59
+ r := chi.NewRouter()
60
+ r.Use(middleware.Logger)
61
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
62
+ w.Write([]byte("welcome"))
63
+ })
64
+ http.ListenAndServe(":3000", r)
65
+ }
66
+ ```
67
+
68
+ **REST Preview:**
69
+
70
+ Here is a little preview of what routing looks like with chi. Also take a look at the generated routing docs
71
+ in JSON ([routes.json](https://github.com/go-chi/chi/blob/master/_examples/rest/routes.json)) and in
72
+ Markdown ([routes.md](https://github.com/go-chi/chi/blob/master/_examples/rest/routes.md)).
73
+
74
+ I highly recommend reading the source of the [examples](https://github.com/go-chi/chi/blob/master/_examples/) listed
75
+ above, they will show you all the features of chi and serve as a good form of documentation.
76
+
77
+ ```go
78
+ import (
79
+ //...
80
+ "context"
81
+ "github.com/go-chi/chi/v5"
82
+ "github.com/go-chi/chi/v5/middleware"
83
+ )
84
+
85
+ func main() {
86
+ r := chi.NewRouter()
87
+
88
+ // A good base middleware stack
89
+ r.Use(middleware.RequestID)
90
+ r.Use(middleware.RealIP)
91
+ r.Use(middleware.Logger)
92
+ r.Use(middleware.Recoverer)
93
+
94
+ // Set a timeout value on the request context (ctx), that will signal
95
+ // through ctx.Done() that the request has timed out and further
96
+ // processing should be stopped.
97
+ r.Use(middleware.Timeout(60 * time.Second))
98
+
99
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
100
+ w.Write([]byte("hi"))
101
+ })
102
+
103
+ // RESTy routes for "articles" resource
104
+ r.Route("/articles", func(r chi.Router) {
105
+ r.With(paginate).Get("/", listArticles) // GET /articles
106
+ r.With(paginate).Get("/{month}-{day}-{year}", listArticlesByDate) // GET /articles/01-16-2017
107
+
108
+ r.Post("/", createArticle) // POST /articles
109
+ r.Get("/search", searchArticles) // GET /articles/search
110
+
111
+ // Regexp url parameters:
112
+ r.Get("/{articleSlug:[a-z-]+}", getArticleBySlug) // GET /articles/home-is-toronto
113
+
114
+ // Subrouters:
115
+ r.Route("/{articleID}", func(r chi.Router) {
116
+ r.Use(ArticleCtx)
117
+ r.Get("/", getArticle) // GET /articles/123
118
+ r.Put("/", updateArticle) // PUT /articles/123
119
+ r.Delete("/", deleteArticle) // DELETE /articles/123
120
+ })
121
+ })
122
+
123
+ // Mount the admin sub-router
124
+ r.Mount("/admin", adminRouter())
125
+
126
+ http.ListenAndServe(":3333", r)
127
+ }
128
+
129
+ func ArticleCtx(next http.Handler) http.Handler {
130
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
131
+ articleID := chi.URLParam(r, "articleID")
132
+ article, err := dbGetArticle(articleID)
133
+ if err != nil {
134
+ http.Error(w, http.StatusText(404), 404)
135
+ return
136
+ }
137
+ ctx := context.WithValue(r.Context(), "article", article)
138
+ next.ServeHTTP(w, r.WithContext(ctx))
139
+ })
140
+ }
141
+
142
+ func getArticle(w http.ResponseWriter, r *http.Request) {
143
+ ctx := r.Context()
144
+ article, ok := ctx.Value("article").(*Article)
145
+ if !ok {
146
+ http.Error(w, http.StatusText(422), 422)
147
+ return
148
+ }
149
+ w.Write([]byte(fmt.Sprintf("title:%s", article.Title)))
150
+ }
151
+
152
+ // A completely separate router for administrator routes
153
+ func adminRouter() http.Handler {
154
+ r := chi.NewRouter()
155
+ r.Use(AdminOnly)
156
+ r.Get("/", adminIndex)
157
+ r.Get("/accounts", adminListAccounts)
158
+ return r
159
+ }
160
+
161
+ func AdminOnly(next http.Handler) http.Handler {
162
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
163
+ ctx := r.Context()
164
+ perm, ok := ctx.Value("acl.permission").(YourPermissionType)
165
+ if !ok || !perm.IsAdmin() {
166
+ http.Error(w, http.StatusText(403), 403)
167
+ return
168
+ }
169
+ next.ServeHTTP(w, r)
170
+ })
171
+ }
172
+ ```
173
+
174
+
175
+ ## Router interface
176
+
177
+ chi's router is based on a kind of [Patricia Radix trie](https://en.wikipedia.org/wiki/Radix_tree).
178
+ The router is fully compatible with `net/http`.
179
+
180
+ Built on top of the tree is the `Router` interface:
181
+
182
+ ```go
183
+ // Router consisting of the core routing methods used by chi's Mux,
184
+ // using only the standard net/http.
185
+ type Router interface {
186
+ http.Handler
187
+ Routes
188
+
189
+ // Use appends one or more middlewares onto the Router stack.
190
+ Use(middlewares ...func(http.Handler) http.Handler)
191
+
192
+ // With adds inline middlewares for an endpoint handler.
193
+ With(middlewares ...func(http.Handler) http.Handler) Router
194
+
195
+ // Group adds a new inline-Router along the current routing
196
+ // path, with a fresh middleware stack for the inline-Router.
197
+ Group(fn func(r Router)) Router
198
+
199
+ // Route mounts a sub-Router along a `pattern` string.
200
+ Route(pattern string, fn func(r Router)) Router
201
+
202
+ // Mount attaches another http.Handler along ./pattern/*
203
+ Mount(pattern string, h http.Handler)
204
+
205
+ // Handle and HandleFunc adds routes for `pattern` that matches
206
+ // all HTTP methods.
207
+ Handle(pattern string, h http.Handler)
208
+ HandleFunc(pattern string, h http.HandlerFunc)
209
+
210
+ // Method and MethodFunc adds routes for `pattern` that matches
211
+ // the `method` HTTP method.
212
+ Method(method, pattern string, h http.Handler)
213
+ MethodFunc(method, pattern string, h http.HandlerFunc)
214
+
215
+ // HTTP-method routing along `pattern`
216
+ Connect(pattern string, h http.HandlerFunc)
217
+ Delete(pattern string, h http.HandlerFunc)
218
+ Get(pattern string, h http.HandlerFunc)
219
+ Head(pattern string, h http.HandlerFunc)
220
+ Options(pattern string, h http.HandlerFunc)
221
+ Patch(pattern string, h http.HandlerFunc)
222
+ Post(pattern string, h http.HandlerFunc)
223
+ Put(pattern string, h http.HandlerFunc)
224
+ Trace(pattern string, h http.HandlerFunc)
225
+
226
+ // NotFound defines a handler to respond whenever a route could
227
+ // not be found.
228
+ NotFound(h http.HandlerFunc)
229
+
230
+ // MethodNotAllowed defines a handler to respond whenever a method is
231
+ // not allowed.
232
+ MethodNotAllowed(h http.HandlerFunc)
233
+ }
234
+
235
+ // Routes interface adds two methods for router traversal, which is also
236
+ // used by the github.com/go-chi/docgen package to generate documentation for Routers.
237
+ type Routes interface {
238
+ // Routes returns the routing tree in an easily traversable structure.
239
+ Routes() []Route
240
+
241
+ // Middlewares returns the list of middlewares in use by the router.
242
+ Middlewares() Middlewares
243
+
244
+ // Match searches the routing tree for a handler that matches
245
+ // the method/path - similar to routing a http request, but without
246
+ // executing the handler thereafter.
247
+ Match(rctx *Context, method, path string) bool
248
+ }
249
+ ```
250
+
251
+ Each routing method accepts a URL `pattern` and chain of `handlers`. The URL pattern
252
+ supports named params (ie. `/users/{userID}`) and wildcards (ie. `/admin/*`). URL parameters
253
+ can be fetched at runtime by calling `chi.URLParam(r, "userID")` for named parameters
254
+ and `chi.URLParam(r, "*")` for a wildcard parameter.
255
+
256
+
257
+ ### Middleware handlers
258
+
259
+ chi's middlewares are just stdlib net/http middleware handlers. There is nothing special
260
+ about them, which means the router and all the tooling is designed to be compatible and
261
+ friendly with any middleware in the community. This offers much better extensibility and reuse
262
+ of packages and is at the heart of chi's purpose.
263
+
264
+ Here is an example of a standard net/http middleware where we assign a context key `"user"`
265
+ the value of `"123"`. This middleware sets a hypothetical user identifier on the request
266
+ context and calls the next handler in the chain.
267
+
268
+ ```go
269
+ // HTTP middleware setting a value on the request context
270
+ func MyMiddleware(next http.Handler) http.Handler {
271
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
272
+ // create new context from `r` request context, and assign key `"user"`
273
+ // to value of `"123"`
274
+ ctx := context.WithValue(r.Context(), "user", "123")
275
+
276
+ // call the next handler in the chain, passing the response writer and
277
+ // the updated request object with the new context value.
278
+ //
279
+ // note: context.Context values are nested, so any previously set
280
+ // values will be accessible as well, and the new `"user"` key
281
+ // will be accessible from this point forward.
282
+ next.ServeHTTP(w, r.WithContext(ctx))
283
+ })
284
+ }
285
+ ```
286
+
287
+
288
+ ### Request handlers
289
+
290
+ chi uses standard net/http request handlers. This little snippet is an example of a http.Handler
291
+ func that reads a user identifier from the request context - hypothetically, identifying
292
+ the user sending an authenticated request, validated+set by a previous middleware handler.
293
+
294
+ ```go
295
+ // HTTP handler accessing data from the request context.
296
+ func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
297
+ // here we read from the request context and fetch out `"user"` key set in
298
+ // the MyMiddleware example above.
299
+ user := r.Context().Value("user").(string)
300
+
301
+ // respond to the client
302
+ w.Write([]byte(fmt.Sprintf("hi %s", user)))
303
+ }
304
+ ```
305
+
306
+
307
+ ### URL parameters
308
+
309
+ chi's router parses and stores URL parameters right onto the request context. Here is
310
+ an example of how to access URL params in your net/http handlers. And of course, middlewares
311
+ are able to access the same information.
312
+
313
+ ```go
314
+ // HTTP handler accessing the url routing parameters.
315
+ func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
316
+ // fetch the url parameter `"userID"` from the request of a matching
317
+ // routing pattern. An example routing pattern could be: /users/{userID}
318
+ userID := chi.URLParam(r, "userID")
319
+
320
+ // fetch `"key"` from the request context
321
+ ctx := r.Context()
322
+ key := ctx.Value("key").(string)
323
+
324
+ // respond to the client
325
+ w.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key)))
326
+ }
327
+ ```
328
+
329
+
330
+ ## Middlewares
331
+
332
+ chi comes equipped with an optional `middleware` package, providing a suite of standard
333
+ `net/http` middlewares. Please note, any middleware in the ecosystem that is also compatible
334
+ with `net/http` can be used with chi's mux.
335
+
336
+ ### Core middlewares
337
+
338
+ ----------------------------------------------------------------------------------------------------
339
+ | chi/middleware Handler | description |
340
+ | :--------------------- | :---------------------------------------------------------------------- |
341
+ | [AllowContentEncoding] | Enforces a whitelist of request Content-Encoding headers |
342
+ | [AllowContentType] | Explicit whitelist of accepted request Content-Types |
343
+ | [BasicAuth] | Basic HTTP authentication |
344
+ | [Compress] | Gzip compression for clients that accept compressed responses |
345
+ | [ContentCharset] | Ensure charset for Content-Type request headers |
346
+ | [CleanPath] | Clean double slashes from request path |
347
+ | [GetHead] | Automatically route undefined HEAD requests to GET handlers |
348
+ | [Heartbeat] | Monitoring endpoint to check the servers pulse |
349
+ | [Logger] | Logs the start and end of each request with the elapsed processing time |
350
+ | [NoCache] | Sets response headers to prevent clients from caching |
351
+ | [Profiler] | Easily attach net/http/pprof to your routers |
352
+ | [RealIP] | Sets a http.Request's RemoteAddr to either X-Real-IP or X-Forwarded-For |
353
+ | [Recoverer] | Gracefully absorb panics and prints the stack trace |
354
+ | [RequestID] | Injects a request ID into the context of each request |
355
+ | [RedirectSlashes] | Redirect slashes on routing paths |
356
+ | [RouteHeaders] | Route handling for request headers |
357
+ | [SetHeader] | Short-hand middleware to set a response header key/value |
358
+ | [StripSlashes] | Strip slashes on routing paths |
359
+ | [Sunset] | Sunset set Deprecation/Sunset header to response |
360
+ | [Throttle] | Puts a ceiling on the number of concurrent requests |
361
+ | [Timeout] | Signals to the request context when the timeout deadline is reached |
362
+ | [URLFormat] | Parse extension from url and put it on request context |
363
+ | [WithValue] | Short-hand middleware to set a key/value on the request context |
364
+ ----------------------------------------------------------------------------------------------------
365
+
366
+ [AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentEncoding
367
+ [AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentType
368
+ [BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/middleware#BasicAuth
369
+ [Compress]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compress
370
+ [ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ContentCharset
371
+ [CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/middleware#CleanPath
372
+ [GetHead]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetHead
373
+ [GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetReqID
374
+ [Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Heartbeat
375
+ [Logger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Logger
376
+ [NoCache]: https://pkg.go.dev/github.com/go-chi/chi/middleware#NoCache
377
+ [Profiler]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Profiler
378
+ [RealIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RealIP
379
+ [Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Recoverer
380
+ [RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RedirectSlashes
381
+ [RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestLogger
382
+ [RequestID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestID
383
+ [RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RouteHeaders
384
+ [SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#SetHeader
385
+ [StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#StripSlashes
386
+ [Sunset]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Sunset
387
+ [Throttle]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Throttle
388
+ [ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleBacklog
389
+ [ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleWithOpts
390
+ [Timeout]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Timeout
391
+ [URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#URLFormat
392
+ [WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithLogEntry
393
+ [WithValue]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithValue
394
+ [Compressor]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compressor
395
+ [DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#DefaultLogFormatter
396
+ [EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/middleware#EncoderFunc
397
+ [HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRoute
398
+ [HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRouter
399
+ [LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogEntry
400
+ [LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogFormatter
401
+ [LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LoggerInterface
402
+ [ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleOpts
403
+ [WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WrapResponseWriter
404
+
405
+ ### Extra middlewares & packages
406
+
407
+ Please see https://github.com/go-chi for additional packages.
408
+
409
+ --------------------------------------------------------------------------------------------------------------------
410
+ | package | description |
411
+ |:---------------------------------------------------|:-------------------------------------------------------------
412
+ | [cors](https://github.com/go-chi/cors) | Cross-origin resource sharing (CORS) |
413
+ | [docgen](https://github.com/go-chi/docgen) | Print chi.Router routes at runtime |
414
+ | [jwtauth](https://github.com/go-chi/jwtauth) | JWT authentication |
415
+ | [hostrouter](https://github.com/go-chi/hostrouter) | Domain/host based request routing |
416
+ | [httplog](https://github.com/go-chi/httplog) | Small but powerful structured HTTP request logging |
417
+ | [httprate](https://github.com/go-chi/httprate) | HTTP request rate limiter |
418
+ | [httptracer](https://github.com/go-chi/httptracer) | HTTP request performance tracing library |
419
+ | [httpvcr](https://github.com/go-chi/httpvcr) | Write deterministic tests for external sources |
420
+ | [stampede](https://github.com/go-chi/stampede) | HTTP request coalescer |
421
+ --------------------------------------------------------------------------------------------------------------------
422
+
423
+
424
+ ## context?
425
+
426
+ `context` is a tiny pkg that provides simple interface to signal context across call stacks
427
+ and goroutines. It was originally written by [Sameer Ajmani](https://github.com/Sajmani)
428
+ and is available in stdlib since go1.7.
429
+
430
+ Learn more at https://blog.golang.org/context
431
+
432
+ and..
433
+ * Docs: https://golang.org/pkg/context
434
+ * Source: https://github.com/golang/go/tree/master/src/context
435
+
436
+
437
+ ## Benchmarks
438
+
439
+ The benchmark suite: https://github.com/pkieltyka/go-http-routing-benchmark
440
+
441
+ Results as of Nov 29, 2020 with Go 1.15.5 on Linux AMD 3950x
442
+
443
+ ```shell
444
+ BenchmarkChi_Param 3075895 384 ns/op 400 B/op 2 allocs/op
445
+ BenchmarkChi_Param5 2116603 566 ns/op 400 B/op 2 allocs/op
446
+ BenchmarkChi_Param20 964117 1227 ns/op 400 B/op 2 allocs/op
447
+ BenchmarkChi_ParamWrite 2863413 420 ns/op 400 B/op 2 allocs/op
448
+ BenchmarkChi_GithubStatic 3045488 395 ns/op 400 B/op 2 allocs/op
449
+ BenchmarkChi_GithubParam 2204115 540 ns/op 400 B/op 2 allocs/op
450
+ BenchmarkChi_GithubAll 10000 113811 ns/op 81203 B/op 406 allocs/op
451
+ BenchmarkChi_GPlusStatic 3337485 359 ns/op 400 B/op 2 allocs/op
452
+ BenchmarkChi_GPlusParam 2825853 423 ns/op 400 B/op 2 allocs/op
453
+ BenchmarkChi_GPlus2Params 2471697 483 ns/op 400 B/op 2 allocs/op
454
+ BenchmarkChi_GPlusAll 194220 5950 ns/op 5200 B/op 26 allocs/op
455
+ BenchmarkChi_ParseStatic 3365324 356 ns/op 400 B/op 2 allocs/op
456
+ BenchmarkChi_ParseParam 2976614 404 ns/op 400 B/op 2 allocs/op
457
+ BenchmarkChi_Parse2Params 2638084 439 ns/op 400 B/op 2 allocs/op
458
+ BenchmarkChi_ParseAll 109567 11295 ns/op 10400 B/op 52 allocs/op
459
+ BenchmarkChi_StaticAll 16846 71308 ns/op 62802 B/op 314 allocs/op
460
+ ```
461
+
462
+ Comparison with other routers: https://gist.github.com/pkieltyka/123032f12052520aaccab752bd3e78cc
463
+
464
+ NOTE: the allocs in the benchmark above are from the calls to http.Request's
465
+ `WithContext(context.Context)` method that clones the http.Request, sets the `Context()`
466
+ on the duplicated (alloc'd) request and returns it the new request object. This is just
467
+ how setting context on a request in Go works.
468
+
469
+
470
+ ## Credits
471
+
472
+ * Carl Jackson for https://github.com/zenazn/goji
473
+ * Parts of chi's thinking comes from goji, and chi's middleware package
474
+ sources from [goji](https://github.com/zenazn/goji/tree/master/web/middleware).
475
+ * Please see goji's [LICENSE](https://github.com/zenazn/goji/blob/master/LICENSE) (MIT)
476
+ * Armon Dadgar for https://github.com/armon/go-radix
477
+ * Contributions: [@VojtechVitek](https://github.com/VojtechVitek)
478
+
479
+ We'll be more than happy to see [your contributions](./CONTRIBUTING.md)!
480
+
481
+
482
+ ## Beyond REST
483
+
484
+ chi is just a http router that lets you decompose request handling into many smaller layers.
485
+ Many companies use chi to write REST services for their public APIs. But, REST is just a convention
486
+ for managing state via HTTP, and there's a lot of other pieces required to write a complete client-server
487
+ system or network of microservices.
488
+
489
+ Looking beyond REST, I also recommend some newer works in the field:
490
+ * [webrpc](https://github.com/webrpc/webrpc) - Web-focused RPC client+server framework with code-gen
491
+ * [gRPC](https://github.com/grpc/grpc-go) - Google's RPC framework via protobufs
492
+ * [graphql](https://github.com/99designs/gqlgen) - Declarative query language
493
+ * [NATS](https://nats.io) - lightweight pub-sub
494
+
495
+
496
+ ## License
497
+
498
+ Copyright (c) 2015-present [Peter Kieltyka](https://github.com/pkieltyka)
499
+
500
+ Licensed under [MIT License](./LICENSE)
501
+
502
+ [GoDoc]: https://pkg.go.dev/github.com/go-chi/chi/v5
503
+ [GoDoc Widget]: https://godoc.org/github.com/go-chi/chi?status.svg
504
+ [Travis]: https://travis-ci.org/go-chi/chi
505
+ [Travis Widget]: https://travis-ci.org/go-chi/chi.svg?branch=master
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/SECURITY.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Reporting Security Issues
2
+
3
+ We appreciate your efforts to responsibly disclose your findings, and will make every effort to acknowledge your contributions.
4
+
5
+ To report a security issue, please use the GitHub Security Advisory ["Report a Vulnerability"](https://github.com/go-chi/chi/security/advisories/new) tab.
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/README.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ chi examples
2
+ ============
3
+
4
+ * [custom-handler](https://github.com/go-chi/chi/blob/master/_examples/custom-handler/main.go) - Use a custom handler function signature
5
+ * [custom-method](https://github.com/go-chi/chi/blob/master/_examples/custom-method/main.go) - Add a custom HTTP method
6
+ * [fileserver](https://github.com/go-chi/chi/blob/master/_examples/fileserver/main.go) - Easily serve static files
7
+ * [graceful](https://github.com/go-chi/chi/blob/master/_examples/graceful/main.go) - Graceful context signaling and server shutdown
8
+ * [hello-world](https://github.com/go-chi/chi/blob/master/_examples/hello-world/main.go) - Hello World!
9
+ * [limits](https://github.com/go-chi/chi/blob/master/_examples/limits/main.go) - Timeouts and Throttling
10
+ * [logging](https://github.com/go-chi/chi/blob/master/_examples/logging/main.go) - Easy structured logging for any backend
11
+ * [rest](https://github.com/go-chi/chi/blob/master/_examples/rest/main.go) - REST APIs made easy, productive and maintainable
12
+ * [router-walk](https://github.com/go-chi/chi/blob/master/_examples/router-walk/main.go) - Print to stdout a router's routes
13
+ * [todos-resource](https://github.com/go-chi/chi/blob/master/_examples/todos-resource/main.go) - Struct routers/handlers, an example of another code layout style
14
+ * [versions](https://github.com/go-chi/chi/blob/master/_examples/versions/main.go) - Demo of `chi/render` subpkg
15
+
16
+
17
+ ## Usage
18
+
19
+ 1. `go get -v -d -u ./...` - fetch example deps
20
+ 2. `cd <example>/` ie. `cd rest/`
21
+ 3. `go run *.go` - note, example services run on port 3333
22
+ 4. Open another terminal and use curl to send some requests to your example service,
23
+ `curl -v http://localhost:3333/`
24
+ 5. Read <example>/main.go source to learn how service works and read comments for usage
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/chi.svg ADDED
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/custom-handler/main.go ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "errors"
5
+ "net/http"
6
+
7
+ "github.com/go-chi/chi/v5"
8
+ )
9
+
10
+ type Handler func(w http.ResponseWriter, r *http.Request) error
11
+
12
+ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
13
+ if err := h(w, r); err != nil {
14
+ // handle returned error here.
15
+ w.WriteHeader(503)
16
+ w.Write([]byte("bad"))
17
+ }
18
+ }
19
+
20
+ func main() {
21
+ r := chi.NewRouter()
22
+ r.Method("GET", "/", Handler(customHandler))
23
+ http.ListenAndServe(":3333", r)
24
+ }
25
+
26
+ func customHandler(w http.ResponseWriter, r *http.Request) error {
27
+ q := r.URL.Query().Get("err")
28
+
29
+ if q != "" {
30
+ return errors.New(q)
31
+ }
32
+
33
+ w.Write([]byte("foo"))
34
+ return nil
35
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/custom-method/main.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "net/http"
5
+
6
+ "github.com/go-chi/chi/v5"
7
+ "github.com/go-chi/chi/v5/middleware"
8
+ )
9
+
10
+ func init() {
11
+ chi.RegisterMethod("LINK")
12
+ chi.RegisterMethod("UNLINK")
13
+ chi.RegisterMethod("WOOHOO")
14
+ }
15
+
16
+ func main() {
17
+ r := chi.NewRouter()
18
+ r.Use(middleware.RequestID)
19
+ r.Use(middleware.Logger)
20
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
21
+ w.Write([]byte("hello world"))
22
+ })
23
+ r.MethodFunc("LINK", "/link", func(w http.ResponseWriter, r *http.Request) {
24
+ w.Write([]byte("custom link method"))
25
+ })
26
+ r.MethodFunc("WOOHOO", "/woo", func(w http.ResponseWriter, r *http.Request) {
27
+ w.Write([]byte("custom woohoo method"))
28
+ })
29
+ r.HandleFunc("/everything", func(w http.ResponseWriter, r *http.Request) {
30
+ w.Write([]byte("capturing all standard http methods, as well as LINK, UNLINK and WOOHOO"))
31
+ })
32
+ http.ListenAndServe(":3333", r)
33
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/fileserver/data/notes.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Notessszzz
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/fileserver/main.go ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This example demonstrates how to serve static files from your filesystem.
2
+ //
3
+ // Boot the server:
4
+ //
5
+ // $ go run main.go
6
+ //
7
+ // Client requests:
8
+ //
9
+ // $ curl http://localhost:3333/files/
10
+ // <pre>
11
+ // <a href="notes.txt">notes.txt</a>
12
+ // </pre>
13
+ //
14
+ // $ curl http://localhost:3333/files/notes.txt
15
+ // Notessszzz
16
+ package main
17
+
18
+ import (
19
+ "net/http"
20
+ "os"
21
+ "path/filepath"
22
+ "strings"
23
+
24
+ "github.com/go-chi/chi/v5"
25
+ "github.com/go-chi/chi/v5/middleware"
26
+ )
27
+
28
+ func main() {
29
+ r := chi.NewRouter()
30
+ r.Use(middleware.Logger)
31
+
32
+ // Index handler
33
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
34
+ w.Write([]byte("hi"))
35
+ })
36
+
37
+ // Create a route along /files that will serve contents from
38
+ // the ./data/ folder.
39
+ workDir, _ := os.Getwd()
40
+ filesDir := http.Dir(filepath.Join(workDir, "data"))
41
+ FileServer(r, "/files", filesDir)
42
+
43
+ http.ListenAndServe(":3333", r)
44
+ }
45
+
46
+ // FileServer conveniently sets up a http.FileServer handler to serve
47
+ // static files from a http.FileSystem.
48
+ func FileServer(r chi.Router, path string, root http.FileSystem) {
49
+ if strings.ContainsAny(path, "{}*") {
50
+ panic("FileServer does not permit any URL parameters.")
51
+ }
52
+
53
+ if path != "/" && path[len(path)-1] != '/' {
54
+ r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
55
+ path += "/"
56
+ }
57
+ path += "*"
58
+
59
+ r.Get(path, func(w http.ResponseWriter, r *http.Request) {
60
+ rctx := chi.RouteContext(r.Context())
61
+ pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
62
+ fs := http.StripPrefix(pathPrefix, http.FileServer(root))
63
+ fs.ServeHTTP(w, r)
64
+ })
65
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/graceful/main.go ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "log"
7
+ "net/http"
8
+ "os"
9
+ "os/signal"
10
+ "syscall"
11
+ "time"
12
+
13
+ "github.com/go-chi/chi/v5"
14
+ "github.com/go-chi/chi/v5/middleware"
15
+ )
16
+
17
+ func main() {
18
+ // The HTTP Server
19
+ server := &http.Server{Addr: "0.0.0.0:3333", Handler: service()}
20
+
21
+ // Server run context
22
+ serverCtx, serverStopCtx := context.WithCancel(context.Background())
23
+
24
+ // Listen for syscall signals for process to interrupt/quit
25
+ sig := make(chan os.Signal, 1)
26
+ signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
27
+ go func() {
28
+ <-sig
29
+
30
+ // Shutdown signal with grace period of 30 seconds
31
+ shutdownCtx, _ := context.WithTimeout(serverCtx, 30*time.Second)
32
+
33
+ go func() {
34
+ <-shutdownCtx.Done()
35
+ if shutdownCtx.Err() == context.DeadlineExceeded {
36
+ log.Fatal("graceful shutdown timed out.. forcing exit.")
37
+ }
38
+ }()
39
+
40
+ // Trigger graceful shutdown
41
+ err := server.Shutdown(shutdownCtx)
42
+ if err != nil {
43
+ log.Fatal(err)
44
+ }
45
+ serverStopCtx()
46
+ }()
47
+
48
+ // Run the server
49
+ err := server.ListenAndServe()
50
+ if err != nil && err != http.ErrServerClosed {
51
+ log.Fatal(err)
52
+ }
53
+
54
+ // Wait for server context to be stopped
55
+ <-serverCtx.Done()
56
+ }
57
+
58
+ func service() http.Handler {
59
+ r := chi.NewRouter()
60
+
61
+ r.Use(middleware.RequestID)
62
+ r.Use(middleware.Logger)
63
+
64
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
65
+ w.Write([]byte("sup"))
66
+ })
67
+
68
+ r.Get("/slow", func(w http.ResponseWriter, r *http.Request) {
69
+ // Simulates some hard work.
70
+ //
71
+ // We want this handler to complete successfully during a shutdown signal,
72
+ // so consider the work here as some background routine to fetch a long running
73
+ // search query to find as many results as possible, but, instead we cut it short
74
+ // and respond with what we have so far. How a shutdown is handled is entirely
75
+ // up to the developer, as some code blocks are preemptible, and others are not.
76
+ time.Sleep(5 * time.Second)
77
+
78
+ w.Write([]byte(fmt.Sprintf("all done.\n")))
79
+ })
80
+
81
+ return r
82
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/hello-world/main.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "net/http"
5
+
6
+ "github.com/go-chi/chi/v5"
7
+ "github.com/go-chi/chi/v5/middleware"
8
+ )
9
+
10
+ func main() {
11
+ r := chi.NewRouter()
12
+ r.Use(middleware.RequestID)
13
+ r.Use(middleware.Logger)
14
+ r.Use(middleware.Recoverer)
15
+
16
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
17
+ w.Write([]byte("hello world"))
18
+ })
19
+
20
+ http.ListenAndServe(":3333", r)
21
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/limits/main.go ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This example demonstrates the use of Timeout, and Throttle middlewares.
2
+ //
3
+ // Timeout: cancel a request if processing takes longer than 2.5 seconds,
4
+ // server will respond with a http.StatusGatewayTimeout.
5
+ //
6
+ // Throttle: limit the number of in-flight requests along a particular
7
+ // routing path and backlog the others.
8
+ package main
9
+
10
+ import (
11
+ "context"
12
+ "fmt"
13
+ "math/rand"
14
+ "net/http"
15
+ "time"
16
+
17
+ "github.com/go-chi/chi/v5"
18
+ "github.com/go-chi/chi/v5/middleware"
19
+ )
20
+
21
+ func main() {
22
+ r := chi.NewRouter()
23
+
24
+ r.Use(middleware.RequestID)
25
+ r.Use(middleware.Logger)
26
+ r.Use(middleware.Recoverer)
27
+
28
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
29
+ w.Write([]byte("root."))
30
+ })
31
+
32
+ r.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
33
+ w.Write([]byte("pong"))
34
+ })
35
+
36
+ r.Get("/panic", func(w http.ResponseWriter, r *http.Request) {
37
+ panic("test")
38
+ })
39
+
40
+ // Slow handlers/operations.
41
+ r.Group(func(r chi.Router) {
42
+ // Stop processing after 2.5 seconds.
43
+ r.Use(middleware.Timeout(2500 * time.Millisecond))
44
+
45
+ r.Get("/slow", func(w http.ResponseWriter, r *http.Request) {
46
+ rand.Seed(time.Now().Unix())
47
+
48
+ // Processing will take 1-5 seconds.
49
+ processTime := time.Duration(rand.Intn(4)+1) * time.Second
50
+
51
+ select {
52
+ case <-r.Context().Done():
53
+ return
54
+
55
+ case <-time.After(processTime):
56
+ // The above channel simulates some hard work.
57
+ }
58
+
59
+ w.Write([]byte(fmt.Sprintf("Processed in %v seconds\n", processTime)))
60
+ })
61
+ })
62
+
63
+ // Throttle very expensive handlers/operations.
64
+ r.Group(func(r chi.Router) {
65
+ // Stop processing after 30 seconds.
66
+ r.Use(middleware.Timeout(30 * time.Second))
67
+
68
+ // Only one request will be processed at a time.
69
+ r.Use(middleware.Throttle(1))
70
+
71
+ r.Get("/throttled", func(w http.ResponseWriter, r *http.Request) {
72
+ select {
73
+ case <-r.Context().Done():
74
+ switch r.Context().Err() {
75
+ case context.DeadlineExceeded:
76
+ w.WriteHeader(504)
77
+ w.Write([]byte("Processing too slow\n"))
78
+ default:
79
+ w.Write([]byte("Canceled\n"))
80
+ }
81
+ return
82
+
83
+ case <-time.After(5 * time.Second):
84
+ // The above channel simulates some hard work.
85
+ }
86
+
87
+ w.Write([]byte("Processed\n"))
88
+ })
89
+ })
90
+
91
+ http.ListenAndServe(":3333", r)
92
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/logging/main.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ // Please see https://github.com/go-chi/httplog for a complete package
4
+ // and example for writing a structured logger on chi built on
5
+ // the Go 1.21+ "log/slog" package.
6
+
7
+ func main() {
8
+ // See https://github.com/go-chi/httplog/blob/master/_example/main.go
9
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/go.mod ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ module rest-example
2
+
3
+ go 1.16
4
+
5
+ require (
6
+ github.com/go-chi/chi/v5 v5.0.1
7
+ github.com/go-chi/docgen v1.2.0
8
+ github.com/go-chi/render v1.0.1
9
+ )
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/go.sum ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ github.com/go-chi/chi/v5 v5.0.1 h1:ALxjCrTf1aflOlkhMnCUP86MubbWFrzB3gkRPReLpTo=
2
+ github.com/go-chi/chi/v5 v5.0.1/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
3
+ github.com/go-chi/docgen v1.2.0 h1:da0Nq2PKU9W9pSOTUfVrKI1vIgTGpauo9cfh4Iwivek=
4
+ github.com/go-chi/docgen v1.2.0/go.mod h1:G9W0G551cs2BFMSn/cnGwX+JBHEloAgo17MBhyrnhPI=
5
+ github.com/go-chi/render v1.0.1 h1:4/5tis2cKaNdnv9zFLfXzcquC9HbeZgCnxGnKrltBS8=
6
+ github.com/go-chi/render v1.0.1/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1OvJns=
7
+ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
8
+ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/main.go ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This example demonstrates a HTTP REST web service with some fixture data.
2
+ // Follow along the example and patterns.
3
+ //
4
+ // Also check routes.json for the generated docs from passing the -routes flag,
5
+ // to run yourself do: `go run . -routes`
6
+ //
7
+ // Boot the server:
8
+ //
9
+ // $ go run main.go
10
+ //
11
+ // Client requests:
12
+ //
13
+ // $ curl http://localhost:3333/
14
+ // root.
15
+ //
16
+ // $ curl http://localhost:3333/articles
17
+ // [{"id":"1","title":"Hi"},{"id":"2","title":"sup"}]
18
+ //
19
+ // $ curl http://localhost:3333/articles/1
20
+ // {"id":"1","title":"Hi"}
21
+ //
22
+ // $ curl -X DELETE http://localhost:3333/articles/1
23
+ // {"id":"1","title":"Hi"}
24
+ //
25
+ // $ curl http://localhost:3333/articles/1
26
+ // "Not Found"
27
+ //
28
+ // $ curl -X POST -d '{"id":"will-be-omitted","title":"awesomeness"}' http://localhost:3333/articles
29
+ // {"id":"97","title":"awesomeness"}
30
+ //
31
+ // $ curl http://localhost:3333/articles/97
32
+ // {"id":"97","title":"awesomeness"}
33
+ //
34
+ // $ curl http://localhost:3333/articles
35
+ // [{"id":"2","title":"sup"},{"id":"97","title":"awesomeness"}]
36
+ package main
37
+
38
+ import (
39
+ "context"
40
+ "errors"
41
+ "flag"
42
+ "fmt"
43
+ "math/rand"
44
+ "net/http"
45
+ "strings"
46
+
47
+ "github.com/go-chi/chi/v5"
48
+ "github.com/go-chi/chi/v5/middleware"
49
+ "github.com/go-chi/docgen"
50
+ "github.com/go-chi/render"
51
+ )
52
+
53
+ var routes = flag.Bool("routes", false, "Generate router documentation")
54
+
55
+ func main() {
56
+ flag.Parse()
57
+
58
+ r := chi.NewRouter()
59
+
60
+ r.Use(middleware.RequestID)
61
+ r.Use(middleware.Logger)
62
+ r.Use(middleware.Recoverer)
63
+ r.Use(middleware.URLFormat)
64
+ r.Use(render.SetContentType(render.ContentTypeJSON))
65
+
66
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
67
+ w.Write([]byte("root."))
68
+ })
69
+
70
+ r.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
71
+ w.Write([]byte("pong"))
72
+ })
73
+
74
+ r.Get("/panic", func(w http.ResponseWriter, r *http.Request) {
75
+ panic("test")
76
+ })
77
+
78
+ // RESTy routes for "articles" resource
79
+ r.Route("/articles", func(r chi.Router) {
80
+ r.With(paginate).Get("/", ListArticles)
81
+ r.Post("/", CreateArticle) // POST /articles
82
+ r.Get("/search", SearchArticles) // GET /articles/search
83
+
84
+ r.Route("/{articleID}", func(r chi.Router) {
85
+ r.Use(ArticleCtx) // Load the *Article on the request context
86
+ r.Get("/", GetArticle) // GET /articles/123
87
+ r.Put("/", UpdateArticle) // PUT /articles/123
88
+ r.Delete("/", DeleteArticle) // DELETE /articles/123
89
+ })
90
+
91
+ // GET /articles/whats-up
92
+ r.With(ArticleCtx).Get("/{articleSlug:[a-z-]+}", GetArticle)
93
+ })
94
+
95
+ // Mount the admin sub-router, which btw is the same as:
96
+ // r.Route("/admin", func(r chi.Router) { admin routes here })
97
+ r.Mount("/admin", adminRouter())
98
+
99
+ // Passing -routes to the program will generate docs for the above
100
+ // router definition. See the `routes.json` file in this folder for
101
+ // the output.
102
+ if *routes {
103
+ // fmt.Println(docgen.JSONRoutesDoc(r))
104
+ fmt.Println(docgen.MarkdownRoutesDoc(r, docgen.MarkdownOpts{
105
+ ProjectPath: "github.com/go-chi/chi/v5",
106
+ Intro: "Welcome to the chi/_examples/rest generated docs.",
107
+ }))
108
+ return
109
+ }
110
+
111
+ http.ListenAndServe(":3333", r)
112
+ }
113
+
114
+ func ListArticles(w http.ResponseWriter, r *http.Request) {
115
+ if err := render.RenderList(w, r, NewArticleListResponse(articles)); err != nil {
116
+ render.Render(w, r, ErrRender(err))
117
+ return
118
+ }
119
+ }
120
+
121
+ // ArticleCtx middleware is used to load an Article object from
122
+ // the URL parameters passed through as the request. In case
123
+ // the Article could not be found, we stop here and return a 404.
124
+ func ArticleCtx(next http.Handler) http.Handler {
125
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
126
+ var article *Article
127
+ var err error
128
+
129
+ if articleID := chi.URLParam(r, "articleID"); articleID != "" {
130
+ article, err = dbGetArticle(articleID)
131
+ } else if articleSlug := chi.URLParam(r, "articleSlug"); articleSlug != "" {
132
+ article, err = dbGetArticleBySlug(articleSlug)
133
+ } else {
134
+ render.Render(w, r, ErrNotFound)
135
+ return
136
+ }
137
+ if err != nil {
138
+ render.Render(w, r, ErrNotFound)
139
+ return
140
+ }
141
+
142
+ ctx := context.WithValue(r.Context(), "article", article)
143
+ next.ServeHTTP(w, r.WithContext(ctx))
144
+ })
145
+ }
146
+
147
+ // SearchArticles searches the Articles data for a matching article.
148
+ // It's just a stub, but you get the idea.
149
+ func SearchArticles(w http.ResponseWriter, r *http.Request) {
150
+ render.RenderList(w, r, NewArticleListResponse(articles))
151
+ }
152
+
153
+ // CreateArticle persists the posted Article and returns it
154
+ // back to the client as an acknowledgement.
155
+ func CreateArticle(w http.ResponseWriter, r *http.Request) {
156
+ data := &ArticleRequest{}
157
+ if err := render.Bind(r, data); err != nil {
158
+ render.Render(w, r, ErrInvalidRequest(err))
159
+ return
160
+ }
161
+
162
+ article := data.Article
163
+ dbNewArticle(article)
164
+
165
+ render.Status(r, http.StatusCreated)
166
+ render.Render(w, r, NewArticleResponse(article))
167
+ }
168
+
169
+ // GetArticle returns the specific Article. You'll notice it just
170
+ // fetches the Article right off the context, as its understood that
171
+ // if we made it this far, the Article must be on the context. In case
172
+ // its not due to a bug, then it will panic, and our Recoverer will save us.
173
+ func GetArticle(w http.ResponseWriter, r *http.Request) {
174
+ // Assume if we've reach this far, we can access the article
175
+ // context because this handler is a child of the ArticleCtx
176
+ // middleware. The worst case, the recoverer middleware will save us.
177
+ article := r.Context().Value("article").(*Article)
178
+
179
+ if err := render.Render(w, r, NewArticleResponse(article)); err != nil {
180
+ render.Render(w, r, ErrRender(err))
181
+ return
182
+ }
183
+ }
184
+
185
+ // UpdateArticle updates an existing Article in our persistent store.
186
+ func UpdateArticle(w http.ResponseWriter, r *http.Request) {
187
+ article := r.Context().Value("article").(*Article)
188
+
189
+ data := &ArticleRequest{Article: article}
190
+ if err := render.Bind(r, data); err != nil {
191
+ render.Render(w, r, ErrInvalidRequest(err))
192
+ return
193
+ }
194
+ article = data.Article
195
+ dbUpdateArticle(article.ID, article)
196
+
197
+ render.Render(w, r, NewArticleResponse(article))
198
+ }
199
+
200
+ // DeleteArticle removes an existing Article from our persistent store.
201
+ func DeleteArticle(w http.ResponseWriter, r *http.Request) {
202
+ var err error
203
+
204
+ // Assume if we've reach this far, we can access the article
205
+ // context because this handler is a child of the ArticleCtx
206
+ // middleware. The worst case, the recoverer middleware will save us.
207
+ article := r.Context().Value("article").(*Article)
208
+
209
+ article, err = dbRemoveArticle(article.ID)
210
+ if err != nil {
211
+ render.Render(w, r, ErrInvalidRequest(err))
212
+ return
213
+ }
214
+
215
+ render.Render(w, r, NewArticleResponse(article))
216
+ }
217
+
218
+ // A completely separate router for administrator routes
219
+ func adminRouter() chi.Router {
220
+ r := chi.NewRouter()
221
+ r.Use(AdminOnly)
222
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
223
+ w.Write([]byte("admin: index"))
224
+ })
225
+ r.Get("/accounts", func(w http.ResponseWriter, r *http.Request) {
226
+ w.Write([]byte("admin: list accounts.."))
227
+ })
228
+ r.Get("/users/{userId}", func(w http.ResponseWriter, r *http.Request) {
229
+ w.Write([]byte(fmt.Sprintf("admin: view user id %v", chi.URLParam(r, "userId"))))
230
+ })
231
+ return r
232
+ }
233
+
234
+ // AdminOnly middleware restricts access to just administrators.
235
+ func AdminOnly(next http.Handler) http.Handler {
236
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
237
+ isAdmin, ok := r.Context().Value("acl.admin").(bool)
238
+ if !ok || !isAdmin {
239
+ http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
240
+ return
241
+ }
242
+ next.ServeHTTP(w, r)
243
+ })
244
+ }
245
+
246
+ // paginate is a stub, but very possible to implement middleware logic
247
+ // to handle the request params for handling a paginated request.
248
+ func paginate(next http.Handler) http.Handler {
249
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
250
+ // just a stub.. some ideas are to look at URL query params for something like
251
+ // the page number, or the limit, and send a query cursor down the chain
252
+ next.ServeHTTP(w, r)
253
+ })
254
+ }
255
+
256
+ // This is entirely optional, but I wanted to demonstrate how you could easily
257
+ // add your own logic to the render.Respond method.
258
+ func init() {
259
+ render.Respond = func(w http.ResponseWriter, r *http.Request, v interface{}) {
260
+ if err, ok := v.(error); ok {
261
+
262
+ // We set a default error status response code if one hasn't been set.
263
+ if _, ok := r.Context().Value(render.StatusCtxKey).(int); !ok {
264
+ w.WriteHeader(400)
265
+ }
266
+
267
+ // We log the error
268
+ fmt.Printf("Logging err: %s\n", err.Error())
269
+
270
+ // We change the response to not reveal the actual error message,
271
+ // instead we can transform the message something more friendly or mapped
272
+ // to some code / language, etc.
273
+ render.DefaultResponder(w, r, render.M{"status": "error"})
274
+ return
275
+ }
276
+
277
+ render.DefaultResponder(w, r, v)
278
+ }
279
+ }
280
+
281
+ //--
282
+ // Request and Response payloads for the REST api.
283
+ //
284
+ // The payloads embed the data model objects an
285
+ //
286
+ // In a real-world project, it would make sense to put these payloads
287
+ // in another file, or another sub-package.
288
+ //--
289
+
290
+ type UserPayload struct {
291
+ *User
292
+ Role string `json:"role"`
293
+ }
294
+
295
+ func NewUserPayloadResponse(user *User) *UserPayload {
296
+ return &UserPayload{User: user}
297
+ }
298
+
299
+ // Bind on UserPayload will run after the unmarshalling is complete, its
300
+ // a good time to focus some post-processing after a decoding.
301
+ func (u *UserPayload) Bind(r *http.Request) error {
302
+ return nil
303
+ }
304
+
305
+ func (u *UserPayload) Render(w http.ResponseWriter, r *http.Request) error {
306
+ u.Role = "collaborator"
307
+ return nil
308
+ }
309
+
310
+ // ArticleRequest is the request payload for Article data model.
311
+ //
312
+ // NOTE: It's good practice to have well defined request and response payloads
313
+ // so you can manage the specific inputs and outputs for clients, and also gives
314
+ // you the opportunity to transform data on input or output, for example
315
+ // on request, we'd like to protect certain fields and on output perhaps
316
+ // we'd like to include a computed field based on other values that aren't
317
+ // in the data model. Also, check out this awesome blog post on struct composition:
318
+ // http://attilaolah.eu/2014/09/10/json-and-struct-composition-in-go/
319
+ type ArticleRequest struct {
320
+ *Article
321
+
322
+ User *UserPayload `json:"user,omitempty"`
323
+
324
+ ProtectedID string `json:"id"` // override 'id' json to have more control
325
+ }
326
+
327
+ func (a *ArticleRequest) Bind(r *http.Request) error {
328
+ // a.Article is nil if no Article fields are sent in the request. Return an
329
+ // error to avoid a nil pointer dereference.
330
+ if a.Article == nil {
331
+ return errors.New("missing required Article fields.")
332
+ }
333
+
334
+ // a.User is nil if no Userpayload fields are sent in the request. In this app
335
+ // this won't cause a panic, but checks in this Bind method may be required if
336
+ // a.User or further nested fields like a.User.Name are accessed elsewhere.
337
+
338
+ // just a post-process after a decode..
339
+ a.ProtectedID = "" // unset the protected ID
340
+ a.Article.Title = strings.ToLower(a.Article.Title) // as an example, we down-case
341
+ return nil
342
+ }
343
+
344
+ // ArticleResponse is the response payload for the Article data model.
345
+ // See NOTE above in ArticleRequest as well.
346
+ //
347
+ // In the ArticleResponse object, first a Render() is called on itself,
348
+ // then the next field, and so on, all the way down the tree.
349
+ // Render is called in top-down order, like a http handler middleware chain.
350
+ type ArticleResponse struct {
351
+ *Article
352
+
353
+ User *UserPayload `json:"user,omitempty"`
354
+
355
+ // We add an additional field to the response here.. such as this
356
+ // elapsed computed property
357
+ Elapsed int64 `json:"elapsed"`
358
+ }
359
+
360
+ func NewArticleResponse(article *Article) *ArticleResponse {
361
+ resp := &ArticleResponse{Article: article}
362
+
363
+ if resp.User == nil {
364
+ if user, _ := dbGetUser(resp.UserID); user != nil {
365
+ resp.User = NewUserPayloadResponse(user)
366
+ }
367
+ }
368
+
369
+ return resp
370
+ }
371
+
372
+ func (rd *ArticleResponse) Render(w http.ResponseWriter, r *http.Request) error {
373
+ // Pre-processing before a response is marshalled and sent across the wire
374
+ rd.Elapsed = 10
375
+ return nil
376
+ }
377
+
378
+ func NewArticleListResponse(articles []*Article) []render.Renderer {
379
+ list := []render.Renderer{}
380
+ for _, article := range articles {
381
+ list = append(list, NewArticleResponse(article))
382
+ }
383
+ return list
384
+ }
385
+
386
+ // NOTE: as a thought, the request and response payloads for an Article could be the
387
+ // same payload type, perhaps will do an example with it as well.
388
+ // type ArticlePayload struct {
389
+ // *Article
390
+ // }
391
+
392
+ //--
393
+ // Error response payloads & renderers
394
+ //--
395
+
396
+ // ErrResponse renderer type for handling all sorts of errors.
397
+ //
398
+ // In the best case scenario, the excellent github.com/pkg/errors package
399
+ // helps reveal information on the error, setting it on Err, and in the Render()
400
+ // method, using it to set the application-specific error code in AppCode.
401
+ type ErrResponse struct {
402
+ Err error `json:"-"` // low-level runtime error
403
+ HTTPStatusCode int `json:"-"` // http response status code
404
+
405
+ StatusText string `json:"status"` // user-level status message
406
+ AppCode int64 `json:"code,omitempty"` // application-specific error code
407
+ ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
408
+ }
409
+
410
+ func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
411
+ render.Status(r, e.HTTPStatusCode)
412
+ return nil
413
+ }
414
+
415
+ func ErrInvalidRequest(err error) render.Renderer {
416
+ return &ErrResponse{
417
+ Err: err,
418
+ HTTPStatusCode: 400,
419
+ StatusText: "Invalid request.",
420
+ ErrorText: err.Error(),
421
+ }
422
+ }
423
+
424
+ func ErrRender(err error) render.Renderer {
425
+ return &ErrResponse{
426
+ Err: err,
427
+ HTTPStatusCode: 422,
428
+ StatusText: "Error rendering response.",
429
+ ErrorText: err.Error(),
430
+ }
431
+ }
432
+
433
+ var ErrNotFound = &ErrResponse{HTTPStatusCode: 404, StatusText: "Resource not found."}
434
+
435
+ //--
436
+ // Data model objects and persistence mocks:
437
+ //--
438
+
439
+ // User data model
440
+ type User struct {
441
+ ID int64 `json:"id"`
442
+ Name string `json:"name"`
443
+ }
444
+
445
+ // Article data model. I suggest looking at https://upper.io for an easy
446
+ // and powerful data persistence adapter.
447
+ type Article struct {
448
+ ID string `json:"id"`
449
+ UserID int64 `json:"user_id"` // the author
450
+ Title string `json:"title"`
451
+ Slug string `json:"slug"`
452
+ }
453
+
454
+ // Article fixture data
455
+ var articles = []*Article{
456
+ {ID: "1", UserID: 100, Title: "Hi", Slug: "hi"},
457
+ {ID: "2", UserID: 200, Title: "sup", Slug: "sup"},
458
+ {ID: "3", UserID: 300, Title: "alo", Slug: "alo"},
459
+ {ID: "4", UserID: 400, Title: "bonjour", Slug: "bonjour"},
460
+ {ID: "5", UserID: 500, Title: "whats up", Slug: "whats-up"},
461
+ }
462
+
463
+ // User fixture data
464
+ var users = []*User{
465
+ {ID: 100, Name: "Peter"},
466
+ {ID: 200, Name: "Julia"},
467
+ }
468
+
469
+ func dbNewArticle(article *Article) (string, error) {
470
+ article.ID = fmt.Sprintf("%d", rand.Intn(100)+10)
471
+ articles = append(articles, article)
472
+ return article.ID, nil
473
+ }
474
+
475
+ func dbGetArticle(id string) (*Article, error) {
476
+ for _, a := range articles {
477
+ if a.ID == id {
478
+ return a, nil
479
+ }
480
+ }
481
+ return nil, errors.New("article not found.")
482
+ }
483
+
484
+ func dbGetArticleBySlug(slug string) (*Article, error) {
485
+ for _, a := range articles {
486
+ if a.Slug == slug {
487
+ return a, nil
488
+ }
489
+ }
490
+ return nil, errors.New("article not found.")
491
+ }
492
+
493
+ func dbUpdateArticle(id string, article *Article) (*Article, error) {
494
+ for i, a := range articles {
495
+ if a.ID == id {
496
+ articles[i] = article
497
+ return article, nil
498
+ }
499
+ }
500
+ return nil, errors.New("article not found.")
501
+ }
502
+
503
+ func dbRemoveArticle(id string) (*Article, error) {
504
+ for i, a := range articles {
505
+ if a.ID == id {
506
+ articles = append((articles)[:i], (articles)[i+1:]...)
507
+ return a, nil
508
+ }
509
+ }
510
+ return nil, errors.New("article not found.")
511
+ }
512
+
513
+ func dbGetUser(id int64) (*User, error) {
514
+ for _, u := range users {
515
+ if u.ID == id {
516
+ return u, nil
517
+ }
518
+ }
519
+ return nil, errors.New("user not found.")
520
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/routes.json ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "router": {
3
+ "middlewares": [
4
+ {
5
+ "pkg": "github.com/go-chi/chi/v5/middleware",
6
+ "func": "RequestID",
7
+ "comment": "RequestID is a middleware that injects a request ID into the context of each\nrequest. A request ID is a string of the form \"host.example.com/random-0001\",\nwhere \"random\" is a base62 random string that uniquely identifies this go\nprocess, and where the last number is an atomically incremented request\ncounter.\n",
8
+ "file": "github.com/go-chi/chi/middleware/request_id.go",
9
+ "line": 63
10
+ },
11
+ {
12
+ "pkg": "github.com/go-chi/chi/v5/middleware",
13
+ "func": "Logger",
14
+ "comment": "Logger is a middleware that logs the start and end of each request, along\nwith some useful data about what was requested, what the response status was,\nand how long it took to return. When standard output is a TTY, Logger will\nprint in color, otherwise it will print in black and white. Logger prints a\nrequest ID if one is provided.\n\nAlternatively, look at https://github.com/pressly/lg and the `lg.RequestLogger`\nmiddleware pkg.\n",
15
+ "file": "github.com/go-chi/chi/middleware/logger.go",
16
+ "line": 26
17
+ },
18
+ {
19
+ "pkg": "github.com/go-chi/chi/v5/middleware",
20
+ "func": "Recoverer",
21
+ "comment": "Recoverer is a middleware that recovers from panics, logs the panic (and a\nbacktrace), and returns a HTTP 500 (Internal Server Error) status if\npossible. Recoverer prints a request ID if one is provided.\n\nAlternatively, look at https://github.com/pressly/lg middleware pkgs.\n",
22
+ "file": "github.com/go-chi/chi/middleware/recoverer.go",
23
+ "line": 18
24
+ },
25
+ {
26
+ "pkg": "github.com/go-chi/chi/v5/middleware",
27
+ "func": "URLFormat",
28
+ "comment": "URLFormat is a middleware that parses the url extension from a request path and stores it\non the context as a string under the key `middleware.URLFormatCtxKey`. The middleware will\ntrim the suffix from the routing path and continue routing.\n\nRouters should not include a url parameter for the suffix when using this middleware.\n\nSample usage.. for url paths: `/articles/1`, `/articles/1.json` and `/articles/1.xml`\n\n func routes() http.Handler {\n r := chi.NewRouter()\n r.Use(middleware.URLFormat)\n\n r.Get(\"/articles/{id}\", ListArticles)\n\n return r\n }\n\n func ListArticles(w http.ResponseWriter, r *http.Request) {\n\t urlFormat, _ := r.Context().Value(middleware.URLFormatCtxKey).(string)\n\n\t switch urlFormat {\n\t case \"json\":\n\t \trender.JSON(w, r, articles)\n\t case \"xml:\"\n\t \trender.XML(w, r, articles)\n\t default:\n\t \trender.JSON(w, r, articles)\n\t }\n}\n",
29
+ "file": "github.com/go-chi/chi/middleware/url_format.go",
30
+ "line": 45
31
+ },
32
+ {
33
+ "pkg": "github.com/go-chi/render",
34
+ "func": "SetContentType.func1",
35
+ "comment": "",
36
+ "file": "github.com/go-chi/render/content_type.go",
37
+ "line": 49,
38
+ "anonymous": true
39
+ }
40
+ ],
41
+ "routes": {
42
+ "/": {
43
+ "handlers": {
44
+ "GET": {
45
+ "middlewares": [],
46
+ "method": "GET",
47
+ "pkg": "",
48
+ "func": "main.main.func1",
49
+ "comment": "",
50
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
51
+ "line": 69,
52
+ "anonymous": true
53
+ }
54
+ }
55
+ },
56
+ "/admin/*": {
57
+ "router": {
58
+ "middlewares": [
59
+ {
60
+ "pkg": "",
61
+ "func": "main.AdminOnly",
62
+ "comment": "AdminOnly middleware restricts access to just administrators.\n",
63
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
64
+ "line": 238
65
+ }
66
+ ],
67
+ "routes": {
68
+ "/": {
69
+ "handlers": {
70
+ "GET": {
71
+ "middlewares": [],
72
+ "method": "GET",
73
+ "pkg": "",
74
+ "func": "main.adminRouter.func1",
75
+ "comment": "",
76
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
77
+ "line": 225,
78
+ "anonymous": true
79
+ }
80
+ }
81
+ },
82
+ "/accounts": {
83
+ "handlers": {
84
+ "GET": {
85
+ "middlewares": [],
86
+ "method": "GET",
87
+ "pkg": "",
88
+ "func": "main.adminRouter.func2",
89
+ "comment": "",
90
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
91
+ "line": 228,
92
+ "anonymous": true
93
+ }
94
+ }
95
+ },
96
+ "/users/{userId}": {
97
+ "handlers": {
98
+ "GET": {
99
+ "middlewares": [],
100
+ "method": "GET",
101
+ "pkg": "",
102
+ "func": "main.adminRouter.func3",
103
+ "comment": "",
104
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
105
+ "line": 231,
106
+ "anonymous": true
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
112
+ },
113
+ "/articles/*": {
114
+ "router": {
115
+ "middlewares": [],
116
+ "routes": {
117
+ "/": {
118
+ "handlers": {
119
+ "GET": {
120
+ "middlewares": [
121
+ {
122
+ "pkg": "",
123
+ "func": "main.paginate",
124
+ "comment": "paginate is a stub, but very possible to implement middleware logic\nto handle the request params for handling a paginated request.\n",
125
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
126
+ "line": 251
127
+ }
128
+ ],
129
+ "method": "GET",
130
+ "pkg": "",
131
+ "func": "main.ListArticles",
132
+ "comment": "",
133
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
134
+ "line": 117
135
+ },
136
+ "POST": {
137
+ "middlewares": [],
138
+ "method": "POST",
139
+ "pkg": "",
140
+ "func": "main.CreateArticle",
141
+ "comment": "CreateArticle persists the posted Article and returns it\nback to the client as an acknowledgement.\n",
142
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
143
+ "line": 158
144
+ }
145
+ }
146
+ },
147
+ "/search": {
148
+ "handlers": {
149
+ "GET": {
150
+ "middlewares": [],
151
+ "method": "GET",
152
+ "pkg": "",
153
+ "func": "main.SearchArticles",
154
+ "comment": "SearchArticles searches the Articles data for a matching article.\nIt's just a stub, but you get the idea.\n",
155
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
156
+ "line": 152
157
+ }
158
+ }
159
+ },
160
+ "/{articleID}/*": {
161
+ "router": {
162
+ "middlewares": [
163
+ {
164
+ "pkg": "",
165
+ "func": "main.ArticleCtx",
166
+ "comment": "ArticleCtx middleware is used to load an Article object from\nthe URL parameters passed through as the request. In case\nthe Article could not be found, we stop here and return a 404.\n",
167
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
168
+ "line": 127
169
+ }
170
+ ],
171
+ "routes": {
172
+ "/": {
173
+ "handlers": {
174
+ "DELETE": {
175
+ "middlewares": [],
176
+ "method": "DELETE",
177
+ "pkg": "",
178
+ "func": "main.DeleteArticle",
179
+ "comment": "DeleteArticle removes an existing Article from our persistent store.\n",
180
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
181
+ "line": 204
182
+ },
183
+ "GET": {
184
+ "middlewares": [],
185
+ "method": "GET",
186
+ "pkg": "",
187
+ "func": "main.GetArticle",
188
+ "comment": "GetArticle returns the specific Article. You'll notice it just\nfetches the Article right off the context, as its understood that\nif we made it this far, the Article must be on the context. In case\nits not due to a bug, then it will panic, and our Recoverer will save us.\n",
189
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
190
+ "line": 176
191
+ },
192
+ "PUT": {
193
+ "middlewares": [],
194
+ "method": "PUT",
195
+ "pkg": "",
196
+ "func": "main.UpdateArticle",
197
+ "comment": "UpdateArticle updates an existing Article in our persistent store.\n",
198
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
199
+ "line": 189
200
+ }
201
+ }
202
+ }
203
+ }
204
+ }
205
+ },
206
+ "/{articleSlug:[a-z-]+}": {
207
+ "handlers": {
208
+ "GET": {
209
+ "middlewares": [
210
+ {
211
+ "pkg": "",
212
+ "func": "main.ArticleCtx",
213
+ "comment": "ArticleCtx middleware is used to load an Article object from\nthe URL parameters passed through as the request. In case\nthe Article could not be found, we stop here and return a 404.\n",
214
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
215
+ "line": 127
216
+ }
217
+ ],
218
+ "method": "GET",
219
+ "pkg": "",
220
+ "func": "main.GetArticle",
221
+ "comment": "GetArticle returns the specific Article. You'll notice it just\nfetches the Article right off the context, as its understood that\nif we made it this far, the Article must be on the context. In case\nits not due to a bug, then it will panic, and our Recoverer will save us.\n",
222
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
223
+ "line": 176
224
+ }
225
+ }
226
+ }
227
+ }
228
+ }
229
+ },
230
+ "/panic": {
231
+ "handlers": {
232
+ "GET": {
233
+ "middlewares": [],
234
+ "method": "GET",
235
+ "pkg": "",
236
+ "func": "main.main.func3",
237
+ "comment": "",
238
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
239
+ "line": 77,
240
+ "anonymous": true
241
+ }
242
+ }
243
+ },
244
+ "/ping": {
245
+ "handlers": {
246
+ "GET": {
247
+ "middlewares": [],
248
+ "method": "GET",
249
+ "pkg": "",
250
+ "func": "main.main.func2",
251
+ "comment": "",
252
+ "file": "github.com/go-chi/chi/_examples/rest/main.go",
253
+ "line": 73,
254
+ "anonymous": true
255
+ }
256
+ }
257
+ }
258
+ }
259
+ }
260
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/rest/routes.md ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # github.com/go-chi/chi
2
+
3
+ Welcome to the chi/_examples/rest generated docs.
4
+
5
+ ## Routes
6
+
7
+ <details>
8
+ <summary>`/`</summary>
9
+
10
+ - [RequestID](/middleware/request_id.go#L63)
11
+ - [Logger](/middleware/logger.go#L26)
12
+ - [Recoverer](/middleware/recoverer.go#L18)
13
+ - [URLFormat](/middleware/url_format.go#L45)
14
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
15
+ - **/**
16
+ - _GET_
17
+ - [main.main.func1](/_examples/rest/main.go#L69)
18
+
19
+ </details>
20
+ <details>
21
+ <summary>`/admin/*`</summary>
22
+
23
+ - [RequestID](/middleware/request_id.go#L63)
24
+ - [Logger](/middleware/logger.go#L26)
25
+ - [Recoverer](/middleware/recoverer.go#L18)
26
+ - [URLFormat](/middleware/url_format.go#L45)
27
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
28
+ - **/admin/***
29
+ - [main.AdminOnly](/_examples/rest/main.go#L238)
30
+ - **/**
31
+ - _GET_
32
+ - [main.adminRouter.func1](/_examples/rest/main.go#L225)
33
+
34
+ </details>
35
+ <details>
36
+ <summary>`/admin/*/accounts`</summary>
37
+
38
+ - [RequestID](/middleware/request_id.go#L63)
39
+ - [Logger](/middleware/logger.go#L26)
40
+ - [Recoverer](/middleware/recoverer.go#L18)
41
+ - [URLFormat](/middleware/url_format.go#L45)
42
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
43
+ - **/admin/***
44
+ - [main.AdminOnly](/_examples/rest/main.go#L238)
45
+ - **/accounts**
46
+ - _GET_
47
+ - [main.adminRouter.func2](/_examples/rest/main.go#L228)
48
+
49
+ </details>
50
+ <details>
51
+ <summary>`/admin/*/users/{userId}`</summary>
52
+
53
+ - [RequestID](/middleware/request_id.go#L63)
54
+ - [Logger](/middleware/logger.go#L26)
55
+ - [Recoverer](/middleware/recoverer.go#L18)
56
+ - [URLFormat](/middleware/url_format.go#L45)
57
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
58
+ - **/admin/***
59
+ - [main.AdminOnly](/_examples/rest/main.go#L238)
60
+ - **/users/{userId}**
61
+ - _GET_
62
+ - [main.adminRouter.func3](/_examples/rest/main.go#L231)
63
+
64
+ </details>
65
+ <details>
66
+ <summary>`/articles/*`</summary>
67
+
68
+ - [RequestID](/middleware/request_id.go#L63)
69
+ - [Logger](/middleware/logger.go#L26)
70
+ - [Recoverer](/middleware/recoverer.go#L18)
71
+ - [URLFormat](/middleware/url_format.go#L45)
72
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
73
+ - **/articles/***
74
+ - **/**
75
+ - _GET_
76
+ - [main.paginate](/_examples/rest/main.go#L251)
77
+ - [main.ListArticles](/_examples/rest/main.go#L117)
78
+ - _POST_
79
+ - [main.CreateArticle](/_examples/rest/main.go#L158)
80
+
81
+ </details>
82
+ <details>
83
+ <summary>`/articles/*/search`</summary>
84
+
85
+ - [RequestID](/middleware/request_id.go#L63)
86
+ - [Logger](/middleware/logger.go#L26)
87
+ - [Recoverer](/middleware/recoverer.go#L18)
88
+ - [URLFormat](/middleware/url_format.go#L45)
89
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
90
+ - **/articles/***
91
+ - **/search**
92
+ - _GET_
93
+ - [main.SearchArticles](/_examples/rest/main.go#L152)
94
+
95
+ </details>
96
+ <details>
97
+ <summary>`/articles/*/{articleID}/*`</summary>
98
+
99
+ - [RequestID](/middleware/request_id.go#L63)
100
+ - [Logger](/middleware/logger.go#L26)
101
+ - [Recoverer](/middleware/recoverer.go#L18)
102
+ - [URLFormat](/middleware/url_format.go#L45)
103
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
104
+ - **/articles/***
105
+ - **/{articleID}/***
106
+ - [main.ArticleCtx](/_examples/rest/main.go#L127)
107
+ - **/**
108
+ - _DELETE_
109
+ - [main.DeleteArticle](/_examples/rest/main.go#L204)
110
+ - _GET_
111
+ - [main.GetArticle](/_examples/rest/main.go#L176)
112
+ - _PUT_
113
+ - [main.UpdateArticle](/_examples/rest/main.go#L189)
114
+
115
+ </details>
116
+ <details>
117
+ <summary>`/articles/*/{articleSlug:[a-z-]+}`</summary>
118
+
119
+ - [RequestID](/middleware/request_id.go#L63)
120
+ - [Logger](/middleware/logger.go#L26)
121
+ - [Recoverer](/middleware/recoverer.go#L18)
122
+ - [URLFormat](/middleware/url_format.go#L45)
123
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
124
+ - **/articles/***
125
+ - **/{articleSlug:[a-z-]+}**
126
+ - _GET_
127
+ - [main.ArticleCtx](/_examples/rest/main.go#L127)
128
+ - [main.GetArticle](/_examples/rest/main.go#L176)
129
+
130
+ </details>
131
+ <details>
132
+ <summary>`/panic`</summary>
133
+
134
+ - [RequestID](/middleware/request_id.go#L63)
135
+ - [Logger](/middleware/logger.go#L26)
136
+ - [Recoverer](/middleware/recoverer.go#L18)
137
+ - [URLFormat](/middleware/url_format.go#L45)
138
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
139
+ - **/panic**
140
+ - _GET_
141
+ - [main.main.func3](/_examples/rest/main.go#L77)
142
+
143
+ </details>
144
+ <details>
145
+ <summary>`/ping`</summary>
146
+
147
+ - [RequestID](/middleware/request_id.go#L63)
148
+ - [Logger](/middleware/logger.go#L26)
149
+ - [Recoverer](/middleware/recoverer.go#L18)
150
+ - [URLFormat](/middleware/url_format.go#L45)
151
+ - [SetContentType.func1](https://github.com/go-chi/render/content_type.go#L49)
152
+ - **/ping**
153
+ - _GET_
154
+ - [main.main.func2](/_examples/rest/main.go#L73)
155
+
156
+ </details>
157
+
158
+ Total # of routes: 10
159
+
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/router-walk/main.go ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ "net/http"
6
+ "strings"
7
+
8
+ "github.com/go-chi/chi/v5"
9
+ )
10
+
11
+ func main() {
12
+ r := chi.NewRouter()
13
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
14
+ w.Write([]byte("root."))
15
+ })
16
+
17
+ r.Route("/road", func(r chi.Router) {
18
+ r.Get("/left", func(w http.ResponseWriter, r *http.Request) {
19
+ w.Write([]byte("left road"))
20
+ })
21
+ r.Post("/right", func(w http.ResponseWriter, r *http.Request) {
22
+ w.Write([]byte("right road"))
23
+ })
24
+ })
25
+
26
+ r.Put("/ping", Ping)
27
+
28
+ walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
29
+ route = strings.Replace(route, "/*/", "/", -1)
30
+ fmt.Printf("%s %s\n", method, route)
31
+ return nil
32
+ }
33
+
34
+ if err := chi.Walk(r, walkFunc); err != nil {
35
+ fmt.Printf("Logging err: %s\n", err.Error())
36
+ }
37
+ }
38
+
39
+ // Ping returns pong
40
+ func Ping(w http.ResponseWriter, r *http.Request) {
41
+ w.Write([]byte("pong"))
42
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/todos-resource/main.go ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This example demonstrates a project structure that defines a subrouter and its
2
+ // handlers on a struct, and mounting them as subrouters to a parent router.
3
+ // See also _examples/rest for an in-depth example of a REST service, and apply
4
+ // those same patterns to this structure.
5
+ package main
6
+
7
+ import (
8
+ "net/http"
9
+
10
+ "github.com/go-chi/chi/v5"
11
+ "github.com/go-chi/chi/v5/middleware"
12
+ )
13
+
14
+ func main() {
15
+ r := chi.NewRouter()
16
+
17
+ r.Use(middleware.RequestID)
18
+ r.Use(middleware.RealIP)
19
+ r.Use(middleware.Logger)
20
+ r.Use(middleware.Recoverer)
21
+
22
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
23
+ w.Write([]byte("."))
24
+ })
25
+
26
+ r.Mount("/users", usersResource{}.Routes())
27
+ r.Mount("/todos", todosResource{}.Routes())
28
+
29
+ http.ListenAndServe(":3333", r)
30
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/todos-resource/todos.go ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "net/http"
5
+
6
+ "github.com/go-chi/chi/v5"
7
+ )
8
+
9
+ type todosResource struct{}
10
+
11
+ // Routes creates a REST router for the todos resource
12
+ func (rs todosResource) Routes() chi.Router {
13
+ r := chi.NewRouter()
14
+ // r.Use() // some middleware..
15
+
16
+ r.Get("/", rs.List) // GET /todos - read a list of todos
17
+ r.Post("/", rs.Create) // POST /todos - create a new todo and persist it
18
+ r.Put("/", rs.Delete)
19
+
20
+ r.Route("/{id}", func(r chi.Router) {
21
+ // r.Use(rs.TodoCtx) // lets have a todos map, and lets actually load/manipulate
22
+ r.Get("/", rs.Get) // GET /todos/{id} - read a single todo by :id
23
+ r.Put("/", rs.Update) // PUT /todos/{id} - update a single todo by :id
24
+ r.Delete("/", rs.Delete) // DELETE /todos/{id} - delete a single todo by :id
25
+ r.Get("/sync", rs.Sync)
26
+ })
27
+
28
+ return r
29
+ }
30
+
31
+ func (rs todosResource) List(w http.ResponseWriter, r *http.Request) {
32
+ w.Write([]byte("todos list of stuff.."))
33
+ }
34
+
35
+ func (rs todosResource) Create(w http.ResponseWriter, r *http.Request) {
36
+ w.Write([]byte("todos create"))
37
+ }
38
+
39
+ func (rs todosResource) Get(w http.ResponseWriter, r *http.Request) {
40
+ w.Write([]byte("todo get"))
41
+ }
42
+
43
+ func (rs todosResource) Update(w http.ResponseWriter, r *http.Request) {
44
+ w.Write([]byte("todo update"))
45
+ }
46
+
47
+ func (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) {
48
+ w.Write([]byte("todo delete"))
49
+ }
50
+
51
+ func (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) {
52
+ w.Write([]byte("todo sync"))
53
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/todos-resource/users.go ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "net/http"
5
+
6
+ "github.com/go-chi/chi/v5"
7
+ )
8
+
9
+ type usersResource struct{}
10
+
11
+ // Routes creates a REST router for the todos resource
12
+ func (rs usersResource) Routes() chi.Router {
13
+ r := chi.NewRouter()
14
+ // r.Use() // some middleware..
15
+
16
+ r.Get("/", rs.List) // GET /users - read a list of users
17
+ r.Post("/", rs.Create) // POST /users - create a new user and persist it
18
+ r.Put("/", rs.Delete)
19
+
20
+ r.Route("/{id}", func(r chi.Router) {
21
+ // r.Use(rs.TodoCtx) // lets have a users map, and lets actually load/manipulate
22
+ r.Get("/", rs.Get) // GET /users/{id} - read a single user by :id
23
+ r.Put("/", rs.Update) // PUT /users/{id} - update a single user by :id
24
+ r.Delete("/", rs.Delete) // DELETE /users/{id} - delete a single user by :id
25
+ })
26
+
27
+ return r
28
+ }
29
+
30
+ func (rs usersResource) List(w http.ResponseWriter, r *http.Request) {
31
+ w.Write([]byte("users list of stuff.."))
32
+ }
33
+
34
+ func (rs usersResource) Create(w http.ResponseWriter, r *http.Request) {
35
+ w.Write([]byte("users create"))
36
+ }
37
+
38
+ func (rs usersResource) Get(w http.ResponseWriter, r *http.Request) {
39
+ w.Write([]byte("user get"))
40
+ }
41
+
42
+ func (rs usersResource) Update(w http.ResponseWriter, r *http.Request) {
43
+ w.Write([]byte("user update"))
44
+ }
45
+
46
+ func (rs usersResource) Delete(w http.ResponseWriter, r *http.Request) {
47
+ w.Write([]byte("user delete"))
48
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/data/article.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ package data
2
+
3
+ // Article is runtime object, that's not meant to be sent via REST.
4
+ type Article struct {
5
+ ID int `db:"id" json:"id" xml:"id"`
6
+ Title string `db:"title" json:"title" xml:"title"`
7
+ Data []string `db:"data,stringarray" json:"data" xml:"data"`
8
+ CustomDataForAuthUsers string `db:"custom_data" json:"-" xml:"-"`
9
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/data/errors.go ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package data
2
+
3
+ import (
4
+ "errors"
5
+ "net/http"
6
+
7
+ "github.com/go-chi/render"
8
+ )
9
+
10
+ var (
11
+ ErrUnauthorized = errors.New("Unauthorized")
12
+ ErrForbidden = errors.New("Forbidden")
13
+ ErrNotFound = errors.New("Resource not found")
14
+ )
15
+
16
+ func PresentError(r *http.Request, err error) (*http.Request, interface{}) {
17
+ switch err {
18
+ case ErrUnauthorized:
19
+ render.Status(r, 401)
20
+ case ErrForbidden:
21
+ render.Status(r, 403)
22
+ case ErrNotFound:
23
+ render.Status(r, 404)
24
+ default:
25
+ render.Status(r, 500)
26
+ }
27
+ return r, map[string]string{"error": err.Error()}
28
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/go.mod ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ module versions
2
+
3
+ go 1.16
4
+
5
+ require (
6
+ github.com/go-chi/chi/v5 v5.1.0
7
+ github.com/go-chi/render v1.0.3
8
+ )
9
+
10
+ require github.com/ajg/form v1.5.1 // indirect
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/go.sum ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
2
+ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
3
+ github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
4
+ github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
5
+ github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
6
+ github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/main.go ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This example demonstrates the use of the render subpackage, with
2
+ // a quick concept for how to support multiple api versions.
3
+ package main
4
+
5
+ import (
6
+ "context"
7
+ "errors"
8
+ "fmt"
9
+ "math/rand"
10
+ "net/http"
11
+ "time"
12
+
13
+ "github.com/go-chi/chi/v5"
14
+ "github.com/go-chi/chi/v5/_examples/versions/data"
15
+ v1 "github.com/go-chi/chi/v5/_examples/versions/presenter/v1"
16
+ v2 "github.com/go-chi/chi/v5/_examples/versions/presenter/v2"
17
+ v3 "github.com/go-chi/chi/v5/_examples/versions/presenter/v3"
18
+ "github.com/go-chi/chi/v5/middleware"
19
+ "github.com/go-chi/render"
20
+ )
21
+
22
+ func main() {
23
+ r := chi.NewRouter()
24
+
25
+ r.Use(middleware.RequestID)
26
+ r.Use(middleware.Logger)
27
+ r.Use(middleware.Recoverer)
28
+
29
+ // API version 3.
30
+ r.Route("/v3", func(r chi.Router) {
31
+ r.Use(apiVersionCtx("v3"))
32
+ r.Mount("/articles", articleRouter())
33
+ })
34
+
35
+ // API version 2.
36
+ r.Route("/v2", func(r chi.Router) {
37
+ r.Use(apiVersionCtx("v2"))
38
+ r.Mount("/articles", articleRouter())
39
+ })
40
+
41
+ // API version 1.
42
+ r.Route("/v1", func(r chi.Router) {
43
+ r.Use(randomErrorMiddleware) // Simulate random error, ie. version 1 is buggy.
44
+ r.Use(apiVersionCtx("v1"))
45
+ r.Mount("/articles", articleRouter())
46
+ })
47
+
48
+ http.ListenAndServe(":3333", r)
49
+ }
50
+
51
+ func apiVersionCtx(version string) func(next http.Handler) http.Handler {
52
+ return func(next http.Handler) http.Handler {
53
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
54
+ r = r.WithContext(context.WithValue(r.Context(), "api.version", version))
55
+ next.ServeHTTP(w, r)
56
+ })
57
+ }
58
+ }
59
+
60
+ func articleRouter() http.Handler {
61
+ r := chi.NewRouter()
62
+ r.Get("/", listArticles)
63
+ r.Route("/{articleID}", func(r chi.Router) {
64
+ r.Get("/", getArticle)
65
+ // r.Put("/", updateArticle)
66
+ // r.Delete("/", deleteArticle)
67
+ })
68
+ return r
69
+ }
70
+
71
+ func listArticles(w http.ResponseWriter, r *http.Request) {
72
+ articles := make(chan render.Renderer, 5)
73
+
74
+ // Load data asynchronously into the channel (simulate slow storage):
75
+ go func() {
76
+ for i := 1; i <= 10; i++ {
77
+ article := &data.Article{
78
+ ID: i,
79
+ Title: fmt.Sprintf("Article #%v", i),
80
+ Data: []string{"one", "two", "three", "four"},
81
+ CustomDataForAuthUsers: "secret data for auth'd users only",
82
+ }
83
+
84
+ apiVersion := r.Context().Value("api.version").(string)
85
+ switch apiVersion {
86
+ case "v1":
87
+ articles <- v1.NewArticleResponse(article)
88
+ case "v2":
89
+ articles <- v2.NewArticleResponse(article)
90
+ default:
91
+ articles <- v3.NewArticleResponse(article)
92
+ }
93
+
94
+ time.Sleep(100 * time.Millisecond)
95
+ }
96
+ close(articles)
97
+ }()
98
+
99
+ // Start streaming data from the channel.
100
+ render.Respond(w, r, articles)
101
+ }
102
+
103
+ func getArticle(w http.ResponseWriter, r *http.Request) {
104
+ // Load article.
105
+ if chi.URLParam(r, "articleID") != "1" {
106
+ render.Respond(w, r, data.ErrNotFound)
107
+ return
108
+ }
109
+ article := &data.Article{
110
+ ID: 1,
111
+ Title: "Article #1",
112
+ Data: []string{"one", "two", "three", "four"},
113
+ CustomDataForAuthUsers: "secret data for auth'd users only",
114
+ }
115
+
116
+ // Simulate some context values:
117
+ // 1. ?auth=true simulates authenticated session/user.
118
+ // 2. ?error=true simulates random error.
119
+ if r.URL.Query().Get("auth") != "" {
120
+ r = r.WithContext(context.WithValue(r.Context(), "auth", true))
121
+ }
122
+ if r.URL.Query().Get("error") != "" {
123
+ render.Respond(w, r, errors.New("error"))
124
+ return
125
+ }
126
+
127
+ var payload render.Renderer
128
+
129
+ apiVersion := r.Context().Value("api.version").(string)
130
+ switch apiVersion {
131
+ case "v1":
132
+ payload = v1.NewArticleResponse(article)
133
+ case "v2":
134
+ payload = v2.NewArticleResponse(article)
135
+ default:
136
+ payload = v3.NewArticleResponse(article)
137
+ }
138
+
139
+ render.Render(w, r, payload)
140
+ }
141
+
142
+ func randomErrorMiddleware(next http.Handler) http.Handler {
143
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
144
+ rand.Seed(time.Now().Unix())
145
+
146
+ // One in three chance of random error.
147
+ if rand.Int31n(3) == 0 {
148
+ errors := []error{data.ErrUnauthorized, data.ErrForbidden, data.ErrNotFound}
149
+ render.Respond(w, r, errors[rand.Intn(len(errors))])
150
+ return
151
+ }
152
+ next.ServeHTTP(w, r)
153
+ })
154
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/presenter/v1/article.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package v1
2
+
3
+ import (
4
+ "net/http"
5
+
6
+ "github.com/go-chi/chi/v5/_examples/versions/data"
7
+ )
8
+
9
+ // Article presented in API version 1.
10
+ type Article struct {
11
+ *data.Article
12
+
13
+ Data map[string]bool `json:"data" xml:"data"`
14
+ }
15
+
16
+ func (a *Article) Render(w http.ResponseWriter, r *http.Request) error {
17
+ return nil
18
+ }
19
+
20
+ func NewArticleResponse(article *data.Article) *Article {
21
+ return &Article{Article: article}
22
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/presenter/v2/article.go ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package v2
2
+
3
+ import (
4
+ "fmt"
5
+ "net/http"
6
+
7
+ "github.com/go-chi/chi/v5/_examples/versions/data"
8
+ )
9
+
10
+ // Article presented in API version 2.
11
+ type Article struct {
12
+ // *v3.Article `json:",inline" xml:",inline"`
13
+
14
+ *data.Article
15
+
16
+ // Additional fields.
17
+ SelfURL string `json:"self_url" xml:"self_url"`
18
+
19
+ // Omitted fields.
20
+ URL interface{} `json:"url,omitempty" xml:"url,omitempty"`
21
+ }
22
+
23
+ func (a *Article) Render(w http.ResponseWriter, r *http.Request) error {
24
+ a.SelfURL = fmt.Sprintf("http://localhost:3333/v2?id=%v", a.ID)
25
+ return nil
26
+ }
27
+
28
+ func NewArticleResponse(article *data.Article) *Article {
29
+ return &Article{Article: article}
30
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/_examples/versions/presenter/v3/article.go ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package v3
2
+
3
+ import (
4
+ "fmt"
5
+ "math/rand"
6
+ "net/http"
7
+
8
+ "github.com/go-chi/chi/v5/_examples/versions/data"
9
+ )
10
+
11
+ // Article presented in API version 2.
12
+ type Article struct {
13
+ *data.Article `json:",inline" xml:",inline"`
14
+
15
+ // Additional fields.
16
+ URL string `json:"url" xml:"url"`
17
+ ViewsCount int64 `json:"views_count" xml:"views_count"`
18
+ APIVersion string `json:"api_version" xml:"api_version"`
19
+
20
+ // Omitted fields.
21
+ // Show custom_data explicitly for auth'd users only.
22
+ CustomDataForAuthUsers interface{} `json:"custom_data,omitempty" xml:"custom_data,omitempty"`
23
+ }
24
+
25
+ func (a *Article) Render(w http.ResponseWriter, r *http.Request) error {
26
+ a.ViewsCount = rand.Int63n(100000)
27
+ a.URL = fmt.Sprintf("http://localhost:3333/v3/?id=%v", a.ID)
28
+
29
+ // Only show to auth'd user.
30
+ if _, ok := r.Context().Value("auth").(bool); ok {
31
+ a.CustomDataForAuthUsers = a.Article.CustomDataForAuthUsers
32
+ }
33
+
34
+ return nil
35
+ }
36
+
37
+ func NewArticleResponse(article *data.Article) *Article {
38
+ return &Article{Article: article}
39
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/chain.go ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package chi
2
+
3
+ import "net/http"
4
+
5
+ // Chain returns a Middlewares type from a slice of middleware handlers.
6
+ func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares {
7
+ return Middlewares(middlewares)
8
+ }
9
+
10
+ // Handler builds and returns a http.Handler from the chain of middlewares,
11
+ // with `h http.Handler` as the final handler.
12
+ func (mws Middlewares) Handler(h http.Handler) http.Handler {
13
+ return &ChainHandler{h, chain(mws, h), mws}
14
+ }
15
+
16
+ // HandlerFunc builds and returns a http.Handler from the chain of middlewares,
17
+ // with `h http.Handler` as the final handler.
18
+ func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler {
19
+ return &ChainHandler{h, chain(mws, h), mws}
20
+ }
21
+
22
+ // ChainHandler is a http.Handler with support for handler composition and
23
+ // execution.
24
+ type ChainHandler struct {
25
+ Endpoint http.Handler
26
+ chain http.Handler
27
+ Middlewares Middlewares
28
+ }
29
+
30
+ func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
31
+ c.chain.ServeHTTP(w, r)
32
+ }
33
+
34
+ // chain builds a http.Handler composed of an inline middleware stack and endpoint
35
+ // handler in the order they are passed.
36
+ func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
37
+ // Return ahead of time if there aren't any middlewares for the chain
38
+ if len(middlewares) == 0 {
39
+ return endpoint
40
+ }
41
+
42
+ // Wrap the end handler with the middleware chain
43
+ h := middlewares[len(middlewares)-1](endpoint)
44
+ for i := len(middlewares) - 2; i >= 0; i-- {
45
+ h = middlewares[i](h)
46
+ }
47
+
48
+ return h
49
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/chi.go ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package chi is a small, idiomatic and composable router for building HTTP services.
2
+ //
3
+ // chi requires Go 1.14 or newer.
4
+ //
5
+ // Example:
6
+ //
7
+ // package main
8
+ //
9
+ // import (
10
+ // "net/http"
11
+ //
12
+ // "github.com/go-chi/chi/v5"
13
+ // "github.com/go-chi/chi/v5/middleware"
14
+ // )
15
+ //
16
+ // func main() {
17
+ // r := chi.NewRouter()
18
+ // r.Use(middleware.Logger)
19
+ // r.Use(middleware.Recoverer)
20
+ //
21
+ // r.Get("/", func(w http.ResponseWriter, r *http.Request) {
22
+ // w.Write([]byte("root."))
23
+ // })
24
+ //
25
+ // http.ListenAndServe(":3333", r)
26
+ // }
27
+ //
28
+ // See github.com/go-chi/chi/_examples/ for more in-depth examples.
29
+ //
30
+ // URL patterns allow for easy matching of path components in HTTP
31
+ // requests. The matching components can then be accessed using
32
+ // chi.URLParam(). All patterns must begin with a slash.
33
+ //
34
+ // A simple named placeholder {name} matches any sequence of characters
35
+ // up to the next / or the end of the URL. Trailing slashes on paths must
36
+ // be handled explicitly.
37
+ //
38
+ // A placeholder with a name followed by a colon allows a regular
39
+ // expression match, for example {number:\\d+}. The regular expression
40
+ // syntax is Go's normal regexp RE2 syntax, except that / will never be
41
+ // matched. An anonymous regexp pattern is allowed, using an empty string
42
+ // before the colon in the placeholder, such as {:\\d+}
43
+ //
44
+ // The special placeholder of asterisk matches the rest of the requested
45
+ // URL. Any trailing characters in the pattern are ignored. This is the only
46
+ // placeholder which will match / characters.
47
+ //
48
+ // Examples:
49
+ //
50
+ // "/user/{name}" matches "/user/jsmith" but not "/user/jsmith/info" or "/user/jsmith/"
51
+ // "/user/{name}/info" matches "/user/jsmith/info"
52
+ // "/page/*" matches "/page/intro/latest"
53
+ // "/page/{other}/latest" also matches "/page/intro/latest"
54
+ // "/date/{yyyy:\\d\\d\\d\\d}/{mm:\\d\\d}/{dd:\\d\\d}" matches "/date/2017/04/01"
55
+ package chi
56
+
57
+ import "net/http"
58
+
59
+ // NewRouter returns a new Mux object that implements the Router interface.
60
+ func NewRouter() *Mux {
61
+ return NewMux()
62
+ }
63
+
64
+ // Router consisting of the core routing methods used by chi's Mux,
65
+ // using only the standard net/http.
66
+ type Router interface {
67
+ http.Handler
68
+ Routes
69
+
70
+ // Use appends one or more middlewares onto the Router stack.
71
+ Use(middlewares ...func(http.Handler) http.Handler)
72
+
73
+ // With adds inline middlewares for an endpoint handler.
74
+ With(middlewares ...func(http.Handler) http.Handler) Router
75
+
76
+ // Group adds a new inline-Router along the current routing
77
+ // path, with a fresh middleware stack for the inline-Router.
78
+ Group(fn func(r Router)) Router
79
+
80
+ // Route mounts a sub-Router along a `pattern`` string.
81
+ Route(pattern string, fn func(r Router)) Router
82
+
83
+ // Mount attaches another http.Handler along ./pattern/*
84
+ Mount(pattern string, h http.Handler)
85
+
86
+ // Handle and HandleFunc adds routes for `pattern` that matches
87
+ // all HTTP methods.
88
+ Handle(pattern string, h http.Handler)
89
+ HandleFunc(pattern string, h http.HandlerFunc)
90
+
91
+ // Method and MethodFunc adds routes for `pattern` that matches
92
+ // the `method` HTTP method.
93
+ Method(method, pattern string, h http.Handler)
94
+ MethodFunc(method, pattern string, h http.HandlerFunc)
95
+
96
+ // HTTP-method routing along `pattern`
97
+ Connect(pattern string, h http.HandlerFunc)
98
+ Delete(pattern string, h http.HandlerFunc)
99
+ Get(pattern string, h http.HandlerFunc)
100
+ Head(pattern string, h http.HandlerFunc)
101
+ Options(pattern string, h http.HandlerFunc)
102
+ Patch(pattern string, h http.HandlerFunc)
103
+ Post(pattern string, h http.HandlerFunc)
104
+ Put(pattern string, h http.HandlerFunc)
105
+ Trace(pattern string, h http.HandlerFunc)
106
+
107
+ // NotFound defines a handler to respond whenever a route could
108
+ // not be found.
109
+ NotFound(h http.HandlerFunc)
110
+
111
+ // MethodNotAllowed defines a handler to respond whenever a method is
112
+ // not allowed.
113
+ MethodNotAllowed(h http.HandlerFunc)
114
+ }
115
+
116
+ // Routes interface adds two methods for router traversal, which is also
117
+ // used by the `docgen` subpackage to generation documentation for Routers.
118
+ type Routes interface {
119
+ // Routes returns the routing tree in an easily traversable structure.
120
+ Routes() []Route
121
+
122
+ // Middlewares returns the list of middlewares in use by the router.
123
+ Middlewares() Middlewares
124
+
125
+ // Match searches the routing tree for a handler that matches
126
+ // the method/path - similar to routing a http request, but without
127
+ // executing the handler thereafter.
128
+ Match(rctx *Context, method, path string) bool
129
+
130
+ // Find searches the routing tree for the pattern that matches
131
+ // the method/path.
132
+ Find(rctx *Context, method, path string) string
133
+ }
134
+
135
+ // Middlewares type is a slice of standard middleware handlers with methods
136
+ // to compose middleware chains and http.Handler's.
137
+ type Middlewares []func(http.Handler) http.Handler
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/context.go ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package chi
2
+
3
+ import (
4
+ "context"
5
+ "net/http"
6
+ "strings"
7
+ )
8
+
9
+ // URLParam returns the url parameter from a http.Request object.
10
+ func URLParam(r *http.Request, key string) string {
11
+ if rctx := RouteContext(r.Context()); rctx != nil {
12
+ return rctx.URLParam(key)
13
+ }
14
+ return ""
15
+ }
16
+
17
+ // URLParamFromCtx returns the url parameter from a http.Request Context.
18
+ func URLParamFromCtx(ctx context.Context, key string) string {
19
+ if rctx := RouteContext(ctx); rctx != nil {
20
+ return rctx.URLParam(key)
21
+ }
22
+ return ""
23
+ }
24
+
25
+ // RouteContext returns chi's routing Context object from a
26
+ // http.Request Context.
27
+ func RouteContext(ctx context.Context) *Context {
28
+ val, _ := ctx.Value(RouteCtxKey).(*Context)
29
+ return val
30
+ }
31
+
32
+ // NewRouteContext returns a new routing Context object.
33
+ func NewRouteContext() *Context {
34
+ return &Context{}
35
+ }
36
+
37
+ var (
38
+ // RouteCtxKey is the context.Context key to store the request context.
39
+ RouteCtxKey = &contextKey{"RouteContext"}
40
+ )
41
+
42
+ // Context is the default routing context set on the root node of a
43
+ // request context to track route patterns, URL parameters and
44
+ // an optional routing path.
45
+ type Context struct {
46
+ Routes Routes
47
+
48
+ // parentCtx is the parent of this one, for using Context as a
49
+ // context.Context directly. This is an optimization that saves
50
+ // 1 allocation.
51
+ parentCtx context.Context
52
+
53
+ // Routing path/method override used during the route search.
54
+ // See Mux#routeHTTP method.
55
+ RoutePath string
56
+ RouteMethod string
57
+
58
+ // URLParams are the stack of routeParams captured during the
59
+ // routing lifecycle across a stack of sub-routers.
60
+ URLParams RouteParams
61
+
62
+ // Route parameters matched for the current sub-router. It is
63
+ // intentionally unexported so it can't be tampered.
64
+ routeParams RouteParams
65
+
66
+ // The endpoint routing pattern that matched the request URI path
67
+ // or `RoutePath` of the current sub-router. This value will update
68
+ // during the lifecycle of a request passing through a stack of
69
+ // sub-routers.
70
+ routePattern string
71
+
72
+ // Routing pattern stack throughout the lifecycle of the request,
73
+ // across all connected routers. It is a record of all matching
74
+ // patterns across a stack of sub-routers.
75
+ RoutePatterns []string
76
+
77
+ methodsAllowed []methodTyp // allowed methods in case of a 405
78
+ methodNotAllowed bool
79
+ }
80
+
81
+ // Reset a routing context to its initial state.
82
+ func (x *Context) Reset() {
83
+ x.Routes = nil
84
+ x.RoutePath = ""
85
+ x.RouteMethod = ""
86
+ x.RoutePatterns = x.RoutePatterns[:0]
87
+ x.URLParams.Keys = x.URLParams.Keys[:0]
88
+ x.URLParams.Values = x.URLParams.Values[:0]
89
+
90
+ x.routePattern = ""
91
+ x.routeParams.Keys = x.routeParams.Keys[:0]
92
+ x.routeParams.Values = x.routeParams.Values[:0]
93
+ x.methodNotAllowed = false
94
+ x.methodsAllowed = x.methodsAllowed[:0]
95
+ x.parentCtx = nil
96
+ }
97
+
98
+ // URLParam returns the corresponding URL parameter value from the request
99
+ // routing context.
100
+ func (x *Context) URLParam(key string) string {
101
+ for k := len(x.URLParams.Keys) - 1; k >= 0; k-- {
102
+ if x.URLParams.Keys[k] == key {
103
+ return x.URLParams.Values[k]
104
+ }
105
+ }
106
+ return ""
107
+ }
108
+
109
+ // RoutePattern builds the routing pattern string for the particular
110
+ // request, at the particular point during routing. This means, the value
111
+ // will change throughout the execution of a request in a router. That is
112
+ // why it's advised to only use this value after calling the next handler.
113
+ //
114
+ // For example,
115
+ //
116
+ // func Instrument(next http.Handler) http.Handler {
117
+ // return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
118
+ // next.ServeHTTP(w, r)
119
+ // routePattern := chi.RouteContext(r.Context()).RoutePattern()
120
+ // measure(w, r, routePattern)
121
+ // })
122
+ // }
123
+ func (x *Context) RoutePattern() string {
124
+ if x == nil {
125
+ return ""
126
+ }
127
+ routePattern := strings.Join(x.RoutePatterns, "")
128
+ routePattern = replaceWildcards(routePattern)
129
+ if routePattern != "/" {
130
+ routePattern = strings.TrimSuffix(routePattern, "//")
131
+ routePattern = strings.TrimSuffix(routePattern, "/")
132
+ }
133
+ return routePattern
134
+ }
135
+
136
+ // replaceWildcards takes a route pattern and recursively replaces all
137
+ // occurrences of "/*/" to "/".
138
+ func replaceWildcards(p string) string {
139
+ if strings.Contains(p, "/*/") {
140
+ return replaceWildcards(strings.Replace(p, "/*/", "/", -1))
141
+ }
142
+ return p
143
+ }
144
+
145
+ // RouteParams is a structure to track URL routing parameters efficiently.
146
+ type RouteParams struct {
147
+ Keys, Values []string
148
+ }
149
+
150
+ // Add will append a URL parameter to the end of the route param
151
+ func (s *RouteParams) Add(key, value string) {
152
+ s.Keys = append(s.Keys, key)
153
+ s.Values = append(s.Values, value)
154
+ }
155
+
156
+ // contextKey is a value for use with context.WithValue. It's used as
157
+ // a pointer so it fits in an interface{} without allocation. This technique
158
+ // for defining context keys was copied from Go 1.7's new use of context in net/http.
159
+ type contextKey struct {
160
+ name string
161
+ }
162
+
163
+ func (k *contextKey) String() string {
164
+ return "chi context value " + k.name
165
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/go.mod ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ module github.com/go-chi/chi/v5
2
+
3
+ // Chi supports the four most recent major versions of Go.
4
+ // See https://github.com/go-chi/chi/issues/963.
5
+ go 1.20
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/basic_auth.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "crypto/subtle"
5
+ "fmt"
6
+ "net/http"
7
+ )
8
+
9
+ // BasicAuth implements a simple middleware handler for adding basic http auth to a route.
10
+ func BasicAuth(realm string, creds map[string]string) func(next http.Handler) http.Handler {
11
+ return func(next http.Handler) http.Handler {
12
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
13
+ user, pass, ok := r.BasicAuth()
14
+ if !ok {
15
+ basicAuthFailed(w, realm)
16
+ return
17
+ }
18
+
19
+ credPass, credUserOk := creds[user]
20
+ if !credUserOk || subtle.ConstantTimeCompare([]byte(pass), []byte(credPass)) != 1 {
21
+ basicAuthFailed(w, realm)
22
+ return
23
+ }
24
+
25
+ next.ServeHTTP(w, r)
26
+ })
27
+ }
28
+ }
29
+
30
+ func basicAuthFailed(w http.ResponseWriter, realm string) {
31
+ w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
32
+ w.WriteHeader(http.StatusUnauthorized)
33
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/clean_path.go ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "net/http"
5
+ "path"
6
+
7
+ "github.com/go-chi/chi/v5"
8
+ )
9
+
10
+ // CleanPath middleware will clean out double slash mistakes from a user's request path.
11
+ // For example, if a user requests /users//1 or //users////1 will both be treated as: /users/1
12
+ func CleanPath(next http.Handler) http.Handler {
13
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14
+ rctx := chi.RouteContext(r.Context())
15
+
16
+ routePath := rctx.RoutePath
17
+ if routePath == "" {
18
+ if r.URL.RawPath != "" {
19
+ routePath = r.URL.RawPath
20
+ } else {
21
+ routePath = r.URL.Path
22
+ }
23
+ rctx.RoutePath = path.Clean(routePath)
24
+ }
25
+
26
+ next.ServeHTTP(w, r)
27
+ })
28
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/compress.go ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "bufio"
5
+ "compress/flate"
6
+ "compress/gzip"
7
+ "errors"
8
+ "fmt"
9
+ "io"
10
+ "net"
11
+ "net/http"
12
+ "strings"
13
+ "sync"
14
+ )
15
+
16
+ var defaultCompressibleContentTypes = []string{
17
+ "text/html",
18
+ "text/css",
19
+ "text/plain",
20
+ "text/javascript",
21
+ "application/javascript",
22
+ "application/x-javascript",
23
+ "application/json",
24
+ "application/atom+xml",
25
+ "application/rss+xml",
26
+ "image/svg+xml",
27
+ }
28
+
29
+ // Compress is a middleware that compresses response
30
+ // body of a given content types to a data format based
31
+ // on Accept-Encoding request header. It uses a given
32
+ // compression level.
33
+ //
34
+ // NOTE: make sure to set the Content-Type header on your response
35
+ // otherwise this middleware will not compress the response body. For ex, in
36
+ // your handler you should set w.Header().Set("Content-Type", http.DetectContentType(yourBody))
37
+ // or set it manually.
38
+ //
39
+ // Passing a compression level of 5 is sensible value
40
+ func Compress(level int, types ...string) func(next http.Handler) http.Handler {
41
+ compressor := NewCompressor(level, types...)
42
+ return compressor.Handler
43
+ }
44
+
45
+ // Compressor represents a set of encoding configurations.
46
+ type Compressor struct {
47
+ // The mapping of encoder names to encoder functions.
48
+ encoders map[string]EncoderFunc
49
+ // The mapping of pooled encoders to pools.
50
+ pooledEncoders map[string]*sync.Pool
51
+ // The set of content types allowed to be compressed.
52
+ allowedTypes map[string]struct{}
53
+ allowedWildcards map[string]struct{}
54
+ // The list of encoders in order of decreasing precedence.
55
+ encodingPrecedence []string
56
+ level int // The compression level.
57
+ }
58
+
59
+ // NewCompressor creates a new Compressor that will handle encoding responses.
60
+ //
61
+ // The level should be one of the ones defined in the flate package.
62
+ // The types are the content types that are allowed to be compressed.
63
+ func NewCompressor(level int, types ...string) *Compressor {
64
+ // If types are provided, set those as the allowed types. If none are
65
+ // provided, use the default list.
66
+ allowedTypes := make(map[string]struct{})
67
+ allowedWildcards := make(map[string]struct{})
68
+ if len(types) > 0 {
69
+ for _, t := range types {
70
+ if strings.Contains(strings.TrimSuffix(t, "/*"), "*") {
71
+ panic(fmt.Sprintf("middleware/compress: Unsupported content-type wildcard pattern '%s'. Only '/*' supported", t))
72
+ }
73
+ if strings.HasSuffix(t, "/*") {
74
+ allowedWildcards[strings.TrimSuffix(t, "/*")] = struct{}{}
75
+ } else {
76
+ allowedTypes[t] = struct{}{}
77
+ }
78
+ }
79
+ } else {
80
+ for _, t := range defaultCompressibleContentTypes {
81
+ allowedTypes[t] = struct{}{}
82
+ }
83
+ }
84
+
85
+ c := &Compressor{
86
+ level: level,
87
+ encoders: make(map[string]EncoderFunc),
88
+ pooledEncoders: make(map[string]*sync.Pool),
89
+ allowedTypes: allowedTypes,
90
+ allowedWildcards: allowedWildcards,
91
+ }
92
+
93
+ // Set the default encoders. The precedence order uses the reverse
94
+ // ordering that the encoders were added. This means adding new encoders
95
+ // will move them to the front of the order.
96
+ //
97
+ // TODO:
98
+ // lzma: Opera.
99
+ // sdch: Chrome, Android. Gzip output + dictionary header.
100
+ // br: Brotli, see https://github.com/go-chi/chi/pull/326
101
+
102
+ // HTTP 1.1 "deflate" (RFC 2616) stands for DEFLATE data (RFC 1951)
103
+ // wrapped with zlib (RFC 1950). The zlib wrapper uses Adler-32
104
+ // checksum compared to CRC-32 used in "gzip" and thus is faster.
105
+ //
106
+ // But.. some old browsers (MSIE, Safari 5.1) incorrectly expect
107
+ // raw DEFLATE data only, without the mentioned zlib wrapper.
108
+ // Because of this major confusion, most modern browsers try it
109
+ // both ways, first looking for zlib headers.
110
+ // Quote by Mark Adler: http://stackoverflow.com/a/9186091/385548
111
+ //
112
+ // The list of browsers having problems is quite big, see:
113
+ // http://zoompf.com/blog/2012/02/lose-the-wait-http-compression
114
+ // https://web.archive.org/web/20120321182910/http://www.vervestudios.co/projects/compression-tests/results
115
+ //
116
+ // That's why we prefer gzip over deflate. It's just more reliable
117
+ // and not significantly slower than deflate.
118
+ c.SetEncoder("deflate", encoderDeflate)
119
+
120
+ // TODO: Exception for old MSIE browsers that can't handle non-HTML?
121
+ // https://zoompf.com/blog/2012/02/lose-the-wait-http-compression
122
+ c.SetEncoder("gzip", encoderGzip)
123
+
124
+ // NOTE: Not implemented, intentionally:
125
+ // case "compress": // LZW. Deprecated.
126
+ // case "bzip2": // Too slow on-the-fly.
127
+ // case "zopfli": // Too slow on-the-fly.
128
+ // case "xz": // Too slow on-the-fly.
129
+ return c
130
+ }
131
+
132
+ // SetEncoder can be used to set the implementation of a compression algorithm.
133
+ //
134
+ // The encoding should be a standardised identifier. See:
135
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
136
+ //
137
+ // For example, add the Brotli algorithm:
138
+ //
139
+ // import brotli_enc "gopkg.in/kothar/brotli-go.v0/enc"
140
+ //
141
+ // compressor := middleware.NewCompressor(5, "text/html")
142
+ // compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
143
+ // params := brotli_enc.NewBrotliParams()
144
+ // params.SetQuality(level)
145
+ // return brotli_enc.NewBrotliWriter(params, w)
146
+ // })
147
+ func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc) {
148
+ encoding = strings.ToLower(encoding)
149
+ if encoding == "" {
150
+ panic("the encoding can not be empty")
151
+ }
152
+ if fn == nil {
153
+ panic("attempted to set a nil encoder function")
154
+ }
155
+
156
+ // If we are adding a new encoder that is already registered, we have to
157
+ // clear that one out first.
158
+ delete(c.pooledEncoders, encoding)
159
+ delete(c.encoders, encoding)
160
+
161
+ // If the encoder supports Resetting (IoReseterWriter), then it can be pooled.
162
+ encoder := fn(io.Discard, c.level)
163
+ if _, ok := encoder.(ioResetterWriter); ok {
164
+ pool := &sync.Pool{
165
+ New: func() interface{} {
166
+ return fn(io.Discard, c.level)
167
+ },
168
+ }
169
+ c.pooledEncoders[encoding] = pool
170
+ }
171
+ // If the encoder is not in the pooledEncoders, add it to the normal encoders.
172
+ if _, ok := c.pooledEncoders[encoding]; !ok {
173
+ c.encoders[encoding] = fn
174
+ }
175
+
176
+ for i, v := range c.encodingPrecedence {
177
+ if v == encoding {
178
+ c.encodingPrecedence = append(c.encodingPrecedence[:i], c.encodingPrecedence[i+1:]...)
179
+ }
180
+ }
181
+
182
+ c.encodingPrecedence = append([]string{encoding}, c.encodingPrecedence...)
183
+ }
184
+
185
+ // Handler returns a new middleware that will compress the response based on the
186
+ // current Compressor.
187
+ func (c *Compressor) Handler(next http.Handler) http.Handler {
188
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
189
+ encoder, encoding, cleanup := c.selectEncoder(r.Header, w)
190
+
191
+ cw := &compressResponseWriter{
192
+ ResponseWriter: w,
193
+ w: w,
194
+ contentTypes: c.allowedTypes,
195
+ contentWildcards: c.allowedWildcards,
196
+ encoding: encoding,
197
+ compressible: false, // determined in post-handler
198
+ }
199
+ if encoder != nil {
200
+ cw.w = encoder
201
+ }
202
+ // Re-add the encoder to the pool if applicable.
203
+ defer cleanup()
204
+ defer cw.Close()
205
+
206
+ next.ServeHTTP(cw, r)
207
+ })
208
+ }
209
+
210
+ // selectEncoder returns the encoder, the name of the encoder, and a closer function.
211
+ func (c *Compressor) selectEncoder(h http.Header, w io.Writer) (io.Writer, string, func()) {
212
+ header := h.Get("Accept-Encoding")
213
+
214
+ // Parse the names of all accepted algorithms from the header.
215
+ accepted := strings.Split(strings.ToLower(header), ",")
216
+
217
+ // Find supported encoder by accepted list by precedence
218
+ for _, name := range c.encodingPrecedence {
219
+ if matchAcceptEncoding(accepted, name) {
220
+ if pool, ok := c.pooledEncoders[name]; ok {
221
+ encoder := pool.Get().(ioResetterWriter)
222
+ cleanup := func() {
223
+ pool.Put(encoder)
224
+ }
225
+ encoder.Reset(w)
226
+ return encoder, name, cleanup
227
+
228
+ }
229
+ if fn, ok := c.encoders[name]; ok {
230
+ return fn(w, c.level), name, func() {}
231
+ }
232
+ }
233
+
234
+ }
235
+
236
+ // No encoder found to match the accepted encoding
237
+ return nil, "", func() {}
238
+ }
239
+
240
+ func matchAcceptEncoding(accepted []string, encoding string) bool {
241
+ for _, v := range accepted {
242
+ if strings.Contains(v, encoding) {
243
+ return true
244
+ }
245
+ }
246
+ return false
247
+ }
248
+
249
+ // An EncoderFunc is a function that wraps the provided io.Writer with a
250
+ // streaming compression algorithm and returns it.
251
+ //
252
+ // In case of failure, the function should return nil.
253
+ type EncoderFunc func(w io.Writer, level int) io.Writer
254
+
255
+ // Interface for types that allow resetting io.Writers.
256
+ type ioResetterWriter interface {
257
+ io.Writer
258
+ Reset(w io.Writer)
259
+ }
260
+
261
+ type compressResponseWriter struct {
262
+ http.ResponseWriter
263
+
264
+ // The streaming encoder writer to be used if there is one. Otherwise,
265
+ // this is just the normal writer.
266
+ w io.Writer
267
+ contentTypes map[string]struct{}
268
+ contentWildcards map[string]struct{}
269
+ encoding string
270
+ wroteHeader bool
271
+ compressible bool
272
+ }
273
+
274
+ func (cw *compressResponseWriter) isCompressible() bool {
275
+ // Parse the first part of the Content-Type response header.
276
+ contentType := cw.Header().Get("Content-Type")
277
+ contentType, _, _ = strings.Cut(contentType, ";")
278
+
279
+ // Is the content type compressible?
280
+ if _, ok := cw.contentTypes[contentType]; ok {
281
+ return true
282
+ }
283
+ if contentType, _, hadSlash := strings.Cut(contentType, "/"); hadSlash {
284
+ _, ok := cw.contentWildcards[contentType]
285
+ return ok
286
+ }
287
+ return false
288
+ }
289
+
290
+ func (cw *compressResponseWriter) WriteHeader(code int) {
291
+ if cw.wroteHeader {
292
+ cw.ResponseWriter.WriteHeader(code) // Allow multiple calls to propagate.
293
+ return
294
+ }
295
+ cw.wroteHeader = true
296
+ defer cw.ResponseWriter.WriteHeader(code)
297
+
298
+ // Already compressed data?
299
+ if cw.Header().Get("Content-Encoding") != "" {
300
+ return
301
+ }
302
+
303
+ if !cw.isCompressible() {
304
+ cw.compressible = false
305
+ return
306
+ }
307
+
308
+ if cw.encoding != "" {
309
+ cw.compressible = true
310
+ cw.Header().Set("Content-Encoding", cw.encoding)
311
+ cw.Header().Add("Vary", "Accept-Encoding")
312
+
313
+ // The content-length after compression is unknown
314
+ cw.Header().Del("Content-Length")
315
+ }
316
+ }
317
+
318
+ func (cw *compressResponseWriter) Write(p []byte) (int, error) {
319
+ if !cw.wroteHeader {
320
+ cw.WriteHeader(http.StatusOK)
321
+ }
322
+
323
+ return cw.writer().Write(p)
324
+ }
325
+
326
+ func (cw *compressResponseWriter) writer() io.Writer {
327
+ if cw.compressible {
328
+ return cw.w
329
+ }
330
+ return cw.ResponseWriter
331
+ }
332
+
333
+ type compressFlusher interface {
334
+ Flush() error
335
+ }
336
+
337
+ func (cw *compressResponseWriter) Flush() {
338
+ if f, ok := cw.writer().(http.Flusher); ok {
339
+ f.Flush()
340
+ }
341
+ // If the underlying writer has a compression flush signature,
342
+ // call this Flush() method instead
343
+ if f, ok := cw.writer().(compressFlusher); ok {
344
+ f.Flush()
345
+
346
+ // Also flush the underlying response writer
347
+ if f, ok := cw.ResponseWriter.(http.Flusher); ok {
348
+ f.Flush()
349
+ }
350
+ }
351
+ }
352
+
353
+ func (cw *compressResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
354
+ if hj, ok := cw.writer().(http.Hijacker); ok {
355
+ return hj.Hijack()
356
+ }
357
+ return nil, nil, errors.New("chi/middleware: http.Hijacker is unavailable on the writer")
358
+ }
359
+
360
+ func (cw *compressResponseWriter) Push(target string, opts *http.PushOptions) error {
361
+ if ps, ok := cw.writer().(http.Pusher); ok {
362
+ return ps.Push(target, opts)
363
+ }
364
+ return errors.New("chi/middleware: http.Pusher is unavailable on the writer")
365
+ }
366
+
367
+ func (cw *compressResponseWriter) Close() error {
368
+ if c, ok := cw.writer().(io.WriteCloser); ok {
369
+ return c.Close()
370
+ }
371
+ return errors.New("chi/middleware: io.WriteCloser is unavailable on the writer")
372
+ }
373
+
374
+ func (cw *compressResponseWriter) Unwrap() http.ResponseWriter {
375
+ return cw.ResponseWriter
376
+ }
377
+
378
+ func encoderGzip(w io.Writer, level int) io.Writer {
379
+ gw, err := gzip.NewWriterLevel(w, level)
380
+ if err != nil {
381
+ return nil
382
+ }
383
+ return gw
384
+ }
385
+
386
+ func encoderDeflate(w io.Writer, level int) io.Writer {
387
+ dw, err := flate.NewWriter(w, level)
388
+ if err != nil {
389
+ return nil
390
+ }
391
+ return dw
392
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/content_charset.go ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "net/http"
5
+ "strings"
6
+ )
7
+
8
+ // ContentCharset generates a handler that writes a 415 Unsupported Media Type response if none of the charsets match.
9
+ // An empty charset will allow requests with no Content-Type header or no specified charset.
10
+ func ContentCharset(charsets ...string) func(next http.Handler) http.Handler {
11
+ for i, c := range charsets {
12
+ charsets[i] = strings.ToLower(c)
13
+ }
14
+
15
+ return func(next http.Handler) http.Handler {
16
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17
+ if !contentEncoding(r.Header.Get("Content-Type"), charsets...) {
18
+ w.WriteHeader(http.StatusUnsupportedMediaType)
19
+ return
20
+ }
21
+
22
+ next.ServeHTTP(w, r)
23
+ })
24
+ }
25
+ }
26
+
27
+ // Check the content encoding against a list of acceptable values.
28
+ func contentEncoding(ce string, charsets ...string) bool {
29
+ _, ce = split(strings.ToLower(ce), ";")
30
+ _, ce = split(ce, "charset=")
31
+ ce, _ = split(ce, ";")
32
+ for _, c := range charsets {
33
+ if ce == c {
34
+ return true
35
+ }
36
+ }
37
+
38
+ return false
39
+ }
40
+
41
+ // Split a string in two parts, cleaning any whitespace.
42
+ func split(str, sep string) (string, string) {
43
+ a, b, found := strings.Cut(str, sep)
44
+ a = strings.TrimSpace(a)
45
+ if found {
46
+ b = strings.TrimSpace(b)
47
+ }
48
+
49
+ return a, b
50
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/content_encoding.go ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "net/http"
5
+ "strings"
6
+ )
7
+
8
+ // AllowContentEncoding enforces a whitelist of request Content-Encoding otherwise responds
9
+ // with a 415 Unsupported Media Type status.
10
+ func AllowContentEncoding(contentEncoding ...string) func(next http.Handler) http.Handler {
11
+ allowedEncodings := make(map[string]struct{}, len(contentEncoding))
12
+ for _, encoding := range contentEncoding {
13
+ allowedEncodings[strings.TrimSpace(strings.ToLower(encoding))] = struct{}{}
14
+ }
15
+ return func(next http.Handler) http.Handler {
16
+ fn := func(w http.ResponseWriter, r *http.Request) {
17
+ requestEncodings := r.Header["Content-Encoding"]
18
+ // skip check for empty content body or no Content-Encoding
19
+ if r.ContentLength == 0 {
20
+ next.ServeHTTP(w, r)
21
+ return
22
+ }
23
+ // All encodings in the request must be allowed
24
+ for _, encoding := range requestEncodings {
25
+ if _, ok := allowedEncodings[strings.TrimSpace(strings.ToLower(encoding))]; !ok {
26
+ w.WriteHeader(http.StatusUnsupportedMediaType)
27
+ return
28
+ }
29
+ }
30
+ next.ServeHTTP(w, r)
31
+ }
32
+ return http.HandlerFunc(fn)
33
+ }
34
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/content_type.go ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "net/http"
5
+ "strings"
6
+ )
7
+
8
+ // SetHeader is a convenience handler to set a response header key/value
9
+ func SetHeader(key, value string) func(http.Handler) http.Handler {
10
+ return func(next http.Handler) http.Handler {
11
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12
+ w.Header().Set(key, value)
13
+ next.ServeHTTP(w, r)
14
+ })
15
+ }
16
+ }
17
+
18
+ // AllowContentType enforces a whitelist of request Content-Types otherwise responds
19
+ // with a 415 Unsupported Media Type status.
20
+ func AllowContentType(contentTypes ...string) func(http.Handler) http.Handler {
21
+ allowedContentTypes := make(map[string]struct{}, len(contentTypes))
22
+ for _, ctype := range contentTypes {
23
+ allowedContentTypes[strings.TrimSpace(strings.ToLower(ctype))] = struct{}{}
24
+ }
25
+
26
+ return func(next http.Handler) http.Handler {
27
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
28
+ if r.ContentLength == 0 {
29
+ // Skip check for empty content body
30
+ next.ServeHTTP(w, r)
31
+ return
32
+ }
33
+
34
+ s, _, _ := strings.Cut(r.Header.Get("Content-Type"), ";")
35
+ s = strings.ToLower(strings.TrimSpace(s))
36
+
37
+ if _, ok := allowedContentTypes[s]; ok {
38
+ next.ServeHTTP(w, r)
39
+ return
40
+ }
41
+
42
+ w.WriteHeader(http.StatusUnsupportedMediaType)
43
+ })
44
+ }
45
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/get_head.go ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "net/http"
5
+
6
+ "github.com/go-chi/chi/v5"
7
+ )
8
+
9
+ // GetHead automatically route undefined HEAD requests to GET handlers.
10
+ func GetHead(next http.Handler) http.Handler {
11
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12
+ if r.Method == "HEAD" {
13
+ rctx := chi.RouteContext(r.Context())
14
+ routePath := rctx.RoutePath
15
+ if routePath == "" {
16
+ if r.URL.RawPath != "" {
17
+ routePath = r.URL.RawPath
18
+ } else {
19
+ routePath = r.URL.Path
20
+ }
21
+ }
22
+
23
+ // Temporary routing context to look-ahead before routing the request
24
+ tctx := chi.NewRouteContext()
25
+
26
+ // Attempt to find a HEAD handler for the routing path, if not found, traverse
27
+ // the router as through its a GET route, but proceed with the request
28
+ // with the HEAD method.
29
+ if !rctx.Routes.Match(tctx, "HEAD", routePath) {
30
+ rctx.RouteMethod = "GET"
31
+ rctx.RoutePath = routePath
32
+ next.ServeHTTP(w, r)
33
+ return
34
+ }
35
+ }
36
+
37
+ next.ServeHTTP(w, r)
38
+ })
39
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/heartbeat.go ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "net/http"
5
+ "strings"
6
+ )
7
+
8
+ // Heartbeat endpoint middleware useful to setting up a path like
9
+ // `/ping` that load balancers or uptime testing external services
10
+ // can make a request before hitting any routes. It's also convenient
11
+ // to place this above ACL middlewares as well.
12
+ func Heartbeat(endpoint string) func(http.Handler) http.Handler {
13
+ f := func(h http.Handler) http.Handler {
14
+ fn := func(w http.ResponseWriter, r *http.Request) {
15
+ if (r.Method == "GET" || r.Method == "HEAD") && strings.EqualFold(r.URL.Path, endpoint) {
16
+ w.Header().Set("Content-Type", "text/plain")
17
+ w.WriteHeader(http.StatusOK)
18
+ w.Write([]byte("."))
19
+ return
20
+ }
21
+ h.ServeHTTP(w, r)
22
+ }
23
+ return http.HandlerFunc(fn)
24
+ }
25
+ return f
26
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/logger.go ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import (
4
+ "bytes"
5
+ "context"
6
+ "log"
7
+ "net/http"
8
+ "os"
9
+ "runtime"
10
+ "time"
11
+ )
12
+
13
+ var (
14
+ // LogEntryCtxKey is the context.Context key to store the request log entry.
15
+ LogEntryCtxKey = &contextKey{"LogEntry"}
16
+
17
+ // DefaultLogger is called by the Logger middleware handler to log each request.
18
+ // Its made a package-level variable so that it can be reconfigured for custom
19
+ // logging configurations.
20
+ DefaultLogger func(next http.Handler) http.Handler
21
+ )
22
+
23
+ // Logger is a middleware that logs the start and end of each request, along
24
+ // with some useful data about what was requested, what the response status was,
25
+ // and how long it took to return. When standard output is a TTY, Logger will
26
+ // print in color, otherwise it will print in black and white. Logger prints a
27
+ // request ID if one is provided.
28
+ //
29
+ // Alternatively, look at https://github.com/goware/httplog for a more in-depth
30
+ // http logger with structured logging support.
31
+ //
32
+ // IMPORTANT NOTE: Logger should go before any other middleware that may change
33
+ // the response, such as middleware.Recoverer. Example:
34
+ //
35
+ // r := chi.NewRouter()
36
+ // r.Use(middleware.Logger) // <--<< Logger should come before Recoverer
37
+ // r.Use(middleware.Recoverer)
38
+ // r.Get("/", handler)
39
+ func Logger(next http.Handler) http.Handler {
40
+ return DefaultLogger(next)
41
+ }
42
+
43
+ // RequestLogger returns a logger handler using a custom LogFormatter.
44
+ func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler {
45
+ return func(next http.Handler) http.Handler {
46
+ fn := func(w http.ResponseWriter, r *http.Request) {
47
+ entry := f.NewLogEntry(r)
48
+ ww := NewWrapResponseWriter(w, r.ProtoMajor)
49
+
50
+ t1 := time.Now()
51
+ defer func() {
52
+ entry.Write(ww.Status(), ww.BytesWritten(), ww.Header(), time.Since(t1), nil)
53
+ }()
54
+
55
+ next.ServeHTTP(ww, WithLogEntry(r, entry))
56
+ }
57
+ return http.HandlerFunc(fn)
58
+ }
59
+ }
60
+
61
+ // LogFormatter initiates the beginning of a new LogEntry per request.
62
+ // See DefaultLogFormatter for an example implementation.
63
+ type LogFormatter interface {
64
+ NewLogEntry(r *http.Request) LogEntry
65
+ }
66
+
67
+ // LogEntry records the final log when a request completes.
68
+ // See defaultLogEntry for an example implementation.
69
+ type LogEntry interface {
70
+ Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{})
71
+ Panic(v interface{}, stack []byte)
72
+ }
73
+
74
+ // GetLogEntry returns the in-context LogEntry for a request.
75
+ func GetLogEntry(r *http.Request) LogEntry {
76
+ entry, _ := r.Context().Value(LogEntryCtxKey).(LogEntry)
77
+ return entry
78
+ }
79
+
80
+ // WithLogEntry sets the in-context LogEntry for a request.
81
+ func WithLogEntry(r *http.Request, entry LogEntry) *http.Request {
82
+ r = r.WithContext(context.WithValue(r.Context(), LogEntryCtxKey, entry))
83
+ return r
84
+ }
85
+
86
+ // LoggerInterface accepts printing to stdlib logger or compatible logger.
87
+ type LoggerInterface interface {
88
+ Print(v ...interface{})
89
+ }
90
+
91
+ // DefaultLogFormatter is a simple logger that implements a LogFormatter.
92
+ type DefaultLogFormatter struct {
93
+ Logger LoggerInterface
94
+ NoColor bool
95
+ }
96
+
97
+ // NewLogEntry creates a new LogEntry for the request.
98
+ func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry {
99
+ useColor := !l.NoColor
100
+ entry := &defaultLogEntry{
101
+ DefaultLogFormatter: l,
102
+ request: r,
103
+ buf: &bytes.Buffer{},
104
+ useColor: useColor,
105
+ }
106
+
107
+ reqID := GetReqID(r.Context())
108
+ if reqID != "" {
109
+ cW(entry.buf, useColor, nYellow, "[%s] ", reqID)
110
+ }
111
+ cW(entry.buf, useColor, nCyan, "\"")
112
+ cW(entry.buf, useColor, bMagenta, "%s ", r.Method)
113
+
114
+ scheme := "http"
115
+ if r.TLS != nil {
116
+ scheme = "https"
117
+ }
118
+ cW(entry.buf, useColor, nCyan, "%s://%s%s %s\" ", scheme, r.Host, r.RequestURI, r.Proto)
119
+
120
+ entry.buf.WriteString("from ")
121
+ entry.buf.WriteString(r.RemoteAddr)
122
+ entry.buf.WriteString(" - ")
123
+
124
+ return entry
125
+ }
126
+
127
+ type defaultLogEntry struct {
128
+ *DefaultLogFormatter
129
+ request *http.Request
130
+ buf *bytes.Buffer
131
+ useColor bool
132
+ }
133
+
134
+ func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
135
+ switch {
136
+ case status < 200:
137
+ cW(l.buf, l.useColor, bBlue, "%03d", status)
138
+ case status < 300:
139
+ cW(l.buf, l.useColor, bGreen, "%03d", status)
140
+ case status < 400:
141
+ cW(l.buf, l.useColor, bCyan, "%03d", status)
142
+ case status < 500:
143
+ cW(l.buf, l.useColor, bYellow, "%03d", status)
144
+ default:
145
+ cW(l.buf, l.useColor, bRed, "%03d", status)
146
+ }
147
+
148
+ cW(l.buf, l.useColor, bBlue, " %dB", bytes)
149
+
150
+ l.buf.WriteString(" in ")
151
+ if elapsed < 500*time.Millisecond {
152
+ cW(l.buf, l.useColor, nGreen, "%s", elapsed)
153
+ } else if elapsed < 5*time.Second {
154
+ cW(l.buf, l.useColor, nYellow, "%s", elapsed)
155
+ } else {
156
+ cW(l.buf, l.useColor, nRed, "%s", elapsed)
157
+ }
158
+
159
+ l.Logger.Print(l.buf.String())
160
+ }
161
+
162
+ func (l *defaultLogEntry) Panic(v interface{}, stack []byte) {
163
+ PrintPrettyStack(v)
164
+ }
165
+
166
+ func init() {
167
+ color := true
168
+ if runtime.GOOS == "windows" {
169
+ color = false
170
+ }
171
+ DefaultLogger = RequestLogger(&DefaultLogFormatter{Logger: log.New(os.Stdout, "", log.LstdFlags), NoColor: !color})
172
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/maybe.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import "net/http"
4
+
5
+ // Maybe middleware will allow you to change the flow of the middleware stack execution depending on return
6
+ // value of maybeFn(request). This is useful for example if you'd like to skip a middleware handler if
7
+ // a request does not satisfy the maybeFn logic.
8
+ func Maybe(mw func(http.Handler) http.Handler, maybeFn func(r *http.Request) bool) func(http.Handler) http.Handler {
9
+ return func(next http.Handler) http.Handler {
10
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
11
+ if maybeFn(r) {
12
+ mw(next).ServeHTTP(w, r)
13
+ } else {
14
+ next.ServeHTTP(w, r)
15
+ }
16
+ })
17
+ }
18
+ }
tasks/go-chi__chi.23c395f8.func_pm_flip_operators__idlllt54/environment/source/middleware/middleware.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package middleware
2
+
3
+ import "net/http"
4
+
5
+ // New will create a new middleware handler from a http.Handler.
6
+ func New(h http.Handler) func(next http.Handler) http.Handler {
7
+ return func(next http.Handler) http.Handler {
8
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
9
+ h.ServeHTTP(w, r)
10
+ })
11
+ }
12
+ }
13
+
14
+ // contextKey is a value for use with context.WithValue. It's used as
15
+ // a pointer so it fits in an interface{} without allocation. This technique
16
+ // for defining context keys was copied from Go 1.7's new use of context in net/http.
17
+ type contextKey struct {
18
+ name string
19
+ }
20
+
21
+ func (k *contextKey) String() string {
22
+ return "chi/middleware context value " + k.name
23
+ }