forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
48 lines (40 loc) · 1.15 KB
/
router.go
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
package clusterrouter
import (
"encoding/json"
"net/http"
"github.com/rancher/norman/httperror"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/config/dialer"
"k8s.io/client-go/rest"
)
type Router struct {
serverFactory *factory
}
func New(localConfig *rest.Config, lookup ClusterLookup, dialer dialer.Factory, clusterLister v3.ClusterLister) http.Handler {
serverFactory := newFactory(localConfig, dialer, lookup, clusterLister)
return &Router{
serverFactory: serverFactory,
}
}
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
c, handler, err := r.serverFactory.get(req)
if err != nil {
e, ok := err.(*httperror.APIError)
if ok {
response(rw, e.Code, e.Message)
} else {
response(rw, httperror.ServerError, err.Error())
}
return
}
if c == nil {
response(rw, httperror.NotFound, "No cluster available")
return
}
handler.ServeHTTP(rw, req)
}
func response(rw http.ResponseWriter, code httperror.ErrorCode, message string) {
rw.WriteHeader(code.Status)
rw.Header().Set("content-type", "application/json")
json.NewEncoder(rw).Encode(httperror.NewAPIError(code, message))
}