本文整理汇总了Golang中code/google/com/p/gorilla/sessions.NewCookieStore函数的典型用法代码示例。如果您正苦于以下问题:Golang NewCookieStore函数的具体用法?Golang NewCookieStore怎么用?Golang NewCookieStore使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewCookieStore函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: init
func init() {
peopleModel = model.PeopleModel{"people"}
store = sessions.NewCookieStore([]byte("hellogolang.org"))
postModel = model.PostModel{"post"}
postClassModel = model.PostClassModel{"post_class"}
commentModel = model.CommentModel{"comment"}
}
开发者ID:xulingjue,项目名称:hellogolang,代码行数:7,代码来源:init.go
示例2: main
func main() {
var err error
session, err = mgo.Dial(os.Getenv("DATABASE_URL"))
if err != nil {
panic(err)
}
database = session.DB("").Name
//create an index for the username field on the users collection
if err := session.DB("").C("users").EnsureIndex(mgo.Index{
Key: []string{"username"},
Unique: true,
}); err != nil {
panic(err)
}
store = sessions.NewCookieStore([]byte(os.Getenv("KEY")))
router = pat.New()
router.Add("GET", "/login", handler(loginForm)).Name("login")
router.Add("POST", "/login", handler(login))
router.Add("GET", "/register", handler(registerForm)).Name("register")
router.Add("POST", "/register", handler(register))
router.Add("GET", "/logout", handler(logout)).Name("logout")
router.Add("GET", "/", handler(hello)).Name("index")
router.Add("POST", "/sign", handler(sign)).Name("sign")
if err = http.ListenAndServe(":"+os.Getenv("PORT"), router); err != nil {
panic(err)
}
}
开发者ID:postfix,项目名称:gostbook,代码行数:35,代码来源:main.go
示例3: main
func main() {
var cfgfile *string = flag.String("config", "", "configuration file")
flag.Parse()
if *cfgfile == "" {
flag.Usage()
os.Exit(1)
}
log.Printf("this is activities, revision %s", gitRevision)
log.Printf("GOMAXPROCS = %d", runtime.GOMAXPROCS(0))
log.Printf("NumCPU = %d", runtime.NumCPU())
cfg, err := goconf.ReadConfigFile(*cfgfile)
// TODO: add error handling
driver, _ := cfg.GetString("database", "driver")
dsn, _ := cfg.GetString("database", "dsn")
auth_key, _ := cfg.GetString("sessions", "authkey")
enc_key, _ := cfg.GetString("sessions", "enckey")
db_handle, err := sql.Open(driver, dsn)
if err != nil {
log.Fatalf("sql.Open: %v", err)
}
defer db_handle.Close()
db := NewDatabase(db_handle)
store := sessions.NewCookieStore([]byte(auth_key), []byte(enc_key))
r := pat.New()
r.Add("POST", "/auth/try", &TryAuthenticateHandler{Db: db, Store: store})
r.Add("POST", "/auth/signup", &SignupHandler{Db: db})
r.Add("POST", "/auth/logout", &LogoutHandler{Store: store})
r.Add("POST", "/auth", &AuthenticateHandler{Db: db, Store: store})
r.Add("POST", "/activity/add", &AddActivityHandler{Store: store, Db: db})
r.Add("GET", "/activity/list/{page:[0-9]+}", &ListActivitiesHandler{Db: db, Store: store})
r.Add("POST", "/activity/type/add", &AddActivityTypeHandler{Db: db, Store: store})
r.Add("POST", "/activity/type/edit", &EditActivityTypeHandler{Db: db, Store: store})
r.Add("POST", "/activity/type/del", &DeleteActivityTypeHandler{Db: db, Store: store})
r.Add("GET", "/activity/type/list", &ListActivityTypesHandler{Db: db, Store: store})
r.Add("GET", "/activity/latest", &LatestActivitiesHandler{Db: db, Store: store})
r.Add("GET", "/", http.FileServer(http.Dir("htdocs")))
httpsrv := &http.Server{Handler: Logger(r), Addr: ":8000"}
if err := httpsrv.ListenAndServe(); err != nil {
log.Fatalf("ListenAndServe: %v", err)
}
}
开发者ID:bignoyrb,项目名称:activitylog,代码行数:51,代码来源:main.go
示例4: main
func main() {
var cfgfile *string = flag.String("config", "", "configuration file")
flag.Parse()
if *cfgfile == "" {
flag.Usage()
os.Exit(1)
}
cfg, err := goconf.ReadConfigFile(*cfgfile)
// TODO: add error handling
driver, _ := cfg.GetString("database", "driver")
dsn, _ := cfg.GetString("database", "dsn")
auth_key, _ := cfg.GetString("sessions", "authkey")
enc_key, _ := cfg.GetString("sessions", "enckey")
db, err = sql.Open(driver, dsn)
if err != nil {
log.Fatalf("sql.Open: %v", err)
}
defer db.Close()
store = sessions.NewCookieStore([]byte(auth_key), []byte(enc_key))
r := pat.New()
r.Post("/auth/try", http.HandlerFunc(TryAuthenticate))
r.Post("/auth/signup", http.HandlerFunc(Signup))
r.Post("/auth/logout", http.HandlerFunc(Logout))
r.Post("/auth", http.HandlerFunc(Authenticate))
r.Post("/activity/add", http.HandlerFunc(AddActivity))
r.Get("/activity/list/{page:[0-9]+}", http.HandlerFunc(ListActivities))
r.Post("/activity/type/add", http.HandlerFunc(AddActivityType))
r.Post("/activity/type/edit", http.HandlerFunc(EditActivityType))
r.Post("/activity/type/del", http.HandlerFunc(DeleteActivityType))
r.Get("/activity/type/list", http.HandlerFunc(ListActivityTypes))
r.Get("/activity/latest", http.HandlerFunc(LatestActivities))
r.Add("GET", "/", http.FileServer(http.Dir("htdocs")))
httpsrv := &http.Server{Handler: r, Addr: ":8000"}
if err := httpsrv.ListenAndServe(); err != nil {
log.Fatalf("ListenAndServe: %v", err)
}
}
开发者ID:Gehry,项目名称:activitylog,代码行数:46,代码来源:activities.go
示例5: TestAuthenticateHandler
func TestAuthenticateHandler(t *testing.T) {
testdata := []struct {
auth_data string
http_code int
authenticated_result bool
}{
{"username=foo&password=bar", http.StatusOK, true},
{"username=invalid&password=invalid", http.StatusOK, false},
}
for _, td := range testdata {
req, _ := http.NewRequest("POST", "http://localhost/auth", bytes.NewBufferString(td.auth_data))
req.Header["Content-Length"] = []string{fmt.Sprintf("%d", len(td.auth_data))}
req.Header["Content-Type"] = []string{"application/x-www-form-urlencoded"}
mock_db := &MockCredentialsVerifierActivityTypesGetter{}
handler := &AuthenticateHandler{Db: mock_db, Store: sessions.NewCookieStore([]byte(""))}
resp := NewMockResponseWriter()
handler.ServeHTTP(resp, req)
if resp.StatusCode != td.http_code {
t.Errorf("AuthenticateHandler responded with %d (expected: %d)", resp.StatusCode, td.http_code)
}
if len(resp.Header()["Content-Type"]) < 1 || resp.Header()["Content-Type"][0] != "application/json" {
t.Errorf("AuthenticateHandler sends wrong Content-Type (%v)", resp.Header()["Content-Type"][0])
}
data := make(map[string]interface{})
if err := json.Unmarshal(resp.Buffer.Bytes(), &data); err != nil {
t.Errorf("AuthenticateHandler returned invalid JSON: %v", err)
}
if authenticated, ok := data["authenticated"].(bool); !ok {
t.Errorf("JSON authenticated field didn't contain bool")
} else {
if authenticated != td.authenticated_result {
t.Errorf("AuthenticateHandler authenticated returns %v (expected %v)", authenticated, td.authenticated_result)
}
}
}
}
开发者ID:bignoyrb,项目名称:activitylog,代码行数:45,代码来源:auth_test.go
示例6: init
func init() {
logFile, err := os.OpenFile("systic.log", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Printf("Couldn't open systic.log. Logging to stdout.\n")
} else {
log.SetOutput(logFile)
}
Config, err := config.LoadConfig(filepath.Join("config", "app.conf"))
if err != nil {
log.Fatalf("Couldn't read app.conf: %s\n", err)
}
appName = Config.AppName
if len(Config.Secret) < 20 {
log.Fatalln("That secret in app.conf is not long enough! Make it hella long!")
}
Jar = sessions.NewCookieStore([]byte(Config.Secret))
}
开发者ID:shunyata,项目名称:systic,代码行数:20,代码来源:globals.go
示例7: main
func main() {
store = sessions.NewCookieStore([]byte("rape"))
var c = ballsite.BallCount()
fmt.Println("Ball count:", c)
/*
var ball = ballsite.Ball{}
ball.Title = "First Ball"
ball.Description = "Dies ist der erste Ball mit dem storm clouds and rainbow image"
ball.ImagePath = "/var/www/polandball/media/images/storm_clouds_and_rainbow-wallpaper-1920x1200.jpg"
ball.ThumbPath = "/var/www/polandball/media/thumbnails/storm_clouds_and_rainbow-wallpaper-1920x1200.jpg.png"
fmt.Println("before insert:", ball)
ball = ballsite.InsertBall(ball)
fmt.Println("after insert:", ball)
ball = ballsite.Ball{}
ball.Title = "Second Ball"
ball.Description = "Dies ist der zweite Ball mit dem hacker redux image"
ball.ImagePath = "/var/www/polandball/media/images/hacker_redux_by_hashbox.png"
ball.ThumbPath = "/var/www/polandball/media/thumbnails/hacker_redux_by_hashbox.png.png"
fmt.Println("before insert:", ball)
ball = ballsite.InsertBall(ball)
fmt.Println("after insert:", ball)
return
*/
http.Handle("/", makeHandler(index))
http.Handle("/ball/", makeHandler(ball))
http.Handle("/rand", makeHandler(random))
http.Handle("/view/image/", makeHandler(image))
http.Handle("/view/thumbnail/", makeHandler(thumb))
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}
开发者ID:kybernetyk,项目名称:golandball,代码行数:41,代码来源:site.go
示例8: init
func init() {
logFile, err := os.OpenFile("systic.log", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Printf("Couldn't open systic.log. Logging to stdout.\n")
} else {
log.SetOutput(logFile)
}
configBytes, err := ioutil.ReadFile(srcPath)
if err != nil {
log.Fatalf("Couldn't read app.conf: %s\n", err)
}
err = json.Unmarshal(configBytes, &config)
if err != nil {
log.Fatalf("Error unmarshalling app.conf: %s\n", err)
}
appName = config["appname"].(string)
Jar = sessions.NewCookieStore([]byte(config["secret"]))
}
开发者ID:shunyata,项目名称:systic-showcase,代码行数:22,代码来源:globals.go
示例9: randInt
"any": Any,
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
func randomString(l int) string {
bytes := make([]byte, l)
for i := 0; i < l; i++ {
bytes[i] = byte(randInt(65, 90))
}
return string(bytes)
}
var Store = sessions.NewCookieStore([]byte(randomString(100)))
// any reports whether the first argument is equal to
// any of the remaining arguments.
func Any(args ...interface{}) bool {
if len(args) == 0 {
return false
}
x := args[0]
switch x := x.(type) {
case string, int, int64, byte, float32, float64:
for _, y := range args[1:] {
if x == y {
return true
}
}
开发者ID:jakecoffman,项目名称:portfolio,代码行数:31,代码来源:templates.go
示例10: init
func init() {
if config["db"] == "" {
println("数据库地址还没有配置,请到config.json内配置db字段.")
return
}
session, err := mgo.Dial(config["db"])
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
db = session.DB("gopher")
cookie_secret := config["cookie_secret"]
store = sessions.NewCookieStore([]byte(cookie_secret))
utils = &Utils{}
// 如果没有status,创建
var status Status
c := db.C("status")
err = c.Find(nil).One(&status)
if err != nil {
c.Insert(&Status{
Id_: bson.NewObjectId(),
UserCount: 0,
TopicCount: 0,
ReplyCount: 0,
UserIndex: 0,
})
}
// 检查是否有超级账户设置
var superusers []string
for _, username := range strings.Split(config["superusers"], ",") {
username = strings.TrimSpace(username)
if username != "" {
superusers = append(superusers, username)
}
}
if len(superusers) == 0 {
println("你没有设置超级账户,请在config.json中的superusers中设置,如有多个账户,用逗号分开")
}
c = db.C("users")
var users []User
c.Find(bson.M{"issuperuser": true}).All(&users)
// 如果mongodb中的超级用户不在配置文件中,取消超级用户
for _, user := range users {
if !stringInArray(superusers, user.Username) {
c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"issuperuser": false}})
}
}
// 设置超级用户
for _, username := range superusers {
c.Update(bson.M{"username": username, "issuperuser": false}, bson.M{"$set": bson.M{"issuperuser": true}})
}
}
开发者ID:JoonyLi,项目名称:gopher,代码行数:66,代码来源:views.go
示例11: Get
package sessions
import (
"code.google.com/p/gorilla/sessions"
"net/http"
)
const (
_ = iota
Anonymous
User
)
var (
store = sessions.NewCookieStore([]byte("NiseGoPostSecret"))
)
type Session struct {
*sessions.Session
}
func Get(r *http.Request) *Session {
s, _ := store.Get(r, "session")
return &Session{s}
}
func New(r *http.Request) *Session {
s, _ := store.New(r, "session")
s.Values["hasError"] = false
return &Session{s}
}
开发者ID:nise-nabe,项目名称:NisePostGo,代码行数:31,代码来源:session.go
示例12:
recent_amount = 20
)
var (
mode = tmplmgr.Production
//TODO: make sure these things happen after the env import
assets_dir = filepath.Join(env("APPROOT", ""), "assets")
template_dir = filepath.Join(env("APPROOT", ""), "templates")
dist_dir = filepath.Join(env("APPROOT", ""), "dist")
base_template = tmplmgr.Parse(tmpl_root("base.tmpl"))
recent_template = tmplmgr.Parse(tmpl_root("recent.tmpl"))
current_template = tmplmgr.Parse(tmpl_root("current.tmpl"))
store = sessions.NewCookieStore([]byte(store_key))
base_meta = &Meta{
CSS: list{
"bootstrap-superhero.min.css",
// "bootstrap-responsive.min.css",
"main.css",
},
JS: list{
"jquery.min.js",
"jquery-ui.min.js",
"bootstrap.js",
"status.js",
"main.js",
},
BaseTitle: "GoCI",
}
开发者ID:jbaikge,项目名称:goci,代码行数:30,代码来源:app.go
示例13: userCookie
import (
"code.google.com/p/gorilla/sessions"
"errors"
"fmt"
"github.com/fzzbt/radix"
"net/http"
"net/url"
"time"
)
var ErrUserNotLoggedIn = errors.New("session: user not logged in")
var ErrResourceRedirected = errors.New("session: resource was redirected")
// used for flashes
var sessionStore = sessions.NewCookieStore([]byte("something-very-secret"))
type session struct {
id string
user *user
}
// Fetch user from cookie, set cookie, sync cookies x-domain
// main cookie flexer, called before every resource handler
func userCookie(w http.ResponseWriter, r *http.Request) (u *user, err error) {
// login cookie
c, err := r.Cookie("vafanLogin")
if err != nil {
if err == http.ErrNoCookie {
err = nil
开发者ID:saulhoward,项目名称:vafan,代码行数:30,代码来源:session.go
示例14: Set
/*
sessioner stores your session variables
*/
package sessioner
import (
"code.google.com/p/gorilla/sessions"
"net/http"
)
var store = sessions.NewCookieStore([]byte("Go Game Lobby!"))
/*
The Session is the interface exposed to the rest of the program
*/
type Session interface {
Set(k, v interface{}) // Set will set a session variable
Get(k interface{}) interface{} //Get will obtain the result of a session variable
Clear(k interface{}) interface{} //Clear will obstain the result of a session variable, and then delete it from the session value
}
type session struct {
sess *sessions.Session
r *http.Request
}
func (this *session) Set(k, v interface{}) {
this.sess.Values[k] = v
}
func (this *session) Get(k interface{}) interface{} {
开发者ID:ScruffyProdigy,项目名称:Middleware,代码行数:31,代码来源:session.go
示例15: main
"code.google.com/p/gorilla/schema"
"code.google.com/p/gorilla/sessions"
"fmt"
"html/template"
"log"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/order", OrderHandler)
r.HandleFunc("/order/{id}", ViewHandler)
log.Fatal(http.ListenAndServe(":8080", r))
}
var store = sessions.NewCookieStore([]byte("randomsecrets"))
func Reply(file string, w http.ResponseWriter, r *http.Request, session *sessions.Session) {
buf := bufio.NewWriter(w)
t, _ := template.ParseFiles(file)
t.Execute(buf, session)
session.Save(r, w)
buf.Flush()
}
var itemlist = []string{"Bacon", "Ham", "More bacon"}
func ViewHandler(w http.ResponseWriter, r *http.Request) {
PreventCaching(w)
session, _ := store.Get(r, "session-stuff")
开发者ID:errnoh,项目名称:wepa2012,代码行数:31,代码来源:controllers.go
示例16: main
package main
import (
"code.google.com/p/gorilla/sessions"
"html/template"
"log"
"net/http"
"os"
)
const cookieSecret = "" // put a random string here
const sessionName = "" // sensible name related to your app
// cookie store for sessions
var store = sessions.NewCookieStore([]byte(cookieSecret))
const defaultPort = "12000" // change it
func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl := template.New("main.html")
tmpl, err := tmpl.ParseGlob("templates/*.html")
if err != nil {
log.Println("error parsing:", err)
}
开发者ID:hasenj,项目名称:gobase,代码行数:30,代码来源:main.go
示例17: processRequest
}
address := controller.processRequest(w, r)
if strings.HasPrefix(address, "redirect:") {
address = "/" + strings.SplitAfterN(address, ":", 2)[1]
http.Redirect(w, r, address, http.StatusFound)
return
}
// html/template oletuksena estää injektiot
t := getTemplate(address)
t.Execute(w, r)
}
var store = sessions.NewCookieStore([]byte("baconbaconbacon"))
//----------
type Controller interface {
processRequest(w http.ResponseWriter, r *http.Request) string
}
type IndexController struct{}
func (c *IndexController) processRequest(w http.ResponseWriter, r *http.Request) string {
return "login.html"
}
type LoginController struct {
}
开发者ID:errnoh,项目名称:wepa2012,代码行数:31,代码来源:controllers.go
示例18: init
package hello
import (
"fmt"
"net/http"
"code.google.com/p/gorilla/mux"
"code.google.com/p/gorilla/sessions"
gaeSessions "code.google.com/p/gorilla/appengine/sessions"
)
var router = new(mux.Router)
var store = sessions.NewCookieStore([]byte("my-secret-key"),
[]byte("1234567890123456"))
var dStore = gaeSessions.NewDatastoreStore("", []byte("my-secret-key"),
[]byte("1234567890123456"))
var mStore = gaeSessions.NewMemcacheStore("", []byte("my-secret-key"),
[]byte("1234567890123456"))
func init() {
// Register a couple of routes.
router.HandleFunc("/", homeHandler).Name("home")
router.HandleFunc("/{salutation}/{name}", helloHandler).Name("hello")
router.HandleFunc("/datastore-session", datastoreSessionHandler).Name("datastore-session")
router.HandleFunc("/cookie-session", cookieSessionHandler).Name("cookie-session")
router.HandleFunc("/memcache-session", memcacheSessionHandler).Name("memcache-session")
// Send all incoming requests to router.
http.Handle("/", router)
}
开发者ID:Bobberino,项目名称:musings,代码行数:30,代码来源:hello.go
示例19:
// Copyright 2012 The AEGo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package session provides an interface for Sessions. Currently using:
"code.google.com/p/gorilla/sessions"
*/
package session
import (
"code.google.com/p/gorilla/sessions"
//"config"
)
// Store is a gorilla/session store.
var Store = sessions.NewCookieStore([]byte("123456789"))
//var Store = sessions.NewCookieStore([]byte(config.SecretKey))
开发者ID:scotch,项目名称:aego,代码行数:21,代码来源:store.go
示例20: readConfig
// 由于golang 可以直接仍个编译后的文件过去
// 所以密码采用 email+raw_pwd 进行加密,即使数据库被盗,源码对方也看不到,无法了解加密方式,破解难度提高 加密方式是 bcrypt
package user
import (
"labix.org/v2/mgo"
"os"
//"fmt"
"code.google.com/p/gorilla/sessions"
"encoding/json"
//"io/ioutil"
//"text/template"
)
var store = sessions.NewCookieStore([]byte("secret-code"))
/*
config/user.json 是用户模块的专属配置文件
里面有:
"db": "localhost",
"email": "[email protected]",
"pwd": "xxx"
*/
var config map[string]string
//var email_tmpl *template.Template
var db_user, db_resertpwd *mgo.Collection
func readConfig() {
// 读取配置文件
开发者ID:ruandao,项目名称:old-jucan_golang,代码行数:31,代码来源:init.go
注:本文中的code/google/com/p/gorilla/sessions.NewCookieStore函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论