ParseOptionalBody parses --data JSON for methods that accept a request body. Supports stdin (-), @file, @@-escape, and single-quote stripping via ResolveInput. Returns (nil, nil) if the method has no body or data is empty.
(httpMethod, data string, stdin io.Reader, fileIO fileio.FileIO)
| 15 | // Supports stdin (-), @file, @@-escape, and single-quote stripping via ResolveInput. |
| 16 | // Returns (nil, nil) if the method has no body or data is empty. |
| 17 | func ParseOptionalBody(httpMethod, data string, stdin io.Reader, fileIO fileio.FileIO) (interface{}, error) { |
| 18 | switch httpMethod { |
| 19 | case "POST", "PUT", "PATCH", "DELETE": |
| 20 | default: |
| 21 | return nil, nil |
| 22 | } |
| 23 | resolved, err := ResolveInput(data, stdin, fileIO) |
| 24 | if err != nil { |
| 25 | return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--data: %s", err). |
| 26 | WithParam("--data"). |
| 27 | WithCause(err) |
| 28 | } |
| 29 | if resolved == "" { |
| 30 | return nil, nil |
| 31 | } |
| 32 | var body interface{} |
| 33 | if err := json.Unmarshal([]byte(resolved), &body); err != nil { |
| 34 | return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--data invalid JSON format"). |
| 35 | WithParam("--data"). |
| 36 | WithCause(err) |
| 37 | } |
| 38 | return body, nil |
| 39 | } |
| 40 | |
| 41 | // ParseJSONMap parses a JSON string into a map. Returns an empty (never nil) map |
| 42 | // for empty input or the JSON literal null, so callers can always overlay onto |