summaryrefslogtreecommitdiff
path: root/pkg/api/server/handler_api.go
blob: 4b93998ee79777fafcaf35ce883f29a0973a46e1 (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
package server

import (
	"context"
	"net/http"

	log "github.com/sirupsen/logrus"
)

// APIHandler is a wrapper to enhance HandlerFunc's and remove redundant code
func APIHandler(ctx context.Context, h http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Debugf("APIHandler -- Method: %s URL: %s", r.Method, r.URL.String())
		if err := r.ParseForm(); err != nil {
			log.Infof("Failed Request: unable to parse form: %q", err)
		}

		// TODO: Use ConnContext when ported to go 1.13
		c := context.WithValue(r.Context(), "decoder", ctx.Value("decoder"))
		c = context.WithValue(c, "runtime", ctx.Value("runtime"))
		c = context.WithValue(c, "shutdownFunc", ctx.Value("shutdownFunc"))
		r = r.WithContext(c)

		h(w, r)

		shutdownFunc := r.Context().Value("shutdownFunc").(func() error)
		if err := shutdownFunc(); err != nil {
			log.Errorf("Failed to shutdown Server in APIHandler(): %s", err.Error())
		}
	})
}

// VersionedPath prepends the version parsing code
// any handler may override this default when registering URL(s)
func VersionedPath(p string) string {
	return "/v{version:[0-9][0-9.]*}" + p
}