當前位置: 首頁>>代碼示例>>Golang>>正文


Golang session.Sessioner函數代碼示例

本文整理匯總了Golang中github.com/macaron-contrib/session.Sessioner函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sessioner函數的具體用法?Golang Sessioner怎麽用?Golang Sessioner使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Sessioner函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Test_GenerateToken

func Test_GenerateToken(t *testing.T) {
	Convey("Generate token", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer())

		// Simulate login.
		m.Get("/login", func(sess session.Store, x CSRF) {
			sess.Set("uid", "123456")
		})

		// Generate token.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)
	})
}
開發者ID:macaron-contrib,項目名稱:csrf,代碼行數:29,代碼來源:csrf_test.go

示例2: newInstance

func newInstance() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("static"))
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory:  "views",
		IndentJSON: macaron.Env != macaron.PROD,
		IndentXML:  macaron.Env != macaron.PROD,
	}))
	m.Use(cache.Cacher())
	m.Use(session.Sessioner())

	//DoXXX 表示GET請求;
	//OnXXX 表示POST請求;
	//AnyXXX 表示GET、POST混合請求
	m.Any("/", AnyValidate)

	m.Get("/dogs", DoDogs)
	m.Get("/pups", DoPups)
	m.Get("/about", DoAbout)
	m.Get("/comment", DoComment)
	m.Get("/signin", DoSignin)
	m.Get("/dogDetail", DoDogDetail)
	m.Get("/pupDetail", DoPupDetail)

	m.Post("/onComment", OnComment)
	m.Post("/onSignin", OnSignin)
	return m
}
開發者ID:zileyuan,項目名稱:hidog,代碼行數:30,代碼來源:main.go

示例3: newMacaron

// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	if setting.EnableGzip {
		m.Use(macaron.Gziper())
	}
	m.Use(macaron.Static(
		path.Join(setting.StaticRootPath, "public"),
		macaron.StaticOptions{
			SkipLogging: !setting.DisableRouterLog,
		},
	))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  path.Join(setting.StaticRootPath, "templates"),
		Funcs:      []template.FuncMap{base.TemplateFuncs},
		IndentJSON: macaron.Env != macaron.PROD,
	}))
	m.Use(i18n.I18n(i18n.Options{
		SubURL:          setting.AppSubUrl,
		Directory:       path.Join(setting.ConfRootPath, "locale"),
		CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
		Langs:           setting.Langs,
		Names:           setting.Names,
		Redirect:        true,
	}))
	m.Use(cache.Cacher(cache.Options{
		Adapter:  setting.CacheAdapter,
		Interval: setting.CacheInternal,
		Conn:     setting.CacheConn,
	}))
	m.Use(captcha.Captchaer(captcha.Options{
		SubURL: setting.AppSubUrl,
	}))
	m.Use(session.Sessioner(session.Options{
		Provider: setting.SessionProvider,
		Config:   *setting.SessionConfig,
	}))
	m.Use(csrf.Generate(csrf.Options{
		Secret:     setting.SecretKey,
		SetCookie:  true,
		Header:     "X-Csrf-Token",
		CookiePath: setting.AppSubUrl,
	}))
	m.Use(toolbox.Toolboxer(m, toolbox.Options{
		HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
			&toolbox.HealthCheckFuncDesc{
				Desc: "Database connection",
				Func: models.Ping,
			},
		},
	}))
	m.Use(middleware.Contexter())
	return m
}
開發者ID:ericcapricorn,項目名稱:gogs,代碼行數:56,代碼來源:web.go

示例4: main

