Use gorilla/mux to route HTTP requests. Make /sync and /send use the right API paths

This commit is contained in:
Kegan Dougal 2017-02-17 17:31:00 +00:00
parent 2410ed6860
commit 79e5c8a07b
2 changed files with 17 additions and 41 deletions

View file

@ -1,56 +1,29 @@
package routing package routing
import ( import (
"net/http"
"github.com/gorilla/mux"
"github.com/matrix-org/dendrite/clientapi/readers" "github.com/matrix-org/dendrite/clientapi/readers"
_ "github.com/matrix-org/dendrite/clientapi/writers" "github.com/matrix-org/dendrite/clientapi/writers"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"net/http"
"strings"
) )
const pathPrefixR0 = "/_matrix/client/r0" const pathPrefixR0 = "/_matrix/client/r0"
// Return true if this path should be handled by this handler func make(metricsName string, h util.JSONRequestHandler) http.Handler {
type matcher func(path string) bool return prometheus.InstrumentHandler(metricsName, util.MakeJSONAPI(h))
type lookup struct {
Matches matcher
Handler http.Handler
}
func newLookup(name string, m matcher, h util.JSONRequestHandler) lookup {
return lookup{
Matches: m,
Handler: prometheus.InstrumentHandler(name, util.MakeJSONAPI(h)),
}
}
func matchesString(str string) func(path string) bool {
return func(path string) bool {
return path == str
}
} }
// Setup registers HTTP handlers with the given ServeMux. It also supplies the given http.Client // Setup registers HTTP handlers with the given ServeMux. It also supplies the given http.Client
// to clients which need to make outbound HTTP requests. // to clients which need to make outbound HTTP requests.
func Setup(mux *http.ServeMux, httpClient *http.Client) { func Setup(servMux *http.ServeMux, httpClient *http.Client) {
var r0lookups []lookup apiMux := mux.NewRouter()
r0lookups = append(r0lookups, newLookup("sync", matchesString("/sync"), &readers.Sync{})) r0mux := apiMux.PathPrefix("/_matrix/client/r0").Subrouter()
r0mux.Handle("/sync", make("sync", &readers.Sync{}))
r0mux.Handle("/rooms/{roomID}/send/{eventType}", make("send_message", &writers.SendMessage{}))
mux.Handle("/metrics", prometheus.Handler()) servMux.Handle("/metrics", prometheus.Handler())
mux.HandleFunc("/api/", func(w http.ResponseWriter, req *http.Request) { servMux.Handle("/api/", http.StripPrefix("/api", apiMux))
clientServerPath := strings.TrimPrefix(req.URL.Path, "/api")
if strings.HasPrefix(clientServerPath, pathPrefixR0) {
apiPath := strings.TrimPrefix(clientServerPath, pathPrefixR0)
for _, lookup := range r0lookups {
if lookup.Matches(apiPath) {
lookup.Handler.ServeHTTP(w, req)
return
}
}
}
w.WriteHeader(404)
w.Write([]byte(`{"error":"Not found","errcode":"M_NOT_FOUND"}`))
})
} }

View file

@ -4,6 +4,7 @@ import (
"net/http" "net/http"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -14,7 +15,9 @@ type SendMessage struct {
// OnIncomingRequest implements util.JSONRequestHandler // OnIncomingRequest implements util.JSONRequestHandler
func (s *SendMessage) OnIncomingRequest(req *http.Request) (interface{}, *util.HTTPError) { func (s *SendMessage) OnIncomingRequest(req *http.Request) (interface{}, *util.HTTPError) {
logger := req.Context().Value(util.CtxValueLogger).(*log.Entry) logger := req.Context().Value(util.CtxValueLogger).(*log.Entry)
logger.Info("Doing stuff...") vars := mux.Vars(req)
roomID := vars["roomID"]
logger.WithField("roomID", roomID).Info("Doing stuff...")
return nil, &util.HTTPError{ return nil, &util.HTTPError{
Code: 404, Code: 404,
Message: "Not implemented yet", Message: "Not implemented yet",