Created
February 13, 2020 18:52
-
-
Save cghiban/3035e554e8943a5fc10ac7637e8c70ce to your computer and use it in GitHub Desktop.
golang json PUT example
This file contains hidden or 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 ( | |
"bytes" | |
"encoding/json" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
type Data struct { | |
A string `json:"z"` | |
B string `json:"x"` | |
} | |
const endPoint string = "https://...." | |
func main() { | |
data := Data{A: "aaa", B: "bbb"} | |
log.Println(data) | |
b, err := json.Marshal(data) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println("json:", string(b)) | |
var client http.Client | |
req, err := http.NewRequest( | |
"PUT", | |
endPoint, | |
bytes.NewBuffer(b), | |
) | |
req.Header.Set("Content-Type", "application/json") | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer resp.Body.Close() | |
log.Println("status:", resp.Status) | |
log.Println("status code:", resp.StatusCode) | |
//fmt.Println("body:", resp.) | |
body, _ := ioutil.ReadAll(resp.Body) | |
log.Println("response Body:", string(body)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment