-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_form.go
59 lines (50 loc) · 1.09 KB
/
http_form.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package golib
import (
"encoding/json"
"fmt"
"mime"
"net/http"
)
// ParseForm works like http.Request.ParseForm but additionally
// adds values received in json format to request.Form
func ParseForm(req *http.Request) error {
err := req.ParseForm()
if err != nil {
return err
}
ct := req.Header.Get("content-type")
if ct == "" { // Assume "GET"
return nil
}
mediatype, _, err := mime.ParseMediaType(ct)
if err != nil {
return err
}
switch mediatype {
case "application/x-www-form-urlencoded":
return nil
case "multipart/form-data":
err = req.ParseMultipartForm(4096)
if err != nil {
return fmt.Errorf("Unable to parse form: %w", err)
}
case "application/json":
jsonForm := map[string]interface{}{}
err = json.NewDecoder(req.Body).Decode(&jsonForm)
if err != nil {
return fmt.Errorf("ParseForm failed: %w", err)
}
for k, v := range jsonForm {
switch v1 := v.(type) {
case string:
req.Form.Set(k, v1)
case *string:
req.Form.Set(k, *v1)
default:
bytes, _ := json.Marshal(v)
req.Form.Set(k, string(bytes))
}
}
}
return nil
}