summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
authorBen Burwell <ben.burwell@trifecta.com>2015-11-18 15:09:33 -0500
committerBen Burwell <ben.burwell@trifecta.com>2015-11-18 15:09:33 -0500
commit0ab4e43eabd89f6a789d6f168f680bffe17c6e99 (patch)
tree0faecb22b9713dcf8843c3d0592c7ce91741bb36 /main.go
Initial commit
Diffstat (limited to 'main.go')
-rw-r--r--main.go51
1 files changed, 51 insertions, 0 deletions
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))
+}