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


Golang context.BaseCtxKey函数代码示例

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


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

示例1: GetRenderer

// GetRenderer returns the current raw renderer from the context.
func GetRenderer(c context.Context) renderer.Renderer {
	if val, ok := c.GetGlobal(context.BaseCtxKey("renderer")); ok {
		return val.(renderer.Renderer)
	}

	return renderer.NewRenderer("template", "base.tmpl")
}
开发者ID:urandom,项目名称:webfw,代码行数:8,代码来源:context_util.go

示例2: GetUser

func GetUser(c context.Context, r *http.Request) content.User {
	if v, ok := c.Get(r, context.BaseCtxKey("user")); ok {
		return v.(content.User)
	}

	return nil
}
开发者ID:urandom,项目名称:readeef,代码行数:7,代码来源:context_util.go

示例3: GetLogger

// GetLogger returns the error logger, to be used if an error occurs during
// a request.
func GetLogger(c context.Context) Logger {
	if val, ok := c.GetGlobal(context.BaseCtxKey("logger")); ok {
		return val.(Logger)
	}

	return NewStandardLogger(os.Stderr, "", 0)
}
开发者ID:urandom,项目名称:webfw,代码行数:9,代码来源:context_util.go

示例4: GetParams

// GetParams returns the current request path parameters from the context.
func GetParams(c context.Context, r *http.Request) RouteParams {
	if val, ok := c.Get(r, context.BaseCtxKey("params")); ok {
		return val.(RouteParams)
	}

	return RouteParams{}
}
开发者ID:urandom,项目名称:webfw,代码行数:8,代码来源:context_util.go

示例5: GetLanguage

// GetLanguage returns the current request language, such as "en", or "bg-BG"
// from the context, if the I18N middleware is in use.
func GetLanguage(c context.Context, r *http.Request) string {
	if val, ok := c.Get(r, context.BaseCtxKey("lang")); ok {
		return val.(string)
	}

	return GetFallbackLanguage(c, r)
}
开发者ID:urandom,项目名称:webfw,代码行数:9,代码来源:context_util.go

示例6: GetConfig

// GetConfig is a helper function for getting the current config
// from the request context.
func GetConfig(c context.Context) Config {
	if val, ok := c.GetGlobal(context.BaseCtxKey("config")); ok {
		return val.(Config)
	}

	return Config{}
}
开发者ID:urandom,项目名称:webfw,代码行数:9,代码来源:context_util.go

示例7: RegisterControllers

func RegisterControllers(config readeef.Config, dispatcher *webfw.Dispatcher, apiPattern string) {
	dispatcher.Renderer = renderer.NewRenderer(dispatcher.Config.Renderer.Dir,
		dispatcher.Config.Renderer.Base)

	dispatcher.Renderer.Delims("{%", "%}")
	dispatcher.Context.SetGlobal(context.BaseCtxKey("readeefConfig"), config)

	middleware.InitializeDefault(dispatcher)

	dispatcher.Handle(NewApp())
	dispatcher.Handle(NewComponent(dispatcher, apiPattern))
}
开发者ID:RavenB,项目名称:readeef,代码行数:12,代码来源:web.go

示例8: RegisterControllers

