From 0ab4e43eabd89f6a789d6f168f680bffe17c6e99 Mon Sep 17 00:00:00 2001 From: Ben Burwell Date: Wed, 18 Nov 2015 15:09:33 -0500 Subject: Initial commit --- main.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 main.go (limited to 'main.go') diff --git a/main.go b/main.go new file mode 100644 index 0000000..4c3c3b5 --- /dev/null +++ b/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" +) + +func main() { + db := getInitializedDatabase() + + http.HandleFunc("/zip/", func(w http.ResponseWriter, r *http.Request) { + handleZipcodeRequest(w, r, db) + }) + + http.ListenAndServe(":8080", nil) +} + +func getInitializedDatabase() *ZipcodeDatabase { + db := NewZipcodeDatabase() + err := db.LoadFromCSV("./zips.csv") + if err != nil { + fmt.Printf("%s\n", err) + } + + return db +} + +func handleZipcodeRequest(response http.ResponseWriter, request *http.Request, db *ZipcodeDatabase) { + zip := zipcodeForRequest(request) + if details := db.Find(zip); details == nil { + http.Error(response, "", 404) + } else { + setResponseHeaders(response) + sendZipcodeDetails(details, response) + } +} + +func setResponseHeaders(response http.ResponseWriter) { + response.Header().Set("Access-Control-Allow-Origin", "*") + response.Header().Set("Content-Type", "application/json") +} + +func zipcodeForRequest(request *http.Request) string { + return request.URL.Path[len("/zip/"):] +} + +func sendZipcodeDetails(details *ZipcodeDetails, response http.ResponseWriter) { + data, _ := json.MarshalIndent(details, "", " ") + fmt.Fprintf(response, string(data)) +} -- cgit v1.2.3