func main() {
	server_root := "https://nicksite.com:3000"
	local_login_url := "http://nicksite.com:4000/login"

	m := macaron.Classic()
	m.Use(macaron.Renderer())
	m.Use(session.Sessioner())

	m.Get("/login", func(ctx *macaron.Context, s session.Store) {
		ticket := ctx.Query("ticket")
		if len(ticket) == 0 {
			ctx.Redirect(server_root + "/login?service=" + local_login_url)
			return
		} else {
			s.Set("ticket", ticket)
			ctx.Redirect("/")
		}
	})

	m.Get("/", func(ctx *macaron.Context, s session.Store) string {
		if s.Get("login") != nil {
			return "Welcome, " + s.Get("login").(string)
		}

		// Retrieve the ticket
		if s.Get("ticket") == nil {
			ctx.Redirect("/login")
			return ""
		}

		// Validate the ticket
		ticket := s.Get("ticket").(string)
		resp, err := http.Get(server_root + "/validate?ticket=" + ticket + "&service=" + local_login_url)

		if err != nil {
			log.Fatalf("ERROR: %s\n", err)
			return "Unable to validate the ticket"
		}

		bs, _ := ioutil.ReadAll(resp.Body)
		split := strings.Split(string(bs), "\n")
		ticketValid, login := split[0] == "yes", split[1]

		if ticketValid {
			s.Set("login", login)
			ctx.Redirect("/")
			return ""
		}

		return "Invalid login"
	})

	m.Run()
}
開發者ID:henryluki,項目名稱:cas,代碼行數:54,代碼來源:go_cas_client.go

示例5: newMacaron

func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("static"))
	m.Use(session.Sessioner(session.Options{
		Provider:       "mysql",
		ProviderConfig: beego.AppConfig.String("mysqlstring"),
	}))
	m.Use(middleware.Contexter())
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory: "views",
	}))
	return m

}
開發者ID:trigrass2,項目名稱:tech_oa,代碼行數:16,代碼來源:main.go

示例6: newMacaron

// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			SkipLogging: setting.ProdMode,
		},
	))
	m.Use(macaron.Static("raw",
		macaron.StaticOptions{
			Prefix:      "raw",
			SkipLogging: setting.ProdMode,
		}))
	m.Use(pongo2.Pongoer(pongo2.Options{
		IndentJSON: !setting.ProdMode,
	}))
	m.Use(i18n.I18n())
	m.Use(session.Sessioner())
	m.Use(middleware.Contexter())
	return m
}
開發者ID:fanbuchi,項目名稱:gowalker,代碼行數:23,代碼來源:gowalker.go

示例7: Test_Invalid

func Test_Invalid(t *testing.T) {
	Convey("Invalid session data type", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer())

		// Simulate login.
		m.Get("/login", func(sess session.Store, x CSRF) {
			sess.Set("uid", true)
		})

		// Generate token.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)
	})

	Convey("Invalid request", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer())

		// Simulate login.
		m.Get("/login", Validate, func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		So(resp.Code, ShouldEqual, http.StatusBadRequest)
	})

	Convey("Invalid token", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer())

		// Simulate login.
		m.Get("/login", Validate, func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)

		req.Header.Set("X-CSRFToken", "invalid")
		m.ServeHTTP(resp, req)

		So(resp.Code, ShouldEqual, http.StatusBadRequest)
	})
}
開發者ID:macaron-contrib,項目名稱:csrf,代碼行數:63,代碼來源:csrf_test.go

示例8: Test_GenerateCookie

func Test_GenerateCookie(t *testing.T) {
	Convey("Generate token to Cookie", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer(Options{
			SetCookie: true,
		}))

		// Simulate login.
		m.Get("/login", func(sess session.Store) {
			sess.Set("uid", 123456)
		})

		// Generate cookie.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Header().Get("Set-Cookie"), ShouldContainSubstring, "_csrf")
	})

	Convey("Generate token to custom Cookie", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer(Options{
			Cookie:    "custom",
			SetCookie: true,
		}))

		// Simulate login.
		m.Get("/login", func(sess session.Store) {
			sess.Set("uid", int64(123456))
		})

		// Generate cookie.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Header().Get("Set-Cookie"), ShouldContainSubstring, "custom")
	})
}
開發者ID:macaron-contrib,項目名稱:csrf,代碼行數:66,代碼來源:csrf_test.go