func RegisterControllers(config readeef.Config, dispatcher *webfw.Dispatcher, apiPattern string) {
	dispatcher.Renderer = renderer.NewRenderer(dispatcher.Config.Renderer.Dir,
		dispatcher.Config.Renderer.Base)

	hasProxy := false
	for _, p := range config.FeedParser.Processors {
		if p == "proxy-http" {
			hasProxy = true
			break
		}
	}

	if !hasProxy {
		for _, p := range config.Content.ArticleProcessors {
			if p == "proxy-http" {
				hasProxy = true
				break
			}
		}
	}

	mw := make([]string, 0, len(dispatcher.Config.Dispatcher.Middleware))
	for _, m := range dispatcher.Config.Dispatcher.Middleware {
		switch m {
		case "Session":
			if hasProxy {
				mw = append(mw, m)
			}
		default:
			mw = append(mw, m)
		}
	}

	dispatcher.Config.Dispatcher.Middleware = mw

	dispatcher.Renderer.Delims("{%", "%}")
	dispatcher.Context.SetGlobal(readeef.CtxKey("config"), config)
	dispatcher.Context.SetGlobal(context.BaseCtxKey("readeefConfig"), config)

	middleware.InitializeDefault(dispatcher)

	dispatcher.Handle(NewApp())
	dispatcher.Handle(NewComponent(dispatcher, apiPattern))

	if hasProxy {
		dispatcher.Handle(NewProxy())
	}

}
开发者ID:urandom,项目名称:readeef,代码行数:49,代码来源:web.go

示例9: URL

// The URL function provides the functionality of the url template functions
// for use outside of the template context. The dispatcherPattern is the
// pattern used by the dispatcher responsible for handling the resulting url.
// In most cases it will probably be "/".
func URL(c context.Context, r *http.Request, dispatcherPattern string, parts []string) (string, error) {
	base, err := unlocalizedUrl(r, parts)

	if err != nil {
		return "", err
	}

	if lang, ok := c.Get(r, context.BaseCtxKey("lang")); ok && len(lang.(string)) > 0 {
		base = "/" + lang.(string) + base
	}
	if len(dispatcherPattern) > 1 {
		base = dispatcherPattern[:len(dispatcherPattern)-1] + base
	}

	if len(base) > 1 && base[len(base)-1] == '/' {
		base = base[:len(base)-1]
	}
	return base, nil
}
开发者ID:urandom,项目名称:webfw,代码行数:23,代码来源:url.go

示例10: GetSession

// GetSession returns the current session from the context,
// if the Session middleware is in use.
func GetSession(c context.Context, r *http.Request) context.Session {
	if val, ok := c.Get(r, context.BaseCtxKey("session")); ok {
		return val.(context.Session)
	}

	conf := GetConfig(c)
	var abspath string

	if filepath.IsAbs(conf.Session.Dir) {
		abspath = conf.Session.Dir
	} else {
		var err error
		abspath, err = filepath.Abs(path.Join(filepath.Dir(os.Args[0]), conf.Session.Dir))

		if err != nil {
			abspath = os.TempDir()
		}
	}

	sess := context.NewSession([]byte(conf.Session.Secret), []byte(conf.Session.Cipher), abspath)
	sess.SetName(util.UUID())
	return sess
}
开发者ID:urandom,项目名称:webfw,代码行数:25,代码来源:context_util.go

示例11: GetFallbackLanguage

// GetFallbackLanguage tries to obtain a requested language via the session,
// or the Accept-Language request header, or the LANG or LC_MESSAGES
// environment variables
func GetFallbackLanguage(c context.Context, r *http.Request, fallback ...string) string {
	if val, ok := c.Get(r, context.BaseCtxKey("session")); ok {
		sess := val.(context.Session)

		if language, ok := sess.Get("language"); ok {
			return language.(string)
		}
	}

	langs := lng.Parse(r.Header.Get("Accept-Language"))

	if len(langs) > 0 {
		return langs[0].String()
	}

	language := os.Getenv("LANG")

	if language == "" {
		language = os.Getenv("LC_MESSAGES")
		language = localeRegexp.ReplaceAllLiteralString(language, "")
	}

	if language == "" {
		if len(fallback) > 0 {
			language = fallback[0]
		} else {
			language = "en"
		}
	} else {
		langs := lng.Parse(language)
		if len(langs) > 0 {
			return langs[0].String()
		}
	}

	return language
}
开发者ID:urandom,项目名称:webfw,代码行数:40,代码来源:context_util.go

示例12: GetNamedForward

