Created
August 31, 2013 23:36
-
-
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
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
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