本文整理匯總了Golang中github.com/gorilla/context.Clear函數的典型用法代碼示例。如果您正苦於以下問題:Golang Clear函數的具體用法?Golang Clear怎麽用?Golang Clear使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Clear函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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)
}
}
示例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.
})
}
示例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)
}
}
示例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()
}
}
示例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.")
}
}
示例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 ""
}
示例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)
}
示例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)
})
}
示例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
}
示例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)
}
示例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)
}
示例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)
}
}
示例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())
}
示例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)
}
示例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)
}
}