Hi guys a have a question about POST REQUEST
I have a some python code like this data = { "name": "Frank", "age": 21, "nationality": ["Britan"], }
r = requests.post('somesite', json=data) How i can make a POST requst similar this on GOLANG, i tried use "nationality": ["Britan"] but i have a some errors with [] i tried to use map[string]string but ofc its not working May be i can use some structure to resolve my problem
CodePudding user response:
You should use map[string]interface{} instead of map[string]string
As this link (https://go.dev/blog/maps):
map[KeyType]ValueType
where KeyType may be any type that is comparable, and ValueType may be any type at all, including another map!
Your body has both string and slice type, so ValueType is interface{} better than string.
CodePudding user response:
maybe you should use map[string]interface{}
or you can also use strings.NewReader
to send request directly
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "http://localhost:8080"
method := "POST"
payload := strings.NewReader(`{
"name": "Flank",
"age": 21,
"nationality": ["Britan"]
}`)
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}