本文整理汇总了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))
}
示例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)
}
示例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)
}
}
}
示例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)
}
示例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
}
}
示例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)
}
}
示例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}
}
示例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
}
示例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
}
示例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)
}
示例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)
}
示例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)
}
示例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))
}
示例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)
}
示例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
}
}