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


Golang cookiestore.New函數代碼示例

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


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

示例1: Test_LoginRedirectAfterLoginRequired

func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.New()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(Google(&Config{
		ClientID:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	n.Use(LoginRequired())

	mux := http.NewServeMux()

	mux.HandleFunc("/login-required", func(w http.ResponseWriter, req *http.Request) {
		t.Log("hi there")
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
	n.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)
	}
}
開發者ID:GoIncremental,項目名稱:negroni-oauth2,代碼行數:33,代碼來源:oauth2_test.go

示例2: Test_LoginRequired

func Test_LoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(Google(&Config{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))

	n.Use(LoginRequired())

	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)
	r, _ := http.NewRequest("GET", "/", nil)
	n.ServeHTTP(recorder, r)
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page although user is not logged in. %d\n", recorder.Code)
	}
}
開發者ID:GoIncremental,項目名稱:negroni-oauth2,代碼行數:25,代碼來源:oauth2_test.go

示例3: main

func main() {
	fmt.Println("Starting sample auth...")

	n := negroni.Classic()

	n.Use(sessions.Sessions("mysession", cookiestore.New([]byte("secret12"))))

	n.Use(KeyCloak(&oauth2.Config{
		ClientID:     "grafana",
		ClientSecret: "10b54f7c-a8ed-4a61-abd7-eb993d12367b",
		RedirectURL:  "http://127.0.0.1:8090/oauth2callback",
		Scopes:       []string{"name", "email"}}))

	router := mux.NewRouter()

	router.HandleFunc("/", Home)
	router.HandleFunc("/version", Version)

	router.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "World !")
	})

	n.Use(oauth2.LoginRequired())

	n.UseHandler(router)
	n.Run(":8090")
}
開發者ID:biswanaths,項目名稱:sample-oauth,代碼行數:27,代碼來源:main.go

示例4: Serve

// Serve set the route handlers and serve
func Serve() {
	// Setup middleware
	middle := negroni.Classic()
	store := cookiestore.New([]byte("keyboard cat"))
	middle.Use(sessions.Sessions("hugoku", store))

	router := httprouter.New()
	router.GET("/", routes.Index)
	router.GET("/auth/login", routes.GithubLogin)
	router.GET("/auth/logout", routes.GithubLogout)
	router.GET("/auth/callback", routes.GithubLoginCallback)
	router.GET("/project/:id", routes.GetProject)
	router.POST("/project", routes.PostProject)
	router.DELETE("/project/:id", routes.DeleteProject)
	router.GET("/about", routes.About)
	router.GET("/faq", routes.FAQ)

	// Apply middleware to the router
	middle.UseHandler(router)

	log.Println("Started running on http://127.0.0.1:8080")

	// TODO: Get the port from flag, config file or environment var
	log.Fatal(http.ListenAndServe(":8080", middle))
}
開發者ID:gophergala2016,項目名稱:hugoku,代碼行數:26,代碼來源:main.go

示例5: Test_LogoutOnAccessTokenExpiration

func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := cookiestore.New([]byte("secret123"))

	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", s))
	n.Use(Google(&Config{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))

	mux := http.NewServeMux()
	mux.HandleFunc("/addtoken", func(w http.ResponseWriter, req *http.Request) {
		SetToken(req, "dummy token")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		tok := GetToken(req)
		if tok != nil {
			t.Errorf("User not logged out although access token is expired. %v\n", tok)
		}
	})
	n.UseHandler(mux)
	addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
	index, _ := http.NewRequest("GET", "/", nil)
	n.ServeHTTP(recorder, addtoken)
	n.ServeHTTP(recorder, index)
}
開發者ID:GoIncremental,項目名稱:negroni-oauth2,代碼行數:30,代碼來源:oauth2_test.go

示例6: Test_SessionsDeleteValue