示例9: Test_Validate

func Test_Validate(t *testing.T) {
	Convey("Validate token", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer())

		// Simulate login.
		m.Get("/login", func(sess session.Store) {
			sess.Set("uid", 123456)
		})

		// Generate token.
		m.Get("/private", func(x CSRF) string {
			return x.GetToken()
		})

		m.Post("/private", Validate, func() {})

		// Login to set session.
		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		// Get a new token.
		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		token := resp.Body.String()

		// Post using _csrf form value.
		data := url.Values{}
		data.Set("_csrf", token)

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("POST", "/private", bytes.NewBufferString(data.Encode()))
		So(err, ShouldBeNil)

		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Set("Content-Length", com.ToStr(len(data.Encode())))
		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Code, ShouldNotEqual, http.StatusBadRequest)

		// Post using X-CSRFToken HTTP header.
		resp = httptest.NewRecorder()
		req, err = http.NewRequest("POST", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("X-CSRFToken", token)
		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Code, ShouldNotEqual, http.StatusBadRequest)
	})

	Convey("Validate custom token", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer(Options{
			Header: "X-Custom",
			Form:   "_custom",
		}))

		// Simulate login.
		m.Get("/login", func(sess session.Store) {
			sess.Set("uid", 123456)
		})

		// Generate token.
		m.Get("/private", func(x CSRF) string {
			return x.GetToken()
		})

		m.Post("/private", Validate, func() {})

		// Login to set session.
		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		// Get a new token.
		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		token := resp.Body.String()
//.........這裏部分代碼省略.........
開發者ID:macaron-contrib,項目名稱:csrf,代碼行數:101,代碼來源:csrf_test.go

示例10: main

func main() {
	// initiate the app
	m := macaron.Classic()

	// register middleware
	m.Use(macaron.Recovery())
	m.Use(macaron.Gziper())
	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			// Prefix is the optional prefix used to serve the static directory content. Default is empty string.
			Prefix: "public",
			// SkipLogging will disable [Static] log messages when a static file is served. Default is false.
			SkipLogging: true,
			// IndexFile defines which file to serve as index if it exists. Default is "index.html".
			IndexFile: "index.html",
			// Expires defines which user-defined function to use for producing a HTTP Expires Header. Default is nil.
			// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
			Expires: func() string { return "max-age=0" },
		}))
	m.Use(session.Sessioner(session.Options{
		// Name of provider. Default is "memory".
		Provider: "memory",
		// Provider configuration, it's corresponding to provider.
		ProviderConfig: "",
		// Cookie name to save session ID. Default is "MacaronSession".
		CookieName: "MacaronSession",
		// Cookie path to store. Default is "/".
		CookiePath: "/",
		// GC interval time in seconds. Default is 3600.
		Gclifetime: 3600,
		// Max life time in seconds. Default is whatever GC interval time is.
		Maxlifetime: 3600,
		// Use HTTPS only. Default is false.
		Secure: false,
		// Cookie life time. Default is 0.
		CookieLifeTime: 0,
		// Cookie domain name. Default is empty.
		Domain: "",
		// Session ID length. Default is 16.
		IDLength: 16,
		// Configuration section name. Default is "session".
		Section: "session",
	}))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		// Directory to load templates. Default is "templates".
		Directory: "templates",
		// Extensions to parse template files from. Defaults are [".tmpl", ".html"].
		Extensions: []string{".tmpl", ".html"},
		// Funcs is a slice of FuncMaps to apply to the template upon compilation. Default is [].
		Funcs: []template.FuncMap{map[string]interface{}{
			"AppName": func() string {
				return "Macaron"
			},
			"AppVer": func() string {
				return "1.0.0"
			},
		}},
		// Delims sets the action delimiters to the specified strings. Defaults are ["{{", "}}"].
		Delims: macaron.Delims{"{{", "}}"},
		// Appends the given charset to the Content-Type header. Default is "UTF-8".
		Charset: "UTF-8",
		// Outputs human readable JSON. Default is false.
		IndentJSON: true,
		// Outputs human readable XML. Default is false.
		IndentXML: true,
		// Prefixes the JSON output with the given bytes. Default is no prefix.
		// PrefixJSON: []byte("macaron"),
		// Prefixes the XML output with the given bytes. Default is no prefix.
		// PrefixXML: []byte("macaron"),
		// Allows changing of output to XHTML instead of HTML. Default is "text/html".
		HTMLContentType: "text/html",
	}))
	m.Use(cache.Cacher(cache.Options{
		// Name of adapter. Default is "memory".
		Adapter: "memory",
		// Adapter configuration, it's corresponding to adapter.
		AdapterConfig: "",
		// GC interval time in seconds. Default is 60.
		Interval: 60,
		// Configuration section name. Default is "cache".
		Section: "cache",
	}))

	// setup handlers
	m.Get("/", myHandler)
	m.Get("/welcome", myOtherHandler)
	m.Get("/query", myQueryStringHandler) // /query?name=Some+Name
	m.Get("/json", myJsonHandler)
	m.Post("/contact/submit", binding.Bind(ContactForm{}), mySubmitHandler)
	m.Get("/session", mySessionHandler)
	m.Get("/set/cookie/:value", mySetCookieHandler)
	m.Get("/get/cookie", myGetCookieHandler)
	m.Get("/database", myDatabaseHandler)
	m.Get("/database/list", myDatabaseListHandler)
	m.Get("/cache/write/:key/:value", myCacheWriteHandler)
	m.Get("/cache/read/:key", myCacheReadHandler)

	log.Println("Server is running on localhost:4000...")
	log.Println(http.ListenAndServe("0.0.0.0:4000", m))
}
開發者ID:james2doyle,項目名稱:macaron-example,代碼行數:100,代碼來源:main.go

