示例#1
0
文件: provider.go 项目: bentranter/id
// HTTPRouterCallback is the thing as `Callback` but for
// Julien Schmidt's HttpRouter
func HTTPRouterCallback(p Provider, redirectURL string) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		code := p.GetCodeURL(r)
		tok, err := p.GetToken(code)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		user, err := p.GetIdentity(tok)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		cookie, err := GenToken(user)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		http.SetCookie(w, cookie)

		http.Redirect(w, r, "http://localhost:3000/"+redirectURL, http.StatusFound)
	})
}
func HttpAdapter(next http.Handler) httprouter.Handle {
	return httprouter.Handle(
		func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
			ctx := Get(req)
			ctx.Params = ps
			next.ServeHTTP(w, req)
		})
}
示例#3
0
// InjectParamsToContext extend existing context with Paramer implementation based on httprouter.Params object.
func InjectParamsToContext(handler *rest.Server) httprouter.Handle {
	return httprouter.Handle(func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
		handler.Context = rest.NewParamerContext(handler.Context, &httpRouterParamer{
			params: p,
		})

		handler.ServeHTTP(rw, r)
	})
}
示例#4
0
文件: httprouter.go 项目: pilwon/gogo
func wrapHandler(c context.Context, h middleware.Handler) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		params := gogocontext.Params{}
		for _, param := range p {
			params[param.Key] = param.Value
		}
		c = gogocontext.ParamsWithContext(c, params)
		h.ServeHTTP(c, w, r)
	})
}
示例#5
0
func Adapt(handler http.Handler) httprouter.Handle {

	return httprouter.Handle(
		func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
			ctx := &Context{
				Params: params,
			}
			gorillaContext.Set(r, keyContext, ctx)

			handler.ServeHTTP(w, r)
		})
}
示例#6
0
文件: httprouter.go 项目: wlMalk/gapi
func getHandle(h middleware.Handler) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		req := request.New(r)
		res := response.New(w)
		params := map[string]string{}
		for _, p := range ps {
			params[p.Key] = p.Value
		}
		req.Attributes.Set(wrapper.PathParamsKey, params)
		h.ServeHTTP(res, req)
	})
}
示例#7
0
// wrapToHandle wraps ContextHandlers to the httprouter.Handle type using a
// function closure which passes httprouter.Params as Context.Values to the
// registered ContextHandlers
func (s *ContextRouter) wrapToHandle(handler ContextHandler) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		// readlock to prevent the context from being changed by when a request is in flight
		s.RLock()
		c := s.context
		for _, p := range params {
			c = context.WithValue(c, p.Key, p.Value)
		}
		handler.ServeHTTP(c, w, req)
		s.RUnlock()
	})
}
示例#8
0
func sampleRoutes() []mockserver.Route {
	first := mockserver.Route{
		Method: "GET",
		Path:   "/hello/world",
		Handle: httprouter.Handle(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
			w.WriteHeader(200)
			w.Header().Set("Content-Type", "plain/text")
			fmt.Fprint(w, "Hello world")
		}),
	}
	second := mockserver.Route{
		Method: "POST",
		Path:   "/welcome/:name",
		Handle: httprouter.Handle(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
			w.WriteHeader(200)
			w.Header().Set("Content-Type", "plain/text")
			fmt.Fprint(w, "Welcome ", p.ByName("name"))
		}),
	}
	return []mockserver.Route{first, second}
}
示例#9
0
// Handle is our middleware handler. It executes each function passed through
// it.
func (a *App) Handle(handlers ...Handler) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		for _, handler := range handlers {
			err := handler(a, w, r, ps)
			if err != nil {
				// Should we redirect to the error handler based on the type of
				// error thrown here?
				return
			}
		}
	})
}
示例#10
0
文件: wctx.go 项目: orian/wctx
func (r *Router) wrap(h HandleFunc) httprouter.Handle {
	// builds wrapper
	for i := len(r.m) - 1; i >= 0; i-- {
		h = r.m[i](h)
	}
	return httprouter.Handle(func(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
		ctx := r.ContextFactory(req)
		if p != nil {
			ctx = context.WithValue(ctx, &paramsKey, p)
		}
		h(ctx, w, req)
	})
}
示例#11
0
//Handle is a helper function for providing generic error handling for any controllers
//that choose to wrap their actions with it.
func (c *baseController) handle(a action) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		err := a(w, r, ps)
		if err != nil {
			switch e := err.(type) {
			// This refers to controllers.Error
			case Error:
				// We can retrieve the status here and write out a specific
				// HTTP status code.
				log.Debugf("HTTP %d - %s", e.Status(), e)
				http.Error(w, e.Error(), e.Status())
			default:
				// Any error types we don't specifically look out for default
				// to serving a HTTP 500
				http.Error(w, http.StatusText(http.StatusInternalServerError),
					http.StatusInternalServerError)
			}
		}
	})
}
示例#12
0
// AuthenticatedRoute protects the route.
func AuthenticatedRoute(next httprouterHandler) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		cookie, err := r.Cookie(cookieName)
		if err != nil {
			// If there isn't a cookie, send the user to the sign in page. We
			// should probably tell the user that they must be signed in to
			// view anything under /admin.
			http.Redirect(w, r, "/admin/login", http.StatusFound)
			return
		}
		err = verifyToken(cookie.Value)
		if err != nil {
			// If the token can't be verified, then redirect them to the sign
			// in page. In the future, we should show a message that informs
			// the user that tokens are invalidated between server restarts,
			// since that's what typically causes the error.
			http.Redirect(w, r, "/admin/login", http.StatusFound)
			return
		}
		next(w, r, ps)
	})
}
示例#13
0
func Logger(inner httprouter.Handle, name string) httprouter.Handle {
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		log.Printf(
			"Start to handle : %s\t%s\t%s\t",
			r.Method,
			r.RequestURI,
			name,
		)
		start := time.Now()
		//time.Sleep(time.Millisecond * 1000)

		inner(w, r, ps)

		log.Printf(
			"%s\t%s\t%s\t%s",
			r.Method,
			r.RequestURI,
			name,
			time.Since(start),
		)
	})
}
示例#14
0
文件: action.go 项目: snikch/api
// HTTPHandler takes an ActionHandler and returns a http.Handler instance
// that can be used. The type and action are used to determine the context in
// several areas, such as transformers and metrics.
func (p *ActionProcessor) HTTPHandler(typ, action string, handler ActionHandler) httprouter.Handle {
	// Create a new timer for timing this handler.
	timer := metrics.NewTimer()
	p.MetricsRegistry.Register(typ+"-"+action, timer)
	sideloadTimer := metrics.NewTimer()
	p.MetricsRegistry.Register(typ+"-"+action+"-sideload", sideloadTimer)
	unlockTimer := metrics.NewTimer()
	p.MetricsRegistry.Register(typ+"-"+action+"-unlock", unlockTimer)

	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
		// At the end of this function, add a time metric.
		defer timer.UpdateSince(time.Now())

		// Create a new context for this action.
		context := ctx.NewContext()
		context.Request = r
		context.EntityType = typ
		SetContextParams(context, params)

		// Get any criteria, and transform it if required.
		criteria := RequestCriteria(r)
		for _, transformer := range requestCriteriaTransformers {
			transformer(context, criteria)
		}
		// Make the criteria available on the content.
		SetContextCriteria(context, criteria)

		// Get the base payload back from the ActionHandler instance.
		payload, code, err := handler.HandleAction(context)
		if err != nil {
			RespondWithError(w, r, err)
			return
		}

		// If an empty response is required, return an empty response.
		if payload == EmptyResponse {
			RespondWithStatusCode(w, r, code)
			return
		}

		// Build up a response.
		response := Response{
			Payload: payload,
		}

		if p.SideloadEnabled {
			start := time.Now()
			// Retrieve any sideloaded entities.
			sideloaded, err := sideload.Load(context, payload, criteria.Sideload)

			response.Sideload = &sideloaded
			if err != nil {
				timer.UpdateSince(start)
				RespondWithError(w, r, err)
				return
			}
			timer.UpdateSince(start)
		}

		// Unlock any entities registered for this request.
		unlockStartTime := time.Now()
		err = lynx.ContextStore(context).Unlock()
		unlockTimer.UpdateSince(unlockStartTime)

		if err != nil {
			RespondWithError(w, r, err)
			return
		}

		RespondWithData(w, r, response, code)
	})
}
示例#15
0
文件: provider.go 项目: bentranter/id
// HTTPRouterAuthorize is the same thing as the regular
// `Authorize`, but for Julien Schmidt's HttpRouter.
//
// This should be moved into it's own package.
func HTTPRouterAuthorize(p Provider) httprouter.Handle {
	url := p.BuildAuthURL("state")
	return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	})
}
示例#16
0
func (srv *Server) wire() {
	if srv.wired {
		return
	}
	// Build HTTP server.
	if srv.Server == nil {
		srv.Server = &http.Server{
			Addr:         srv.Addr,
			ReadTimeout:  srv.ReadTimeout,
			WriteTimeout: srv.WriteTimeout,
		}
	}
	if srv.Addr != "" {
		srv.Server.Addr = srv.Addr
	}
	if srv.ReadTimeout != 0 {
		srv.Server.ReadTimeout = srv.ReadTimeout
	}
	if srv.WriteTimeout != 0 {
		srv.Server.WriteTimeout = srv.WriteTimeout
	}
	if srv.Server.ReadTimeout == 0 {
		srv.Server.ReadTimeout = 30 * time.Second
	}
	if srv.Server.WriteTimeout == 0 {
		srv.Server.WriteTimeout = 30 * time.Second
	}
	// Build REST service routing.
	srv.router = httprouter.New()
	srv.router.RedirectTrailingSlash = true
	srv.router.HandleMethodNotAllowed = true
	srv.router.RedirectFixedPath = true
	srv.router.NotFound = http.HandlerFunc(srv.notFound)
	srv.router.MethodNotAllowed = http.HandlerFunc(srv.methodNotAllowed)
	srv.router.PanicHandler = srv.panicHandler
	if srv.HomeURL != "" {
		srv.router.GET("/", func(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
			http.Redirect(w, req, srv.HomeURL, 307)
		})
	}
	for version, routes := range srv.Routes {
		for _, route := range routes {
			path := "/" + version + route.Path
			register := srv.routerFunc(route.Method)
			// Register HTTP handler.
			switch handler := route.Handler.(type) {
			case http.HandlerFunc:
				register(path, handle(handler))
				continue
			case func(http.ResponseWriter, *http.Request):
				register(path, handle(http.HandlerFunc(handler)))
				continue
			case httprouter.Handle:
				register(path, handler)
				continue
			case func(http.ResponseWriter, *http.Request, httprouter.Params):
				register(path, httprouter.Handle(handler))
				continue
			}
			// Register RPC service handler.
			var handler httprouter.Handle
			switch srv.detectType(route.Handler) {
			case serviceHTTP:
				register(path, srv.buildServiceHTTP(route.Handler))
				continue
			case serviceHTTPParam:
				register(path, srv.buildServiceHTTPParam(route.Handler))
				continue
			case serviceRPC:
				handler = srv.buildServiceHandler(route.Handler)
				if route.DanglingParam != "" {
					handler = srv.strippingHandler(handler, route.DanglingParam)
					register(path, handler)
					continue
				}
				register(path, handler)
				register(path+".json", handler)
			default:
				panic(fmt.Sprintf("unsupported handler type: %T", route.Handler))
			}
		}
	}
	srv.Server.Handler = http.HandlerFunc(srv.serveHTTP)
	srv.wired = true
	return
}