summaryrefslogtreecommitdiff
path: root/main.go
blob: 9385f852e1460d1174d85b5f3cc46e2f34a29f18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func main() {
	db := getInitializedDatabase()

	http.HandleFunc("/zip/", func(w http.ResponseWriter, r *http.Request) {
		handleZipcodeRequest(w, r, db)
	})

	http.ListenAndServe(getListeningAddress(), nil)
}

func getInitializedDatabase() *ZipcodeDatabase {
	db := NewZipcodeDatabase()
	err := db.LoadFromCSV("./zips.csv")
	if err != nil {
		fmt.Printf("%s\n", err)
	}

	return db
}

func getListeningAddress() string {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	return strings.Join([]string{
		":",
		port,
	}, "")
}
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))
}