示例11: main

func main() {
	initParse()

	err := readConfig("service.conf", &c.Config)
	if err != nil {
		glog.V(1).Infof("Read Configure file fail:%#v", err)
		return
	}

	initDB(c.Config)

	m := macaron.Classic()
	macaron.Env = macaron.PROD
	m.Use(macaron.Renderer())
	m.Use(session.Sessioner(session.Options{
		Provider:       "redis",
		ProviderConfig: "addr=127.0.0.1:6379",
	}))

	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			// 請求靜態資源時的 URL 前綴,默認沒有前綴
			Prefix: "public",
			// 禁止記錄靜態資源路由日誌,默認為不禁止記錄
			SkipLogging: true,
			// 當請求目錄時的默認索引文件,默認為 "index.html"
			IndexFile: "index.html",
			// 用於返回自定義過期響應頭,不能為不設置
			// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
			Expires: func() string {
				return time.Now().Add(24 * 60 * time.Minute).UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT")
			},
		}))

	m.Use(macaron.Renderer(macaron.RenderOptions{
		// 模板文件目錄,默認為 "templates"
		Directory: "templates",
		// 模板文件後綴,默認為 [".tmpl", ".html"]
		Extensions: []string{".tmpl", ".html"},
		// 模板函數,默認為 []
		Funcs: []template.FuncMap{map[string]interface{}{
			"AppName": func() string {
				return "Macaron"
			},
			"AppVer": func() string {
				return "1.0.0"
			},
		}},
		// 模板語法分隔符,默認為 ["{{", "}}"]
		Delims: macaron.Delims{"{{", "}}"},
		// 追加的 Content-Type 頭信息,默認為 "UTF-8"
		Charset: "UTF-8",
		// 渲染具有縮進格式的 JSON,默認為不縮進
		IndentJSON: true,
		// 渲染具有縮進格式的 XML,默認為不縮進
		IndentXML: true,
		// 渲染具有前綴的 JSON,默認為無前綴
		PrefixJSON: []byte(""),
		// 渲染具有前綴的 XML,默認為無前綴
		PrefixXML: []byte(""),
		// 允許輸出格式為 XHTML 而不是 HTML,默認為 "text/html"
		HTMLContentType: "text/html",
	}))
	m.Map(x)
	m.SetDefaultCookieSecret("UYCNJSHA123JCN409")
	//	m.Post("/login",controller.Login)
	//	m.Get("/logout",controller.Logout)

	m.Group("/users", func() {
		m.Post("", binding.Bind(Customer{}), controller.PostCustomer)
		m.Get("", controller.GetCustomers)
	})

	m.Group("/goods", func() {
		m.Post("", binding.Bind(Goods{}), controller.PostGood)
		m.Get("", controller.GetGoods)
	})

	m.Group("/orders", func() {
		m.Post("/alipay", binding.Bind(Order{}), controller.PostOrder)
		m.Get("", controller.GetOrders)
	})

	m.Group("/alipay", func() {
		m.Post("/notify", controller.AlipayNotify)
		m.Get("/return", controller.AlipayReturn)
	})

	m.Run(8080)
}
開發者ID:renhuiyang,項目名稱:macaron_xorm_shoppingweb_practise,代碼行數:90,代碼來源:main.go

