Skip to content

Instantly share code, notes, and snippets.

@oscarryz
Last active August 29, 2015 14:10
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 oscarryz/1aa2b71d2dbda156a677 to your computer and use it in GitHub Desktop.
Save oscarryz/1aa2b71d2dbda156a677 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
type User struct {
Name string `json:"name"`
}
func main() {
fmt.Println("Starting")
var helloRE = regexp.MustCompile(`/hello/(\d)`)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if helloRE.MatchString(r.RequestURI) {
var id = helloRE.FindStringSubmatch(r.RequestURI)[1]
res, err := http.Get("http://jsonplaceholder.typicode.com/users/" + id)
if err != nil {
fmt.Fprintf(w, "Oops: %s", err)
}
jsonStream, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Fprintf(w, "Oops: %s", err)
}
dec := json.NewDecoder(strings.NewReader(string(jsonStream)))
var user User
if err := dec.Decode(&user); err != nil {
fmt.Fprintf(w, "Oops: %s", err)
}
fmt.Fprintf(w, "The name for id %s is %s", id, user.Name)
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Usage: /hello/id where id = single digit")
}
})
fmt.Println(http.ListenAndServe(":6060", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment