本文整理匯總了Golang中github.com/gin-gonic/contrib/sessions.Sessions函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sessions函數的具體用法?Golang Sessions怎麽用?Golang Sessions使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Sessions函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Sessions
func Sessions() gin.HandlerFunc {
switch conf.SESSION_STORE {
case conf.REDIS:
store, err := gin_sessions.NewRedisStore(10, "tcp", conf.REDIS_SERVER, conf.REDIS_PWD, []byte("secret"))
if err != nil {
panic(err)
}
return gin_sessions.Sessions("mysession", store)
default:
store := gin_sessions.NewCookieStore([]byte("secret"))
return gin_sessions.Sessions("mysession", store)
}
}
示例2: Init
func Init() {
if router == nil {
gin.SetMode(gin.TestMode)
router = gin.Default()
templ := template.New("index")
router.SetHTMLTemplate(templ)
store := sessions.NewCookieStore([]byte("foundation"))
router.Use(sessions.Sessions("foundation", store))
portNo := 0
go func() {
router.GET("/", func(c *gin.Context) {
shared = *c
})
for portNo = 8124; true; portNo++ {
addr := fmt.Sprintf(`:%d`, portNo)
err := router.Run(addr)
if err != nil {
if strings.HasSuffix(err.Error(), `address already in use`) {
continue
}
}
break
}
}()
time.Sleep(50 * time.Millisecond)
http.Get(fmt.Sprintf("http://localhost:%d/", portNo)) // portNoが0じゃなくなるまでwaitしたほうが良い気もするが一旦
}
}
示例3: main
func main() {
r := gin.Default()
r.Static("/assets", "assets")
store := sessions.NewCookieStore([]byte("gssecret"))
r.Use(sessions.Sessions("mysession", store))
r.LoadHTMLGlob("templates/*")
fc := new(FrontController)
r.GET("/", fc.HomeCtr)
r.GET("/about", fc.AboutCtr)
r.GET("/view/:id", fc.ViewCtr)
r.GET("/view.php", fc.ViewAltCtr)
r.GET("/ping", fc.PingCtr)
r.GET("/search", fc.SearchCtr)
ac := new(AdminController)
admin := r.Group("/admin")
{
admin.GET("/", ac.ListBlogCtr)
admin.GET("/login", ac.LoginCtr)
admin.POST("/login-process", ac.LoginProcessCtr)
admin.GET("/logout", ac.LogoutCtr)
admin.GET("/addblog", ac.AddBlogCtr)
admin.POST("/save-blog-add", ac.SaveBlogAddCtr)
admin.GET("/listblog", ac.ListBlogCtr)
admin.GET("/deleteblog/:id", ac.DeleteBlogCtr)
admin.POST("/save-blog-edit", ac.SaveBlogEditCtr)
admin.GET("/editblog/:id", ac.EditBlogCtr)
}
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
示例4: setupMiddleware
// setupMiddleware is an internal method where we setup GIN middleware
func setupMiddleware(r *gin.Engine) {
// TODO: CACHE_URL should come from an environment variable but this requires
// validating and parsing of the connection url into it's base components.
store, err := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte(config.Config.Session_Secret))
if err != nil {
log.Fatalln("Failed to connect to Redis.", err)
}
r.Use(
secure.Secure(secure.Options{ // TODO: we should get these from config
AllowedHosts: []string{},
SSLRedirect: false,
SSLHost: "",
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
STSSeconds: 315360000,
STSIncludeSubdomains: true,
FrameDeny: true,
ContentTypeNosniff: true,
BrowserXssFilter: true,
ContentSecurityPolicy: "default-src 'self'",
}),
sessions.Sessions("session", store),
auth.UserMiddleware(),
)
}
示例5: init
func init() {
//初始化gin處理引擎
// gin.SetMode(gin.ReleaseMode)
g = gin.New()
g.Use(HandlerError())
{
funcMap := template.FuncMap{"Equals": func(v1, v2 interface{}) bool {
log.Logger.Debug("invoke function Equals")
return v1 == v2
}}
tmp := template.New("myTemplate")
templatePages := TemplatesFinder("templates")
tmp.Funcs(funcMap).ParseFiles(templatePages...)
g.SetHTMLTemplate(tmp)
{ //這三個順序不能變更,否則得不到正常處理
//先設置/讀取session信息
g.Use(sessions.Sessions("my_session", session.SessionStore))
//然後校驗請求的URL
g.Use(userauth.CheckLoginPage())
//最後處理靜態文件
g.Use(static.ServeRoot("/", "static")) // static files have higher priority over dynamic routes
}
}
}
示例6: main
func main() {
r := gin.Default()
r.Use(RequestIdMiddleware())
DB, err := db.Connect(db.ConnectOpts{
Address: fmt.Sprintf("%s:%d", os.Getenv("RETHINKDB_PORT_28015_TCP_ADDR"), 28015),
Database: "test",
})
if err != nil {
log.Fatalln(err.Error())
}
db.TableCreate("users").RunWrite(DB)
db.TableCreate("resources").RunWrite(DB)
store, err := sessions.NewRedisStore(10, "tcp", fmt.Sprintf("%s:%d", os.Getenv("REDIS_1_PORT_6379_TCP_ADDR"), 6379), "", []byte(os.Getenv("REDIS_SECRET")))
if err != nil {
log.Fatalln(err.Error())
}
gob.Register(models.User{})
r.Use(sessions.Sessions("session", store))
api.Init(r, DB, RequestAuthMiddleware)
login.Init(r, DB)
r.Any("/ping", func(c *gin.Context) {
if DB.IsConnected() {
c.String(200, "ok")
} else {
c.String(500, "not ok")
}
})
r.Run(":8080") // listen and serve on 0.0.0.0:8080
}
示例7: main
func main() {
r := gin.Default()
store := sessions.NewCookieStore([]byte(helper.Cookiesecret))
r.Use(sessions.Sessions("todo_session", store))
r.LoadHTMLGlob("templates/*")
r.GET("/todo", displayTodo)
r.Run(":8200")
}
示例8: main
func main() {
r := gin.Default()
store := sessions.NewCookieStore([]byte(helper.Cookiesecret))
r.Use(sessions.Sessions("todo_session", store))
r.LoadHTMLGlob("templates/*")
r.GET("/login", displayLogin)
r.POST("/login", postLogin)
r.GET("/user/:username", displayProfile)
r.Run(":8100")
}
示例9: Run
func Run(config *config.Config, etcd *store.Etcd) {
oauthConf := oauth2.Config{
ClientID: config.GitHubClientID,
ClientSecret: config.GitHubClientSecret,
Scopes: []string{"user", "read:public_key"},
Endpoint: githuboauth.Endpoint,
}
if config.ReleaseMode {
gin.SetMode(gin.ReleaseMode)
}
sessionStore := sessions.NewCookieStore([]byte(config.SecretKeyBase))
r := gin.Default()
r.Use(sessions.Sessions(AppName, sessionStore))
r.Static("/assets", "assets")
r.LoadHTMLGlob("templates/*")
rootController := controller.NewRootController(config, etcd)
appController := controller.NewAppController(config, etcd)
argController := controller.NewArgController(config, etcd)
envController := controller.NewEnvController(config, etcd)
healthcheckController := controller.NewHealthcheckController(config, etcd)
sessionController := controller.NewSessionController(config, etcd, oauthConf)
r.GET("/", rootController.Index)
r.GET("/signin", sessionController.SignIn)
r.GET("/signout", sessionController.SignOut)
r.GET("/oauth/callback", sessionController.Callback)
r.GET("/update-keys", sessionController.UpdateKeys)
r.GET("/apps", appController.Index)
r.POST("/apps", appController.New)
r.GET("/apps/:appName", appController.Get)
r.POST("/apps/:appName/build-args", argController.New)
r.POST("/apps/:appName/build-args/delete", argController.Delete) // TODO: DELETE /apps/:appName/build-args
r.POST("/apps/:appName/envs", envController.New)
r.POST("/apps/:appName/envs/delete", envController.Delete) // TODO: DELETE /apps/:appName/envs
r.POST("/apps/:appName/envs/upload", envController.Upload)
r.POST("/apps/:appName/healthcheck", healthcheckController.Update)
r.Run()
}
示例10: setSessions
//setSessions initializes sessions & csrf middlewares
func setSessions(router *gin.Engine) {
config := system.GetConfig()
//https://github.com/gin-gonic/contrib/tree/master/sessions
store := sessions.NewCookieStore([]byte(config.SessionSecret))
store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400}) //Also set Secure: true if using SSL, you should though
router.Use(sessions.Sessions("gin-session", store))
//https://github.com/utrack/gin-csrf
router.Use(csrf.Middleware(csrf.Options{
Secret: config.SessionSecret,
ErrorFunc: func(c *gin.Context) {
c.String(400, "CSRF token mismatch")
c.Abort()
},
}))
}
示例11: init
func init() {
gin.SetMode(gin.DebugMode)
rand.Seed(time.Now().UnixNano())
servidor = gin.Default()
store := sessions.NewCookieStore([]byte("ef7fbfd3d599befe7a86cbf37c8f05c814dcad918b8dbefb441de846c4f62ea3"))
servidor.Use(sessions.Sessions("mysession", store))
cargarTemplates()
servidor.Use(static.Serve("/", static.LocalFile("./public", false)))
servidor.StaticFile("/login", "./public/index.html")
servidor.NoRoute(func(c *gin.Context) {
html.ExecuteTemplate(c.Writer, "404.html", nil)
})
}
示例12: main
/*
* Main function
*/
func main() {
//fmt.Printf("Register function . Sqrt1(4) = %v\n", register.Sqrt1(4))
r := gin.New()
// r := gin.Default()
store := sessions.NewCookieStore([]byte("myappsecret"))
r.Use(sessions.Sessions("mygroups", store))
r.Use(Is_authorised())
//r.LoadHTMLGlob("templates/*")
templates := multitemplate.New()
templates.AddFromFiles("home", "home.html", "header.html", "footer.html")
templates.AddFromFiles("register", "register.html", "header.html", "footer.html")
r.HTMLRender = templates
//fmt.Println(register.Sqrt(2))
//r.HTMLRender = loadTemplates("./templates")
r.StaticFS("/css/", http.Dir("css"))
r.StaticFS("/images/", http.Dir("images"))
/*
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK,
"home",
gin.H{
"Title": "Login Here",
},
)
})
*/
r.GET("/", register.HomeHandler)
r.POST("/", register.LoginHandler)
r.POST("/register", register.RegisterHandler)
r.GET("/register", func(c *gin.Context) {
c.HTML(http.StatusOK,
"register",
gin.H{
"Title": "New Registration",
},
)
})
r.Run(":8090")
}
示例13: init
func init() {
r := gin.New()
r.LoadHTMLGlob("templates/*")
r.Use(sessions.Sessions("session_id", store))
r.Static("/assets", "./assets")
r.Use(gin.Recovery())
v1 := r.Group("api/v1")
v1.Use(loginWithGoogle())
{
v1.GET("/systems", controllers.GetSystems)
v1.POST("/systems", controllers.CreateSystem)
v1.GET("/systems/:id", controllers.GetSystem)
v1.PUT("/systems/:id", controllers.UpdateSystem)
v1.DELETE("/systems/:id", controllers.DeleteSystem)
v1.GET("/developers", controllers.UpdatePage)
v1.POST("/developers", controllers.UpdateDeveloper)
v1.GET("/deploys", controllers.GetDeploys)
v1.POST("/deploys", controllers.CreateDeploy)
}
r.Use(loginWithGoogle())
r.Use(updateDevPending())
{
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{})
})
}
r.GET("/logout", func(c *gin.Context) {
ctx := appengine.NewContext(c.Request)
url, _ := user.LogoutURL(ctx, "/")
c.Redirect(http.StatusTemporaryRedirect, url)
})
http.Handle("/", r)
/*
Use this for https instead of r.Run()
r.RunTLS(":8080", pathToCertFile, pathToKeyFile)
*/
}
示例14: main
func main() {
r := gin.Default()
store, _ := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte("secret"))
r.Use(sessions.Sessions("mysession", store))
r.GET("/incr", func(c *gin.Context) {
session := sessions.Default(c)
var count int
v := session.Get("count")
if v == nil {
count = 0
} else {
count = v.(int)
count += 1
}
session.Set("count", count)
session.Save()
c.JSON(200, gin.H{"count": count})
})
r.Run(":8000")
}
示例15: main
func main() {
log.Printf("setting up gin ...")
r := gin.Default()
r.Static("/static", "static")
r.LoadHTMLGlob("templates/*")
log.Printf("setting up session store ...")
store := sessions.NewCookieStore([]byte("secret"))
r.Use(sessions.Sessions("whiskee", store))
log.Printf("setting up database ...")
r.Use(PostgresDatabase())
log.Printf("setting up transloadit ...")
r.Use(Transloadit())
log.Printf("setting up routes ...")
r.GET("/", HomeR)
r.GET("/auth/callback", CallbackR)
r.GET("/auth/logout", LogoutR)
r.GET("/home", HomeR)
r.GET("/whisky", WhiskyListR)
r.GET("/whisky/:id", WhiskyR)
r.GET("/user", UserListR)
r.GET("/user/:id", UserR)
r.GET("/add/whisky", AddWhiskyFormR)
r.POST("/add/whisky", AddWhiskyR)
r.GET("/edit/whisky/:id", EditWhiskyFormR)
r.POST("/edit/whisky/:id", EditWhiskyR)
r.POST("/add/review", AddReviewR)
r.GET("/edit/review/:id", EditReviewFormR)
r.POST("/edit/review/:id", EditReviewR)
port := os.Getenv("PORT")
log.Printf("listening on :%s", port)
r.Run(":" + port)
}