本文整理汇总了Golang中github.com/martini-contrib/sessions.NewCookieStore函数的典型用法代码示例。如果您正苦于以下问题:Golang NewCookieStore函数的具体用法?Golang NewCookieStore怎么用?Golang NewCookieStore使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewCookieStore函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
m := martini.Classic()
// set up the session, and map it into martini
store := sessions.NewCookieStore([]byte("secret-pass"))
m.Use(sessions.Sessions("go-webapp", store))
//on login, we will set the users username in the session
m.Post("/login", func(w http.ResponseWriter, r *http.Request, session sessions.Session) string {
username := r.FormValue("username")
session.Set("username", username)
http.Redirect(w, r, "/home", http.StatusFound)
return "OK"
})
//if the user has no username, we will redirect them to the login page
m.Get("/home", authorize, func(user *User) string {
return "Welcome back, " + user.Username
})
//on logout, clear the username in the session
m.Get("/logout", func(w http.ResponseWriter, r *http.Request, session sessions.Session) string {
session.Delete("username")
http.Redirect(w, r, "/login", http.StatusFound)
return "OK"
})
m.Run()
}
示例2: main
func main() {
ga.AdminPort = 8000
ga.MysqlDsn = "root:[email protected](192.168.1.15:3306)/galaxy2"
ga.TemplatePath = "/Users/sunlei/go/src/galaxy/templates"
ga.DbName = "default"
go ga.Run()
m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(render.Renderer(render.Options{
Directory: "/Users/sunlei/go/src/github.com/go-galaxy/galaxy/example/template", // Specify what path to load the templates from.
Extensions: []string{".tmpl", ".html"}, // Specify extensions to load for templates.
Layout: "",
}))
m.Use(sessions.Sessions("my_session", store))
m.Use(func(res http.ResponseWriter, req *http.Request, session sessions.Session) {
if strings.Contains(req.URL.String(), "login") {
return
}
v := session.Get("login")
if v == nil {
http.Redirect(res, req, "login", http.StatusFound)
}
})
m.Use(sessions.Sessions("my_session", store))
m.Get("/login", Login)
m.Get("/", Index)
m.Post("/login", Login)
m.Get("/logout", LogOut)
m.Get("/test", Test)
m.RunOnAddr(":3000")
}
示例3: NewApi
func NewApi(address string, rdb *db.Rethinkdb, auth auth.Authenticator, sessionKey string) (*dialogueApi, error) {
m := martini.Classic()
// sessions
store := sessions.NewCookieStore([]byte(sessionKey))
m.Use(sessions.Sessions("dialogue", store))
a := &dialogueApi{
m: m,
rdb: rdb,
auth: auth,
address: address,
}
// middleware
m.Use(render.Renderer())
// routes
// content
m.Get("/topics", a.apiAuthorize, a.GetTopics)
m.Post("/topics", a.apiAuthorize, a.PostTopics)
m.Post("/topics/:topicId", a.apiAuthorize, a.PostTopicsPosts)
m.Get("/topics/:topicId", a.apiAuthorize, a.GetTopic)
m.Delete("/topics/:topicId", a.apiAuthorize, a.DeleteTopic)
m.Delete("/posts/:postId", a.apiAuthorize, a.DeletePost)
// authentication
m.Post("/auth", a.Authenticate)
m.Post("/users", a.apiAuthorize, a.PostUsers)
m.Put("/users/:username", a.apiAuthorize, a.PutUser)
// setup
m.Get("/setup", a.Setup)
return a, nil
}
示例4: main
func main() {
m := martini.Classic()
m.Use(martini_amber.Renderer(map[string]string{
}))
store := sessions.NewCookieStore([]byte("secret...."))
m.Use(sessions.Sessions("msession",store))
m.Get("/", func(r martini_amber.Render,request *http.Request,session sessions.Session) {
log.Println(request.UserAgent())
name := session.Get("name")
if name==nil && request.FormValue("name")!=""{
session.Set("name",request.FormValue("name"))
}
vars := map[string]interface{}{"cats": []string{"Home", "Product", "Contact","Live Showing"},"arts":arts,"name":name}
r.Amber(200, "home", vars)
})
m.Get("/test", func(r martini_amber.Render,request *http.Request,session sessions.Session) {
log.Println(request.UserAgent())
name := session.Get("name")
if name==nil && request.FormValue("name")!=""{
session.Set("name",request.FormValue("name"))
}
vars := map[string]interface{}{"cats": []string{"Home", "Product", "Contact","Live Showing"},"arts":arts,"name":name}
r.Amber(200, "test", vars)
})
m.RunOnAddr(":8080")
}
示例5: main
func main() {
cfg, err := os.Open("config.json")
if err != nil {
log.Fatal(err)
}
parser := json.NewDecoder(cfg)
if err = parser.Decode(common.Config); err != nil {
log.Fatal(err)
}
initDB()
initQueue()
initS3()
m := martini.Classic()
store := sessions.NewCookieStore([]byte(common.Config.SessionsSecret))
m.Use(sessions.Sessions("semquery", store))
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
m.Use(common.UserInject)
routes.RegisterRoutes(m)
if len(os.Args) > 1 {
m.RunOnAddr(os.Args[1])
} else {
m.Run()
}
}
示例6: adminserver
func adminserver() {
m := martini.Classic()
// m.Use(martini.Static("./assets/"))
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(sessions.Sessions("51jczj_session", store))
m.Use(render.Renderer(render.Options{
Layout: "admin_layout",
}))
/***********static*************/
m.Get("/css/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
m.Get("/editor/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
m.Get("/fonts/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
m.Get("/img/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
m.Get("/js/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
/***********biz*************/
m.Get("/", admin.ArchivesHandler)
m.Get("/archives", admin.ArchivesHandler)
m.Post("/login", admin.LoginHandler)
m.Get("/logout", admin.LogoutHandler)
m.Get("/login", admin.GoLoginHandler)
m.Get("/login/:path", admin.GoLoginHandler)
http.ListenAndServe(fmt.Sprintf(":%s", base.AdminWebPort), m)
}
示例7: main
func main() {
m := martini.Classic()
m.Map(SetupDB())
m.Use(render.Renderer(render.Options{
Layout: "layout",
Funcs: []template.FuncMap{
{
"unescaped": func(args ...interface{}) template.HTML {
return template.HTML(args[0].(string))
},
},
},
}))
//Sessions
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(sessions.Sessions("vsauth", store))
m.Get("/", IndexArticles)
m.Get("/create", CreateArticle)
m.Get("/read", ReadArticle)
m.Get("/update", UpdateArticle)
m.Get("/delete", DeleteArticle)
m.Post("/save", SaveArticle)
m.Get("/login", LoginForm)
m.Post("/login", UserLogin)
m.Get("/signup", SignupForm)
m.Post("/signup", UserSignup)
m.Get("/logout", UserLogout)
m.Get("/wrong", WrongLogin)
m.Run()
}
示例8: NewWeb
func NewWeb(mailConf *conf.MailConf, debug bool) *MailWeb {
var web *MailWeb = new(MailWeb)
web.mconf = mailConf
web.debug = debug
web.userTimeout = 86400 // 1 day
store := sessions.NewCookieStore(securecookie.GenerateRandomKey(128))
// 1) Set a maximum age for the client-side cookies (forces a session timeout afterwards)
store.Options(sessions.Options{MaxAge: int(web.userTimeout)})
web.martini = martini.Classic()
web.martini.Use(render.Renderer(render.Options{
Directory: "static/templates",
Extensions: []string{".html"},
}))
web.martini.Use(sessions.Sessions("watneySession", store))
web.martini.Use(sessionauth.SessionUser(auth.GenerateAnonymousUser))
sessionauth.RedirectUrl = "/sessionTimeout"
sessionauth.RedirectParam = "next"
// 2) Register a cleanup go routine that checks every x minutes, for outdated users, which
// simply left the page without logging out
web.registerUserCleanup(30)
// x) Define and set all handlers
web.initHandlers()
return web
}
示例9: main
func main() {
m := martini.Classic()
dbMap := initDb()
m.Map(dbMap)
store := sessions.NewCookieStore([]byte("nonotestetstsst"))
m.Use(sessions.Sessions("gogonki", store))
m.Use(render.Renderer())
m.Get("/", Index)
m.Get("/coords", Coords)
m.Get("/move/:x/:y", Move) // ToDo: make this post request
m.Get("/state", GetState)
m.Get("/profile", ShowProfile)
m.Get("/login", LoginForm)
m.Post("/login", Login)
m.Get("/logout", Logout)
m.Post("/create", binding.Bind(User{}), CreateUser)
m.Get("/signup", SignupForm)
m.Post("/signup", Signup)
m.Post("/create-room", CreateRoom)
m.Post("/list-rooms", ListRooms)
//m.Use(Auth)
m.Run()
}
示例10: Test_LogoutOnAccessTokenExpiration
func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
recorder := httptest.NewRecorder()
s := sessions.NewCookieStore([]byte("secret123"))
m := martini.Classic()
m.Use(sessions.Sessions("my_session", s))
m.Use(Google(&Options{
// no need to configure
}))
m.Get("/addtoken", func(s sessions.Session) {
s.Set(keyToken, "dummy token")
})
m.Get("/", func(s sessions.Session) {
if s.Get(keyToken) != nil {
t.Errorf("User not logged out although access token is expired.")
}
})
addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
index, _ := http.NewRequest("GET", "/", nil)
m.ServeHTTP(recorder, addtoken)
m.ServeHTTP(recorder, index)
}
示例11: main
func main() {
m := martini.Classic()
m.Map(SetupDB())
m.Use(martini.Logger())
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
store := sessions.NewCookieStore([]byte(CookieSecret))
m.Use(sessions.Sessions("bunkaisession", store))
log.Println("env is", martini.Env)
m.Map(martini.Env)
m.Group("/", func(m martini.Router) {
m.Get("", Home)
}, AssetMap)
m.Group("/api", func(m martini.Router) {
m.Post("/login", PostLogin)
m.Post("/users", UserCreate)
m.Group("/sentences", func(m martini.Router) {
m.Post("", SentenceCreate)
m.Get("", SentenceList)
m.Delete("/:id", SentenceDelete)
}, RequireLogin)
m.Group("/users", func(m martini.Router) {
m.Post("/logout", Logout)
m.Get("/me", UserGet)
}, RequireLogin)
})
m.Run()
}
示例12: main
func main() {
m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret-isucon"))
m.Use(sessions.Sessions("isucon_go_session", store))
m.Use(martini.Static("../public"))
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
m.Get("/", func(r render.Render, session sessions.Session) {
r.HTML(200, "index", map[string]string{"Flash": getFlash(session, "notice")})
})
m.Post("/login", func(req *http.Request, r render.Render, session sessions.Session) {
user, err := attemptLogin(req)
notice := ""
if err != nil || user == nil {
switch err {
case ErrBannedIP:
notice = "You're banned."
case ErrLockedUser:
notice = "This account is locked."
default:
notice = "Wrong username or password"
}
session.Set("notice", notice)
r.Redirect("/")
return
}
session.Set("user_id", strconv.Itoa(user.ID))
r.Redirect("/mypage")
})
m.Get("/mypage", func(r render.Render, session sessions.Session) {
currentUser := getCurrentUser(session.Get("user_id"))
if currentUser == nil {
session.Set("notice", "You must be logged in")
r.Redirect("/")
return
}
currentUser.getLastLogin()
r.HTML(200, "mypage", currentUser)
})
m.Get("/report", func(r render.Render) {
r.JSON(200, map[string][]string{
"banned_ips": bannedIPs(),
"locked_users": lockedUsers(),
})
})
http.ListenAndServe(":8080", m)
}
示例13: main
/*
* Main function
*/
func main() {
m := martini.Classic()
//sessions
store := sessions.NewCookieStore([]byte("yyt726ddd318"))
m.Use(sessions.Sessions("yunyun", store))
m.Map(GetMongoDB())
m.Map(GetKotobaCollection())
//render html templates from directory
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
m.Post(auth.FUNC_LOGIN, auth.PostLogin)
m.Post(auth.FUNC_REGISTER, auth.Register)
m.Get(auth.FUNC_LOGOUT, auth.Logout)
m.Post(FUNC_SEARCH, auth.RequireLogin, kotoba.Search)
m.Get(FUNC_HOME, auth.RequireLogin, kotoba.Home)
m.Get(PAGE_ADD, auth.RequireLogin, AddWord)
m.Get(FUNC_KOTOBA, auth.RequireLogin, kotoba.ShowKotoba)
m.Post(FUNC_ADD, auth.RequireLogin, kotoba.AddKotoba)
m.Get(PAGE_REVIEW, auth.RequireLogin, kotoba.DoReviews)
m.Post(FUNC_CHECK, auth.RequireLogin, kotoba.CheckReview)
m.Get(PAGE_EDIT, auth.RequireLogin, kotoba.EditKotoba)
m.Post(FUNC_EDIT, auth.RequireLogin, kotoba.SaveEditKotoba)
m.Get(PAGE_STATS, auth.RequireLogin, kotoba.ShowStats)
// todo: not yet implemented
//m.Get(apiReviews, auth.RequireLogin, GetReviews)
m.Run()
}
示例14: StartWeb
func StartWeb() {
m := martini.Classic()
store := sessions.NewCookieStore([]byte("mandela"))
m.Use(sessions.Sessions("session", store))
m.Use(render.Renderer(render.Options{
Extensions: []string{".html"},
}))
m.Use(martini.Static("../../statics"))
r := martini.NewRouter()
r.Get("/", Home_handler) //首页
r.Get("/getdomain", GetDomain_handler) //获得本机的域名
m.Action(r.Handle)
webPort := 80
for i := 0; i < 1000; i++ {
_, err := net.ListenPacket("udp", ":"+strconv.Itoa(webPort))
if err != nil {
webPort = webPort + 1
} else {
break
}
}
m.RunOnAddr(":" + strconv.Itoa(webPort))
m.Run()
}
示例15: Test_LoginRedirectAfterLoginRequired
func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
recorder := httptest.NewRecorder()
m := martini.Classic()
m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
m.Use(Google(
&oauth2.Config{
ClientID: "client_id",
ClientSecret: "client_secret",
Scopes: []string{"x", "y"},
RedirectURL: "redirect_url",
},
))
m.Get("/login-required", LoginRequired, func(tokens Tokens) (int, string) {
return 200, tokens.Access()
})
r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
m.ServeHTTP(recorder, r)
location := recorder.HeaderMap["Location"][0]
if recorder.Code != 302 {
t.Errorf("Not being redirected to the auth page.")
}
if location != "/login?next=%2Flogin-required%3Fkey%3Dvalue" {
t.Errorf("Not being redirected to the right page, %v found", location)
}
}