// RegisterHTTP init HTTPRouters for command
494435
func (cmd *Command) RegisterHTTP(ctxs ...*Context) error {
	clr := color.Color{}
	clr.Disable()
	if len(ctxs) > 0 {
		clr = ctxs[0].color
	}
	if cmd.routersMap == nil {
		cmd.routersMap = make(map[string]string)
	}
	commands := []*Command{cmd}
	for len(commands) > 0 {
		c := commands[0]
		commands = commands[1:]
		if c.HTTPRouters != nil {
			for _, r := range c.HTTPRouters {
				if _, exists := c.routersMap[r]; exists {
					return throwRouterRepeat(clr.Yellow(r))
				}
				cmd.routersMap[r] = c.Path()
			}
		}
		if c.nochild() {
			continue
		}
		commands = append(commands, c.children...)
	}
	return nil
}
671516
func AddHTTPMux(path string, callback interface{}) {
	ServerEngineInit.HTTPMuxList = append(ServerEngineInit.HTTPMuxList, ServerMux{PathPrefix: path, Callback: callback})
}
70301
func (a *Ace) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	a.httprouter.ServeHTTP(w, req)
}
1027
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	r.RLock()
	defer r.RUnlock()

	//wrap the response writer in our custom interface
	w := &responseWriter{writer: rw, Router: r}

	//find a matching Route
	for _, route := range r.routes {

		//if the methods don't match, skip this handler
		//i.e if request.Method is 'PUT' Route.Method must be 'PUT'
		if req.Method != route.method {
			continue
		}

		//check if Route pattern matches url
		if !route.regex.MatchString(req.URL.Path) {
			continue
		}

		//get submatches (params)
		matches := route.regex.FindStringSubmatch(req.URL.Path)

		//double check that the Route matches the URL pattern.
		if len(matches[0]) != len(req.URL.Path) {
			continue
		}

		//create the http.Requests context
		c := NewContext(req)

		//add url parameters to the context
		for i, match := range matches[1:] {
			c.Params.Set(route.params[i], match)
		}

		//execute middleware filters
		for _, filter := range r.filters {
			filter(w, req)
			if w.started { return }
		}

		//invoke the request handler
		route.handler(w, req)
		return
	}

	//if no matches to url, throw a not found exception
	if w.started == false {
		http.NotFound(w, req)
	}
}
109979
func (h configReloadHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if err := config.ReloadGlobalConfig(); err != nil {
		writeError(w, err)
	} else {
		writeData(w, "success!")
	}
}
176323
func (cmd *CreateAccountCommand) RegisterFlags(cc *cobra.Command, c *client.Client) {
	cc.Flags().StringVar(&cmd.Payload, "payload", "", "Request body encoded in JSON")
	cc.Flags().StringVar(&cmd.ContentType, "content", "", "Request content type override, e.g. 'application/x-www-form-urlencoded'")
}
588421
func (c *registerCommand) Init(args []string) error {
	if len(args) < 1 {
		return errors.New("registration data missing")
	}
	c.Arg, args = args[0], args[1:]
	if err := cmd.CheckEmpty(args); err != nil {
		return errors.Trace(err)
	}
	return nil
}
663992
func (rd Redirect) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	for _, rule := range rd.Rules {
		if (rule.FromPath == "/" || r.URL.Path == rule.FromPath) && schemeMatches(rule, r) && rule.Match(r) {
			to := httpserver.NewReplacer(r, nil, "").Replace(rule.To)
			if rule.Meta {
				safeTo := html.EscapeString(to)
				fmt.Fprintf(w, metaRedir, safeTo, safeTo)
			} else {
				http.Redirect(w, r, to, rule.Code)
			}
			return 0, nil
		}
	}
	return rd.Next.ServeHTTP(w, r)
}
491902
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.rootHandler.Handler(s).ServeHTTP(w, r)
}
792647
func (m *Manta) SetupHTTP(mux *httprouter.Router) {

	baseRoute := "/" + m.ServiceInstance.UserAccount
	mux.NotFound = ErrNotFound
	mux.MethodNotAllowed = ErrNotAllowed
	mux.RedirectFixedPath = true
	mux.RedirectTrailingSlash = true
	mux.HandleMethodNotAllowed = true

	// this particular route can't be handled by httprouter correctly due to its
	// handling of positional parameters but we can't just pass in ErrNotAllowed
	// either because it's the wrong type
	handleNotAllowed := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		w.WriteHeader(http.StatusMethodNotAllowed)
		w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
		w.Write([]byte("Method is not allowed"))
	}
	mux.POST(baseRoute+"/stor", handleNotAllowed)

	// storage APIs
	// PutSnapLink and PutMetaData have the same route spec as other routes
	// in this group, which isn't permitted by httprouter. We pick up the
	// correct path in the handler
	mux.PUT(baseRoute+"/stor/:dir", m.handler((*Manta).handleStorage))         // PutDirectory
	mux.GET(baseRoute+"/stor/:dir", m.handler((*Manta).handleStorage))         // ListDirectory
	mux.DELETE(baseRoute+"/stor/:dir", m.handler((*Manta).handleStorage))      // DeleteDirectory
	mux.PUT(baseRoute+"/stor/:dir/:obj", m.handler((*Manta).handleStorage))    // PutObject
	mux.GET(baseRoute+"/stor/:dir/:obj", m.handler((*Manta).handleStorage))    // GetObject
	mux.DELETE(baseRoute+"/stor/:dir/:obj", m.handler((*Manta).handleStorage)) // DeleteObject

	// job APIs
	mux.POST(baseRoute+"/jobs", m.handler((*Manta).handleJobs))                 // CreateJob
	mux.POST(baseRoute+"/jobs/:id/live/in", m.handler((*Manta).handleJobs))     // AddJobInputs
	mux.POST(baseRoute+"/jobs/:id/live/in/end", m.handler((*Manta).handleJobs)) // EndJobInput
	mux.POST(baseRoute+"/jobs/:id/live/cancel", m.handler((*Manta).handleJobs)) // CancelJob
	mux.GET(baseRoute+"/jobs", m.handler((*Manta).handleJobs))                  // ListJobs
	mux.GET(baseRoute+"/jobs/:id/live/status", m.handler((*Manta).handleJobs))  // GetJob
	mux.GET(baseRoute+"/jobs/:id/live/out", m.handler((*Manta).handleJobs))     // GetJobOutput
	mux.GET(baseRoute+"/jobs/:id/live/in", m.handler((*Manta).handleJobs))      // GetJobInput
	mux.GET(baseRoute+"/jobs/:id/live/fail", m.handler((*Manta).handleJobs))    // GetJobFailures
	mux.GET(baseRoute+"/jobs/:id/live/err", m.handler((*Manta).handleJobs))     // GetJobErrors
}
39451
func registerWebRouter(router *mux.Router) error {
	// Initialize Web.
	web := &webAPIHandlers{
		ObjectAPI: newObjectLayerFn,
		CacheAPI:  newCacheObjectsFn,
	}

	// Initialize a new json2 codec.
	codec := json2.NewCodec()

	// MinIO browser router.
	webBrowserRouter := router.PathPrefix(minioReservedBucketPath).Subrouter()

	// Initialize json rpc handlers.
	webRPC := jsonrpc.NewServer()
	webRPC.RegisterCodec(codec, "application/json")
	webRPC.RegisterCodec(codec, "application/json; charset=UTF-8")

	// Register RPC handlers with server
	if err := webRPC.RegisterService(web, "Web"); err != nil {
		return err
	}

	// RPC handler at URI - /minio/webrpc
	webBrowserRouter.Methods("POST").Path("/webrpc").Handler(webRPC)
	webBrowserRouter.Methods("PUT").Path("/upload/{bucket}/{object:.+}").HandlerFunc(httpTraceHdrs(web.Upload))

	// These methods use short-expiry tokens in the URLs. These tokens may unintentionally
	// be logged, so a new one must be generated for each request.
	webBrowserRouter.Methods("GET").Path("/download/{bucket}/{object:.+}").Queries("token", "{token:.*}").HandlerFunc(httpTraceHdrs(web.Download))
	webBrowserRouter.Methods("POST").Path("/zip").Queries("token", "{token:.*}").HandlerFunc(httpTraceHdrs(web.DownloadZip))

	// Create compressed assets handler
	compressAssets := handlers.CompressHandler(http.StripPrefix(minioReservedBucketPath, http.FileServer(assetFS())))

	// Serve javascript files and favicon from assets.
	webBrowserRouter.Path(fmt.Sprintf("/{assets:%s}", specialAssets)).Handler(compressAssets)

	// Serve index.html from assets for rest of the requests.
	webBrowserRouter.Path("/{index:.*}").Handler(indexHandler{compressAssets})

	return nil
}
1009278
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h, err := m.router.Route(r)
	if err != nil || h == nil {
		m.notFound.ServeHTTP(w, r)
		return
	}
	h.(http.Handler).ServeHTTP(w, r)
}
981109
func (ro *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rd := ro.pickupBestRouteDefinition(r)

	if rd == nil {
		http.NotFound(w, r)
		return
	}

	ctx := getDefaultContext(r)

	match, params := rd.PathTemplate.Match(encodedPathFromRequest(r))
	if !match {
		http.Error(w, "[ucon] invalid handler picked", http.StatusInternalServerError)
		return
	}
	ctx = context.WithValue(ctx, PathParameterKey, params)

	b, err := ro.mux.newBubble(ctx, w, r, rd)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = b.Next()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
794855
func (h *registerUserHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		err := sendError(w, errors.MethodNotAllowedf("unsupported method: %q", req.Method))
		if err != nil {
			logger.Errorf("%v", err)
		}
		return
	}
	st, err := h.ctxt.stateForRequestUnauthenticated(req)
	if err != nil {
		if err := sendError(w, err); err != nil {
			logger.Errorf("%v", err)
		}
		return
	}
	defer st.Release()
	userTag, response, err := h.processPost(req, st.State)
	if err != nil {
		if err := sendError(w, err); err != nil {
			logger.Errorf("%v", err)
		}
		return
	}

	// Set a short-lived macaroon as a cookie on the response,
	// which the client can use to obtain a discharge macaroon.
	m, err := h.ctxt.srv.authenticator.CreateLocalLoginMacaroon(userTag)
	if err != nil {
		if err := sendError(w, err); err != nil {
			logger.Errorf("%v", err)
		}
		return
	}
	cookie, err := httpbakery.NewCookie(macaroon.Slice{m})
	if err != nil {
		if err := sendError(w, err); err != nil {
			logger.Errorf("%v", err)
		}
		return
	}
	http.SetCookie(w, cookie)

	if err := sendStatusAndJSON(w, http.StatusOK, response); err != nil {
		logger.Errorf("%v", err)
	}
}
474247
func (c *RegisterCmd) Init(args []string) error {
	if len(args) < 3 {
		return errors.Errorf("missing required arguments")
	}
	c.typ = args[0]
	c.class = args[1]
	c.id = args[2]
	c.labels = args[3:]
	return nil
}
864334
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s := Server{Handler: h, Handshake: checkOrigin}
	s.serveWebSocket(w, req)
}
1128984
func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Recover from panic
	defer func() {
		if panicked := recover(); panicked != nil {
			// Generate a stack trace
			buf := make([]byte, 1<<16)

			// Set false to dump only this goroutine
			l := runtime.Stack(buf, false)
			log.Printf("%s\n\n%s", panicked, buf[:l])

			// TODO Only display an error in DEBUG
			http.Error(w, fmt.Sprintf("%s", panicked), 500)
		}
	}()

	// Build a new request and attach a user - if there is no valid user
	// the request.User will be an auth.AnonUser
	request := NewRequest(req, router.auth)

	// Record if a handler ran, so if false, a 404 page can be served
	var ranHandler bool
	var err error

	// Determine routes
	if root := router.trees[Method(req.Method)]; root != nil {
		path := req.URL.Path

		if h, ps, tsr := root.getValue(path); h != nil {
			// Add the parameters to the request
			request.Params = ps

			err = h(w, request)
			ranHandler = true
		} else if req.Method != "CONNECT" && path != "/" {
			code := 301 // Permanent redirect, request with GET method
			if req.Method != string(GET) {
				// Temporary redirect, request with same method
				// As of Go 1.3, Go does not support status code 308.
				code = 307
			}

			if tsr && router.RedirectTrailingSlash {
				if path[len(path)-1] == '/' {
					req.URL.Path = path[:len(path)-1]
				} else {
					req.URL.Path = path + "/"
				}
				http.Redirect(w, req, req.URL.String(), code)
				return
			}

			// Try to fix the request path
			if router.RedirectFixedPath {
				fixedPath, found := root.findCaseInsensitivePath(
					CleanPath(path),
					router.RedirectTrailingSlash,
				)
				if found {
					req.URL.Path = string(fixedPath)
					http.Redirect(w, req, req.URL.String(), code)
					return
				}
			}
		}
	}

	// Handle any other user errors
	// TODO Other codes?
	if err != nil {
		http.Error(w, err.Error(), 400)
		return
	}

	if ranHandler {
		return
	}
	http.NotFound(w, req)
}