// GetNamedForward returns a name, used by the dispatcher to lookup a route to
// forward to.
func GetNamedForward(c context.Context, r *http.Request) string {
	if val, ok := c.Get(r, context.BaseCtxKey("named-forward")); ok {
		return val.(string)
	}
	return ""
}
开发者ID:urandom,项目名称:webfw,代码行数:8,代码来源:context_util.go

示例13: TestRenderer

func TestRenderer(t *testing.T) {
	r := NewRenderer("testdata", "test.tmpl")
	cd := context.ContextData{}

	buf := new(bytes.Buffer)

	if err := r.Render(buf, nil, cd); err != nil {
		t.Fatal(err)
	}

	res := strings.TrimSpace(buf.String())
	expected := ""
	if res != expected {
		t.Fatalf("Expected result to be '%s', got '%s'\n", expected, res)
	}

	buf.Reset()
	if err := r.Render(buf, nil, cd, "test_normal.tmpl"); err != nil {
		t.Fatal(err)
	}

	res = strings.TrimSpace(buf.String())

	expected = `[content: test1]

[ctx: ]
[base: ]`
	if res != expected {
		t.Fatalf("Expected '%s', got '%s'\n", expected, res)
	}

	buf.Reset()
	if err := r.Render(buf, nil, cd, "test_inner.tmpl", "test_normal.tmpl"); err != nil {
		t.Fatal(err)
	}

	res = strings.TrimSpace(buf.String())

	expected = `[content: test1]

[inner: test3]

[ctx: ]
[base: ]`
	if res != expected {
		t.Fatalf("Expected '%s', got '%s'\n", expected, res)
	}

	buf.Reset()
	cd[context.BaseCtxKey("test")] = "foo"
	cd["test"] = "bar"
	if err := r.Render(buf, nil, cd, "test_inner.tmpl", "test_normal.tmpl"); err != nil {
		t.Fatal(err)
	}

	res = strings.TrimSpace(buf.String())

	expected = `[content: test1]

[inner: test3]

[ctx: bar]
[base: foo]`
	if res != expected {
		t.Fatalf("Expected '%s', got '%s'\n", expected, res)
	}

	r = NewRenderer("testdata", "test.tmpl")
	r.Funcs(template.FuncMap{
		"foo": func(dot string) string {
			return strings.ToUpper(dot)
		},
	})

	buf.Reset()
	data := RenderData{"test": "stuff"}
	if err := r.Render(buf, data, cd, "test_inner.tmpl", "test_func.tmpl"); err != nil {
		t.Fatal(err)
	}

	res = strings.TrimSpace(buf.String())

	expected = `STUFF`
	if res != expected {
		t.Fatalf("Expected '%s', got '%s'\n", expected, res)
	}
}
开发者ID:urandom,项目名称:webfw,代码行数:87,代码来源:renderer_test.go

示例14: TestSessionHandler

