@kjk1/

gobook http client put json

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.7277140284703105","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"Ly8gbm8gcGxheWdyb3VuZApwYWNrYWdlIG1haW4KCmltcG9ydCAoCgkiYnl0ZXMiCgkiZW5jb2RpbmcvanNvbiIKCSJmbXQiCgkiaW8vaW91dGlsIgoJImxvZyIKCSJuZXQvaHR0cCIKCSJ0aW1lIgopCgp0eXBlIFVzZXIgc3RydWN0IHsKCU5hbWUgIHN0cmluZwoJRW1haWwgc3RyaW5nCn0KCmZ1bmMgbWFpbigpIHsKCS8vIDpzaG93IHN0YXJ0Cgl1c2VyIDo9IFVzZXJ7CgkJTmFtZTogICJKb2huIERvZSIsCgkJRW1haWw6ICJqb2huZG9lQGV4YW1wbGUuY29tIiwKCX0KCglkLCBlcnIgOj0ganNvbi5NYXJzaGFsKHVzZXIpCglpZiBlcnIgIT0gbmlsIHsKCQlsb2cuRmF0YWxmKCJqc29uLk1hcnNoYWwoKSBmYWlsZWQgd2l0aCAnJXMnXG4iLCBlcnIpCgl9CgoJY2xpZW50IDo9ICZodHRwLkNsaWVudHt9CgljbGllbnQuVGltZW91dCA9IHRpbWUuU2Vjb25kICogMTUKCgl1cmkgOj0gImh0dHBzOi8vaHR0cGJpbi5vcmcvcHV0IgoJYm9keSA6PSBieXRlcy5OZXdCdWZmZXIoZCkKCXJlcSwgZXJyIDo9IGh0dHAuTmV3UmVxdWVzdChodHRwLk1ldGhvZFB1dCwgdXJpLCBib2R5KQoJaWYgZXJyICE9IG5pbCB7CgkJbG9nLkZhdGFsZigiaHR0cC5OZXdSZXF1ZXN0KCkgZmFpbGVkIHdpdGggJyVzJ1xuIiwgZXJyKQoJfQoKCXJlcS5IZWFkZXIuU2V0KCJDb250ZW50LVR5cGUiLCAiYXBwbGljYXRpb24vanNvbjsgY2hhcnNldD11dGYtOCIpCglyZXNwLCBlcnIgOj0gY2xpZW50LkRvKHJlcSkKCWlmIGVyciAhPSBuaWwgewoJCWxvZy5GYXRhbGYoImNsaWVudC5EbygpIGZhaWxlZCB3aXRoICclcydcbiIsIGVycikKCX0KCglkZWZlciByZXNwLkJvZHkuQ2xvc2UoKQoJZCwgZXJyID0gaW91dGlsLlJlYWRBbGwocmVzcC5Cb2R5KQoJaWYgZXJyICE9IG5pbCB7CgkJbG9nLkZhdGFsZigiaW91dGlsLlJlYWRBbGwoKSBmYWlsZWQgd2l0aCAnJXMnXG4iLCBlcnIpCgl9CgoJZm10LlByaW50ZigiUmVzcG9uc2Ugc3RhdHVzIGNvZGU6ICVkLCB0ZXh0OlxuJXNcbiIsIHJlc3AuU3RhdHVzQ29kZSwgc3RyaW5nKGQpKQoJLy8gOnNob3cgZW5kCn0="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// no playground
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

type User struct {
	Name  string
	Email string
}

func main() {
	// :show start
	user := User{
		Name:  "John Doe",
		Email: "[email protected]",
	}

	d, err := json.Marshal(user)
	if err != nil {
		log.Fatalf("json.Marshal() failed with '%s'\n", err)
	}

	client := &http.Client{}
	client.Timeout = time.Second * 15

	uri := "https://httpbin.org/put"
	body := bytes.NewBuffer(d)
	req, err := http.NewRequest(http.MethodPut, uri, body)
	if err != nil {
		log.Fatalf("http.NewRequest() failed with '%s'\n", err)
	}

	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("client.Do() failed with '%s'\n", err)
	}

	defer resp.Body.Close()
	d, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
	}

	fmt.Printf("Response status code: %d, text:\n%s\n", resp.StatusCode, string(d))
	// :show end
}