aboutsummaryrefslogtreecommitdiff
path: root/pkg/server/handler.go
blob: 6d17af7534ca0cd084452b7065b2766d79b139a3 (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
package server

import (
	"fmt"
	"net/http"
)

// handler implements the http.Handler interface
type handler struct {
	method   string
	endpoint string
	callback func(w http.ResponseWriter, r *http.Request) (int, string)
}

func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	if r.Method != h.method {
		http.Error(w, "Invalid HTTP method, expected "+h.method, http.StatusMethodNotAllowed)
		return
	}
	code, text := h.callback(w, r)
	if code != http.StatusOK {
		http.Error(w, text, code)
		return
	}
	fmt.Fprintf(w, fmt.Sprintf("%s\n", text))
}

func (h handler) register(mux *http.ServeMux) {
	mux.Handle("/"+h.endpoint, h)
}