示例12: Test_GenerateHeader

func Test_GenerateHeader(t *testing.T) {
	Convey("Generate token to header", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer(Options{
			SetHeader: true,
		}))

		// Simulate login.
		m.Get("/login", func(sess session.Store) {
			sess.Set("uid", "123456")
		})

		// Generate HTTP header.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Header().Get("X-CSRFToken"), ShouldNotBeEmpty)
	})

	Convey("Generate token to header with origin", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer(Options{
			SetHeader: true,
			Origin:    true,
		}))

		// Simulate login.
		m.Get("/login", func(sess session.Store) {
			sess.Set("uid", "123456")
		})

		// Generate HTTP header.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		req.Header.Set("Origin", "https://www.example.com")
		m.ServeHTTP(resp, req)

		So(resp.Header().Get("X-CSRFToken"), ShouldBeEmpty)
	})

	Convey("Generate token to custom header", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer(Options{
			Header:    "X-Custom",
			SetHeader: true,
		}))

		// Simulate login.
		m.Get("/login", func(sess session.Store) {
			sess.Set("uid", "123456")
		})

		// Generate HTTP header.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Header().Get("X-Custom"), ShouldNotBeEmpty)
	})
}
開發者ID:macaron-contrib,項目名稱:csrf,代碼行數:100,代碼來源:csrf_test.go

示例13: Test_LedisProvider

func Test_LedisProvider(t *testing.T) {
	Convey("Test ledis session provider", t, func() {
		opt := session.Options{
			Provider:       "ledis",
			ProviderConfig: "data_dir=./tmp.db",
		}

		Convey("Basic operation", func() {
			m := macaron.New()
			m.Use(session.Sessioner(opt))

			m.Get("/", func(ctx *macaron.Context, sess session.Store) {
				sess.Set("uname", "unknwon")
			})
			m.Get("/reg", func(ctx *macaron.Context, sess session.Store) {
				raw, err := sess.RegenerateId(ctx)
				So(err, ShouldBeNil)
				So(raw, ShouldNotBeNil)

				uname := raw.Get("uname")
				So(uname, ShouldNotBeNil)
				So(uname, ShouldEqual, "unknwon")
			})
			m.Get("/get", func(ctx *macaron.Context, sess session.Store) {
				sid := sess.ID()
				So(sid, ShouldNotBeEmpty)

				raw, err := sess.Read(sid)
				So(err, ShouldBeNil)
				So(raw, ShouldNotBeNil)

				uname := sess.Get("uname")
				So(uname, ShouldNotBeNil)
				So(uname, ShouldEqual, "unknwon")

				So(sess.Delete("uname"), ShouldBeNil)
				So(sess.Get("uname"), ShouldBeNil)

				So(sess.Destory(ctx), ShouldBeNil)
			})

			resp := httptest.NewRecorder()
			req, err := http.NewRequest("GET", "/", nil)
			So(err, ShouldBeNil)
			m.ServeHTTP(resp, req)

			cookie := resp.Header().Get("Set-Cookie")

			resp = httptest.NewRecorder()
			req, err = http.NewRequest("GET", "/reg", nil)
			So(err, ShouldBeNil)
			req.Header.Set("Cookie", cookie)
			m.ServeHTTP(resp, req)

			cookie = resp.Header().Get("Set-Cookie")

			resp = httptest.NewRecorder()
			req, err = http.NewRequest("GET", "/get", nil)
			So(err, ShouldBeNil)
			req.Header.Set("Cookie", cookie)
			m.ServeHTTP(resp, req)

			Convey("Regenrate empty session", func() {
				m.Get("/empty", func(ctx *macaron.Context, sess session.Store) {
					raw, err := sess.RegenerateId(ctx)
					So(err, ShouldBeNil)
					So(raw, ShouldNotBeNil)
				})

				resp = httptest.NewRecorder()
				req, err = http.NewRequest("GET", "/empty", nil)
				So(err, ShouldBeNil)
				req.Header.Set("Cookie", "MacaronSession=ad2c7e3cbecfcf486; Path=/;")
				m.ServeHTTP(resp, req)
			})
		})
	})
}
開發者ID:mbrukman,項目名稱:grafana,代碼行數:78,代碼來源:ledis_test.go

