routing.go 1.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package routing

import (
	"net/http"

	"github.com/gorilla/mux"
	"github.com/matrix-org/dendrite/clientapi/readers"
	"github.com/matrix-org/dendrite/clientapi/writers"
	"github.com/matrix-org/util"
	"github.com/prometheus/client_golang/prometheus"
)

const pathPrefixR0 = "/_matrix/client/r0"

// Setup registers HTTP handlers with the given ServeMux. It also supplies the given http.Client
// to clients which need to make outbound HTTP requests.
func Setup(servMux *http.ServeMux, httpClient *http.Client) {
	apiMux := mux.NewRouter()
	r0mux := apiMux.PathPrefix(pathPrefixR0).Subrouter()
K
Kegsay 已提交
20
	r0mux.Handle("/sync", make("sync", wrap(func(req *http.Request) util.JSONResponse {
21 22 23
		return readers.Sync(req)
	})))
	r0mux.Handle("/rooms/{roomID}/send/{eventType}",
K
Kegsay 已提交
24
		make("send_message", wrap(func(req *http.Request) util.JSONResponse {
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
			vars := mux.Vars(req)
			return writers.SendMessage(req, vars["roomID"], vars["eventType"])
		})),
	)

	servMux.Handle("/metrics", prometheus.Handler())
	servMux.Handle("/api/", http.StripPrefix("/api", apiMux))
}

// make a util.JSONRequestHandler into an http.Handler
func make(metricsName string, h util.JSONRequestHandler) http.Handler {
	return prometheus.InstrumentHandler(metricsName, util.MakeJSONAPI(h))
}

// jsonRequestHandlerWrapper is a wrapper to allow in-line functions to conform to util.JSONRequestHandler
type jsonRequestHandlerWrapper struct {
K
Kegsay 已提交
41
	function func(req *http.Request) util.JSONResponse
42 43
}

K
Kegsay 已提交
44
func (r *jsonRequestHandlerWrapper) OnIncomingRequest(req *http.Request) util.JSONResponse {
45 46
	return r.function(req)
}
K
Kegsay 已提交
47
func wrap(f func(req *http.Request) util.JSONResponse) *jsonRequestHandlerWrapper {
48 49
	return &jsonRequestHandlerWrapper{f}
}