Golang code-google-com-p-gorilla-sessions.NewCookieStore类(方法)实例源码

下面列出了Golang code-google-com-p-gorilla-sessions.NewCookieStore 类(方法)源码代码实例,从而了解它的用法。

作者:xulingju    项目:hellogolan   
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"}
}

作者:postfi    项目:gostboo   
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)
	}
}

作者:bignoyr    项目:activitylo   
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)
	}
}

作者:Gehr    项目:activitylo   
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)
	}
}

作者:bignoyr    项目:activitylo   
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)
			}
		}
	}
}

作者:shunyat    项目:systi   
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))
}

作者:kybernety    项目:golandbal   
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)
	}
}

作者:shunyat    项目:systic-showcas   
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"]))
}

作者:jakecoffma    项目:portfoli   
"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
			}
		}

作者:JoonyL    项目:gophe   
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}})
	}
}

作者:nise-nab    项目:NisePostG   
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}
}

作者:jbaikg    项目:goc   
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",
	}

作者:saulhowar    项目:vafa   
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

作者:ScruffyProdig    项目:Middlewar   
/*
	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{} {

作者:errno    项目:wepa201   
"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")

作者:hasen    项目:gobas   
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)
		}

作者:errno    项目:wepa201   
}

	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 {
}

作者:Bobberin    项目:musing   
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)
}

作者:scotc    项目:aeg   
// 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))

作者:ruanda    项目:old-jucan_golan   
// 由于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() {
	// 读取配置文件


问题


面经


文章

微信
公众号

扫码关注公众号