本文整理汇总了Golang中net/http.ServeMux.Handle方法的典型用法代码示例。如果您正苦于以下问题:Golang ServeMux.Handle方法的具体用法?Golang ServeMux.Handle怎么用?Golang ServeMux.Handle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.ServeMux
的用法示例。
在下文中一共展示了ServeMux.Handle方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: startSecureServing
func startSecureServing(opt *options.HeapsterRunOptions, handler http.Handler, promHandler http.Handler,
mux *http.ServeMux, address string) {
if len(opt.TLSClientCAFile) > 0 {
authPprofHandler, err := newAuthHandler(opt, handler)
if err != nil {
glog.Fatalf("Failed to create authorized pprof handler: %v", err)
}
handler = authPprofHandler
authPromHandler, err := newAuthHandler(opt, promHandler)
if err != nil {
glog.Fatalf("Failed to create authorized prometheus handler: %v", err)
}
promHandler = authPromHandler
}
mux.Handle("/", handler)
mux.Handle("/metrics", promHandler)
// If allowed users is set, then we need to enable Client Authentication
if len(opt.AllowedUsers) > 0 {
server := &http.Server{
Addr: address,
Handler: mux,
TLSConfig: &tls.Config{ClientAuth: tls.RequestClientCert},
}
glog.Fatal(server.ListenAndServeTLS(opt.TLSCertFile, opt.TLSKeyFile))
} else {
glog.Fatal(http.ListenAndServeTLS(address, opt.TLSCertFile, opt.TLSKeyFile, mux))
}
}
示例2: newMethodRouter
// newMethodRouter takes the server mux that will dispatch to this router based on the matched path.
func newMethodRouter(mux *http.ServeMux, path string) *methodRouter {
mr := &methodRouter{
handlers: map[string]http.Handler{},
}
mux.Handle(path, mr)
return mr
}
示例3: HandleFunc
// HandleFunc registers a handler at the given path. It's
// http.HandleFunc(), but with a wrapper around the handler that
// provides some generic per-request functionality:
//
// * Set a Replay-Nonce header.
//
// * Respond to OPTIONS requests, including CORS preflight requests.
//
// * Set a no cache header
//
// * Respond http.StatusMethodNotAllowed for HTTP methods other than
// those listed.
//
// * Set CORS headers when responding to CORS "actual" requests.
//
// * Never send a body in response to a HEAD request. Anything
// written by the handler will be discarded if the method is HEAD.
// Also, all handlers that accept GET automatically accept HEAD.
func (wfe *WebFrontEndImpl) HandleFunc(mux *http.ServeMux, pattern string, h wfeHandlerFunc, methods ...string) {
methodsMap := make(map[string]bool)
for _, m := range methods {
methodsMap[m] = true
}
if methodsMap["GET"] && !methodsMap["HEAD"] {
// Allow HEAD for any resource that allows GET
methods = append(methods, "HEAD")
methodsMap["HEAD"] = true
}
methodsStr := strings.Join(methods, ", ")
handler := http.StripPrefix(pattern, &topHandler{
log: wfe.log,
clk: clock.Default(),
wfe: wfeHandlerFunc(func(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
// We do not propagate errors here, because (1) they should be
// transient, and (2) they fail closed.
nonce, err := wfe.nonceService.Nonce()
if err == nil {
response.Header().Set("Replay-Nonce", nonce)
logEvent.ResponseNonce = nonce
} else {
logEvent.AddError("unable to make nonce: %s", err)
}
switch request.Method {
case "HEAD":
// Go's net/http (and httptest) servers will strip out the body
// of responses for us. This keeps the Content-Length for HEAD
// requests as the same as GET requests per the spec.
case "OPTIONS":
wfe.Options(response, request, methodsStr, methodsMap)
return
}
// No cache header is set for all requests, succeed or fail.
addNoCacheHeader(response)
if !methodsMap[request.Method] {
response.Header().Set("Allow", methodsStr)
wfe.sendError(response, logEvent, probs.MethodNotAllowed(), nil)
return
}
wfe.setCORSHeaders(response, request, "")
timeout := wfe.RequestTimeout
if timeout == 0 {
timeout = 5 * time.Minute
}
ctx, cancel := context.WithTimeout(ctx, timeout)
// TODO(riking): add request context using WithValue
// Call the wrapped handler.
h(ctx, logEvent, response, request)
cancel()
}),
})
mux.Handle(pattern, handler)
}
示例4: loadApps
// Create the individual API (app) specs based on live configurations and assign middleware
func loadApps(APISpecs []APISpec, Muxer *http.ServeMux) {
// load the APi defs
log.Info("Loading API configurations.")
for _, spec := range APISpecs {
// Create a new handler for each API spec
remote, err := url.Parse(spec.APIDefinition.Proxy.TargetURL)
if err != nil {
log.Error("Culdn't parse target URL")
log.Error(err)
}
if spec.UseOauth2 {
addOAuthHandlers(spec, Muxer, false)
}
proxy := TykNewSingleHostReverseProxy(remote)
spec.target = remote
proxyHandler := http.HandlerFunc(ProxyHandler(proxy, spec))
tykMiddleware := TykMiddleware{spec, proxy}
if spec.APIDefinition.UseKeylessAccess {
// for KeyLessAccess we can't support rate limiting, versioning or access rules
chain := alice.New().Then(proxyHandler)
Muxer.Handle(spec.Proxy.ListenPath, chain)
} else {
// Select the keying method to use for setting session states
var keyCheck func(http.Handler) http.Handler
if spec.APIDefinition.UseOauth2 {
// Oauth2
keyCheck = CreateMiddleware(&Oauth2KeyExists{tykMiddleware}, tykMiddleware)
} else if spec.APIDefinition.UseBasicAuth {
// Basic Auth
keyCheck = CreateMiddleware(&BasicAuthKeyIsValid{tykMiddleware}, tykMiddleware)
} else if spec.EnableSignatureChecking {
// HMAC Auth
keyCheck = CreateMiddleware(&HMACMiddleware{tykMiddleware}, tykMiddleware)
} else {
// Auth key
keyCheck = CreateMiddleware(&AuthKey{tykMiddleware}, tykMiddleware)
}
// Use CreateMiddleware(&ModifiedMiddleware{tykMiddleware}, tykMiddleware) to run custom middleware
chain := alice.New(
keyCheck,
CreateMiddleware(&KeyExpired{tykMiddleware}, tykMiddleware),
CreateMiddleware(&VersionCheck{tykMiddleware}, tykMiddleware),
CreateMiddleware(&AccessRightsCheck{tykMiddleware}, tykMiddleware),
CreateMiddleware(&RateLimitAndQuotaCheck{tykMiddleware}, tykMiddleware)).Then(proxyHandler)
Muxer.Handle(spec.Proxy.ListenPath, chain)
}
}
}
示例5: SetupWebsocket
func SetupWebsocket(mux *http.ServeMux) chan commons.Notification {
wsSlice = make([]*webSocketWrapper, 0)
conChan = make(chan *webSocketWrapper)
notifChan = make(chan commons.Notification)
go handleIncomingConnection()
mux.Handle("/websocket", websocket.Handler(webSocketHandler))
return notifChan
}
示例6: Register
func Register(mux *http.ServeMux) {
if mux == nil {
mux = http.DefaultServeMux
}
mux.HandleFunc("/webclock", index)
mux.Handle("/webclock/ws", websocket.Handler(handle))
log.Printf("registered webclock at /webclock and /webclock/ws")
}
示例7: Register
func Register(mux *http.ServeMux) {
if mux == nil {
mux = http.DefaultServeMux
}
mux.HandleFunc("/weechat", handleHome)
mux.HandleFunc("/weechat/buflines", handleLines)
mux.Handle("/weechat/ws", ws.Handler(handleWebsocket))
}
示例8: Register
func Register(mux *http.ServeMux) {
if mux == nil {
mux = http.DefaultServeMux
}
mux.HandleFunc("/irc", home)
mux.Handle("/irc/ws", websocket.Handler(connect))
log.Printf("registered irc at /irc and /irc/ws")
}
示例9: handlePathRedirects
func handlePathRedirects(mux *http.ServeMux, redirects map[string]string, prefix string) {
for source, target := range redirects {
h := Handler(prefix + target + "/")
p := prefix + source
mux.Handle(p, h)
mux.Handle(p+"/", h)
}
}
示例10: RegisterPublicDir
func (ah *apiHandler) RegisterPublicDir(mux *http.ServeMux) {
if ah.conf.PublicDir == "" {
return
}
fs := http.FileServer(http.Dir(ah.conf.PublicDir))
fs = prometheus.InstrumentHandler("frontend", fs)
prefix := ah.prefix("")
mux.Handle(prefix, http.StripPrefix(prefix, fs))
}
示例11: registerHandlers
// Serve all files in the current directory, or only a few select filetypes (html, css, js, png and txt)
func registerHandlers(mux *http.ServeMux, handlePath, servedir string, perm pinterface.IPermissions, luapool *lStatePool, cache *FileCache, addDomain bool) {
// Handle all requests with this function
allRequests := func(w http.ResponseWriter, req *http.Request) {
if perm.Rejected(w, req) {
// Get and call the Permission Denied function
perm.DenyFunction()(w, req)
// Reject the request by returning
return
}
// Local to this function
servedir := servedir
// Look for the directory that is named the same as the host
if addDomain {
servedir = filepath.Join(servedir, getDomain(req))
}
urlpath := req.URL.Path
filename := url2filename(servedir, urlpath)
// Remove the trailing slash from the filename, if any
noslash := filename
if strings.HasSuffix(filename, pathsep) {
noslash = filename[:len(filename)-1]
}
hasdir := fs.exists(filename) && fs.isDir(filename)
dirname := filename
hasfile := fs.exists(noslash)
// Set the server header.
serverHeaders(w)
// Share the directory or file
if hasdir {
dirPage(w, req, servedir, dirname, perm, luapool, cache)
return
} else if !hasdir && hasfile {
// Share a single file instead of a directory
filePage(w, req, noslash, perm, luapool, cache)
return
}
// Not found
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, noPage(filename))
}
// Handle requests differently depending on if rate limiting is enabled or not
if disableRateLimiting {
mux.HandleFunc(handlePath, allRequests)
} else {
limiter := tollbooth.NewLimiter(limitRequests, time.Second)
limiter.MessageContentType = "text/html; charset=utf-8"
limiter.Message = easyPage("Rate-limit exceeded", "<div style='color:red'>You have reached the maximum request limit.</div>")
mux.Handle(handlePath, tollbooth.LimitFuncHandler(limiter, allRequests))
}
}
示例12: registerPublicHandlers
func registerPublicHandlers(mux *http.ServeMux) {
mux.Handle(cmdHandler.pattern, &cmdHandler)
mux.Handle(pkgHandler.pattern, &pkgHandler)
mux.HandleFunc("/doc/codewalk/", codewalk)
mux.HandleFunc("/search", search)
mux.Handle("/robots.txt", fileServer)
mux.HandleFunc("/opensearch.xml", serveSearchDesc)
mux.HandleFunc("/", serveFile)
}
示例13: NewTHTTPServerFromMux
func NewTHTTPServerFromMux(
mux *http.ServeMux,
pattern string,
) (*THTTPServer, error) {
server := &THTTPServer{deliveries: make(chan *THTTPRequest)}
mux.Handle(pattern, &HTTPHandler{server})
return server, nil
}
示例14: AddDischargeHandler
// AddDischargeHandler adds handlers to the given
// ServeMux to serve third party caveat discharges
// using the given service.
//
// The handlers are added under the given rootPath,
// which must be non-empty.
//
// The check function is used to check whether a client making the given
// request should be allowed a discharge for the given caveat. If it
// does not return an error, the caveat will be discharged, with any
// returned caveats also added to the discharge macaroon.
// If it returns an error with a *Error cause, the error will be marshaled
// and sent back to the client.
//
// The name space served by DischargeHandler is as follows.
// All parameters can be provided either as URL attributes
// or form attributes. The result is always formatted as a JSON
// object.
//
// On failure, all endpoints return an error described by
// the Error type.
//
// POST /discharge
// params:
// id: id of macaroon to discharge
// location: location of original macaroon (optional (?))
// ?? flow=redirect|newwindow
// result on success (http.StatusOK):
// {
// Macaroon *macaroon.Macaroon
// }
//
// GET /publickey
// result:
// public key of service
// expiry time of key
func AddDischargeHandler(mux *http.ServeMux, rootPath string, svc *bakery.Service, checker func(req *http.Request, cavId, cav string) ([]checkers.Caveat, error)) {
d := &dischargeHandler{
svc: svc,
checker: checker,
}
mux.Handle(path.Join(rootPath, "discharge"), mkHandler(handleJSON(d.serveDischarge)))
// TODO(rog) is there a case for making public key caveat signing
// optional?
mux.Handle(path.Join(rootPath, "publickey"), mkHandler(handleJSON(d.servePublicKey)))
}
示例15: HandleHttp
// Configures the server to handler API requests to the default paths.
// If mux is not specified then http.DefaultServeMux is used.
func (ed *EndpointsServer) HandleHttp(mux *http.ServeMux) {
if mux == nil {
mux = http.DefaultServeMux
}
r := newRouter()
r.HandleFunc("/_ah/api/explorer", ed.HandleApiExplorerRequest)
r.HandleFunc("/_ah/api/static", ed.HandleApiStaticRequest)
r.HandleFunc("/_ah/api/", ed.ServeHTTP)
mux.Handle("/", r)
}