func Test_SessionsDeleteValue(t *testing.T) {
	n := negroni.Classic()

	store := cookiestore.New([]byte("secret123"))
	n.Use(sessions.Sessions("my_session", store))

	mux := http.NewServeMux()

	mux.HandleFunc("/testsession", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		session.Set("hello", "world")
		session.Delete("hello")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		if session.Get("hello") == "world" {
			t.Error("Session value deleting failed")
		}
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/testsession", nil)
	n.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/show", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	n.ServeHTTP(res2, req2)
}
開發者ID:vitalie,項目名稱:negroni-sessions,代碼行數:34,代碼來源:sessions_test.go

示例7: main

func main() {
	// 라우터 생성
	router := httprouter.New()

	// 핸들러 정의
	router.GET("/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		// 렌더러를 사용하여 템플릿 렌더링
		renderer.HTML(w, http.StatusOK, "index", map[string]interface{}{"host": r.Host})
	})

	router.GET("/rooms", retrieveRooms)
	router.GET("/rooms/:id", retrieveRoom)
	router.POST("/rooms", createRoom)
	router.DELETE("/rooms/:id", deleteRoom)

	router.GET("/rooms/:id/messages", retrieveMessages)
	// router.POST("/rooms/:id/messages", createMessage)

	router.GET("/info", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		u := GetCurrentUser(r)
		info := map[string]interface{}{"currrent_user": u, "clients": clients}
		renderer.JSON(w, http.StatusOK, info)
	})

	router.GET("/login", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		// login 페이지 렌더링
		renderer.HTML(w, http.StatusOK, "login", nil)
	})
	router.GET("/logout", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		// 세션에서 사용자 정보 제거 후 로그인 페이지로 이동
		sessions.GetSession(r).Delete(currentUserKey)
		http.Redirect(w, r, "/login", http.StatusFound)
	})
	router.GET("/auth/:action/:provider", loginHandler)

	router.GET("/ws/:room_id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		socket, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Fatal("ServeHTTP:", err)
			return
		}
		newClient(socket, ps.ByName("room_id"), GetCurrentUser(r))
	})

	// negroni 미들웨어 생성
	n := negroni.Classic()

	store := cookiestore.New([]byte(sessionSecret))
	n.Use(sessions.Sessions(sessionKey, store))

	n.Use(LoginRequired("/login", "/auth"))

	// negroni에 router를 핸들러로 등록
	n.UseHandler(router)

	// 웹서버 실행
	n.Run(":3000")
}
開發者ID:RorNHJ,項目名稱:GoLanguage,代碼行數:58,代碼來源:main.go

示例8: main

func main() {
	// Load the configuration.
	err := envconfig.Process("elwinar", &configuration)
	if err != nil {
		log.Fatalln("unable to read the configuration from env:", err)
	}

	// Open the database connection.
	database, err = sqlx.Connect("sqlite3", configuration.Database)
	if err != nil {
		log.Fatalln("unable to open the database:", err)
	}

	// Initialize the router.
	router := httprouter.New()

	// Add the front-office handlers.
	router.GET("/", Index)
	router.GET("/read", List)
	router.GET("/article/:slug", View)
	router.GET("/fortune", Fortune)
	router.GET("/sitemap.xml", Sitemap)

	// Add the back-office handlers.
	router.GET("/login", Login)
	router.POST("/login", Authenticate)
	router.GET("/logout", Logout)
	router.GET("/write", Write)
	router.POST("/write", Create)
	router.GET("/article/:slug/edit", Edit)
	router.POST("/article/:slug/edit", Update)
	router.GET("/article/:slug/delete", Delete)
	router.GET("/article/:slug/publish", Publish)
	router.GET("/article/:slug/unpublish", Unpublish)

	// Initialize the server middleware stack.
	stack := negroni.New()
	stack.Use(gzip.Gzip(gzip.DefaultCompression))
	stack.Use(negroni.NewRecovery())
	stack.Use(negroni.NewStatic(http.Dir(configuration.Public)))
	stack.Use(sessions.Sessions("elwinar", cookiestore.New([]byte(configuration.Secret))))
	stack.UseHandler(router)

	// Initialize the HTTP server.
	server := &graceful.Server{
		Timeout: 1 * time.Second,
		Server: &http.Server{
			Addr:    fmt.Sprintf(":%d", configuration.Port),
			Handler: stack,
		},
	}

	// Run the server.
	err = server.ListenAndServe()
	if err != nil {
		log.Fatalln("unable to run the server:", err)
	}
}
開發者ID:chibimi,項目名稱:elwinar,代碼行數:58,代碼來源:elwinar.go