func TestSessionHandler(t *testing.T) {
	c := context.NewContext()
	mw := Session{
		Path:            path.Join(os.TempDir(), "session"),
		Secret:          secret,
		MaxAge:          "1s",
		CleanupInterval: "1s",
		CleanupMaxAge:   "1s",
	}

	h := mw.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	}), c)

	r, _ := http.NewRequest("GET", "http://localhost:8080/some/url", nil)
	rec := httptest.NewRecorder()
	c.Set(r, context.BaseCtxKey("r"), r)
	c.Set(r, context.BaseCtxKey("lang"), "en")

	h.ServeHTTP(rec, r)

	var cookie string
	if s, ok := c.Get(r, context.BaseCtxKey("session")); ok {
		sess := s.(context.Session)
		if sess.MaxAge() != time.Second {
			t.Fatalf("Expected Session.MaxAge to be '%s', got '%s'\n", time.Second, sess.MaxAge())
		}

		if err := sess.Write(rec); err != nil {
			t.Fatal(err)
		}
		sess.Set("foo", "bar")
		cookie = rec.Header().Get("Set-Cookie")
	} else {
		t.Fatalf("Expected a new session")
	}

	if ft, ok := c.Get(r, context.BaseCtxKey("firstTimer")); ok {
		if !ft.(bool) {
			t.Fatalf("Expected a true first-timer flag")
		}
	} else {
		t.Fatalf("Expected a first-timer flag")
	}

	time.Sleep(2 * time.Second)

	r, _ = http.NewRequest("GET", "http://localhost:8080/some/url", nil)
	rec = httptest.NewRecorder()
	r.Header.Set("Cookie", cookie[:strings.Index(cookie, ";")])

	h.ServeHTTP(rec, r)

	if ft, ok := c.Get(r, context.BaseCtxKey("firstTimer")); ok {
		if ft.(bool) {
			t.Fatalf("Expected a false first-timer flag")
		}
	} else {
		t.Fatalf("Expected a first-timer flag")
	}

	sess, _ := c.Get(r, context.BaseCtxKey("session"))
	if _, ok := sess.(context.Session).Get("foo"); ok {
		t.Fatalf("Expected the session to be empty")
	}

}
开发者ID:urandom,项目名称:webfw,代码行数:66,代码来源:session_test.go

示例15: Handler


//.........这里部分代码省略.........
				}

				http.Redirect(w, r, path, http.StatusMovedPermanently)
				return
			}

		case ApiAuthController:
			if !ac.AuthRequired(c, r) {
				ph.ServeHTTP(w, r)
				return
			}

			url, login, signature, nonce, date, t := authData(r)

			validUser := false

			var u content.User

			if login != "" && signature != "" && !t.IsZero() {
				switch {
				default:
					u = repo.UserByLogin(data.Login(login))
					if u.HasErr() {
						logger.Printf("Error getting db user '%s': %v\n", login, u.Err())
						break
					}

					decoded, err := base64.StdEncoding.DecodeString(signature)
					if err != nil {
						logger.Printf("Error decoding auth header: %v\n", err)
						break
					}

					if t.Add(30 * time.Second).Before(time.Now()) {
						break
					}

					if !mw.Nonce.Check(nonce) {
						break
					}
					mw.Nonce.Remove(nonce)

					buf := util.BufferPool.GetBuffer()
					defer util.BufferPool.Put(buf)

					buf.ReadFrom(r.Body)
					r.Body = ioutil.NopCloser(buf)

					bodyHash := md5.New()
					if _, err := bodyHash.Write(buf.Bytes()); err != nil {
						logger.Printf("Error generating the hash for the request body: %v\n", err)
						break
					}

					contentMD5 := base64.StdEncoding.EncodeToString(bodyHash.Sum(nil))

					message := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n",
						url, r.Method, contentMD5, r.Header.Get("Content-Type"),
						date, nonce)

					b := make([]byte, base64.StdEncoding.EncodedLen(len(u.Data().MD5API)))
					base64.StdEncoding.Encode(b, u.Data().MD5API)

					hm := hmac.New(sha256.New, b)
					if _, err := hm.Write([]byte(message)); err != nil {
						logger.Printf("Error generating the hashed message: %v\n", err)
						break
					}

					if !hmac.Equal(hm.Sum(nil), decoded) {
						logger.Printf("Error matching the supplied auth message to the generated one.\n")
						break
					}

					if !u.Data().Active {
						logger.Println("User " + u.Data().Login + " is inactive")
						break
					}

					validUser = true
				}
			}

			if validUser {
				c.Set(r, context.BaseCtxKey("user"), u)
			} else {
				if rej, ok := ac.(AuthRejectHandler); ok {
					rej.AuthReject(c, r)
				} else {
					w.WriteHeader(http.StatusUnauthorized)
					return
				}
			}
		}

		ph.ServeHTTP(w, r)
	}

	return http.HandlerFunc(handler)
}
开发者ID:urandom,项目名称:readeef,代码行数:101,代码来源:auth.go


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