about summary refs log tree commit diff stats
path: root/http.go
blob: e67560cdb6eb5b114bbadfe7cf986b400064b1ed (plain) (blame)
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
65
66
67
package main

import (
	"errors"
	"net/http"
	"strings"
)

const mimePlain = "text/plain; charset=utf-8"
const mimeJSON = "application/json; charset=utf-8"

// Validates the request and then queries the cache for the response.
func mainHandler(w http.ResponseWriter, r *http.Request) {
	if !methodHop(r) {
		errHTTP(w, r, errors.New("405 Method Not Allowed"), http.StatusMethodNotAllowed)
		return
	}

	format := formatHop(r)
	if format != "plain" && format != "json" && r.URL.Path != "/" {
		errHTTP(w, r, errors.New("400 Bad Request"), http.StatusBadRequest)
		return
	}

	err := cache.bap(r.URL.Path)
	if err != nil {
		errHTTP(w, r, err, http.StatusInternalServerError)
		return
	}

	if format == "json" {
		w.Header().Set("Content-Type", mimeJSON)
	} else {
		w.Header().Set("Content-Type", mimePlain)
	}

	out, expires := cache.yoink(r.URL.Path)
	w.Header().Set("Expires", expires)

	_, err = w.Write(out)
	if err != nil {
		errHTTP(w, r, err, http.StatusBadRequest)
		return
	}
	log200(r)
}

// Simple HTTP method check
func methodHop(r *http.Request) bool {
	return r.Method == http.MethodGet || r.Method == http.MethodHead
}

// Yoinks the response format
func formatHop(r *http.Request) string {
	if r.URL.Path == "/" {
		return ""
	}

	split := strings.Split(r.URL.Path[1:], "/")
	return split[0]
}

// Yoinks the endpoint
func routingHop(r *http.Request) string {
	split := strings.Split(r.URL.Path[1:], "/")
	return split[1]
}