示例9: main

func main() {
	//Loads environment variables from a .env file
	godotenv.Load("environment")

	var (
		clientID     = getEnv("OAUTH2_CLIENT_ID", "client_id")
		clientSecret = getEnv("OAUTH2_CLIENT_SECRET", "client_secret")
		redirectURL  = getEnv("OAUTH2_REDIRECT_URL", "redirect_url")
	)

	secureMux := http.NewServeMux()

	// Routes that require a logged in user
	// can be protected by using a separate route handler
	// If the user is not authenticated, they will be
	// redirected to the login path.
	secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		fmt.Fprintf(w, "OK: %s", token.Access())
	})

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	n := negroni.New()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(oauth2.Google(&oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURL:  redirectURL,
		Scopes:       []string{"https://www.googleapis.com/auth/drive"},
	}))

	router := http.NewServeMux()

	//routes added to mux do not require authentication
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		if token == nil || !token.Valid() {
			fmt.Fprintf(w, "not logged in, or the access token is expired")
			return
		}
		fmt.Fprintf(w, "logged in")
		return
	})

	//There is probably a nicer way to handle this than repeat the restricted routes again
	//of course, you could use something like gorilla/mux and define prefix / regex etc.
	router.Handle("/restrict", secure)

	n.UseHandler(router)

	n.Run(":3000")
}
開發者ID:anyweez,項目名稱:check,代碼行數:55,代碼來源:main.go

示例10: main

func main() {
	ren := render.New(render.Options{
		Layout:        "shared/layout",
		IsDevelopment: true,
	})

	//sessions
	store := cookiestore.New([]byte("secret"))

	//db
	// db, err := sqlx.Connect("postgres", os.Getenv("CONNECTIONSTRING"))
	db, err := sqlx.Connect("postgres", "user=travisjones dbname=cm_app sslmode=disable")
	if err != nil {
		log.Println("Error initializing database...")
		log.Fatalln(err)
	}

	c := ctx{db, ren}

	n := negroni.New()
	nauth := negroni.New()

	//routers
	router := mux.NewRouter()
	authRouter := mux.NewRouter()

	//AUTHORIZED ROUTES
	authRouter.HandleFunc("/", c.Home)
	router.Handle("/", nauth).Methods("GET")

	//OPEN ROUTES
	router.HandleFunc("/account/login", c.Login).Methods("GET")
	router.HandleFunc("/account/login", c.LoginPost).Methods("POST")
	router.HandleFunc("/account/signup", c.Signup).Methods("GET")
	router.HandleFunc("/account/signup", c.SignupPost).Methods("POST")
	router.HandleFunc("/account/logout", c.Logout).Methods("GET")

	//Middleware
	nauth.Use(negroni.HandlerFunc(RequireAuth))
	nauth.UseHandler(authRouter)

	//Sessions
	n.Use(sessions.Sessions("authex", store))

	n.Use(negroni.NewStatic(http.Dir("public")))

	n.UseHandler(router)

	n.Run(
		fmt.Sprint(":", os.Getenv("PORT")),
	)

}
開發者ID:travjones,項目名稱:cm_app,代碼行數:53,代碼來源:main.go

示例11: runWeb

func runWeb() {

	mux := http.NewServeMux()
	mux.HandleFunc("/config", HandleConfig)
	mux.HandleFunc("/", HandleLogin)

	n := negroni.Classic()
	store := cookiestore.New([]byte("ss"))
	n.Use(sessions.Sessions("shadow", store))
	//n.Use(gzip.Gzip(gzip.DefaultCompression))
	n.UseHandler(mux)
	n.Run(":3000")

}
開發者ID:neil-zeng,項目名稱:shadowsocks-go,代碼行數:14,代碼來源:server.go

