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

Golang context.BaseCtxKey函数代码示例

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

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



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


示例16: Handler

func (imw I18N) Handler(ph http.Handler, c context.Context) http.Handler {
	for _, l := range imw.Languages {
		file, err := fs.DefaultFS.OpenRoot(imw.Dir, l+".all.json")
		if err == nil {
			var b []byte

			if b, err = ioutil.ReadAll(file); err == nil {
				err = i18n.ParseTranslationFileBytes(l+".all.json", b)
			}
		}

		if err != nil {
			panic(fmt.Sprintf("Error opening locale file '%s.all.json': %v\n", l, err))
		}
	}

	renderer := webfw.GetRenderer(c)
	renderer.Funcs(imw.TemplateFuncMap())

	handler := func(w http.ResponseWriter, r *http.Request) {
		c.Set(r, context.BaseCtxKey("langs"), imw.Languages)

		if len(imw.Languages) == 0 {
			c.Set(r, context.BaseCtxKey("lang"), "")
			ph.ServeHTTP(w, r)
			return
		}

		found := false

		uriParts := strings.SplitN(r.RequestURI, "?", 2)
		if uriParts[0] == "" {
			uriParts[0] = r.URL.Path
		}
		for _, prefix := range imw.IgnoreURLPrefix {
			if prefix[0] == '/' {
				prefix = prefix[1:]
			}

			if strings.HasPrefix(uriParts[0], imw.Pattern+prefix+"/") {
				found = true
				break
			}

			if uriParts[0] == imw.Pattern+prefix {
				found = true
				break
			}
		}

		if !found {
			for _, language := range imw.Languages {
				if uriParts[0] == imw.Pattern+language {
					url := uriParts[0] + "/"
					if len(uriParts) > 1 && uriParts[1] != "" {
						url += "?" + uriParts[1]
					}

					http.Redirect(w, r, url, http.StatusFound)

					return
				}

				if strings.HasPrefix(uriParts[0], imw.Pattern+language+"/") {
					r.URL.Path = imw.Pattern + r.URL.Path[len(imw.Pattern+language+"/"):]

					uriParts[0] = imw.Pattern + uriParts[0][len(imw.Pattern+language+"/"):]

					r.RequestURI = strings.Join(uriParts, "?")

					c.Set(r, context.BaseCtxKey("lang"), language)
					found = true

					s := webfw.GetSession(c, r)
					s.Set("language", language)

					break
				}
			}
		}

		if !found {
			fallback := webfw.GetFallbackLanguage(c, r, imw.FallbackLanguage)
			index := strings.Index(fallback, "-")
			short := fallback
			if index > -1 {
				short = fallback[:index]
			}
			foundShort := false

			for _, language := range imw.Languages {
				if language == fallback {
					found = true
					break
				}

				if language == short {
					foundShort = true
				}
			}
//.........这里部分代码省略.........
开发者ID:urandom,项目名称:webfw,代码行数:101,代码来源:i18n.go


示例17: TestContextUtil

func TestContextUtil(t *testing.T) {
	c := context.NewContext()
	r, _ := http.NewRequest("GET", "http://localhost:8080", nil)

	conf := GetConfig(c)
	if fmt.Sprintf("%v", conf) != fmt.Sprintf("%v", Config{}) {
		t.Fatalf("Expected a an empty Config, got %v\n", conf)
	}

	conf.Server.Address = "127.0.0.1"
	c.SetGlobal(context.BaseCtxKey("config"), conf)

	conf = GetConfig(c)
	if conf.Server.Address != "127.0.0.1" {
		t.Fatalf("Expected Server.Address to be '127.0.0.1', got '%s'\n", conf.Server.Address)
	}

	params := GetParams(c, r)
	if len(params) != 0 {
		t.Fatalf("Expected empty params, got %v\n", params)
	}

	params["foo"] = "bar"
	c.Set(r, context.BaseCtxKey("params"), params)

	params = GetParams(c, r)
	if len(params) != 1 {
		t.Fatalf("Expected params with 1 entry, got %v\n", params)
	}

	if v := params["foo"]; v != "bar" {
		t.Fatalf("Expected param value for 'foo' to be 'bar', got %s\n", v)
	}

	sess := GetSession(c, r)
	if sess.Name() == "" {
		t.Fatalf("Expected a non-empty session name\n")
	}

	if len(sess.GetAll()) != 0 {
		t.Fatalf("Expected an empty session, got %v\n", sess.GetAll())
	}

	sess.Set("foo", "bar")
	uuid := sess.Name()
	c.Set(r, context.BaseCtxKey("session"), sess)

	sess = GetSession(c, r)
	if sess.Name() != uuid {
		t.Fatalf("Expected Session.Name '%s', got '%s'\n", uuid, sess.Name())
	}

	if v, ok := sess.Get("foo"); ok {
		if v != "bar" {
			t.Fatalf("Expected the value for session key 'foo' to be 'bar', got '%v'\n", v)
		}
	} else {
		t.Fatalf("Expected the session to have a value for key 'foo'\n")
	}

	lang := GetLanguage(c, r)

	if lang != GetFallbackLanguage(c, r) {
		t.Fatalf("Expected lang to be '%s', got '%s'\n", GetFallbackLanguage(c, r), lang)
	}

	c.Set(r, context.BaseCtxKey("lang"), "ZZ")

	lang = GetLanguage(c, r)
	if lang != "ZZ" {
		t.Fatalf("Expected lang to be 'ZZ', got '%s'\n", lang)
	}

	ren := GetRenderer(c)
	if ren == nil {
		t.Fatalf("Expected a non-nil renderer\n")
	}

	log := GetLogger(c)
	if log == nil {
		t.Fatalf("Expected a non-nill logger\n")
	}

	r, _ = http.NewRequest("GET", "http://localhost:8080", nil)
	conf = GetConfig(c)
	if conf.Server.Address != "127.0.0.1" {
		t.Fatalf("Expected Server.Address to be '127.0.0.1', got '%s'\n", conf.Server.Address)
	}

	params = GetParams(c, r)
	if len(params) != 0 {
		t.Fatalf("Expected empty params, got %v\n", params)
	}
}
开发者ID:urandom,项目名称:webfw,代码行数:94,代码来源:context_util_test.go


示例18: Handler


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

	logger := webfw.GetLogger(c)

	if smw.CleanupInterval != "" {
		var err error
		cleanupInterval, err = time.ParseDuration(smw.CleanupInterval)

		if err != nil {
			panic(err)
		}

		cleanupMaxAge, err = time.ParseDuration(smw.CleanupMaxAge)

		if err != nil {
			panic(err)
		}

		go func() {
			for _ = range time.Tick(cleanupInterval) {
				logger.Print("Cleaning up old sessions")

				if err := context.CleanupSessions(abspath, cleanupMaxAge); err != nil {
					logger.Printf("Failed to clean up sessions: %v", err)
				}
			}
		}()
	}

	handler := func(w http.ResponseWriter, r *http.Request) {
		uriParts := strings.SplitN(r.RequestURI, "?", 2)
		if uriParts[0] == "" {
			uriParts[0] = r.URL.Path
		}

		ignore := false
		for _, prefix := range smw.IgnoreURLPrefix {
			if prefix[0] == '/' {
				prefix = prefix[1:]
			}

			if strings.HasPrefix(uriParts[0], smw.Pattern+prefix+"/") {
				ignore = true
				break
			}

			if uriParts[0] == smw.Pattern+prefix {
				ignore = true
				break
			}
		}

		if ignore {
			ph.ServeHTTP(w, r)
			return
		}

		firstTimer := false
		var sess context.Session

		if smw.SessionGenerator == nil {
			sess = context.NewSession(smw.Secret, smw.Cipher, abspath)
		} else {
			sess = smw.SessionGenerator(smw.Secret, smw.Cipher, abspath)
		}
		sess.SetMaxAge(maxAge)

		err := sess.Read(r, c)

		if err != nil && err != context.ErrExpired && err != context.ErrNotExist {
			sess.SetName(util.UUID())
			firstTimer = true

			if err != context.ErrCookieNotExist {
				logger.Printf("Error reading session: %v", err)
			}
		}

		c.Set(r, context.BaseCtxKey("session"), sess)
		c.Set(r, context.BaseCtxKey("firstTimer"), firstTimer)

		rec := util.NewRecorderHijacker(w)

		ph.ServeHTTP(rec, r)

		for k, v := range rec.Header() {
			w.Header()[k] = v
		}

		if sess != nil {
			if err := sess.Write(w); err != nil {
				logger.Printf("Unable to write session: %v", err)
			}
		}

		w.WriteHeader(rec.GetCode())
		w.Write(rec.GetBody().Bytes())
	}

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


示例19: RegisterControllers

func RegisterControllers(config readeef.Config, dispatcher *webfw.Dispatcher, logger webfw.Logger) error {
	repo, err := repo.New(config.DB.Driver, config.DB.Connect, logger)
	if err != nil {
		return err
	}

	if err := initAdminUser(repo, []byte(config.Auth.Secret)); err != nil {
		return err
	}

	dispatcher.Context.SetGlobal(readeef.CtxKey("config"), config)
	dispatcher.Context.SetGlobal(context.BaseCtxKey("readeefConfig"), config)
	dispatcher.Context.SetGlobal(readeef.CtxKey("repo"), repo)

	um := &readeef.UpdateFeedReceiverManager{}

	fm := readeef.NewFeedManager(repo, config, logger, um)

	if config.Hubbub.CallbackURL != "" {
		hubbub := readeef.NewHubbub(repo, config, logger, dispatcher.Pattern, fm.RemoveFeedChannel(), fm.AddFeedChannel(), um)
		if err := hubbub.InitSubscriptions(); err != nil {
			return fmt.Errorf("Error initializing hubbub subscriptions: %v", err)
		}

		fm.SetHubbub(hubbub)
		dispatcher.Handle(readeef.NewHubbubController(hubbub))
	}

	var si readeef.SearchIndex
	if config.SearchIndex.BlevePath != "" {
		var err error
		si, err = readeef.NewSearchIndex(repo, config, logger)
		if err != nil {
			return fmt.Errorf("Error initializing bleve search: %v", err)
		}

		if si.IsNewIndex() {
			go func() {
				si.IndexAllArticles()
			}()
		}

		fm.SetSearchIndex(si)
	}

	fm.Start()

	nonce := readeef.NewNonce()

	var patternController webfw.PatternController
	var multiPatternController webfw.MultiPatternController

	patternController = NewAuth()
	dispatcher.Handle(patternController)

	multiPatternController = NewFeed(fm)
	dispatcher.Handle(multiPatternController)

	multiPatternController = NewArticle(config)
	dispatcher.Handle(multiPatternController)

	if config.SearchIndex.BlevePath != "" {
		patternController = NewSearch(si)
		dispatcher.Handle(patternController)
	}

	multiPatternController = NewUser()
	dispatcher.Handle(multiPatternController)

	patternController = NewUserSettings()
	dispatcher.Handle(patternController)

	patternController = NewNonce(nonce)
	dispatcher.Handle(patternController)

	if config.API.Fever {
		patternController = NewFever(fm)
		dispatcher.Handle(patternController)
	}

	webSocket := NewWebSocket(fm, si)
	dispatcher.Handle(webSocket)
	um.AddUpdateReceiver(webSocket)

	middleware.InitializeDefault(dispatcher)
	dispatcher.RegisterMiddleware(readeef.Auth{Pattern: dispatcher.Pattern, Nonce: nonce, IgnoreURLPrefix: config.Auth.IgnoreURLPrefix})

	dispatcher.Renderer = renderer.NewRenderer(dispatcher.Config.Renderer.Dir,
		dispatcher.Config.Renderer.Base)

	dispatcher.Renderer.Delims("{%", "%}")

	go func() {
		for {
			select {
			case <-time.After(5 * time.Minute):
				nonce.Clean(45 * time.Second)
			}
		}
	}()
//.........这里部分代码省略.........
开发者ID:RavenB,项目名称:readeef,代码行数:101,代码来源:api.go


示例20: Initialize

// Initialize creates all configured middleware handlers, producing a chain of
// functions to be called on each request. Initializes and registers all
// handled controllers. This function is called automatically by the Server
// object, when its ListenAndServe method is called. It should be called
// directly before calling http.Handle() using the dispatcher when the Server
// object is not used.
func (d *Dispatcher) Initialize() {
	if d.Renderer == nil {
		d.Renderer = renderer.NewRenderer(d.Config.Renderer.Dir, d.Config.Renderer.Base)
	}

	d.Context.SetGlobal(context.BaseCtxKey("renderer"), d.Renderer)
	d.Context.SetGlobal(context.BaseCtxKey("logger"), d.Logger)
	d.Context.SetGlobal(context.BaseCtxKey("dispatcher"), d)
	d.Context.SetGlobal(context.BaseCtxKey("config"), d.Config)

	var mw []Middleware
	order := []string{}
	middlewareInserted := make(map[string]bool)

	for _, m := range d.Config.Dispatcher.Middleware {
		if custom, ok := d.middleware[m]; ok {
			d.Logger.Debugf("Queueing middleware %s to the chain.\n", m)
			mw = append(mw, custom)
			order = append(order, m)

			middlewareInserted[m] = true
		}
	}

	reverseOrder := d.middlewareOrder[:]
	sort.Sort(sort.Reverse(sort.StringSlice(reverseOrder)))
	for _, name := range reverseOrder {
		if !middlewareInserted[name] {
			if custom, ok := d.middleware[name]; ok {
				d.Logger.Debugf("Queueing middleware %s to the chain.\n", name)
				mw = append([]Middleware{custom}, mw...)
				order = append([]string{name}, order...)
			}
		}
	}

	handler := d.handlerFunc()

	for _, m := range mw {
		handler = m.Handler(handler, d.Context)
	}

	d.handler = handler
	d.middlewareOrder = order

	for i := range d.Controllers {
		var routes []Route

		switch c := d.Controllers[i].(type) {
		case PatternController:
			r := Route{
				c.Pattern(), c.Method(), c.Handler(d.Context), c.Name(), c,
			}
			routes = append(routes, r)
		case MultiPatternController:
			for _, tuple := range c.Patterns() {
				r := Route{
					tuple.Pattern, tuple.Method, c.Handler(d.Context), "", c,
				}

				routes = append(routes, r)
			}
		default:
			panic(fmt.Sprintf("Controllers of type '%T' are not supported\n", c))
		}

		for _, r := range routes {
			d.Logger.Debugf("Adding route to %s with method %d and controller %T to %s.\n",
				r.Pattern, r.Method, r.Controller, d.Pattern)
			if err := d.trie.AddRoute(r); err != nil {
				panic(fmt.Sprintf("Error adding route for %s to the dispatcher: %v\n", r.Pattern, err))
			}
		}
	}
}
开发者ID:urandom,项目名称:webfw,代码行数:81,代码来源:dispatcher.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang context.Context类代码示例发布时间:2022-05-28
下一篇:
Golang webfw.Logger类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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