From ce99a306c09434f41277fc59e1269bbad4ae68df Mon Sep 17 00:00:00 2001 From: Lathanao Date: Fri, 6 May 2022 17:23:36 +0000 Subject: [PATCH] net.http: make parse_form return POST requests with json data as a map with a `json` key, containing the json payload (#14289) --- vlib/net/http/request.v | 22 ++++++++++++++-------- vlib/net/http/request_test.v | 24 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/vlib/net/http/request.v b/vlib/net/http/request.v index 064ab662df..9572b01203 100644 --- a/vlib/net/http/request.v +++ b/vlib/net/http/request.v @@ -244,16 +244,22 @@ fn parse_request_line(s string) ?(Method, urllib.URL, Version) { // // a possible solution is to use the a list of QueryValue pub fn parse_form(body string) map[string]string { - words := body.split('&') mut form := map[string]string{} - for word in words { - kv := word.split_nth('=', 2) - if kv.len != 2 { - continue + + if body.match_glob('{*}') { + form['json'] = body + } else { + words := body.split('&') + + for word in words { + kv := word.split_nth('=', 2) + if kv.len != 2 { + continue + } + key := urllib.query_unescape(kv[0]) or { continue } + val := urllib.query_unescape(kv[1]) or { continue } + form[key] = val } - key := urllib.query_unescape(kv[0]) or { continue } - val := urllib.query_unescape(kv[1]) or { continue } - form[key] = val } return form // } diff --git a/vlib/net/http/request_test.v b/vlib/net/http/request_test.v index a2838b03e5..4c6f6d9e42 100644 --- a/vlib/net/http/request_test.v +++ b/vlib/net/http/request_test.v @@ -95,6 +95,30 @@ fn test_parse_form() { 'a': 'b' 'c': ' d ' } + assert parse_form('{json}') == { + 'json': '{json}' + } + assert parse_form('{ + "_id": "76c", + "friends": [ + { + "id": 0, + "name": "Mason Luna" + } + ], + "greeting": "Hello." + }') == { + 'json': '{ + "_id": "76c", + "friends": [ + { + "id": 0, + "name": "Mason Luna" + } + ], + "greeting": "Hello." + }' + } } fn test_parse_multipart_form() {