示例12: main

func main() {

	store := cookiestore.New([]byte("secretkey789"))
	router := LoadRoutes()
	n := negroni.Classic()
	static := negroni.NewStatic(http.Dir("static"))
	static.Prefix = "/static"
	n.Use(static)
	n.Use(negroni.HandlerFunc(MgoMiddleware))
	n.Use(sessions.Sessions("global_session_store", store))
	n.UseHandler(router)
	n.Run(":3000")

}
開發者ID:vishnuvr,項目名稱:negroni-angularjs-mgo,代碼行數:14,代碼來源:main.go

示例13: main

func main() {
	rt := httprouter.New()
	rt.GET("/", AuthHandler)
	rt.GET("/tmpl", DlmHandler)
	rt.POST("/upload", upload.UploadHandler)

	n := negroni.Classic()

	store := cookiestore.New([]byte("session_secret"))
	n.Use(sessions.Sessions("my_session", store))

	n.UseHandler(rt)
	n.Run(":10000")
}
開發者ID:MeowLeg,項目名稱:go-template,代碼行數:14,代碼來源:main.go

示例14: main

func main() {
	defer db.Close()

	mux := http.NewServeMux()
	n := negroni.Classic()

	store := cookiestore.New([]byte("ohhhsooosecret"))
	n.Use(sessions.Sessions("global_session_store", store))

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		SimplePage(w, r, "mainpage")
	})

	mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			SimplePage(w, r, "login")
		} else if r.Method == "POST" {
			LoginPost(w, r)
		}
	})

	mux.HandleFunc("/signup", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			SimplePage(w, r, "signup")
		} else if r.Method == "POST" {
			SignupPost(w, r)
		}
	})

	mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
		Logout(w, r)
	})

	mux.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) {
		SimpleAuthenticatedPage(w, r, "home")
	})

	mux.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
		APIHandler(w, r)
	})

	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	n.UseHandler(mux)
	port := os.Getenv("PORT")
	if port == "" {
		port = "3300"
	}
	n.Run(":" + port)
}
開發者ID:jmptrader,項目名稱:Negroni-Example,代碼行數:50,代碼來源:main.go

示例15: NewCoreServer

/**
 * Constructs a new server object.
 */
func NewCoreServer() CoreServer {
	server := CoreServer{
		Router:     mux.NewRouter(),
		Middleware: negroni.New(),
	}

	/**
	 * Add some Negroni middleware.
	 */
	server.Middleware.Use(negroni.NewLogger())
	// TODO: Need to change key.
	storage := cookiestore.New([]byte("temporary"))
	server.Middleware.Use(sessions.Sessions("userprofile", storage))
	config := (oauth2.Config)(GetClientConfig())
	server.Middleware.Use(oauth2.Google(&config))

	/**
	 * Mux describing routes that require the user to be logged in via
	 * oauth first.
	 */
	secureMux := http.NewServeMux()
	// Core app handlers; these require the user to be logged in.
	secureMux.HandleFunc("/app/fetch", fetch)
	secureMux.HandleFunc("/app", app_handler)

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	/**
	 * Handlers that don't require authentication.
	 */
	server.Router.HandleFunc("/auth", auth_handler)
	// Static content handler
	server.Router.PathPrefix("/static").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("web/"))))
	// Simple redirect handler
	server.Router.HandleFunc("/", main_handler)

	/**
	 * And now connect everything together and call it a day.
	 */
	// Make sure the core router knows to let the secure router handle these routes.
	server.Router.Handle("/app/fetch", secure)
	server.Router.Handle("/app", secure)
	// Set negroni handler
	server.Middleware.UseHandler(server.Router)

	return server
}
開發者ID:anyweez,項目名稱:check,代碼行數:52,代碼來源:server.go


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