Last active
September 15, 2015 21:00
-
-
Save pop/f89f53d92c01cb02a803 to your computer and use it in GitHub Desktop.
Simple Golang requests program
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
// Build instructions: | |
// $ go build main.go | |
// | |
// Usage instructions: | |
// $ ./main --method=GET --url=http://example.com | |
// $ ./main --method=POST --url=http://api.example.com/v#/thing/ --content='{"foo": "bar", "baz": True}' | |
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"flag" | |
) | |
// Makes an HTTP request of `method` type to `url` destination with `content` | |
// body (if applicable. `content` may be an empty string [``] if it is a GET | |
// request for instance) | |
func httpRequest(method string, url string, content string) { | |
fmt.Println("url: ", url) | |
var jsonStr = []byte(content) | |
req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr)) | |
req.Header.Set("Content-Type", "application/json") | |
client := &http.Client{} | |
resp, err := client.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
fmt.Printf("response Status: %s\n", resp.Status) | |
fmt.Printf("response Headers: %s\n", resp.Header) | |
body, _ := ioutil.ReadAll(resp.Body) | |
fmt.Printf("response Body: %s\n", string(body)) | |
} | |
// Making a POST request | |
// | |
// httpRequest("POST", "http://private-anon-bff4bcd4a-restapi3.apiary-mock.com/notes", `{"title": "a test"}`) | |
// | |
// Making a GET request | |
// Note the empty content string | |
// | |
// httpRequest("GET", "http://google.com/robots.txt", ``) | |
// | |
func main() { | |
// Argument parsing | |
requestMethod := flag.String("method", `GET`, "The request method used") | |
requestUrl := flag.String("url", `http://example.com/`, "The url being requested") | |
requestContent := flag.String("content", ``, "Content of request being made") | |
flag.Parse() | |
fmt.Printf("requestMethod value: %s\n", *requestMethod) | |
fmt.Printf("requestUrl value: %s\n", *requestUrl) | |
fmt.Printf("requestContent value: %s", *requestContent) | |
if *requestUrl == "" || requestMethod == "" { | |
fmt.Println("\n!!!URLS AND METHODS NEED TO EXIST!!!") | |
return | |
} | |
if *requestMethod == "POST" && *requestContent == "" { | |
fmt.Println("\n!!!POST requests must have content!!!") | |
return | |
} | |
httpRequest(*requestMethod, *requestUrl, *requestContent) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment