| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package requestbody |
| 16 | |
| 17 | import ( |
| 18 | "time" |
| 19 | |
| 20 | "github.com/dustin/go-humanize" |
| 21 | |
| 22 | "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" |
| 23 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 24 | ) |
| 25 | |
| 26 | func init() { |
| 27 | httpcaddyfile.RegisterHandlerDirective("request_body", parseCaddyfile) |
| 28 | } |
| 29 | |
| 30 | func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { |
| 31 | h.Next() // consume directive name |
| 32 | |
| 33 | rb := new(RequestBody) |
| 34 | |
| 35 | // configuration should be in a block |
| 36 | for h.NextBlock(0) { |
| 37 | switch h.Val() { |
| 38 | case "max_size": |
| 39 | var sizeStr string |
| 40 | if !h.AllArgs(&sizeStr) { |
| 41 | return nil, h.ArgErr() |
| 42 | } |
| 43 | size, err := humanize.ParseBytes(sizeStr) |
| 44 | if err != nil { |
| 45 | return nil, h.Errf("parsing max_size: %v", err) |
| 46 | } |
| 47 | rb.MaxSize = int64(size) |
| 48 | |
| 49 | case "read_timeout": |
| 50 | var timeoutStr string |
| 51 | if !h.AllArgs(&timeoutStr) { |
| 52 | return nil, h.ArgErr() |
| 53 | } |
| 54 | timeout, err := time.ParseDuration(timeoutStr) |
| 55 | if err != nil { |
| 56 | return nil, h.Errf("parsing read_timeout: %v", err) |
| 57 | } |
| 58 | rb.ReadTimeout = timeout |
| 59 | |
| 60 | case "write_timeout": |
| 61 | var timeoutStr string |
| 62 | if !h.AllArgs(&timeoutStr) { |
| 63 | return nil, h.ArgErr() |
| 64 | } |
| 65 | timeout, err := time.ParseDuration(timeoutStr) |
| 66 | if err != nil { |
| 67 | return nil, h.Errf("parsing write_timeout: %v", err) |
| 68 | } |
| 69 | rb.WriteTimeout = timeout |
| 70 | |
| 71 | case "set": |
| 72 | var setStr string |
| 73 | if !h.AllArgs(&setStr) { |
| 74 | return nil, h.ArgErr() |
| 75 | } |
| 76 | rb.Set = setStr |
| 77 | default: |
| 78 | return nil, h.Errf("unrecognized request_body subdirective '%s'", h.Val()) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | return rb, nil |
| 83 | } |