Skip to content

Instantly share code, notes, and snippets.

@bhoggard
Created August 31, 2013 23:36
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 bhoggard/6401340 to your computer and use it in GitHub Desktop.
Save bhoggard/6401340 to your computer and use it in GitHub Desktop.
Simple REST API with 2 GETS for testing this ember app https://github.com/bhoggard/ember-simple
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type Organization struct {
ID int `json:"id"`
Name string `json:"name"`
}
func sampleOrg() Organization {
return Organization{ 1, "Hoggard Wagner Gallery" }
}
// wrap our handlers in a function that sets JSON and CORS headers
func makeHandler(fn func (http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
fn(w, r)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
response:= make(map[string]interface{})
orgs := []Organization { sampleOrg() }
response["organizations"] = orgs
output, err := json.Marshal(response)
if err != nil {
panic(err)
}
log.Println("index")
fmt.Fprintf(w, string(output))
}
func objectHandler(w http.ResponseWriter, r *http.Request) {
response:= make(map[string]interface{})
response["organization"] = sampleOrg()
output, err := json.Marshal(response)
if err != nil {
panic(err)
}
log.Println("object")
fmt.Fprintf(w, string(output))
}
func main() {
http.HandleFunc("/organizations", makeHandler(indexHandler))
http.HandleFunc("/organizations/1", makeHandler(objectHandler))
http.ListenAndServe("localhost:4000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment