Skip to content

Instantly share code, notes, and snippets.

@maniankara
Last active November 9, 2022 09:58
Show Gist options
  • Save maniankara/a10d19960293b34b608ac7ef068a3d63 to your computer and use it in GitHub Desktop.
Save maniankara/a10d19960293b34b608ac7ef068a3d63 to your computer and use it in GitHub Desktop.
handling put request in golang
package fragments
import (
"net/http"
"io"
"log"
"strings"
"os"
"bytes"
)
func putRequest(url string, data io.Reader) {
client := &http.Client{}
req, err := http.NewRequest(http.MethodPut, url, data)
if err != nil {
// handle error
log.Fatal(err)
}
_, err = client.Do(req)
if err != nil {
// handle error
log.Fatal(err)
}
}
func httpPutExample() {
putRequest("http://google.com", strings.NewReader("any thing"))
var jsonStr string = []bytes {"name":"Rob", "title":"developer"}
putRequest("http://msn.com", bytes.NewBuffer(jsonStr))
// read the file
data, err := os.Open("/path/to/file.json")
if err != nil {
//handle error
log.Fatal(err)
}
putRequest("http://yahoo.com", data)
}
@ZM-J
Copy link

ZM-J commented Dec 25, 2017

I got an error called ``use of package bytes without selector'' in line 31. Have you encountered this error, and how to solve it?

@dave-johnson
Copy link

dave-johnson commented Mar 19, 2018

I"m using the following snippet to format the body. I used Sprintf to format the string with a bunch of my variables.
body := fmt.Sprintf("{\"name\":%q, \"title\":%q}", name, title)
request, err := http.NewRequest("PUT", url, strings.NewReader(body))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment