DaveUK
DaveUK

Reputation: 1580

using http.PostForm to POST nested json data values?

I've seen the following example of how to use net/http PostForm to send a basic string map as a POST request:

How to send a POST request in Go?

But the data that I need to post is slightly more complicated as it has nested json / nested string maps. An example of the data I need to post:

{"MyAttributes" : {"AttributeOne" : "one", "AttributeTwo":"two"}}

Can net/url Values represent that kind of nested data and/or how do I pass this to net/http PostForm?

Upvotes: 0

Views: 852

Answers (1)

0xedb
0xedb

Reputation: 364

It's possible

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "net/url"
)

type Attributes struct {
    AttributeOne string
    AttributeTwo string
}

func main() {
    attributes := Attributes{"one", "two"}

    data, err := json.Marshal(attributes)

    if err != nil {
        log.Fatal("bad", err)
    }

    values := url.Values{}
    values.Set("MyAttributes", string(data))

    resp, error := http.PostForm("localhost:2021", values)

    // use resp and error later
}

Upvotes: 1

Related Questions