move getting session store to web context
This commit is contained in:
@@ -29,6 +29,7 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/beego/beego/v2/server/web/session"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -195,6 +196,22 @@ func (ctx *Context) RenderMethodResult(result interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Session return session store of this context of request
|
||||
func (ctx *Context) Session() (store session.Store,err error){
|
||||
if ctx.Input != nil {
|
||||
if ctx.Input.CruSession != nil {
|
||||
store = ctx.Input.CruSession
|
||||
return
|
||||
} else {
|
||||
err = errors.New(`no valid session store(please initialize session)`)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
err = errors.New(`no valid input`)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Response is a wrapper for the http.ResponseWriter
|
||||
// Started: if true, response was already written to so the other handler will not be executed
|
||||
type Response struct {
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
package context
|
||||
|
||||
import (
|
||||
"github.com/beego/beego/v2/server/web"
|
||||
"github.com/beego/beego/v2/server/web/filter/session"
|
||||
webSession "github.com/beego/beego/v2/server/web/session"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
@@ -45,3 +48,46 @@ func TestXsrfReset_01(t *testing.T) {
|
||||
t.FailNow()
|
||||
}
|
||||
}
|
||||
|
||||
func testRequest(t *testing.T, handler *web.ControllerRegister, path string, method string, code int) {
|
||||
r, _ := http.NewRequest(method, path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
if w.Code != code {
|
||||
t.Errorf("%s, %s: %d, supposed to be %d", path, method, w.Code, code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContext_Session(t *testing.T) {
|
||||
handler := web.NewControllerRegister()
|
||||
|
||||
handler.InsertFilterChain(
|
||||
"*",
|
||||
session.Session(
|
||||
webSession.ProviderMemory,
|
||||
webSession.CfgCookieName(`go_session_id`),
|
||||
webSession.CfgSetCookie(true),
|
||||
webSession.CfgGcLifeTime(3600),
|
||||
webSession.CfgMaxLifeTime(3600),
|
||||
webSession.CfgSecure(false),
|
||||
webSession.CfgCookieLifeTime(3600),
|
||||
),
|
||||
)
|
||||
handler.InsertFilterChain(
|
||||
"*",
|
||||
func(next web.FilterFunc) web.FilterFunc {
|
||||
return func(ctx *Context) {
|
||||
if _, err := ctx.Session(); err == nil {
|
||||
t.Error()
|
||||
}
|
||||
|
||||
}
|
||||
},
|
||||
)
|
||||
handler.Any("*", func(ctx *Context) {
|
||||
ctx.Output.SetStatus(200)
|
||||
})
|
||||
|
||||
testRequest(t, handler, "/dataset1/resource1", "GET", 200)
|
||||
}
|
||||
Reference in New Issue
Block a user