当前位置: 首页>>代码示例>>Golang>>正文


Golang Request.Context方法代码示例

本文整理汇总了Golang中net/http.Request.Context方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.Context方法的具体用法?Golang Request.Context怎么用?Golang Request.Context使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.Request的用法示例。


在下文中一共展示了Request.Context方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: HTML

// 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))
}
开发者ID:pressly,项目名称:chi,代码行数:8,代码来源:render.go

示例2: v1DataPatch

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)
}
开发者ID:tsandall,项目名称:opa,代码行数:33,代码来源:server.go

示例3: channelIntoSlice

// 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)
		}
	}
}
开发者ID:pressly,项目名称:chi,代码行数:29,代码来源:render.go

示例4: Data

// 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)
}
开发者ID:pressly,项目名称:chi,代码行数:9,代码来源:render.go

示例5: ServeHTTP

// 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
	}
}
开发者ID:pressly,项目名称:chi,代码行数:33,代码来源:throttler.go

示例6: Respond

// 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)
	}
}
开发者ID:pressly,项目名称:chi,代码行数:29,代码来源:render.go

示例7: GetPaginationProp

//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}
}
开发者ID:dictyBase,项目名称:Modware,代码行数:9,代码来源:resources.go

示例8: user

func (t *Transport) user(req *http.Request) *User {
	if t.UserFunc != nil {
		return t.UserFunc(req)
	}
	user, _ := req.Context().Value(UserContextKey).(*User)
	return user
}
开发者ID:koding,项目名称:koding,代码行数:7,代码来源:transport.go

示例9: NewLogEntry

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
}
开发者ID:pressly,项目名称:chi,代码行数:29,代码来源:main.go

示例10: v1PoliciesGet

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)
}
开发者ID:tsandall,项目名称:opa,代码行数:28,代码来源:server.go

示例11: routeHTTP

// 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)
}
开发者ID:pressly,项目名称:chi,代码行数:35,代码来源:mux.go

示例12: getArticle

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)
}
开发者ID:pressly,项目名称:chi,代码行数:26,代码来源:main.go

示例13: Set

func Set(r *http.Request, key, val interface{}) *http.Request {
	if val == nil {
		return r
	}

	return r.WithContext(context.WithValue(r.Context(), key, val))
}
开发者ID:thansau239,项目名称:gophish,代码行数:7,代码来源:context.go

示例14: catalog

func (h serviceBrokerHandler) catalog(w http.ResponseWriter, req *http.Request) {
	catalog := CatalogResponse{
		Services: h.serviceBroker.Services(req.Context()),
	}

	h.respond(w, http.StatusOK, catalog)
}
开发者ID:pivotal-cf,项目名称:brokerapi,代码行数:7,代码来源:api.go

示例15: ServeHTTP

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
	}
}
开发者ID:mozilla-services,项目名称:go-syncstorage,代码行数:28,代码来源:cacheHandler.go


注:本文中的net/http.Request.Context方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。