Skip to content

Instantly share code, notes, and snippets.

@gronnbeck
Last active March 15, 2016 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gronnbeck/452cb79403bf4b4862e4 to your computer and use it in GitHub Desktop.
Save gronnbeck/452cb79403bf4b4862e4 to your computer and use it in GitHub Desktop.
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
}
@yanpozka
Copy link

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