~samwhited/mux

ref: v0.0.4 mux/handlers.go -rw-r--r-- 1009 bytes
fee92349Sam Whited mux: add changelog and release v0.0.4 7 months ago
                                                                                
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
package mux

import (
	"net/http"
	"strings"
)

// defCodeWriter is an http.ResponseWriter that writes the given status code by
// default instead of always defaulting to a 200.
type defCodeWriter struct {
	http.ResponseWriter
	code  int
	wrote bool
}

func (w *defCodeWriter) Write(p []byte) (int, error) {
	if !w.wrote {
		w.wrote = true
		w.WriteHeader(w.code)
	}
	return w.ResponseWriter.Write(p)
}

func (w *defCodeWriter) WriteHeader(statusCode int) {
	w.wrote = true
	w.ResponseWriter.WriteHeader(statusCode)
}

func notFoundHandler(h http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		h.ServeHTTP(&defCodeWriter{
			ResponseWriter: w,
			code:           http.StatusNotFound,
		}, r)
	}
}

func defOptions(node node) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var verbs []string
		for v := range node.handlers {
			verbs = append(verbs, v)
		}
		w.Header().Add("Allow", strings.Join(verbs, ","))
		w.Write(nil)
	})
}