github.com/rancher/longhorn-engine@v0.6.2/replica/rest/router.go (about)

     1  package rest
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/gorilla/mux"
     7  	"github.com/rancher/go-rancher/api"
     8  	"github.com/rancher/go-rancher/client"
     9  
    10  	// add pprof endpoint
    11  	_ "net/http/pprof"
    12  )
    13  
    14  func HandleError(s *client.Schemas, t func(http.ResponseWriter, *http.Request) error) http.Handler {
    15  	return api.ApiHandler(s, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
    16  		if err := t(rw, req); err != nil {
    17  			apiContext := api.GetApiContext(req)
    18  			apiContext.WriteErr(err)
    19  		}
    20  	}))
    21  }
    22  
    23  func checkAction(s *Server, t func(http.ResponseWriter, *http.Request) error) func(http.ResponseWriter, *http.Request) error {
    24  	return func(rw http.ResponseWriter, req *http.Request) error {
    25  		replica := s.Replica(api.GetApiContext(req))
    26  		if replica.Actions[req.URL.Query().Get("action")] == "" {
    27  			rw.WriteHeader(http.StatusNotFound)
    28  			return nil
    29  		}
    30  		return t(rw, req)
    31  	}
    32  }
    33  
    34  func NewRouter(s *Server) *mux.Router {
    35  	schemas := NewSchema()
    36  	router := mux.NewRouter().StrictSlash(true)
    37  	f := HandleError
    38  
    39  	router.Methods("GET").Path("/ping").Handler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
    40  		rw.Write([]byte("pong"))
    41  	}))
    42  
    43  	// API framework routes
    44  	router.Methods("GET").Path("/").Handler(api.VersionsHandler(schemas, "v1"))
    45  	router.Methods("GET").Path("/v1/schemas").Handler(api.SchemasHandler(schemas))
    46  	router.Methods("GET").Path("/v1/schemas/{id}").Handler(api.SchemaHandler(schemas))
    47  	router.Methods("GET").Path("/v1").Handler(api.VersionHandler(schemas, "v1"))
    48  
    49  	// Replicas
    50  	router.Methods("GET").Path("/v1/replicas").Handler(f(schemas, s.ListReplicas))
    51  
    52  	// Actions
    53  	actions := map[string]func(http.ResponseWriter, *http.Request) error{}
    54  
    55  	for name, action := range actions {
    56  		router.Methods("POST").Path("/v1/replicas/{id}").Queries("action", name).Handler(f(schemas, checkAction(s, action)))
    57  	}
    58  
    59  	router.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux)
    60  
    61  	return router
    62  }