forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
44 lines (36 loc) · 1.08 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
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 {
clusterLookup ClusterLookup
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 {
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))
}