Skip to content

Instantly share code, notes, and snippets.

@zgiber
Created September 21, 2015 14:29
Show Gist options
  • Save zgiber/a0b8e12a1d9d98c56d2e to your computer and use it in GitHub Desktop.
Save zgiber/a0b8e12a1d9d98c56d2e to your computer and use it in GitHub Desktop.
API access test
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
var (
hostName = "aerial-valor-93012.appspot.com"
)
type parameters struct {
Token string
Values []json.Number
}
// This is really just a sequential execution of the task description without any cosmetics.
// considering: "we will not be examining your code for quality." :)
func main() {
u := url.URL{
Scheme: "http",
Host: hostName,
Path: "/challenge",
}
resp, err := http.Get(u.String())
if err != nil {
log.Println(err)
return
}
if resp.StatusCode != http.StatusOK {
log.Println("Failed to GET parameters")
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
return
}
params := &parameters{}
err = json.Unmarshal(body, params)
if err != nil {
log.Println(err)
return
}
u.Path, err = generatePath(params)
if err != nil {
log.Println(err)
return
}
resp, err = http.Get(u.String())
if err != nil {
log.Println(err)
return
}
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
return
}
fmt.Println(string(result))
}
func generatePath(params *parameters) (string, error) {
var n float64 // since not stated in the task, we use float64 to be on the safe side.
for _, number := range params.Values {
value, err := number.Float64()
if err != nil {
return "", err
}
n += value
}
return fmt.Sprintf("/challenge/%s/%v", params.Token, n), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment