Created
May 22, 2017 20:16
-
-
Save Noofbiz/4f12ec1a5987288ec79ce48d5971a0e5 to your computer and use it in GitHub Desktop.
Playing around with JSON APIs and making http POST requests in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"encoding/json" | |
"net/http" | |
"io/ioutil" | |
"bytes" | |
) | |
func main(){ | |
url := "https://jsonplaceholder.typicode.com/posts" | |
data := make(map[string]interface{}) | |
data["title"] = "Moby Dick" | |
data["body"] = "Hawt boddd" | |
data["userId"] = "Bartleby" | |
dataJSON, err := json.Marshal(data) | |
if err != nil { | |
fmt.Printf("Error marshalling json! %v \r\n", err.Error()) | |
return | |
} | |
fmt.Printf("dataJSON is: \r\n %v \r\n", string(dataJSON)) | |
resp, err := http.Post(url, "application/json", bytes.NewBuffer(dataJSON)) | |
if err != nil { | |
fmt.Printf("Error making request! %v \r\n", err.Error()) | |
return | |
} | |
defer resp.Body.Close() | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
fmt.Printf("Error reading response body! %v \r\n", err.Error()) | |
return | |
} | |
respMap := make(map[string]interface{}) | |
json.Unmarshal(body, &respMap) | |
fmt.Printf("The response map is: \r\n %v \r\n", respMap) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment