• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang context.Clear函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/gorilla/context.Clear函数的典型用法代码示例。如果您正苦于以下问题:Golang Clear函数的具体用法?Golang Clear怎么用?Golang Clear使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: RequireApiKey

func RequireApiKey(handler http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		apiKeyHeader := r.Header["Api-Key"]
		if len(apiKeyHeader) != 1 {
			w.Header().Set("Content-Type", "text/plain")
			w.WriteHeader(http.StatusUnauthorized)
			w.Write([]byte("No API-KEY header!"))
			ctx.Clear(r)
			return
		}

		apiKey := apiKeyHeader[0]
		user, err := models.GetUserByApiKey(apiKey)
		if err != nil {
			w.Header().Set("Content-Type", "text/plain")
			w.WriteHeader(http.StatusUnauthorized)
			w.Write([]byte("Api Key is incorrect!"))
			ctx.Clear(r)
			return
		}

		ctx.Set(r, "user", user)
		handler.ServeHTTP(w, r)
		ctx.Clear(r)
	}
}
开发者ID:niko3oo,项目名称:lencha,代码行数:26,代码来源:problems.go


示例2: createContext

func createContext(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		context.Set(r, k, Context{})
		next.ServeHTTP(w, r)
		context.Clear(r) // clears after handling everything.
	})
}
开发者ID:fiatjaf,项目名称:summadb,代码行数:7,代码来源:context.go


示例3: httpLogger

func httpLogger(r *http.Request, created time.Time, status, bytes int) {
	//fmt.Println(httpxtra.ApacheCommonLog(r, created, status, bytes))
	var (
		s, ip, msg string
		err        error
	)
	if r.TLS == nil {
		s = "HTTP"
	} else {
		s = "HTTPS"
	}
	if ip, _, err = net.SplitHostPort(r.RemoteAddr); err != nil {
		ip = r.RemoteAddr
	}
	if tmp := context.Get(r, "log"); tmp != nil {
		msg = fmt.Sprintf(" (%s)", tmp)
		context.Clear(r)
	}
	log.Printf("%s %d %s %q (%s) :: %d bytes in %s%s",
		s,
		status,
		r.Method,
		r.URL.Path,
		ip,
		bytes,
		time.Since(created),
		msg,
	)
	if collectStats {
		protocolCount.Add(s, 1)
		statusCount.Add(strconv.Itoa(status), 1)
	}
}
开发者ID:mendosus,项目名称:freegeoip,代码行数:33,代码来源:freegeoip.go


示例4: finished

func (g *Req) finished(appStats AppStats) {
	context.Clear(g.R) // Cleanup  gorilla stash

	reqDuration := time.Since(g.startTime)

	g.app.WriteAccessLog(g, reqDuration)

	// Don't run time-based code for websockets
	if g.WS != nil {
		return
	}

	codeStatsKey := fmt.Sprintf("http_status.%d", g.W.code)
	g.app.Stats.Inc(codeStatsKey, 1)

	slowReqSecs, _ := g.Cfg.GetFloat32("gop", "slow_req_secs", 10)
	if reqDuration.Seconds() > float64(slowReqSecs) && !g.CanBeSlow {
		g.Errorf("Slow request [%s] took %s", g.R.URL.Host, reqDuration)
	} else {
		g.Debug("Request took %s", reqDuration)
	}

	// Tidy up request finalistion (requestMaker, req.finish() method, app.requestFinished())
	restartReqs, _ := g.Cfg.GetInt("gop", "max_requests", 0)
	if restartReqs > 0 && appStats.totalReqs > restartReqs {
		g.Errorf("Graceful restart after max_requests: %d", restartReqs)
		g.app.StartGracefulRestart("Max requests reached")
	}

	gcEveryReqs, _ := g.Cfg.GetInt("gop", "gc_requests", 0)
	if gcEveryReqs > 0 && appStats.totalReqs%gcEveryReqs == 0 {
		g.Info("Forcing GC after %d reqs", appStats.totalReqs)
		runtime.GC()
	}
}
开发者ID:cocoonlife,项目名称:gop,代码行数:35,代码来源:gop.go


示例5: TestUserSession

func TestUserSession(t *testing.T) {
	userStore := store{kUserId}
	sessionStore := newSessionStoreWithUserId(kSessionId, kUserId)
	r := requestWithCookie(kSessionCookieName, kSessionId)
	us, err := session_util.NewUserSession(
		sessionStore,
		r,
		kSessionCookieName,
		func(s *sessions.Session) session_util.UserSession {
			return newUserSession(s)
		},
		userStore,
		errNoSuchId)
	if err != nil {
		t.Fatalf("An error happened getting userSession: %v", err)
	}
	defer context.Clear(r)
	myUserSession := us.(*userSession)
	if output := myUserSession.User; *output != kUserId {
		t.Errorf("Expected %v, got %v", kUserId, *output)
	}
	if myUserSession != session_util.GetUserSession(r) {
		t.Error("User session not stored with request.")
	}
}
开发者ID:keep94,项目名称:appcommon,代码行数:25,代码来源:session_test.go


示例6: logMsg

func logMsg(r *http.Request) string {
	if msg := context.Get(r, "log"); msg != nil {
		defer context.Clear(r)
		return fmt.Sprintf(" (%s)", msg)
	}
	return ""
}
开发者ID:NailClippar,项目名称:go-web,代码行数:7,代码来源:http.go


示例7: InitHandlers

func InitHandlers() {

	initCodeBaseDir()

	// Register datatypes such that it can be saved in the session.
	gob.Register(SessionUserKey(0))
	gob.Register(&User{})

	// Initialize XSRF token key.
	xsrfKey = "My personal very secure XSRF token key"

	sessKey := []byte("secure-key-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa")

	// Create a session cookie store.
	cookieStore = sessions.NewCookieStore(
		sessKey[:64],
		sessKey[:32],
	)

	cookieStore.Options = &sessions.Options{
		MaxAge:   maxSessionIDAge, // Session valid for 30 Minutes.
		HttpOnly: true,
	}

	// Create identity toolkit client.
	c := &gitkit.Config{
		ServerAPIKey: getConfig(siteName, "serverAPIKey"),
		ClientID:     getConfig(siteName, "clientID"),
		WidgetURL:    WidgetSigninAuthorizedRedirectURL,
	}
	// Service account and private key are not required in GAE Prod.
	// GAE App Identity API is used to identify the app.
	if appengine.IsDevAppServer() {
		c.ServiceAccount = getConfig(siteName, "serviceAccount")
		c.PEMKeyPath = privateKeyPath
	}
	var err error
	gitkitClient, err = gitkit.New(c)
	if err != nil {
		log.Fatal(err)
	}

	// The gorilla sessions use gorilla request context
	ClearHandler := func(fc http.HandlerFunc) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			defer gorillaContext.Clear(r)
			fc(w, r)
		})
	}

	http.Handle(homeURL, ClearHandler(handleHome))

	http.Handle(WidgetSigninAuthorizedRedirectURL, ClearHandler(handleWidget))
	http.Handle(signOutURL, ClearHandler(handleSignOut))

	http.Handle(signinLandingDefaultURL, ClearHandler(handleSigninSuccessLanding))
	http.Handle(signoutLandingDefaultURL, ClearHandler(handleSignOutLanding))

	http.HandleFunc(accountChooserBrandingURL, accountChooserBranding)
}
开发者ID:aarzilli,项目名称:tools,代码行数:60,代码来源:register_handlers.go


示例8: AuthHttpInterceptor

func AuthHttpInterceptor(router http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		startTime := time.Now()

		if !Auth(w, req) {
			http.Error(w, "Failed authentication", 401)
			return
		}

		router.ServeHTTP(w, req)

		finishTime := time.Now()
		elapsedTime := finishTime.Sub(startTime)

		switch req.Method {
		case "GET":
			// We may not always want to StatusOK, but for the sake of
			// this example we will
			common.LogAccess(w, req, elapsedTime)
		case "POST":
			// here we might use http.StatusCreated
		}

		context.Clear(req)
	})
}
开发者ID:wlan0,项目名称:host-api,代码行数:26,代码来源:auth.go


示例9: getDB