示例14: newMacaron

// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	if !setting.DisableRouterLog {
		m.Use(macaron.Logger())
	}
	m.Use(macaron.Recovery())
	if setting.EnableGzip {
		m.Use(macaron.Gziper())
	}
	if setting.Protocol == setting.FCGI {
		m.SetURLPrefix(setting.AppSubUrl)
	}
	m.Use(macaron.Static(
		path.Join(setting.StaticRootPath, "public"),
		macaron.StaticOptions{
			SkipLogging: setting.DisableRouterLog,
		},
	))
	m.Use(macaron.Static(
		setting.AvatarUploadPath,
		macaron.StaticOptions{
			Prefix:      "avatars",
			SkipLogging: setting.DisableRouterLog,
		},
	))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  path.Join(setting.StaticRootPath, "templates"),
		Funcs:      []template.FuncMap{base.TemplateFuncs},
		IndentJSON: macaron.Env != macaron.PROD,
	}))

	localeNames, err := bindata.AssetDir("conf/locale")
	if err != nil {
		log.Fatal(4, "Fail to list locale files: %v", err)
	}
	localFiles := make(map[string][]byte)
	for _, name := range localeNames {
		localFiles[name] = bindata.MustAsset("conf/locale/" + name)
	}
	m.Use(i18n.I18n(i18n.Options{
		SubURL:          setting.AppSubUrl,
		Files:           localFiles,
		CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
		Langs:           setting.Langs,
		Names:           setting.Names,
		Redirect:        true,
	}))
	m.Use(cache.Cacher(cache.Options{
		Adapter:       setting.CacheAdapter,
		AdapterConfig: setting.CacheConn,
		Interval:      setting.CacheInternal,
	}))
	m.Use(captcha.Captchaer(captcha.Options{
		SubURL: setting.AppSubUrl,
	}))
	m.Use(session.Sessioner(setting.SessionConfig))
	m.Use(csrf.Csrfer(csrf.Options{
		Secret:     setting.SecretKey,
		SetCookie:  true,
		Header:     "X-Csrf-Token",
		CookiePath: setting.AppSubUrl,
	}))
	m.Use(toolbox.Toolboxer(m, toolbox.Options{
		HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
			&toolbox.HealthCheckFuncDesc{
				Desc: "Database connection",
				Func: models.Ping,
			},
		},
	}))

	// OAuth 2.
	if setting.OauthService != nil {
		for _, info := range setting.OauthService.OauthInfos {
			m.Use(oauth2.NewOAuth2Provider(info.Options, info.AuthUrl, info.TokenUrl))
		}
	}
	m.Use(middleware.Contexter())
	return m
}
開發者ID:peterhadlaw,項目名稱:gogs,代碼行數:81,代碼來源:web.go

