Golang Struct作为POST请求的有效负载

时间:2017-07-31 22:18:20

标签: http go

Golang新手。我试图向auth端点发出POST请求以获取用于进一步请求进行authing的令牌。目前我得到的错误是missing "credentials"。我在Python中编写了相同的逻辑,所以我知道我要做的是系统期待的内容。

package main

import (
    "bufio"
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/http/cookiejar"
    "os"
)

type Auth struct {
    Method   string `json:"credentials"`
    Email    string `json:"email"`
    Password string `json:"password"`
    Mfa      string `json:"mfa_token"`
}

func main() {
    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter Email: ")
    e, _ := reader.ReadString('\n')
    fmt.Print("Enter Password: ")
    p, _ := reader.ReadString('\n')
    fmt.Print("Enter 2FA Token: ")
    authy, _ := reader.ReadString('\n')

    auth := Auth{"manual", e, p, authy}
    j, _ := json.Marshal(auth)
    jar, _ := cookiejar.New(nil)
    client := &http.Client{
        Jar: jar,
    }

    req, err := http.NewRequest("POST", "https://internaltool.com/v3/sessions", bytes.NewBuffer(j))
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Add("Accept-Encoding", "gzip, deflate, br")
    res, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)
    s := string(body)
    if res.StatusCode == 400 {
        fmt.Println("Bad Credentials")
        fmt.Println(s)
        return
    }
}

问题是 - 我是否正确地将AUTH结构编组为JSON并将其适当地添加到POST请求中?由于API甚至没有看到JSON中的credentials键,我认为我必须做错事。一切都有帮助。

2 个答案:

答案 0 :(得分:0)

由于http.Client是一个相对较低的抽象,因此强烈建议使用gorequesthttps://github.com/parnurzeal/gorequest)作为替代。

标头,查询和正文可以以任何类型发布,这有点像我们在Python中经常做的事情。

答案 1 :(得分:0)

虽然这不能直接解决您的问题,但我认为有人正在寻找您标题中引用的主题的答案,Golang Struct as Payload for Post Request,可能会发现以下答案有帮助.

这是在 POST 请求的上下文中使用 json.Marshal 将 Struct 转换为 JSON 对象的最小可行示例。

Go 的标准库非常棒,没有必要引入外部依赖来做这么平凡的事情。

func TestPostRequest(t *testing.T) {

    // Create a new instance of Person
    person := Person{
        Name: "Ryan Alex Martin",
        Age:  27,
    }

    // Marshal it into JSON prior to requesting
    personJSON, err := json.Marshal(person)

    // Make request with marshalled JSON as the POST body
    resp, err := http.Post("https://httpbin.org/anything", "application/json",
        bytes.NewBuffer(personJSON))

    if err != nil {
        t.Error("Could not make POST request to httpbin")
    }

    // That's it!

    // But for good measure, let's look at the response body.
    body, err := ioutil.ReadAll(resp.Body)

    var result PersonResponse
    err = json.Unmarshal([]byte(body), &result)
    if err != nil {
        t.Error("Error unmarshaling data from request.")
    }

    if result.NestedPerson.Name != "Ryan Alex Martin" {
        t.Error("Incorrect or nil name field returned from server: ", result.NestedPerson.Name)
    }

    fmt.Println("Response from server:", result.NestedPerson.Name)
    fmt.Println("Response from server:", result.NestedPerson.Age)

}

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

// NestedPerson is the 'json' field of the response, what we originally sent to httpbin
type PersonResponse struct {
    NestedPerson Person `json:"json"` // Nested Person{} in 'json' field
}


相关问题