func getDB(r *http.Request) *mgo.Session {
	if session := context.Get(r, "db"); session != nil {
		context.Clear(r)
		return session.(*mgo.Session)
	}
	return nil
}
开发者ID:dylanvgils,项目名称:go-test,代码行数:7,代码来源:server.go


示例10: ServeHTTP

func (s *Sessions) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	authorizations := strings.Split(r.Header.Get("Authorization"), ",")
	var authToken string

	for _, v := range authorizations {
		fmt.Sscanf(strings.Trim(v, " "), "AuthToken authToken=%s", &authToken)
		if authToken != "" {
			break
		}
	}

	if authToken == "" {
		cookie, err := r.Cookie("authToken")
		if err == nil {
			authToken = cookie.Value
		}
	}

	if authToken != "" {
		session, _ := s.interactor.CurrentSessionFromToken(authToken)
		if session != nil {
			context.Set(r, "currentSession", *session)
		}
	}

	next(w, r)

	context.Clear(r)
}
开发者ID:wid-la,项目名称:wus,代码行数:29,代码来源:sessions.go


示例11: ServeHTTP

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer context.Clear(r)

	u4, err := gouuid.NewV4()
	if err != nil {
		log.Panic(err)
	}
	uuidToken := u4.String()
	context.Set(r, uuidKey, uuidToken)

	defer bugsnag.OnCapturePanic(r, func(event bugsnag.EventDescriber) {
		event.WithMetaData("request", "uuid", uuidToken)
	})

	log.Println(uuidToken, "Start", r.Method, r.URL, "for", parseRemoteAddr(r))

	w.Header().Set("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0")

	if origin, ok := isWhiteListedCorsOrigin(r); ok {
		w.Header().Set("Access-Control-Allow-Origin", origin)
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Authorization, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method, Connection, Host, Origin, User-Agent")
		w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS, PUT, POST, DELETE")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		w.Header().Set("Access-Control-Max-Age", "1728000")
	}

	if r.Method == "OPTIONS" {
		w.Header().Set("Content-Length", "0")
		w.WriteHeader(http.StatusOK)
		return
	}
	router.Routes.ServeHTTP(w, r)
}
开发者ID:refiito,项目名称:pipes-api,代码行数:33,代码来源:request.go


示例12: SpotifyGetKeys

func (env *Env) SpotifyGetKeys(w http.ResponseWriter, r *http.Request) {
	authClient = setup()
	token, err := pullToken(r, env)
	if err != nil {
		common.DisplayAppError(w, err, "error with pulling token, may need to re-auth", 500)
		return
	}

	//have our SpotifyClient here:
	client := authClient.FinalAuth(token)

	var keys IncomingKeys

	if r.Method == "POST" {
		err := json.NewDecoder(r.Body).Decode(&keys)
		if err != nil {
			common.DisplayAppError(w, err, "Invalid Keys data", 500)
			return
		}
	}

	notesChosen := keys.Data.Keys

	songs, _ := GetSongsByKey(notesChosen, client)

	reqcontext.Clear(r)
	if j, err := json.Marshal(SongKeysResource{Data: songs}); err != nil {
		fmt.Println("error in controllers.SpotifyGetKeys json.Marshal")
		return
	} else {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
	}
}
开发者ID:RhettDelFierro,项目名称:rhett_memory_match,代码行数:35,代码来源:spotify.go


示例13: Test_WillieSessions

func Test_WillieSessions(t *testing.T) {
	r := require.New(t)
	w := willie.New(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		defer context.Clear(req)
		sess, _ := Store.Get(req, "my-session")
		t := sess.Values["foo"]
		fmt.Printf("t: %s\n", t)
		if t != nil {
			res.WriteHeader(200)
			fmt.Fprint(res, t)
		} else {
			sess.Values["foo"] = "bar"
			sess.Save(req, res)
			res.WriteHeader(201)
			fmt.Fprint(res, "setting session")
		}
	}))

	res := w.Get("/", nil)
	r.Equal(201, res.Code)
	r.Equal("setting session", res.Body.String())

	res = w.Get("/", nil)
	r.Equal(200, res.Code)
	r.Equal("bar", res.Body.String())
}
开发者ID:ryanzec,项目名称:going,代码行数:26,代码来源:willie_test.go