示例15: InitApp

func InitApp() *macaron.Macaron {
	app := macaron.Classic()
	app.Use(macaron.Static("public"))
	app.Use(session.Sessioner())
	app.Use(oauth2.Github(
		&goauth2.Config{
			ClientID:     os.Getenv("GITHUB_CLIENT_ID"),
			ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
			// https://developer.github.com/v3/oauth/#scopes
			Scopes:      []string{"user:email", "public_repo", "write:repo_hook"},
			RedirectURL: "",
		},
	))

	app.Use(macaron.Renderer(macaron.RenderOptions{
		Delims: macaron.Delims{"{[", "]}"},
	}))

	app.Get("/", routers.Homepage)
	app.Get("/build", oauth2.LoginRequired, routers.Build)
	app.Post("/stats/:org/:name/:branch/:os/:arch", routers.DownloadStats)

	app.Get("/:org/:name", func(ctx *macaron.Context, r *http.Request) {
		org := ctx.Params(":org")
		//name := ctx.Params(":name")
		if org == "js" {
			ctx.Next()
			return
		}
		ctx.Redirect(r.RequestURI+"/"+"master", 302)
	})

	// api
	app.Group("/api", func() {
		app.Get("/repos", api.RepoList)
		app.Post("/repos", api.AnonymousTriggerBuild)
		app.Any("/user/repos", oauth2.LoginRequired, middleware.UserNeeded, api.UserRepoList)
		app.Get("/recent/repos", api.RecentBuild)
		app.Post("/builds", oauth2.LoginRequired, api.TriggerBuild)

		// accept PUT(callback), POST(trigger build)
		app.Any("/repos/:id/build", oauth2.LoginRequired, middleware.UserNeeded, api.RepoBuild)
		app.Get("/user", oauth2.LoginRequired, middleware.UserNeeded, api.UserInfo)
	})

	app.Get("/explore", func(ctx *macaron.Context) {
		ctx.HTML(200, "explore", nil)
	})
	app.Get("/repos", func(ctx *macaron.Context) {
		ctx.HTML(200, "repos", nil)
	})

	app.Get("/:org/:name/:branch", func(ctx *macaron.Context, r *http.Request) {
		org := ctx.Params(":org")
		name := ctx.Params(":name")
		branch := ctx.Params(":branch")

		// Here need redis connection
		repoPath := org + "/" + name
		domain := "dn-gobuild5.qbox.me"
		buildJson := fmt.Sprintf("//%s/gorelease/%s/%s/%s/%s", domain, org, name, branch, "builds.json")

		ctx.Data["DlCount"], _ = rdx.Get("downloads:" + repoPath).Int64()
		ctx.Data["Org"] = org
		ctx.Data["Name"] = name
		ctx.Data["Branch"] = branch
		ctx.Data["BuildJSON"] = template.URL(buildJson)
		prepo := &Repo{
			Domain: domain,
			Org:    org,
			Name:   name,
			Branch: branch,
			Ext:    "",
		}
		pubs := make([]*Publish, 0)
		pubs = append(pubs, prepo.Pub("darwin", "amd64"))
		pubs = append(pubs, prepo.Pub("linux", "amd64"))
		pubs = append(pubs, prepo.Pub("linux", "386"))
		pubs = append(pubs, prepo.Pub("linux", "arm"))
		pubs = append(pubs, prepo.Pub("windows", "amd64"))
		pubs = append(pubs, prepo.Pub("windows", "386"))
		ctx.Data["Pubs"] = pubs
		ctx.HTML(200, "release")
	})
	return app
}
開發者ID:gobuild,項目名稱:gobuild,代碼行數:86,代碼來源:main.go


注:本文中的github.com/macaron-contrib/session.Sessioner函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。