Skip to content

Instantly share code, notes, and snippets.

@atedja
Created December 31, 2014 00:32
Show Gist options
  • Save atedja/b6d6d65a2f09c8317728 to your computer and use it in GitHub Desktop.
Save atedja/b6d6d65a2f09c8317728 to your computer and use it in GitHub Desktop.
Simple HTTP wrapper in Go
package main
import "net/http"
import "io/ioutil"
import "os"
import "fmt"
import "bytes"
func handleError(e error) {
if e != nil {
fmt.Println(e)
os.Exit(1)
}
}
func fetch(method string, url string, payload []byte, headers map[string]string) string {
client := &http.DefaultClient
request, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
handleError(err)
// copy headers
if headers != nil {
for k, v := range headers {
request.Header.Set(k, v)
}
}
// perform request
resp, err := client.Do(request)
handleError(err)
// read response
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
handleError(err)
return string(contents)
}
func get(url string, payload []byte, headers map[string]string) string {
return fetch("GET", url, payload, headers)
}
func post(url string, payload []byte, headers map[string]string) string {
return fetch("POST", url, payload, headers)
}
func put(url string, payload []byte, headers map[string]string) string {
return fetch("PUT", url, payload, headers)
}
func main() {
headers := make(map[string]string)
headers["Content-Type"] = "application/json"
result := post("http://localhost:4567?omg=lol&whatever=1", []byte("{\"test\":\"me\"}"), headers)
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment