11package api
22
33import (
4+ "encoding/json"
45 "fmt"
56 "io"
67 "io/ioutil"
8+ "mime"
79 "net/http"
810 "net/url"
9- "strings "
11+ "strconv "
1012)
1113
1214type httpClient interface {
@@ -71,7 +73,9 @@ func PostForm(c httpClient, u string, params url.Values) (*FormResponse, error)
7173 requestURI : u ,
7274 }
7375
74- if contentType (resp .Header .Get ("Content-Type" )) == formType {
76+ mediaType , _ , _ := mime .ParseMediaType (resp .Header .Get ("Content-Type" ))
77+ switch mediaType {
78+ case "application/x-www-form-urlencoded" :
7579 var bb []byte
7680 bb , err = ioutil .ReadAll (resp .Body )
7781 if err != nil {
@@ -82,7 +86,24 @@ func PostForm(c httpClient, u string, params url.Values) (*FormResponse, error)
8286 if err != nil {
8387 return r , err
8488 }
85- } else {
89+ case "application/json" :
90+ var values map [string ]interface {}
91+ if err := json .NewDecoder (resp .Body ).Decode (& values ); err != nil {
92+ return r , err
93+ }
94+
95+ r .values = make (url.Values )
96+ for key , value := range values {
97+ switch v := value .(type ) {
98+ case string :
99+ r .values .Set (key , v )
100+ case int64 :
101+ r .values .Set (key , strconv .FormatInt (v , 10 ))
102+ case float64 :
103+ r .values .Set (key , strconv .FormatFloat (v , 'f' , - 1 , 64 ))
104+ }
105+ }
106+ default :
86107 _ , err = io .Copy (ioutil .Discard , resp .Body )
87108 if err != nil {
88109 return r , err
@@ -91,12 +112,3 @@ func PostForm(c httpClient, u string, params url.Values) (*FormResponse, error)
91112
92113 return r , nil
93114}
94-
95- const formType = "application/x-www-form-urlencoded"
96-
97- func contentType (t string ) string {
98- if i := strings .IndexRune (t , ';' ); i >= 0 {
99- return t [0 :i ]
100- }
101- return t
102- }
0 commit comments