本文整理匯總了Golang中code/google/com/p/gorilla/sessions.NewCookieStore函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewCookieStore函數的具體用法?Golang NewCookieStore怎麽用?Golang NewCookieStore使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewCookieStore函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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"}
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
}
}
示例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))
}
示例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)
}
}
示例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"]))
}
示例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
}
}
示例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}})
}
}
示例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}
}
示例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",
}
示例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
示例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{} {
示例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")