示例14: ServeHTTP

func (h Handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	requestLog.Info("%v %v", r.Method, r.RequestURI)

	for _, initializer := range initializers {
		initializer(r)
	}

	buffer := new(httpbuf.Buffer)

	err := h(buffer, r)
	if err != nil {
		fmt.Println(err)
		if webErr, ok := err.(WebError); ok {
			http.Error(w, webErr.Message, webErr.Code)
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}

	err = Session(r).Save(r, buffer)
	context.Clear(r)

	buffer.Apply(w)
}
开发者ID:YouthBuild-USA,项目名称:godata,代码行数:25,代码来源:web.go


示例15: HandlerSocket

// HandlerSocket handles inbound websocket connections only at /publish
func HandlerSocket(w http.ResponseWriter, r *http.Request) {
	clientName, _ := context.Get(r, "ClientName").(string)
	context.Clear(r)

	// Upgrade the request
	socket, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		panic(err)
	}
	defer socket.Close()

	// Create a Connection instance
	c := hub.NewConnection(socket.RemoteAddr().String(), clientName)
	hub.Manager.RegisterConnection(&c)
	defer hub.Manager.Cleanup(&c)

	// Handle inbound publish messages
	for {
		m := message.SocketMessage{
			Action:    "publish",
			CreatedAt: time.Now().UTC(),
		}

		err = socket.ReadJSON(&m)
		if err != nil {
			break
		}

		hub.Manager.Publish(m)
	}
}
开发者ID:projectweekend,项目名称:picloud,代码行数:32,代码来源:handlers.go


示例16: ServeHTTP

// ServeHTTP will store the request details in the analytics store if necessary and proxy the request to it's
// final destination, this is invoked by the ProxyHandler or right at the start of a request chain if the URL
// Spec states the path is Ignored
func (s SuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	// Make sure we get the correct target URL
	if s.Spec.APIDefinition.Proxy.StripListenPath {
		r.URL.Path = strings.Replace(r.URL.Path, s.Spec.Proxy.ListenPath, "", 1)
	}

	if config.EnableAnalytics {
		t := time.Now()

		// Track the key ID if it exists
		authHeaderValue := context.Get(r, AuthHeaderValue)
		keyName := ""
		if authHeaderValue != nil {
			keyName = authHeaderValue.(string)
		}

		// Track version data
		version := s.Spec.getVersionFromRequest(r)
		if version == "" {
			version = "Non Versioned"
		}

		// If OAuth, we need to grab it from the session, which may or may not exist
		OauthClientID := ""
		thisSessionState := context.Get(r, SessionData)

		if thisSessionState != nil {
			OauthClientID = thisSessionState.(SessionState).OauthClientID
		}

		thisRecord := AnalyticsRecord{
			r.Method,
			r.URL.Path,
			r.ContentLength,
			r.Header.Get("User-Agent"),
			t.Day(),
			t.Month(),
			t.Year(),
			t.Hour(),
			200,
			keyName,
			t,
			version,
			s.Spec.APIDefinition.Name,
			s.Spec.APIDefinition.APIID,
			s.Spec.APIDefinition.OrgID,
			OauthClientID}

		go analytics.RecordHit(thisRecord)
	}

	s.Proxy.ServeHTTP(w, r)

	if doMemoryProfile {
		pprof.WriteHeapProfile(profileFile)
	}

	context.Clear(r)
}
开发者ID:joshrendek,项目名称:tyk,代码行数:63,代码来源:handler_success.go


示例17: ServeHTTP

// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Clean path to canonical form and redirect.
	if p := cleanPath(req.URL.Path); p != req.URL.Path {
		w.Header().Set("Location", p)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}
	var match RouteMatch
	var handler http.Handler
	if r.Match(req, &match) {
		handler = match.Handler
		setVars(req, match.Vars)
		setCurrentRoute(req, match.Route)
	}
	if handler == nil {
		if r.NotFoundHandler == nil {
			r.NotFoundHandler = http.NotFoundHandler()
		}
		handler = r.NotFoundHandler
	}
	if !r.KeepContext {
		defer context.Clear(req)
	}
	handler.ServeHTTP(w, req)
}
开发者ID:yindeming,项目名称:ForrestFire,代码行数:29,代码来源:mux.go


