Last active
November 9, 2022 09:58
-
-
Save maniankara/a10d19960293b34b608ac7ef068a3d63 to your computer and use it in GitHub Desktop.
handling put request in golang
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 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) | |
} |
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
I got an error called ``use of package bytes without selector'' in line 31. Have you encountered this error, and how to solve it?