Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Struct as Payload for POST Request

Tags:

http

go

New to golang. I'm trying to make a POST request to an auth endpoint to get back a token for authing further requests. Currently the error I'm getting is missing "credentials". I've written the same logic in Python so I know what I am trying to do is what the system is expecting.

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
    }
}

The question is - am I properly marshalling the AUTH struct into JSON and adding it appropriately to the POST request? As the API is not even seeing the credentials key in the JSON I think I must be doing something wrong. Anything helps.

like image 287
HectorOfTroy407 Avatar asked Jul 31 '17 22:07

HectorOfTroy407


2 Answers

Here's a minimum viable example of using json.Marshal to convert a Struct to a JSON object in the context of a POST request.

Go's standard libraries are fantastic, there is no need to pull in external dependencies to do such a mundane thing.

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
}


like image 160
Ryan Alex Martin Avatar answered Sep 23 '22 19:09

Ryan Alex Martin


As http.Client is relatively a low-level abstraction, gorequest(https://github.com/parnurzeal/gorequest) as an alternative is strongly recommended.

headers, queries, and body can be posted in any type, which is a bit more like what we often do in Python.

like image 35
Arith Avatar answered Sep 19 '22 19:09

Arith