我正在尝试通过将 auth 结构转换为application/x-www-form-urlencoded数据来发送 POST 请求。
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
type Payload struct {
Username string `json:"username"`
Password string `json:"password"`
GrantType string `json:"grant_type"`
Scope string `json:"scope"`
}
func main() {
var endpoint string = "https://api.io/v1/oauth/token"
jsonPay := &Payload{
Username: "email",
Password: "pass",
GrantType: "password",
Scope: "SPACE SEPARATED STRINGS",
}
//byteArr, err := json.Marshal(jsonPay)
//if err != nil {
// log.Printf("Unable to map structure\n%v", err)
//}
payloadBuf := new(bytes.Buffer)
json.NewEncoder(payloadBuf).Encode(jsonPay)
req, err := http.NewRequest("POST", endpoint, payloadBuf)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Printf(string(body))
}
我试过了:
发送一个 JSON 编码的负载缓冲区,它返回
{"error":"invalid_request","error_description":"Missing grant type"}
与编组的 JSON 对象一起使用bytes.NewReader
,它也返回
{"error":"invalid_request","error_description":"Missing grant type"}
strings.NewReader
与 JSON 编码的负载缓冲区一起使用,它返回
cannot use payloadBuf (variable of type *bytes.Buffer) as type string in argument to strings.NewReader
函数式编程
相关分类