示例18: HandleError

// HandleError is the actual error handler and will store the error details in analytics if analytics processing is enabled.
func (e ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, err string, errCode int) {
	if config.EnableAnalytics {
		t := time.Now()

		// Track the key ID if it exists
		authHeaderValue := context.Get(r, AuthHeaderValue)
		keyName := ""
		if authHeaderValue != nil {
			keyName = authHeaderValue.(string)
		}

		version := e.Spec.getVersionFromRequest(r)
		if version == "" {
			version = "Non Versioned"
		}

		if e.TykMiddleware.Spec.APIDefinition.Proxy.StripListenPath {
			r.URL.Path = strings.Replace(r.URL.Path, e.TykMiddleware.Spec.Proxy.ListenPath, "", 1)
		}

		OauthClientID := ""
		thisSessionState := context.Get(r, SessionData)

		if thisSessionState != nil {
			OauthClientID = thisSessionState.(SessionState).OauthClientID
		}

		thisRecord := AnalyticsRecord{
			r.Method,
			r.URL.Path,
			r.ContentLength,
			r.Header.Get("User-Agent"),
			t.Day(),
			t.Month(),
			t.Year(),
			t.Hour(),
			errCode,
			keyName,
			t,
			version,
			e.Spec.APIDefinition.Name,
			e.Spec.APIDefinition.APIID,
			e.Spec.APIDefinition.OrgID,
			OauthClientID}
		go analytics.RecordHit(thisRecord)
	}

	w.Header().Add("Content-Type", "application/json")
	w.Header().Add("X-Generator", "tyk.io")
	log.Debug("Returning error header")
	w.WriteHeader(errCode)
	thisError := APIError{fmt.Sprintf("%s", err)}
	templates.ExecuteTemplate(w, "error.json", &thisError)
	if doMemoryProfile {
		pprof.WriteHeapProfile(profileFile)
	}

	// Clean up
	context.Clear(r)
}
开发者ID:alexpopero,项目名称:tyk,代码行数:61,代码来源:handler_error.go


示例19: AutoLogin

// AutoLogin 用于 echo 框架的自动登录和通过 cookie 获取用户信息
func AutoLogin() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(ctx echo.Context) error {
			// github.com/gorilla/sessions 要求必须 Clear
			defer context.Clear(Request(ctx))

			session := GetCookieSession(ctx)
			username, ok := session.Values["username"]
			if ok {
				if db.MasterDB != nil {
					// TODO: 考虑缓存,或延迟查询,避免每次都查询
					user := logic.DefaultUser.FindCurrentUser(ctx, username)
					if user.Uid != 0 {
						ctx.Set("user", user)
					}
				}
			}

			if err := next(ctx); err != nil {
				return err
			}

			return nil
		}
	}
}
开发者ID:studygolang,项目名称:studygolang,代码行数:27,代码来源:login.go


示例20: newRouter

func newRouter(ctx *Context, next http.Handler) http.Handler {
	if ctx.router == nil {
		ctx.router = DefaultRouter(ctx.spec, ctx.api)
	}
	isRoot := ctx.spec.BasePath() == "" || ctx.spec.BasePath() == "/"

	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		defer context.Clear(r)
		// use context to lookup routes
		if isRoot {
			if _, ok := ctx.RouteInfo(r); ok {
				next.ServeHTTP(rw, r)
				return
			}
		} else {
			if p := strings.TrimPrefix(r.URL.Path, ctx.spec.BasePath()); len(p) < len(r.URL.Path) {
				r.URL.Path = p
				if _, ok := ctx.RouteInfo(r); ok {
					next.ServeHTTP(rw, r)
					return
				}
			}
		}
		// Not found, check if it exists in the other methods first
		if others := ctx.AllowedMethods(r); len(others) > 0 {
			ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others))
			return
		}

		ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.Path))
	})
}
开发者ID:jason-xxl,项目名称:go-swagger,代码行数:32,代码来源:router.go



注:本文中的github.com/gorilla/context.Clear函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang context.ClearHandler函数代码示例发布时间:2022-05-23
下一篇:
Golang cronexpr.Parse函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap