-
-
Save gronnbeck/452cb79403bf4b4862e4 to your computer and use it in GitHub Desktop.
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
import ( | |
"net/http" | |
"time" | |
"log" | |
"encoding/json" | |
uuid "github.com/satori/go.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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To avoid compare with strings and a more idiomatic way on Golang for errors should be:
Substitute this line:
for this:
and just change the method signature for this:
and at the end of the function just return nil