Skip to content

Instantly share code, notes, and snippets.

@gronnbeck gronnbeck/http_request.go Secret
Last active Mar 15, 2016

What would you like to do?
import (
uuid ""
var (
ConnectionFailed = "ConnectionFailed"
UnexpectedResponse = "UnexpectedResponse"
OK = "OK"
type SyntheticPayload struct {
ID string `json:"id"`
Type string `json:"type"`
Timestamp string `json:"timestamp"`
func syntheticHttpRequest(url string, apiToken string) (string) {
payload := SyntheticPayload {
ID: uuid.NewV4().String(),
Type: "BEACON",
Timestamp: time.Now().UTC().Format(time.RFC3339),
byt, err := json.Marshal(payload)
if err != nil {
log.Fatal("Could not parse the payload you specified. Please correct it!")
reader := bytes.NewReader(byt)
req, err := http.NewRequest("POST", url, reader)
if err != nil {
log.Fatal(`[ERROR] Could not create a POST request.
This should not occur and there is something wrong with the code. Exiting.`)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "ApiToken "+apiToken)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println(`[ERROR] An request error occured. Is the service running
or have you specified the wrong url?`)
return ConnectionFailed
} else if resp.StatusCode != 202 {
return UnexpectedResponse
return OK

This comment has been minimized.

Copy link

yanpozka commented Mar 15, 2016

To avoid compare with strings and a more idiomatic way on Golang for errors should be:
Substitute this line:

var (
 ConnectionFailed = "ConnectionFailed"
 UnexpectedResponse = "UnexpectedResponse"
 OK = "OK"

for this:

// import "errors"
var (
    ConnectionFailed = errors.New("ConnectionFailed")
    UnexpectedResponse = errors.New("UnexpectedResponse")

and just change the method signature for this:

func syntheticHttpRequest(url string, apiToken string) error

and at the end of the function just return nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.