Exemple #1
2
func getArticle(w http.ResponseWriter, r *http.Request) {
	// Load article.
	if chi.URLParam(r, "articleID") != "1" {
		render.Respond(w, r, data.ErrNotFound)
		return
	}
	article := &data.Article{
		ID:    1,
		Title: "Article #1",
		Data:  []string{"one", "two", "three", "four"},
		CustomDataForAuthUsers: "secret data for auth'd users only",
	}

	// Simulate some context values:
	// 1. ?auth=true simluates authenticated session/user.
	// 2. ?error=true simulates random error.
	if r.URL.Query().Get("auth") != "" {
		r = r.WithContext(context.WithValue(r.Context(), "auth", true))
	}
	if r.URL.Query().Get("error") != "" {
		render.Respond(w, r, errors.New("error"))
		return
	}

	render.Respond(w, r, article)
}
Exemple #2
0
func (s *Server) v1DataPatch(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	vars := mux.Vars(r)

	ops := []patchV1{}
	if err := util.NewJSONDecoder(r.Body).Decode(&ops); err != nil {
		handleError(w, 400, err)
		return
	}

	txn, err := s.store.NewTransaction(ctx)
	if err != nil {
		handleErrorAuto(w, err)
		return
	}

	defer s.store.Close(ctx, txn)

	patches, err := s.prepareV1PatchSlice(vars["path"], ops)
	if err != nil {
		handleErrorAuto(w, err)
		return
	}

	for _, patch := range patches {
		if err := s.store.Write(ctx, txn, patch.op, patch.path, patch.value); err != nil {
			handleErrorAuto(w, err)
			return
		}
	}

	handleResponse(w, 204, nil)
}
Exemple #3
0
// HTML writes a string to the response, setting the Content-Type as text/html.
func HTML(w http.ResponseWriter, r *http.Request, v string) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if status, ok := r.Context().Value(statusCtxKey).(int); ok {
		w.WriteHeader(status)
	}
	w.Write([]byte(v))
}
Exemple #4
0
// Data writes raw bytes to the response, setting the Content-Type as
// application/octet-stream.
func Data(w http.ResponseWriter, r *http.Request, v []byte) {
	w.Header().Set("Content-Type", "application/octet-stream")
	if status, ok := r.Context().Value(statusCtxKey).(int); ok {
		w.WriteHeader(status)
	}
	w.Write(v)
}
Exemple #5
0
// channelIntoSlice buffers channel data into a slice.
func channelIntoSlice(w http.ResponseWriter, r *http.Request, from interface{}) interface{} {
	ctx := r.Context()

	var to []interface{}
	for {
		switch chosen, recv, ok := reflect.Select([]reflect.SelectCase{
			{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())},
			{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(from)},
		}); chosen {
		case 0: // equivalent to: case <-ctx.Done()
			http.Error(w, "Server Timeout", 504)
			return nil

		default: // equivalent to: case v, ok := <-stream
			if !ok {
				return to
			}
			v := recv.Interface()

			// Present each channel item.
			if presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {
				r, v = presenter.Present(r, v)
			}

			to = append(to, v)
		}
	}
}
Exemple #6
0
// Respond handles streaming JSON and XML responses, automatically setting the
// Content-Type based on request headers. It will default to a JSON response.
func Respond(w http.ResponseWriter, r *http.Request, v interface{}) {
	// Present the object.
	if presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {
		r, v = presenter.Present(r, v)
	}

	switch reflect.TypeOf(v).Kind() {
	case reflect.Chan:
		switch getResponseContentType(r) {
		case ContentTypeEventStream:
			channelEventStream(w, r, v)
			return
		default:
			v = channelIntoSlice(w, r, v)
		}
	}

	// Format data based on Content-Type.
	switch getResponseContentType(r) {
	case ContentTypeJSON:
		JSON(w, r, v)
	case ContentTypeXML:
		XML(w, r, v)
	default:
		JSON(w, r, v)
	}
}
Exemple #7
0
// ServeHTTP is the primary throttler request handler
func (t *throttler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	select {
	case <-ctx.Done():
		http.Error(w, errContextCanceled, http.StatusServiceUnavailable)
		return
	case btok := <-t.backlogTokens:
		timer := time.NewTimer(t.backlogTimeout)

		defer func() {
			t.backlogTokens <- btok
		}()

		select {
		case <-timer.C:
			http.Error(w, errTimedOut, http.StatusServiceUnavailable)
			return
		case <-ctx.Done():
			http.Error(w, errContextCanceled, http.StatusServiceUnavailable)
			return
		case tok := <-t.tokens:
			defer func() {
				t.tokens <- tok
			}()
			t.h.ServeHTTP(w, r)
		}
		return
	default:
		http.Error(w, errCapacityExceeded, http.StatusServiceUnavailable)
		return
	}
}
Exemple #8
0
//GetPaginationProp returns an instance of pagination.Prop from the request context.
//However, if it's not available, returns one with default value
func GetPaginationProp(r *http.Request) *pagination.Props {
	prop, ok := r.Context().Value(pagination.ContextKeyPagination).(*pagination.Props)
	if ok {
		return prop
	}
	return &pagination.Props{Entries: pagination.DefaultEntries, Current: 1}
}
Exemple #9
0
func (t *Transport) user(req *http.Request) *User {
	if t.UserFunc != nil {
		return t.UserFunc(req)
	}
	user, _ := req.Context().Value(UserContextKey).(*User)
	return user
}
Exemple #10
0
func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
	entry := &StructuredLoggerEntry{logger: logrus.NewEntry(l.logger)}
	logFields := logrus.Fields{}

	logFields["ts"] = time.Now().UTC().Format(time.RFC1123)

	if reqID := middleware.GetReqID(r.Context()); reqID != "" {
		logFields["req_id"] = reqID
	}

	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}
	logFields["http_scheme"] = scheme
	logFields["http_proto"] = r.Proto
	logFields["http_method"] = r.Method

	logFields["remote_addr"] = r.RemoteAddr
	logFields["user_agent"] = r.UserAgent()

	logFields["uri"] = fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)

	entry.logger = entry.logger.WithFields(logFields)

	entry.logger.Infoln("request started")

	return entry
}
Exemple #11
0
func (s *Server) v1PoliciesGet(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	vars := mux.Vars(r)
	id := vars["id"]

	txn, err := s.store.NewTransaction(ctx)
	if err != nil {
		handleErrorAuto(w, err)
		return
	}

	defer s.store.Close(ctx, txn)

	_, _, err = s.store.GetPolicy(txn, id)
	if err != nil {
		handleErrorAuto(w, err)
		return
	}

	c := s.Compiler()

	policy := &policyV1{
		ID:     id,
		Module: c.Modules[id],
	}

	handleResponseJSON(w, 200, policy, true)
}
Exemple #12
0
// routeHTTP routes a http.Request through the Mux routing tree to serve
// the matching handler for a particular http method.
func (mx *Mux) routeHTTP(w http.ResponseWriter, r *http.Request) {
	// Grab the route context object
	rctx := r.Context().Value(RouteCtxKey).(*Context)

	// The request routing path
	routePath := rctx.RoutePath
	if routePath == "" {
		routePath = r.URL.Path
	}

	// Check if method is supported by chi
	method, ok := methodMap[r.Method]
	if !ok {
		mx.MethodNotAllowedHandler().ServeHTTP(w, r)
		return
	}

	// Find the route
	hs := mx.tree.FindRoute(rctx, routePath)
	if hs == nil {
		mx.NotFoundHandler().ServeHTTP(w, r)
		return
	}

	h, ok := hs[method]
	if !ok {
		mx.MethodNotAllowedHandler().ServeHTTP(w, r)
		return
	}

	// Serve it up
	h.ServeHTTP(w, r)
}
Exemple #13
0
func Set(r *http.Request, key, val interface{}) *http.Request {
	if val == nil {
		return r
	}

	return r.WithContext(context.WithValue(r.Context(), key, val))
}
Exemple #14
0
func (h serviceBrokerHandler) catalog(w http.ResponseWriter, req *http.Request) {
	catalog := CatalogResponse{
		Services: h.serviceBroker.Services(req.Context()),
	}

	h.respond(w, http.StatusOK, catalog)
}
func (s *CacheHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	var uid string

	if session, ok := SessionFromContext(req.Context()); ok {
		uid = session.Token.UidString()
	} else {
		sendRequestProblem(w, req, http.StatusBadRequest, errors.New("CacheHandler no UID"))
		return
	}

	if req.Method == "GET" && infoCollectionsRoute.MatchString(req.URL.Path) { // info/collections
		s.infoCollection(uid, w, req)
	} else if req.Method == "GET" && infoConfigurationRoute.MatchString(req.URL.Path) { // info/configuration
		s.infoConfiguration(uid, w, req)
	} else {
		// clear the cache for the  user
		if req.Method == "POST" || req.Method == "PUT" || req.Method == "DELETE" {
			if log.GetLevel() == log.DebugLevel {
				log.WithFields(log.Fields{
					"uid": uid,
				}).Debug("CacheHandler clear")
			}
			s.cache.Set(uid, nil)
		}
		s.handler.ServeHTTP(w, req)
		return
	}
}
Exemple #16
0
Fichier : og.go Projet : daaku/rell
// Handles /rog-redirect/ requests.
func (h *Handler) Redirect(w http.ResponseWriter, r *http.Request) error {
	ctx := r.Context()
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 5 {
		return fmt.Errorf("Invalid URL: %s", r.URL.Path)
	}
	status, err := strconv.Atoi(parts[2])
	if err != nil || (status != 301 && status != 302) {
		return fmt.Errorf("Invalid status: %s", parts[2])
	}
	count, err := strconv.Atoi(parts[3])
	if err != nil {
		return fmt.Errorf("Invalid count: %s", parts[3])
	}
	context, err := rellenv.FromContext(ctx)
	if err != nil {
		return err
	}
	if count == 0 {
		http.Redirect(w, r, context.AbsoluteURL("/rog/"+parts[4]).String(), status)
	} else {
		count--
		url := context.AbsoluteURL(fmt.Sprintf(
			"/rog-redirect/%d/%d/%s", status, count, parts[4]))
		http.Redirect(w, r, url.String(), status)
	}
	return nil
}
Exemple #17
0
func (l *defaultLogFormatter) NewLogEntry(r *http.Request) LogEntry {
	entry := &defaultLogEntry{
		defaultLogFormatter: l,
		request:             r,
		buf:                 &bytes.Buffer{},
	}

	reqID := GetReqID(r.Context())
	if reqID != "" {
		cW(entry.buf, nYellow, "[%s] ", reqID)
	}
	cW(entry.buf, nCyan, "\"")
	cW(entry.buf, bMagenta, "%s ", r.Method)

	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}
	cW(entry.buf, nCyan, "%s://%s%s %s\" ", scheme, r.Host, r.RequestURI, r.Proto)

	entry.buf.WriteString("from ")
	entry.buf.WriteString(r.RemoteAddr)
	entry.buf.WriteString(" - ")

	return entry
}
Exemple #18
0
func (rt *router) route(r *http.Request) *http.Request {
	tn := &rt.wildcard
	if tn2, ok := rt.methods[r.Method]; ok {
		tn = tn2
	}

	ctx := r.Context()
	path := ctx.Value(internal.Path).(string)
	for path != "" {
		i := sort.Search(len(tn.children), func(i int) bool {
			return path[0] <= tn.children[i].prefix[0]
		})
		if i == len(tn.children) || !strings.HasPrefix(path, tn.children[i].prefix) {
			break
		}

		path = path[len(tn.children[i].prefix):]
		tn = tn.children[i].node
	}
	for _, i := range tn.routes {
		if r2 := rt.routes[i].Match(r); r2 != nil {
			return r2.WithContext(&match{
				Context: r2.Context(),
				p:       rt.routes[i].Pattern,
				h:       rt.routes[i].Handler,
			})
		}
	}
	return r.WithContext(&match{Context: ctx})
}
Exemple #19
0
func (lb *BackendLoadBalancer) DoWithLoadBalancer(req *http.Request, useTLS bool) (*http.Response, error) {
	connectString, err := lb.LoadBalancer.GetConnectAddress()
	if err != nil {
		return nil, err
	}

	log.Debug("connect string is ", connectString)
	req.URL.Host = connectString
	req.Host = connectString

	var transport *http.Transport
	if useTLS == true {
		log.Debug("Configuring TLS transport")
		transport = lb.httpsTransport
		req.URL.Scheme = "https"
	} else {
		log.Debug("Configuring non-TLS transport")
		transport = lb.httpTransport
		req.URL.Scheme = "http"
	}

	client := &http.Client{
		Transport: transport,
	}

	req.RequestURI = "" //Must clear when using http.Client
	return ctxhttp.Do(req.Context(), client, req)
}
Exemple #20
0
// GetTimer will retreive the timer from the given http request's context.
// If the request has not been wrapped by a ContextHandler, nil will be returned.
func GetTimer(r *http.Request) Timer {
	val := r.Context().Value(contextKey)
	if val == nil {
		return nil
	}
	return val.(*Profile)
}
Exemple #21
0
func jsonCertFromID(w http.ResponseWriter, r *http.Request, id int64) {
	val := r.Context().Value(dbKey)
	if val == nil {
		httpError(w, http.StatusInternalServerError, "Could not find database handler in request context")
		return
	}
	db := val.(*pg.DB)
	cert, err := db.GetCertByID(id)
	if err != nil {
		httpError(w, http.StatusInternalServerError,
			fmt.Sprintf("Could not retrieved stored certificate from database: %v", err))
		return
	}

	certJson, err := json.Marshal(cert)
	if err != nil {
		httpError(w, http.StatusInternalServerError,
			fmt.Sprintf("Could not convert certificate to JSON: %v", err))
		return
	}
	switch r.Method {
	case "GET":
		w.WriteHeader(http.StatusOK)
		logRequest(r, http.StatusOK, len(certJson))
	case "POST":
		w.WriteHeader(http.StatusCreated)
		logRequest(r, http.StatusCreated, len(certJson))
	}
	w.Write(certJson)
}
Exemple #22
0
// An optional, optimized presenter for channnel of Articles.
// If not defined, each item will be preseted using ArticleToV3() func.
func ArticleChanToV3Chan(r *http.Request, fromChan chan *data.Article) (chan *Article, error) {
	log.Printf("channel presenter!")

	rand.Seed(time.Now().Unix())

	toChan := make(chan *Article, 5)
	go func() {
		for from := range fromChan {
			to := &Article{
				Article:    from,
				ViewsCount: rand.Int63n(100000),
				URL:        fmt.Sprintf("http://localhost:3333/v3/?id=%v", from.ID),
				APIVersion: "v3",
			}
			// Only show to auth'd user.
			if _, ok := r.Context().Value("auth").(bool); ok {
				to.CustomDataForAuthUsers = from.CustomDataForAuthUsers
			}

			toChan <- to
		}
		close(toChan)
	}()

	return toChan, nil
}
Exemple #23
0
func (h serviceBrokerHandler) unbind(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	instanceID := vars["instance_id"]
	bindingID := vars["binding_id"]

	logger := h.logger.Session(unbindLogKey, lager.Data{
		instanceIDLogKey: instanceID,
		bindingIDLogKey:  bindingID,
	})

	details := UnbindDetails{
		PlanID:    req.FormValue("plan_id"),
		ServiceID: req.FormValue("service_id"),
	}

	if err := h.serviceBroker.Unbind(req.Context(), instanceID, bindingID, details); err != nil {
		switch err {
		case ErrInstanceDoesNotExist:
			logger.Error(instanceMissingErrorKey, err)
			h.respond(w, http.StatusGone, EmptyResponse{})
		case ErrBindingDoesNotExist:
			logger.Error(bindingMissingErrorKey, err)
			h.respond(w, http.StatusGone, EmptyResponse{})
		default:
			logger.Error(unknownErrorKey, err)
			h.respond(w, http.StatusInternalServerError, ErrorResponse{
				Description: err.Error(),
			})
		}
		return
	}

	h.respond(w, http.StatusOK, EmptyResponse{})
}
Exemple #24
0
func setContext(r *http.Request, key, val interface{}) {
	if val == nil {
		return
	}

	r2 := r.WithContext(context.WithValue(r.Context(), key, val))
	*r = *r2
}
Exemple #25
0
func (s *statusServer) handleVars(w http.ResponseWriter, r *http.Request) {
	w.Header().Set(httputil.ContentTypeHeader, httputil.PlaintextContentType)
	err := s.metricSource.PrintAsText(w)
	if err != nil {
		log.Error(r.Context(), err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Exemple #26
0
func handleAStuff(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("a stuff"))

	val, ok := r.Context().Value(testCtxKey).(string)
	if ok {
		w.Write([]byte(val))
	}
}
Exemple #27
0
func contextGet(r *http.Request, key string) (interface{}, error) {
	val := r.Context().Value(key)
	if val == nil {
		return nil, errors.Errorf("no value exists in the context for key %q", key)
	}

	return val, nil
}
// only viewable if the client has a valid token
func protectedProfile(res http.ResponseWriter, req *http.Request) {
	claims, ok := req.Context().Value(MyKey).(Claims)
	if !ok {
		http.NotFound(res, req)
		return
	}

	fmt.Fprintf(res, "Hello %s", claims.Username)
}
Exemple #29
0
func newRun(w http.ResponseWriter, r *http.Request, handler []http.Handler) *Run {
	run := &Run{
		rWriter: w,
		handler: handler,
	}

	run.request = r.WithContext(context.WithValue(r.Context(), ctxRun, run))
	return run
}
Exemple #30
0
Fichier : mux.go Projet : goji/goji
// ServeHTTP implements net/http.Handler.
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if m.root {
		ctx := r.Context()
		ctx = context.WithValue(ctx, internal.Path, r.URL.EscapedPath())
		r = r.WithContext(ctx)
	}
	r = m.router.route(r)
	m.handler.ServeHTTP(w, r)
}