Skip to content

Instantly share code, notes, and snippets.

@sathishvj
Last active December 18, 2018 04:35
Show Gist options
  • Save sathishvj/e42fcabb69446097b53becf00ec030d5 to your computer and use it in GitHub Desktop.
Save sathishvj/e42fcabb69446097b53becf00ec030d5 to your computer and use it in GitHub Desktop.
curl POST written in go (for those who don't have curl)
// sometimes windows people don't have curl.
// This is a simple way to post a curl POST request.
// On newer windows versions, you can also try ...
// Invoke-WebRequest -Body '{"Author":"A", "Title":"B"}' -Method 'POST' -Uri 'http://localhost:8090/books'
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
func main() {
if len(os.Args) != 3 {
fmt.Println(`2 params required: data url.
Example: go run curl.go '{"A":"B"}' localhost:8090/books`)
os.Exit(1)
}
url := "http://" + os.Args[2]
payload := os.Args[1]
req, _ := http.NewRequest("POST", url, strings.NewReader(payload))
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("Error sending request: %v\n", err)
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println("Response: ", string(body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment