resolve conflict

This commit is contained in:
Ming Deng
2021-01-01 22:34:02 +08:00
307 changed files with 2467 additions and 1523 deletions

View File

@@ -10,4 +10,4 @@ Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
limitations under the License.

View File

@@ -20,7 +20,7 @@ import (
"reflect"
"time"
"github.com/astaxie/beego/core/logs"
"github.com/beego/beego/v2/core/logs"
)
// BeeAdminApp is the default adminApp used by admin module.

View File

@@ -24,7 +24,7 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/astaxie/beego/core/governor"
"github.com/beego/beego/v2/core/admin"
)
type adminController struct {
@@ -51,7 +51,7 @@ func (a *adminController) ProfIndex() {
data = make(map[interface{}]interface{})
result bytes.Buffer
)
governor.ProcessInput(command, &result)
admin.ProcessInput(command, &result)
data["Content"] = template.HTMLEscapeString(result.String())
if format == "json" && command == "gc summary" {
@@ -88,7 +88,7 @@ func (a *adminController) TaskStatus() {
req.ParseForm()
taskname := req.Form.Get("taskname")
if taskname != "" {
cmd := governor.GetCommand("task", "run")
cmd := admin.GetCommand("task", "run")
res := cmd.Execute(taskname)
if res.IsSuccess() {
@@ -103,7 +103,7 @@ func (a *adminController) TaskStatus() {
// List Tasks
content := make(M)
resultList := governor.GetCommand("task", "list").Execute().Content.([][]string)
resultList := admin.GetCommand("task", "list").Execute().Content.([][]string)
var fields = []string{
"Task Name",
"Task Spec",
@@ -141,7 +141,7 @@ func heathCheck(rw http.ResponseWriter, r *http.Request) {
}
)
for name, h := range governor.AdminCheckList {
for name, h := range admin.AdminCheckList {
if err := h.Check(); err != nil {
result = []string{
"error",
@@ -250,7 +250,7 @@ func (a *adminController) ListConf() {
filterTypeData := BeeApp.reportFilter()
filterTypes := make([]string, 0, len(filterTypeData))
for k, _ := range filterTypeData {
for k := range filterTypeData {
filterTypes = append(filterTypes, k)
}

View File

@@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/core/governor"
"github.com/beego/beego/v2/core/admin"
)
type SampleDatabaseCheck struct {
@@ -126,8 +126,8 @@ func TestWriteJSON(t *testing.T) {
func TestHealthCheckHandlerDefault(t *testing.T) {
endpointPath := "/healthcheck"
governor.AddHealthCheck("database", &SampleDatabaseCheck{})
governor.AddHealthCheck("cache", &SampleCacheCheck{})
admin.AddHealthCheck("database", &SampleDatabaseCheck{})
admin.AddHealthCheck("cache", &SampleCacheCheck{})
req, err := http.NewRequest("GET", endpointPath, nil)
if err != nil {
@@ -152,12 +152,12 @@ func TestHealthCheckHandlerDefault(t *testing.T) {
func TestBuildHealthCheckResponseList(t *testing.T) {
healthCheckResults := [][]string{
[]string{
{
"error",
"Database",
"Error occured whie starting the db",
"Error occurred whie starting the db",
},
[]string{
{
"success",
"Cache",
"Cache started successfully",
@@ -187,8 +187,8 @@ func TestBuildHealthCheckResponseList(t *testing.T) {
func TestHealthCheckHandlerReturnsJSON(t *testing.T) {
governor.AddHealthCheck("database", &SampleDatabaseCheck{})
governor.AddHealthCheck("cache", &SampleCacheCheck{})
admin.AddHealthCheck("database", &SampleDatabaseCheck{})
admin.AddHealthCheck("cache", &SampleCacheCheck{})
req, err := http.NewRequest("GET", "/healthcheck?json=true", nil)
if err != nil {

View File

@@ -21,7 +21,7 @@ var indexTpl = `
For detail usage please check our document:
</p>
<p>
<a target="_blank" href="http://beego.me/docs/module/governor.md">Toolbox</a>
<a target="_blank" href="http://beego.me/docs/module/admin.md">Toolbox</a>
</p>
<p>
<a target="_blank" href="http://beego.me/docs/advantage/monitor.md">Live Monitor</a>

View File

@@ -6,9 +6,9 @@ an example for use captcha
package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/cache"
"github.com/astaxie/beego/utils/captcha"
"github.com/beego/beego/v2"
"github.com/beego/beego/v2/cache"
"github.com/beego/beego/v2/utils/captcha"
)
var cpt *captcha.Captcha

View File

@@ -19,9 +19,9 @@
// package controllers
//
// import (
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/cache"
// "github.com/astaxie/beego/utils/captcha"
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/cache"
// "github.com/beego/beego/v2/utils/captcha"
// )
//
// var cpt *captcha.Captcha
@@ -67,11 +67,11 @@ import (
"strings"
"time"
"github.com/astaxie/beego/core/logs"
"github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/core/utils"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/core/utils"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
var (

View File

@@ -17,7 +17,7 @@ package captcha
import (
"testing"
"github.com/astaxie/beego/core/utils"
"github.com/beego/beego/v2/core/utils"
)
type byteCounter struct {

View File

@@ -17,19 +17,20 @@ package web
import (
"crypto/tls"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/core/config"
"github.com/astaxie/beego/core/logs"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2"
"github.com/beego/beego/v2/core/config"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web/session"
"github.com/astaxie/beego/core/utils"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/core/utils"
"github.com/beego/beego/v2/server/web/context"
)
// Config is the main struct for BConfig
@@ -116,6 +117,7 @@ type SessionConfig struct {
SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers
SessionNameInHTTPHeader string
SessionEnableSidInURLQuery bool // enable get the sessionId from Url Query params
SessionCookieSameSite http.SameSite
}
// LogConfig holds Log related config
@@ -274,6 +276,7 @@ func newBConfig() *Config {
SessionEnableSidInHTTPHeader: false, // enable store/get the sessionId into/from http headers
SessionNameInHTTPHeader: "Beegosessionid",
SessionEnableSidInURLQuery: false, // enable get the sessionId from Url Query params
SessionCookieSameSite: http.SameSiteDefaultMode,
},
},
Log: LogConfig{

View File

@@ -19,7 +19,7 @@ import (
"reflect"
"testing"
beeJson "github.com/astaxie/beego/core/config/json"
beeJson "github.com/beego/beego/v2/core/config/json"
)
func TestDefaults(t *testing.T) {

View File

@@ -65,7 +65,7 @@ type nopResetWriter struct {
}
func (n nopResetWriter) Reset(w io.Writer) {
//do nothing
// do nothing
}
type acceptEncoder struct {

View File

@@ -15,7 +15,7 @@
// Package context provide the context utils
// Usage:
//
// import "github.com/astaxie/beego/context"
// import "github.com/beego/beego/v2/context"
//
// ctx := context.Context{Request:req,ResponseWriter:rw}
//
@@ -35,7 +35,7 @@ import (
"strings"
"time"
"github.com/astaxie/beego/core/utils"
"github.com/beego/beego/v2/core/utils"
)
// Commonly used mime-types
@@ -149,7 +149,8 @@ func (ctx *Context) XSRFToken(key string, expire int64) string {
token, ok := ctx.GetSecureCookie(key, "_xsrf")
if !ok {
token = string(utils.RandomCreateBytes(32))
ctx.SetSecureCookie(key, "_xsrf", token, expire, "", "", true, true)
// TODO make it configurable
ctx.SetSecureCookie(key, "_xsrf", token, expire, "", "")
}
ctx._xsrfToken = token
}
@@ -221,7 +222,7 @@ func (r *Response) Write(p []byte) (int, error) {
// and sets `Started` to true.
func (r *Response) WriteHeader(code int) {
if r.Status > 0 {
//prevent multiple response.WriteHeader calls
// prevent multiple response.WriteHeader calls
return
}
r.Status = code

View File

@@ -29,7 +29,7 @@ import (
"strings"
"sync"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
// Regexes for checking the accept headers

View File

@@ -261,15 +261,15 @@ func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error {
}
// ServeFormatted serves YAML, XML or JSON, depending on the value of the Accept header
func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) {
func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) error {
accept := output.Context.Input.Header("Accept")
switch accept {
case ApplicationYAML:
output.YAML(data)
return output.YAML(data)
case ApplicationXML, TextXML:
output.XML(data, hasIndent)
return output.XML(data, hasIndent)
default:
output.JSON(data, hasIndent, len(hasEncode) > 0 && hasEncode[0])
return output.JSON(data, hasIndent, len(hasEncode) > 0 && hasEncode[0])
}
}
@@ -288,7 +288,7 @@ func (output *BeegoOutput) Download(file string, filename ...string) {
} else {
fName = filepath.Base(file)
}
//https://tools.ietf.org/html/rfc6266#section-4.3
// https://tools.ietf.org/html/rfc6266#section-4.3
fn := url.PathEscape(fName)
if fName == fn {
fn = "filename=" + fn

View File

@@ -4,8 +4,8 @@ import (
"fmt"
"reflect"
"github.com/astaxie/beego/core/logs"
beecontext "github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/core/logs"
beecontext "github.com/beego/beego/v2/server/web/context"
)
// ConvertParams converts http method params to values that will be passed to the method controller as arguments

View File

@@ -5,7 +5,7 @@ import (
"strings"
)
//MethodParam keeps param information to be auto passed to controller methods
// MethodParam keeps param information to be auto passed to controller methods
type MethodParam struct {
name string
in paramType

View File

@@ -18,7 +18,7 @@ func getParser(param *MethodParam, t reflect.Type) paramParser {
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return intParser{}
case reflect.Slice:
if t.Elem().Kind() == reflect.Uint8 { //treat []byte as string
if t.Elem().Kind() == reflect.Uint8 { // treat []byte as string
return stringParser{}
}
if param.in == body {

View File

@@ -14,40 +14,40 @@ type testDefinition struct {
func Test_Parsers(t *testing.T) {
//ints
// ints
checkParser(testDefinition{"1", 1, intParser{}}, t)
checkParser(testDefinition{"-1", int64(-1), intParser{}}, t)
checkParser(testDefinition{"1", uint64(1), intParser{}}, t)
//floats
// floats
checkParser(testDefinition{"1.0", float32(1.0), floatParser{}}, t)
checkParser(testDefinition{"-1.0", float64(-1.0), floatParser{}}, t)
//strings
// strings
checkParser(testDefinition{"AB", "AB", stringParser{}}, t)
checkParser(testDefinition{"AB", []byte{65, 66}, stringParser{}}, t)
//bools
// bools
checkParser(testDefinition{"true", true, boolParser{}}, t)
checkParser(testDefinition{"0", false, boolParser{}}, t)
//timeParser
// timeParser
checkParser(testDefinition{"2017-05-30T13:54:53Z", time.Date(2017, 5, 30, 13, 54, 53, 0, time.UTC), timeParser{}}, t)
checkParser(testDefinition{"2017-05-30", time.Date(2017, 5, 30, 0, 0, 0, 0, time.UTC), timeParser{}}, t)
//json
// json
checkParser(testDefinition{`{"X": 5, "Y":"Z"}`, struct {
X int
Y string
}{5, "Z"}, jsonParser{}}, t)
//slice in query is parsed as comma delimited
// slice in query is parsed as comma delimited
checkParser(testDefinition{`1,2`, []int{1, 2}, sliceParser(intParser{})}, t)
//slice in body is parsed as json
// slice in body is parsed as json
checkParser(testDefinition{`["a","b"]`, []string{"a", "b"}, jsonParser{}}, t, MethodParam{in: body})
//pointers
// pointers
var someInt = 1
checkParser(testDefinition{`1`, &someInt, ptrParser(intParser{})}, t)

View File

@@ -6,10 +6,10 @@ import (
)
const (
//BadRequest indicates HTTP error 400
// BadRequest indicates HTTP error 400
BadRequest StatusCode = http.StatusBadRequest
//NotFound indicates HTTP error 404
// NotFound indicates HTTP error 404
NotFound StatusCode = http.StatusNotFound
)

View File

@@ -16,6 +16,7 @@ package web
import (
"bytes"
context2 "context"
"errors"
"fmt"
"html/template"
@@ -28,10 +29,10 @@ import (
"strconv"
"strings"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
"github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web/context/param"
"github.com/beego/beego/v2/server/web/context"
"github.com/beego/beego/v2/server/web/context/param"
)
var (
@@ -250,13 +251,16 @@ func (c *Controller) Render() error {
// RenderString returns the rendered template string. Do not send out response.
func (c *Controller) RenderString() (string, error) {
b, e := c.RenderBytes()
if e != nil {
return "", e
}
return string(b), e
}
// RenderBytes returns the bytes of rendered template string. Do not send out response.
func (c *Controller) RenderBytes() ([]byte, error) {
buf, err := c.renderTemplate()
//if the controller has set layout, then first get the tplName's content set the content to the layout
// if the controller has set layout, then first get the tplName's content set the content to the layout
if err == nil && c.Layout != "" {
c.Data["LayoutContent"] = template.HTML(buf.String())
@@ -276,7 +280,7 @@ func (c *Controller) RenderBytes() ([]byte, error) {
}
buf.Reset()
ExecuteViewPathTemplate(&buf, c.Layout, c.viewPath(), c.Data)
err = ExecuteViewPathTemplate(&buf, c.Layout, c.viewPath(), c.Data)
}
return buf.Bytes(), err
}
@@ -373,50 +377,57 @@ func (c *Controller) URLFor(endpoint string, values ...interface{}) string {
}
// ServeJSON sends a json response with encoding charset.
func (c *Controller) ServeJSON(encoding ...bool) {
func (c *Controller) ServeJSON(encoding ...bool) error {
var (
hasIndent = BConfig.RunMode != PROD
hasEncoding = len(encoding) > 0 && encoding[0]
)
c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding)
return c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding)
}
// ServeJSONP sends a jsonp response.
func (c *Controller) ServeJSONP() {
func (c *Controller) ServeJSONP() error {
hasIndent := BConfig.RunMode != PROD
c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent)
return c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent)
}
// ServeXML sends xml response.
func (c *Controller) ServeXML() {
func (c *Controller) ServeXML() error {
hasIndent := BConfig.RunMode != PROD
c.Ctx.Output.XML(c.Data["xml"], hasIndent)
return c.Ctx.Output.XML(c.Data["xml"], hasIndent)
}
// ServeYAML sends yaml response.
func (c *Controller) ServeYAML() {
c.Ctx.Output.YAML(c.Data["yaml"])
func (c *Controller) ServeYAML() error {
return c.Ctx.Output.YAML(c.Data["yaml"])
}
// ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header
func (c *Controller) ServeFormatted(encoding ...bool) {
func (c *Controller) ServeFormatted(encoding ...bool) error {
hasIndent := BConfig.RunMode != PROD
hasEncoding := len(encoding) > 0 && encoding[0]
c.Ctx.Output.ServeFormatted(c.Data, hasIndent, hasEncoding)
return c.Ctx.Output.ServeFormatted(c.Data, hasIndent, hasEncoding)
}
// Input returns the input data map from POST or PUT request body and query string.
func (c *Controller) Input() url.Values {
func (c *Controller) Input() (url.Values, error) {
if c.Ctx.Request.Form == nil {
c.Ctx.Request.ParseForm()
err := c.Ctx.Request.ParseForm()
if err != nil {
return nil, err
}
}
return c.Ctx.Request.Form
return c.Ctx.Request.Form, nil
}
// ParseForm maps input data map to obj struct.
func (c *Controller) ParseForm(obj interface{}) error {
return ParseForm(c.Input(), obj)
form, err := c.Input()
if err != nil {
return err
}
return ParseForm(form, obj)
}
// GetString returns the input value by key string or the default value while it's present and input is blank
@@ -438,7 +449,7 @@ func (c *Controller) GetStrings(key string, def ...[]string) []string {
defv = def[0]
}
if f := c.Input(); f == nil {
if f, err := c.Input(); f == nil || err != nil {
return defv
} else if vs := f[key]; len(vs) > 0 {
return vs
@@ -618,11 +629,11 @@ func (c *Controller) StartSession() session.Store {
}
// SetSession puts value into session.
func (c *Controller) SetSession(name interface{}, value interface{}) {
func (c *Controller) SetSession(name interface{}, value interface{}) error {
if c.CruSession == nil {
c.StartSession()
}
c.CruSession.Set(nil, name, value)
return c.CruSession.Set(context2.Background(), name, value)
}
// GetSession gets value from session.
@@ -630,32 +641,38 @@ func (c *Controller) GetSession(name interface{}) interface{} {
if c.CruSession == nil {
c.StartSession()
}
return c.CruSession.Get(nil, name)
return c.CruSession.Get(context2.Background(), name)
}
// DelSession removes value from session.
func (c *Controller) DelSession(name interface{}) {
func (c *Controller) DelSession(name interface{}) error {
if c.CruSession == nil {
c.StartSession()
}
c.CruSession.Delete(nil, name)
return c.CruSession.Delete(context2.Background(), name)
}
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
func (c *Controller) SessionRegenerateID() {
func (c *Controller) SessionRegenerateID() error {
if c.CruSession != nil {
c.CruSession.SessionRelease(nil, c.Ctx.ResponseWriter)
c.CruSession.SessionRelease(context2.Background(), c.Ctx.ResponseWriter)
}
c.CruSession = GlobalSessions.SessionRegenerateID(c.Ctx.ResponseWriter, c.Ctx.Request)
var err error
c.CruSession, err = GlobalSessions.SessionRegenerateID(c.Ctx.ResponseWriter, c.Ctx.Request)
c.Ctx.Input.CruSession = c.CruSession
return err
}
// DestroySession cleans session data and session cookie.
func (c *Controller) DestroySession() {
c.Ctx.Input.CruSession.Flush(nil)
func (c *Controller) DestroySession() error {
err := c.Ctx.Input.CruSession.Flush(nil)
if err != nil {
return err
}
c.Ctx.Input.CruSession = nil
GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
return nil
}
// IsAjax returns this request is ajax or not.

View File

@@ -21,9 +21,7 @@ import (
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
func TestGetInt(t *testing.T) {
@@ -46,7 +44,7 @@ func TestGetInt8(t *testing.T) {
if val != 40 {
t.Errorf("TestGetInt8 expect 40,get %T,%v", val, val)
}
//Output: int8
// Output: int8
}
func TestGetInt16(t *testing.T) {
@@ -127,10 +125,9 @@ func TestGetUint64(t *testing.T) {
}
func TestAdditionalViewPaths(t *testing.T) {
wkdir, err := os.Getwd()
assert.Nil(t, err)
dir1 := filepath.Join(wkdir, "_beeTmp", "TestAdditionalViewPaths")
dir2 := filepath.Join(wkdir, "_beeTmp2", "TestAdditionalViewPaths")
tmpDir := os.TempDir()
dir1 := filepath.Join(tmpDir, "_beeTmp", "TestAdditionalViewPaths")
dir2 := filepath.Join(tmpDir, "_beeTmp2", "TestAdditionalViewPaths")
defer os.RemoveAll(dir1)
defer os.RemoveAll(dir2)

View File

@@ -6,7 +6,7 @@ It is used for rapid development of RESTful APIs, web apps and backend services
beego is inspired by Tornado, Sinatra and Flask with the added benefit of some Go-specific features such as interfaces and struct embedding.
package main
import "github.com/astaxie/beego"
import "github.com/beego/beego/v2"
func main() {
beego.Run()

View File

@@ -23,10 +23,10 @@ import (
"strconv"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/core/utils"
"github.com/beego/beego/v2"
"github.com/beego/beego/v2/core/utils"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
const (
@@ -444,13 +444,13 @@ func exception(errCode string, ctx *context.Context) {
return
}
}
//if 50x error has been removed from errorMap
// if 50x error has been removed from errorMap
ctx.ResponseWriter.WriteHeader(atoi(errCode))
ctx.WriteString(errCode)
}
func executeError(err *errorInfo, ctx *context.Context, code int) {
//make sure to log the error in the access log
// make sure to log the error in the access log
LogAccess(ctx, nil, code)
if err.errorType == errorTypeHandler {
@@ -460,16 +460,16 @@ func executeError(err *errorInfo, ctx *context.Context, code int) {
}
if err.errorType == errorTypeController {
ctx.Output.SetStatus(code)
//Invoke the request handler
// Invoke the request handler
vc := reflect.New(err.controllerType)
execController, ok := vc.Interface().(ControllerInterface)
if !ok {
panic("controller is not ControllerInterface")
}
//call the controller init function
// call the controller init function
execController.Init(ctx, err.controllerType.Name(), err.method, vc.Interface())
//call prepare function
// call prepare function
execController.Prepare()
execController.URLMapping()
@@ -477,7 +477,7 @@ func executeError(err *errorInfo, ctx *context.Context, code int) {
method := vc.MethodByName(err.method)
method.Call([]reflect.Value{})
//render template
// render template
if BConfig.WebConfig.AutoRender {
if err := execController.Render(); err != nil {
panic(err)

View File

@@ -17,7 +17,7 @@ package web
import (
"strings"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
// FilterChain is different from pure FilterFunc

View File

@@ -16,8 +16,8 @@
//
// Simple Usage:
// import(
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/apiauth"
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/plugins/apiauth"
// )
//
// func main(){
@@ -65,8 +65,8 @@ import (
"sort"
"time"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
// AppIDToAppSecret gets appsecret through appid

View File

@@ -15,8 +15,8 @@
// Package auth provides handlers to enable basic auth support.
// Simple Usage:
// import(
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/auth"
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/plugins/auth"
// )
//
// func main(){
@@ -40,8 +40,8 @@ import (
"net/http"
"strings"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
var defaultRealm = "Authorization Required"

View File

@@ -15,8 +15,8 @@
// Package authz provides handlers to enable ACL, RBAC, ABAC authorization support.
// Simple Usage:
// import(
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/authz"
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/plugins/authz"
// "github.com/casbin/casbin"
// )
//
@@ -44,8 +44,8 @@ import (
"github.com/casbin/casbin"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
// NewAuthorizer returns the authorizer.

View File

@@ -11,4 +11,4 @@ g = _, _
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")

View File

@@ -4,4 +4,4 @@ p, bob, /dataset2/resource1, *
p, bob, /dataset2/resource2, GET
p, bob, /dataset2/folder1/*, POST
p, dataset1_admin, /dataset1/*, *
g, cathy, dataset1_admin
g, cathy, dataset1_admin
1 p, alice, /dataset1/*, GET
4 p, bob, /dataset2/resource2, GET
5 p, bob, /dataset2/folder1/*, POST
6 p, dataset1_admin, /dataset1/*, *
7 g, cathy, dataset1_admin

View File

@@ -21,9 +21,9 @@ import (
"github.com/casbin/casbin"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web/filter/auth"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
"github.com/beego/beego/v2/server/web/filter/auth"
)
func testRequest(t *testing.T, handler *web.ControllerRegister, user string, path string, method string, code int) {

View File

@@ -15,8 +15,8 @@
// Package cors provides handlers to enable CORS support.
// Usage
// import (
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/cors"
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/plugins/cors"
// )
//
// func main() {
@@ -42,8 +42,8 @@ import (
"strings"
"time"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
const (

View File

@@ -21,8 +21,8 @@ import (
"testing"
"time"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
// HTTPHeaderGuardRecorder is httptest.ResponseRecorder with own http.Header

View File

@@ -17,11 +17,12 @@ package opentracing
import (
"context"
"github.com/astaxie/beego/server/web"
beegoCtx "github.com/astaxie/beego/server/web/context"
logKit "github.com/go-kit/kit/log"
opentracingKit "github.com/go-kit/kit/tracing/opentracing"
"github.com/opentracing/opentracing-go"
"github.com/beego/beego/v2/server/web"
beegoCtx "github.com/beego/beego/v2/server/web/context"
)
// FilterChainBuilder provides an extension point that we can support more configurations if necessary

View File

@@ -22,7 +22,7 @@ import (
"github.com/opentracing/opentracing-go"
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
func TestFilterChainBuilder_FilterChain(t *testing.T) {

View File

@@ -21,9 +21,9 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/astaxie/beego"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
// FilterChainBuilder is an extension point,
@@ -43,7 +43,7 @@ func (builder *FilterChainBuilder) FilterChain(next web.FilterFunc) web.FilterFu
"appname": web.BConfig.AppName,
},
Help: "The statics info for http request",
}, []string{"pattern", "method", "status", "duration"})
}, []string{"pattern", "method", "status"})
prometheus.MustRegister(summaryVec)
@@ -83,5 +83,5 @@ func report(dur time.Duration, ctx *context.Context, vec *prometheus.SummaryVec)
status := ctx.Output.Status
ptn := ctx.Input.GetData("RouterPattern").(string)
ms := dur / time.Millisecond
vec.WithLabelValues(ptn, ctx.Input.Method(), strconv.Itoa(status), strconv.Itoa(int(ms))).Observe(float64(ms))
vec.WithLabelValues(ptn, ctx.Input.Method(), strconv.Itoa(status)).Observe(float64(ms))
}

View File

@@ -21,7 +21,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
func TestFilterChain(t *testing.T) {

View File

@@ -21,7 +21,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
func TestControllerRegister_InsertFilterChain(t *testing.T) {

View File

@@ -19,7 +19,7 @@ import (
"net/http/httptest"
"testing"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
var FilterUser = func(ctx *context.Context) {

View File

@@ -102,7 +102,7 @@ func ReadFromRequest(c *Controller) *FlashData {
}
}
}
//read one time then delete it
// read one time then delete it
c.Ctx.SetCookie(BConfig.WebConfig.FlashName, "", -1, "/")
}
c.Data["flash"] = flash.Data

View File

@@ -22,7 +22,7 @@
// "net/http"
// "os"
//
// "github.com/astaxie/beego/grace"
// "github.com/beego/beego/v2/grace"
// )
//
// func handler(w http.ResponseWriter, r *http.Request) {
@@ -138,7 +138,7 @@ func NewServer(addr string, handler http.Handler) (srv *Server) {
},
state: StateInit,
Network: "tcp",
terminalChan: make(chan error), //no cache channel
terminalChan: make(chan error), // no cache channel
}
srv.Server = &http.Server{
Addr: addr,

View File

@@ -6,9 +6,9 @@ import (
"net/http"
"path/filepath"
"github.com/astaxie/beego/core/logs"
"github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web/context"
"github.com/beego/beego/v2/server/web/session"
)
// register MIME type with content type
@@ -61,6 +61,7 @@ func registerSession() error {
conf.EnableSidInHTTPHeader = BConfig.WebConfig.Session.SessionEnableSidInHTTPHeader
conf.SessionNameInHTTPHeader = BConfig.WebConfig.Session.SessionNameInHTTPHeader
conf.EnableSidInURLQuery = BConfig.WebConfig.Session.SessionEnableSidInURLQuery
conf.CookieSameSite = BConfig.WebConfig.Session.SessionCookieSameSite
} else {
if err = json.Unmarshal([]byte(sessionConfig), conf); err != nil {
return err

View File

@@ -18,7 +18,7 @@ import (
"net/http"
"strings"
beecontext "github.com/astaxie/beego/server/web/context"
beecontext "github.com/beego/beego/v2/server/web/context"
)
type namespaceCond func(*beecontext.Context) bool
@@ -97,91 +97,91 @@ func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace {
}
// Router same as beego.Rourer
// refer: https://godoc.org/github.com/astaxie/beego#Router
// refer: https://godoc.org/github.com/beego/beego/v2#Router
func (n *Namespace) Router(rootpath string, c ControllerInterface, mappingMethods ...string) *Namespace {
n.handlers.Add(rootpath, c, mappingMethods...)
return n
}
// AutoRouter same as beego.AutoRouter
// refer: https://godoc.org/github.com/astaxie/beego#AutoRouter
// refer: https://godoc.org/github.com/beego/beego/v2#AutoRouter
func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace {
n.handlers.AddAuto(c)
return n
}
// AutoPrefix same as beego.AutoPrefix
// refer: https://godoc.org/github.com/astaxie/beego#AutoPrefix
// refer: https://godoc.org/github.com/beego/beego/v2#AutoPrefix
func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace {
n.handlers.AddAutoPrefix(prefix, c)
return n
}
// Get same as beego.Get
// refer: https://godoc.org/github.com/astaxie/beego#Get
// refer: https://godoc.org/github.com/beego/beego/v2#Get
func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace {
n.handlers.Get(rootpath, f)
return n
}
// Post same as beego.Post
// refer: https://godoc.org/github.com/astaxie/beego#Post
// refer: https://godoc.org/github.com/beego/beego/v2#Post
func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace {
n.handlers.Post(rootpath, f)
return n
}
// Delete same as beego.Delete
// refer: https://godoc.org/github.com/astaxie/beego#Delete
// refer: https://godoc.org/github.com/beego/beego/v2#Delete
func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace {
n.handlers.Delete(rootpath, f)
return n
}
// Put same as beego.Put
// refer: https://godoc.org/github.com/astaxie/beego#Put
// refer: https://godoc.org/github.com/beego/beego/v2#Put
func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace {
n.handlers.Put(rootpath, f)
return n
}
// Head same as beego.Head
// refer: https://godoc.org/github.com/astaxie/beego#Head
// refer: https://godoc.org/github.com/beego/beego/v2#Head
func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace {
n.handlers.Head(rootpath, f)
return n
}
// Options same as beego.Options
// refer: https://godoc.org/github.com/astaxie/beego#Options
// refer: https://godoc.org/github.com/beego/beego/v2#Options
func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace {
n.handlers.Options(rootpath, f)
return n
}
// Patch same as beego.Patch
// refer: https://godoc.org/github.com/astaxie/beego#Patch
// refer: https://godoc.org/github.com/beego/beego/v2#Patch
func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace {
n.handlers.Patch(rootpath, f)
return n
}
// Any same as beego.Any
// refer: https://godoc.org/github.com/astaxie/beego#Any
// refer: https://godoc.org/github.com/beego/beego/v2#Any
func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace {
n.handlers.Any(rootpath, f)
return n
}
// Handler same as beego.Handler
// refer: https://godoc.org/github.com/astaxie/beego#Handler
// refer: https://godoc.org/github.com/beego/beego/v2#Handler
func (n *Namespace) Handler(rootpath string, h http.Handler) *Namespace {
n.handlers.Handler(rootpath, h)
return n
}
// Include add include class
// refer: https://godoc.org/github.com/astaxie/beego#Include
// refer: https://godoc.org/github.com/beego/beego/v2#Include
func (n *Namespace) Include(cList ...ControllerInterface) *Namespace {
n.handlers.Include(cList...)
return n
@@ -189,8 +189,8 @@ func (n *Namespace) Include(cList ...ControllerInterface) *Namespace {
// Namespace add nest Namespace
// usage:
//ns := beego.NewNamespace(“/v1”).
//Namespace(
// ns := beego.NewNamespace(“/v1”).
// Namespace(
// beego.NewNamespace("/shop").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("shopinfo"))
@@ -203,7 +203,7 @@ func (n *Namespace) Include(cList ...ControllerInterface) *Namespace {
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("crminfo"))
// }),
//)
// )
func (n *Namespace) Namespace(ns ...*Namespace) *Namespace {
for _, ni := range ns {
for k, v := range ni.handlers.routers {

View File

@@ -20,7 +20,7 @@ import (
"strconv"
"testing"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
func TestNamespaceGet(t *testing.T) {

View File

@@ -15,8 +15,8 @@
package pagination
import (
"github.com/astaxie/beego/core/utils/pagination"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/beego/beego/v2/server/web/context"
)
// SetPaginator Instantiates a Paginator and assigns it to context.Input.Data("paginator").

View File

@@ -30,17 +30,17 @@ import (
"golang.org/x/tools/go/packages"
"github.com/astaxie/beego/core/logs"
"github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/core/utils"
"github.com/astaxie/beego/server/web/context/param"
"github.com/beego/beego/v2/core/utils"
"github.com/beego/beego/v2/server/web/context/param"
)
var globalRouterTemplate = `package {{.routersDir}}
import (
beego "github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context/param"{{.globalimport}}
beego "github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context/param"{{.globalimport}}
)
func init() {
@@ -50,7 +50,6 @@ func init() {
var (
lastupdateFilename = "lastupdate.tmp"
commentFilename string
pkgLastupdate map[string]int64
genInfoList map[string][]ControllerComments
@@ -71,16 +70,13 @@ var (
}
)
const commentPrefix = "commentsRouter_"
const commentFilename = "commentsRouter.go"
func init() {
pkgLastupdate = make(map[string]int64)
}
func parserPkg(pkgRealpath string) error {
rep := strings.NewReplacer("\\", "_", "/", "_", ".", "_")
commentFilename, _ = filepath.Rel(AppPath, pkgRealpath)
commentFilename = commentPrefix + rep.Replace(commentFilename) + ".go"
if !compareFile(pkgRealpath) {
logs.Info(pkgRealpath + " no changed")
return nil
@@ -102,7 +98,10 @@ func parserPkg(pkgRealpath string) error {
if specDecl.Recv != nil {
exp, ok := specDecl.Recv.List[0].Type.(*ast.StarExpr) // Check that the type is correct first beforing throwing to parser
if ok {
parserComments(specDecl, fmt.Sprint(exp.X), pkg.PkgPath)
err = parserComments(specDecl, fmt.Sprint(exp.X), pkg.PkgPath)
if err != nil {
return err
}
}
}
}
@@ -500,7 +499,8 @@ func genRouterCode(pkgRealpath string) {
beego.GlobalControllerRouter["` + k + `"] = append(beego.GlobalControllerRouter["` + k + `"],
beego.ControllerComments{
Method: "` + strings.TrimSpace(c.Method) + `",
` + `Router: "` + c.Router + `"` + `,
` + "Router: `" + c.Router + "`" + `,
AllowHTTPMethods: ` + allmethod + `,
MethodParams: ` + methodParams + `,
Filters: ` + filters + `,
@@ -584,17 +584,6 @@ func getpathTime(pkgRealpath string) (lastupdate int64, err error) {
func getRouterDir(pkgRealpath string) string {
dir := filepath.Dir(pkgRealpath)
for {
routersDir := AppConfig.DefaultString("routersdir", "routers")
d := filepath.Join(dir, routersDir)
if utils.FileExists(d) {
return d
}
if r, _ := filepath.Rel(dir, AppPath); r == "." {
return d
}
// Parent dir.
dir = filepath.Dir(dir)
}
routersDir := AppConfig.DefaultString("routersdir", "routers")
return filepath.Join(dir, routersDir)
}

34
server/web/parser_test.go Normal file
View File

@@ -0,0 +1,34 @@
// Copyright 2020 beego
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_getRouterDir(t *testing.T) {
pkg := filepath.Dir(os.TempDir())
res := getRouterDir(pkg)
assert.Equal(t, filepath.Join(pkg, "routers"), res)
AppConfig.Set("routersdir", "cus_routers")
res = getRouterDir(pkg)
assert.Equal(t, filepath.Join(pkg, "cus_routers"), res)
}

View File

@@ -17,7 +17,7 @@ package web
import (
"strings"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
// PolicyFunc defines a policy function which is invoked before the controller handler is executed.

View File

@@ -25,11 +25,11 @@ import (
"sync"
"time"
"github.com/astaxie/beego/core/logs"
"github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/core/utils"
beecontext "github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web/context/param"
"github.com/beego/beego/v2/core/utils"
beecontext "github.com/beego/beego/v2/server/web/context"
"github.com/beego/beego/v2/server/web/context/param"
)
// default filter execution points
@@ -273,7 +273,6 @@ func (p *ControllerRegister) Include(cList ...ControllerInterface) {
for _, f := range a.Filters {
p.InsertFilter(f.Pattern, f.Pos, f.Filter, WithReturnOnOutput(f.ReturnOnOutput), WithResetParams(f.ResetParams))
}
p.addWithMethodParams(a.Router, c, a.MethodParams, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method)
}
}
@@ -391,13 +390,7 @@ func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) {
}
route.methods = methods
for k := range methods {
if k == "*" {
for m := range HTTPMETHOD {
p.addToRouter(m, pattern, route)
}
} else {
p.addToRouter(k, pattern, route)
}
p.addToRouter(k, pattern, route)
}
}

View File

@@ -21,9 +21,9 @@ import (
"strings"
"testing"
"github.com/astaxie/beego/core/logs"
"github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
type TestController struct {

View File

@@ -31,11 +31,11 @@ import (
"golang.org/x/crypto/acme/autocert"
"github.com/astaxie/beego/core/logs"
beecontext "github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/core/logs"
beecontext "github.com/beego/beego/v2/server/web/context"
"github.com/astaxie/beego/core/utils"
"github.com/astaxie/beego/server/web/grace"
"github.com/beego/beego/v2/core/utils"
"github.com/beego/beego/v2/server/web/grace"
)
var (

View File

@@ -1,67 +1,66 @@
session
==============
session is a Go session manager. It can use many session providers. Just like the `database/sql` and `database/sql/driver`.
session is a Go session manager. It can use many session providers. Just like the `database/sql`
and `database/sql/driver`.
## How to install?
go get github.com/astaxie/beego/session
go get github.com/beego/beego/v2/session
## What providers are supported?
As of now this session manager support memory, file, Redis and MySQL.
## How to use it?
First you must import it
import (
"github.com/astaxie/beego/session"
"github.com/beego/beego/v2/session"
)
Then in you web app init the global session manager
var globalSessions *session.Manager
* Use **memory** as provider:
func init() {
globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid","gclifetime":3600}`)
go globalSessions.GC()
}
func init() {
globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid","gclifetime":3600}`)
go globalSessions.GC()
}
* Use **file** as provider, the last param is the path where you want file to be stored:
func init() {
globalSessions, _ = session.NewManager("file",`{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"./tmp"}`)
go globalSessions.GC()
}
func init() {
globalSessions, _ = session.NewManager("file",`{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"./tmp"}`)
go globalSessions.GC()
}
* Use **Redis** as provider, the last param is the Redis conn address,poolsize,password:
func init() {
globalSessions, _ = session.NewManager("redis", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:6379,100,astaxie"}`)
go globalSessions.GC()
}
* Use **MySQL** as provider, the last param is the DSN, learn more from [mysql](https://github.com/go-sql-driver/mysql#dsn-data-source-name):
func init() {
globalSessions, _ = session.NewManager("redis", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:6379,100,astaxie"}`)
go globalSessions.GC()
}
func init() {
globalSessions, _ = session.NewManager(
"mysql", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"username:password@protocol(address)/dbname?param=value"}`)
go globalSessions.GC()
}
* Use **MySQL** as provider, the last param is the DSN, learn more
from [mysql](https://github.com/go-sql-driver/mysql#dsn-data-source-name):
func init() {
globalSessions, _ = session.NewManager(
"mysql", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"username:password@protocol(address)/dbname?param=value"}`)
go globalSessions.GC()
}
* Use **Cookie** as provider:
func init() {
globalSessions, _ = session.NewManager(
"cookie", `{"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}`)
go globalSessions.GC()
}
func init() {
globalSessions, _ = session.NewManager(
"cookie", `{"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}`)
go globalSessions.GC()
}
Finally in the handlerfunc you can use it like this
@@ -80,14 +79,13 @@ Finally in the handlerfunc you can use it like this
}
}
## How to write own provider?
When you develop a web app, maybe you want to write own provider because you must meet the requirements.
Writing a provider is easy. You only need to define two struct types
(Session and Provider), which satisfy the interface definition.
Maybe you will find the **memory** provider is a good example.
Writing a provider is easy. You only need to define two struct types
(Session and Provider), which satisfy the interface definition. Maybe you will find the **memory** provider is a good
example.
type SessionStore interface {
Set(key, value interface{}) error //set session value
@@ -108,7 +106,6 @@ Maybe you will find the **memory** provider is a good example.
SessionGC()
}
## LICENSE
BSD License http://creativecommons.org/licenses/BSD/

View File

@@ -20,8 +20,8 @@
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/couchbase"
// "github.com/astaxie/beego/session"
// _ "github.com/beego/beego/v2/session/couchbase"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -41,7 +41,7 @@ import (
couchbase "github.com/couchbase/go-couchbase"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
var couchbpder = &Provider{}

View File

@@ -12,7 +12,7 @@ import (
"github.com/ledisdb/ledisdb/config"
"github.com/ledisdb/ledisdb/ledis"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
var (

View File

@@ -20,8 +20,8 @@
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/memcache"
// "github.com/astaxie/beego/session"
// _ "github.com/beego/beego/v2/session/memcache"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -38,7 +38,7 @@ import (
"strings"
"sync"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
"github.com/bradfitz/gomemcache/memcache"
)

View File

@@ -28,8 +28,8 @@
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/mysql"
// "github.com/astaxie/beego/session"
// _ "github.com/beego/beego/v2/session/mysql"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -47,7 +47,7 @@ import (
"sync"
"time"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
// import mysql driver
_ "github.com/go-sql-driver/mysql"
)

View File

@@ -38,8 +38,8 @@
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/postgresql"
// "github.com/astaxie/beego/session"
// _ "github.com/beego/beego/v2/session/postgresql"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -57,7 +57,7 @@ import (
"sync"
"time"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
// import postgresql Driver
_ "github.com/lib/pq"
)

View File

@@ -20,8 +20,8 @@
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/redis"
// "github.com/astaxie/beego/session"
// _ "github.com/beego/beego/v2/session/redis"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -43,7 +43,7 @@ import (
"github.com/go-redis/redis/v7"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
var redispder = &Provider{}

View File

@@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
func TestRedis(t *testing.T) {

View File

@@ -20,8 +20,8 @@
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/redis_cluster"
// "github.com/astaxie/beego/session"
// _ "github.com/beego/beego/v2/session/redis_cluster"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -43,7 +43,7 @@ import (
rediss "github.com/go-redis/redis/v7"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
var redispder = &Provider{}

View File

@@ -20,8 +20,8 @@
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/redis_sentinel"
// "github.com/astaxie/beego/session"
// _ "github.com/beego/beego/v2/session/redis_sentinel"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -43,7 +43,7 @@ import (
"github.com/go-redis/redis/v7"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
var redispder = &Provider{}

View File

@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
func TestRedisSentinel(t *testing.T) {

View File

@@ -27,9 +27,9 @@ var mempder = &MemProvider{list: list.New(), sessions: make(map[string]*list.Ele
// MemSessionStore memory session store.
// it saved sessions in a map in memory.
type MemSessionStore struct {
sid string //session id
timeAccessed time.Time //last access time
value map[interface{}]interface{} //session store
sid string // session id
timeAccessed time.Time // last access time
value map[interface{}]interface{} // session store
lock sync.RWMutex
}

View File

@@ -29,7 +29,7 @@ import (
"strconv"
"time"
"github.com/astaxie/beego/core/utils"
"github.com/beego/beego/v2/core/utils"
)
func init() {

View File

@@ -16,7 +16,7 @@
//
// Usage:
// import(
// "github.com/astaxie/beego/session"
// "github.com/beego/beego/v2/session"
// )
//
// func init() {
@@ -44,12 +44,12 @@ import (
// Store contains all data for one session process with specific id.
type Store interface {
Set(ctx context.Context, key, value interface{}) error //set session value
Get(ctx context.Context, key interface{}) interface{} //get session value
Delete(ctx context.Context, key interface{}) error //delete session value
SessionID(ctx context.Context) string //back current sessionID
Set(ctx context.Context, key, value interface{}) error // set session value
Get(ctx context.Context, key interface{}) interface{} // get session value
Delete(ctx context.Context, key interface{}) error // delete session value
SessionID(ctx context.Context) string // back current sessionID
SessionRelease(ctx context.Context, w http.ResponseWriter) // release the resource & save data to provider & return the data
Flush(ctx context.Context) error //delete all data
Flush(ctx context.Context) error // delete all data
}
// Provider contains global session methods and saved SessionStores.
@@ -60,7 +60,7 @@ type Provider interface {
SessionExist(ctx context.Context, sid string) (bool, error)
SessionRegenerate(ctx context.Context, oldsid, sid string) (Store, error)
SessionDestroy(ctx context.Context, sid string) error
SessionAll(ctx context.Context) int //get all active session
SessionAll(ctx context.Context) int // get all active session
SessionGC(ctx context.Context)
}
@@ -82,7 +82,7 @@ func Register(name string, provide Provider) {
provides[name] = provide
}
//GetProvider
// GetProvider
func GetProvider(name string) (Provider, error) {
provider, ok := provides[name]
if !ok {
@@ -107,6 +107,7 @@ type ManagerConfig struct {
SessionNameInHTTPHeader string `json:"SessionNameInHTTPHeader"`
EnableSidInURLQuery bool `json:"EnableSidInURLQuery"`
SessionIDPrefix string `json:"sessionIDPrefix"`
CookieSameSite http.SameSite `json:"cookieSameSite"`
}
// Manager contains Provider and its configuration.
@@ -239,6 +240,7 @@ func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (se
HttpOnly: !manager.config.DisableHTTPOnly,
Secure: manager.isSecure(r),
Domain: manager.config.Domain,
SameSite: manager.config.CookieSameSite,
}
if manager.config.CookieLifeTime > 0 {
cookie.MaxAge = manager.config.CookieLifeTime
@@ -278,7 +280,9 @@ func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) {
HttpOnly: !manager.config.DisableHTTPOnly,
Expires: expiration,
MaxAge: -1,
Domain: manager.config.Domain}
Domain: manager.config.Domain,
SameSite: manager.config.CookieSameSite,
}
http.SetCookie(w, cookie)
}
@@ -298,25 +302,40 @@ func (manager *Manager) GC() {
}
// SessionRegenerateID Regenerate a session id for this SessionStore who's id is saving in http request.
func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) (session Store) {
func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) (Store, error) {
sid, err := manager.sessionID()
if err != nil {
return
return nil, err
}
var session Store
cookie, err := r.Cookie(manager.config.CookieName)
if err != nil || cookie.Value == "" {
//delete old cookie
session, _ = manager.provider.SessionRead(nil, sid)
// delete old cookie
session, err = manager.provider.SessionRead(nil, sid)
if err != nil {
return nil, err
}
cookie = &http.Cookie{Name: manager.config.CookieName,
Value: url.QueryEscape(sid),
Path: "/",
HttpOnly: !manager.config.DisableHTTPOnly,
Secure: manager.isSecure(r),
Domain: manager.config.Domain,
SameSite: manager.config.CookieSameSite,
}
} else {
oldsid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRegenerate(nil, oldsid, sid)
oldsid, err := url.QueryUnescape(cookie.Value)
if err != nil {
return nil, err
}
session, err = manager.provider.SessionRegenerate(nil, oldsid, sid)
if err != nil {
return nil, err
}
cookie.Value = url.QueryEscape(sid)
cookie.HttpOnly = true
cookie.Path = "/"
@@ -335,7 +354,7 @@ func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Reque
w.Header().Set(manager.config.SessionNameInHTTPHeader, sid)
}
return
return session, nil
}
// GetActiveSession Get all active sessions count number.

View File

@@ -11,7 +11,7 @@ import (
"github.com/ssdb/gossdb/ssdb"
"github.com/astaxie/beego/server/web/session"
"github.com/beego/beego/v2/server/web/session"
)
var ssdbProvider = &Provider{}

View File

@@ -26,10 +26,11 @@ import (
"sync"
"time"
"github.com/astaxie/beego/core/logs"
lru "github.com/hashicorp/golang-lru"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web/context"
)
var errNotStaticRequest = errors.New("request not a static file request")
@@ -65,12 +66,12 @@ func serverStaticRouter(ctx *context.Context) {
}
ctx.Redirect(302, redirectURL)
} else {
//serveFile will list dir
// serveFile will list dir
http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath)
}
return
} else if fileInfo.Size() > int64(BConfig.WebConfig.StaticCacheFileSize) {
//over size file serve with http module
// over size file serve with http module
http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath)
return
}
@@ -102,7 +103,7 @@ type serveContentHolder struct {
data []byte
modTime time.Time
size int64
originSize int64 //original file size:to judge file changed
originSize int64 // original file size:to judge file changed
encoding string
}
@@ -117,7 +118,7 @@ var (
func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, *serveContentReader, error) {
if staticFileLruCache == nil {
//avoid lru cache error
// avoid lru cache error
if BConfig.WebConfig.StaticCacheFileNum >= 1 {
staticFileLruCache, _ = lru.New(BConfig.WebConfig.StaticCacheFileNum)
} else {

View File

@@ -19,7 +19,7 @@ import (
"sync"
"time"
"github.com/astaxie/beego/core/utils"
"github.com/beego/beego/v2/core/utils"
)
// Statistics struct
@@ -35,7 +35,7 @@ type Statistics struct {
// URLMap contains several statistics struct to log different data
type URLMap struct {
lock sync.RWMutex
LengthLimit int //limit the urlmap's length if it's equal to 0 there's no limit
LengthLimit int // limit the urlmap's length if it's equal to 0 there's no limit
urlmap map[string]map[string]*Statistics
}

View File

@@ -106,7 +106,7 @@ type Parameter struct {
type ParameterItems struct {
Type string `json:"type,omitempty" yaml:"type,omitempty"`
Format string `json:"format,omitempty" yaml:"format,omitempty"`
Items []*ParameterItems `json:"items,omitempty" yaml:"items,omitempty"` //Required if type is "array". Describes the type of items in the array.
Items []*ParameterItems `json:"items,omitempty" yaml:"items,omitempty"` // Required if type is "array". Describes the type of items in the array.
CollectionFormat string `json:"collectionFormat,omitempty" yaml:"collectionFormat,omitempty"`
Default string `json:"default,omitempty" yaml:"default,omitempty"`
}

View File

@@ -27,8 +27,8 @@ import (
"strings"
"sync"
"github.com/astaxie/beego/core/logs"
"github.com/astaxie/beego/core/utils"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/core/utils"
)
var (
@@ -163,12 +163,12 @@ func AddTemplateExt(ext string) {
}
// AddViewPath adds a new path to the supported view paths.
//Can later be used by setting a controller ViewPath to this folder
//will panic if called after beego.Run()
// Can later be used by setting a controller ViewPath to this folder
// will panic if called after beego.Run()
func AddViewPath(viewPath string) error {
if beeViewPathTemplateLocked {
if _, exist := beeViewPathTemplates[viewPath]; exist {
return nil //Ignore if viewpath already exists
return nil // Ignore if viewpath already exists
}
panic("Can not add new view paths after beego.Run()")
}
@@ -303,7 +303,7 @@ func _getTemplate(t0 *template.Template, root string, fs http.FileSystem, subMod
if tpl != nil {
continue
}
//first check filename
// first check filename
for _, otherFile := range others {
if otherFile == m[1] {
var subMods1 [][]string
@@ -316,7 +316,7 @@ func _getTemplate(t0 *template.Template, root string, fs http.FileSystem, subMod
break
}
}
//second check define
// second check define
for _, otherFile := range others {
var data []byte
fileAbsPath := filepath.Join(root, otherFile)

View File

@@ -24,7 +24,7 @@ import (
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/stretchr/testify/assert"
"github.com/astaxie/beego/test"
"github.com/beego/beego/v2/test"
)
var header = `{{define "header"}}
@@ -49,9 +49,8 @@ var block = `{{define "block"}}
{{end}}`
func TestTemplate(t *testing.T) {
wkdir, err := os.Getwd()
assert.Nil(t, err)
dir := filepath.Join(wkdir, "_beeTmp", "TestTemplate")
tmpDir := os.TempDir()
dir := filepath.Join(tmpDir, "_beeTmp", "TestTemplate")
files := []string{
"header.tpl",
"index.tpl",
@@ -113,11 +112,10 @@ var user = `<!DOCTYPE html>
`
func TestRelativeTemplate(t *testing.T) {
wkdir, err := os.Getwd()
assert.Nil(t, err)
dir := filepath.Join(wkdir, "_beeTmp")
tmpDir := os.TempDir()
dir := filepath.Join(tmpDir, "_beeTmp")
//Just add dir to known viewPaths
// Just add dir to known viewPaths
if err := AddViewPath(dir); err != nil {
t.Fatal(err)
}
@@ -226,10 +224,10 @@ var output = `<!DOCTYPE html>
`
func TestTemplateLayout(t *testing.T) {
wkdir, err := os.Getwd()
tmpDir, err := os.Getwd()
assert.Nil(t, err)
dir := filepath.Join(wkdir, "_beeTmp", "TestTemplateLayout")
dir := filepath.Join(tmpDir, "_beeTmp", "TestTemplateLayout")
files := []string{
"add.tpl",
"layout_blog.tpl",

View File

@@ -19,9 +19,9 @@ import (
"regexp"
"strings"
"github.com/astaxie/beego/core/utils"
"github.com/beego/beego/v2/core/utils"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
var (

View File

@@ -18,90 +18,122 @@ import (
"strings"
"testing"
"github.com/astaxie/beego/server/web/context"
"github.com/beego/beego/v2/server/web/context"
)
type testinfo struct {
url string
requesturl string
params map[string]string
type testInfo struct {
pattern string
requestUrl string
params map[string]string
shouldMatchOrNot bool
}
var routers []testinfo
var routers []testInfo
func matchTestInfo(pattern, url string, params map[string]string) testInfo {
return testInfo{
pattern: pattern,
requestUrl: url,
params: params,
shouldMatchOrNot: true,
}
}
func notMatchTestInfo(pattern, url string) testInfo {
return testInfo{
pattern: pattern,
requestUrl: url,
params: nil,
shouldMatchOrNot: false,
}
}
func init() {
routers = make([]testinfo, 0)
routers = append(routers, testinfo{"/topic/?:auth:int", "/topic", nil})
routers = append(routers, testinfo{"/topic/?:auth:int", "/topic/123", map[string]string{":auth": "123"}})
routers = append(routers, testinfo{"/topic/:id/?:auth", "/topic/1", map[string]string{":id": "1"}})
routers = append(routers, testinfo{"/topic/:id/?:auth", "/topic/1/2", map[string]string{":id": "1", ":auth": "2"}})
routers = append(routers, testinfo{"/topic/:id/?:auth:int", "/topic/1", map[string]string{":id": "1"}})
routers = append(routers, testinfo{"/topic/:id/?:auth:int", "/topic/1/123", map[string]string{":id": "1", ":auth": "123"}})
routers = append(routers, testinfo{"/:id", "/123", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/hello/?:id", "/hello", map[string]string{":id": ""}})
routers = append(routers, testinfo{"/", "/", nil})
routers = append(routers, testinfo{"/customer/login", "/customer/login", nil})
routers = append(routers, testinfo{"/customer/login", "/customer/login.json", map[string]string{":ext": "json"}})
routers = append(routers, testinfo{"/*", "/http://customer/123/", map[string]string{":splat": "http://customer/123/"}})
routers = append(routers, testinfo{"/*", "/customer/2009/12/11", map[string]string{":splat": "customer/2009/12/11"}})
routers = append(routers, testinfo{"/aa/*/bb", "/aa/2009/bb", map[string]string{":splat": "2009"}})
routers = append(routers, testinfo{"/cc/*/dd", "/cc/2009/11/dd", map[string]string{":splat": "2009/11"}})
routers = append(routers, testinfo{"/cc/:id/*", "/cc/2009/11/dd", map[string]string{":id": "2009", ":splat": "11/dd"}})
routers = append(routers, testinfo{"/ee/:year/*/ff", "/ee/2009/11/ff", map[string]string{":year": "2009", ":splat": "11"}})
routers = append(routers, testinfo{"/thumbnail/:size/uploads/*",
"/thumbnail/100x100/uploads/items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg",
map[string]string{":size": "100x100", ":splat": "items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg"}})
routers = append(routers, testinfo{"/*.*", "/nice/api.json", map[string]string{":path": "nice/api", ":ext": "json"}})
routers = append(routers, testinfo{"/:name/*.*", "/nice/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}})
routers = append(routers, testinfo{"/:name/test/*.*", "/nice/test/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}})
routers = append(routers, testinfo{"/dl/:width:int/:height:int/*.*",
"/dl/48/48/05ac66d9bda00a3acf948c43e306fc9a.jpg",
map[string]string{":width": "48", ":height": "48", ":ext": "jpg", ":path": "05ac66d9bda00a3acf948c43e306fc9a"}})
routers = append(routers, testinfo{"/v1/shop/:id:int", "/v1/shop/123", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(a)", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(b)", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(c)", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/:year:int/:month:int/:id/:endid", "/1111/111/aaa/aaa", map[string]string{":year": "1111", ":month": "111", ":id": "aaa", ":endid": "aaa"}})
routers = append(routers, testinfo{"/v1/shop/:id/:name", "/v1/shop/123/nike", map[string]string{":id": "123", ":name": "nike"}})
routers = append(routers, testinfo{"/v1/shop/:id/account", "/v1/shop/123/account", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/v1/shop/:name:string", "/v1/shop/nike", map[string]string{":name": "nike"}})
routers = append(routers, testinfo{"/v1/shop/:id([0-9]+)", "/v1/shop//123", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/v1/shop/:id([0-9]+)_:name", "/v1/shop/123_nike", map[string]string{":id": "123", ":name": "nike"}})
routers = append(routers, testinfo{"/v1/shop/:id(.+)_cms.html", "/v1/shop/123_cms.html", map[string]string{":id": "123"}})
routers = append(routers, testinfo{"/v1/shop/cms_:id(.+)_:page(.+).html", "/v1/shop/cms_123_1.html", map[string]string{":id": "123", ":page": "1"}})
routers = append(routers, testinfo{"/v1/:v/cms/aaa_:id(.+)_:page(.+).html", "/v1/2/cms/aaa_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}})
routers = append(routers, testinfo{"/v1/:v/cms_:id(.+)_:page(.+).html", "/v1/2/cms_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}})
routers = append(routers, testinfo{"/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", "/v1/2_cms/ttt_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}})
routers = append(routers, testinfo{"/api/projects/:pid/members/?:mid", "/api/projects/1/members", map[string]string{":pid": "1"}})
routers = append(routers, testinfo{"/api/projects/:pid/members/?:mid", "/api/projects/1/members/2", map[string]string{":pid": "1", ":mid": "2"}})
routers = append(routers, testinfo{"/?:year/?:month/?:day", "/2020/11/10", map[string]string{":year": "2020", ":month": "11", ":day": "10"}})
routers = append(routers, testinfo{"/?:year/?:month/?:day", "/2020/11", map[string]string{":year": "2020", ":month": "11"}})
routers = append(routers, testinfo{"/?:year", "/2020", map[string]string{":year": "2020"}})
routers = append(routers, testinfo{"/?:year([0-9]+)/?:month([0-9]+)/mid/?:day([0-9]+)/?:hour([0-9]+)", "/2020/11/mid/10/24", map[string]string{":year": "2020", ":month": "11", ":day": "10", ":hour": "24"}})
routers = append(routers, testinfo{"/?:year/?:month/mid/?:day/?:hour", "/2020/mid/10", map[string]string{":year": "2020", ":day": "10"}})
routers = append(routers, testinfo{"/?:year/?:month/mid/?:day/?:hour", "/2020/11/mid", map[string]string{":year": "2020", ":month": "11"}})
routers = append(routers, testinfo{"/?:year/?:month/mid/?:day/?:hour", "/mid/10/24", map[string]string{":day": "10", ":hour": "24"}})
routers = append(routers, testinfo{"/?:year([0-9]+)/:month([0-9]+)/mid/:day([0-9]+)/?:hour([0-9]+)", "/2020/11/mid/10/24", map[string]string{":year": "2020", ":month": "11", ":day": "10", ":hour": "24"}})
routers = append(routers, testinfo{"/?:year/:month/mid/:day/?:hour", "/11/mid/10/24", map[string]string{":month": "11", ":day": "10"}})
routers = append(routers, testinfo{"/?:year/:month/mid/:day/?:hour", "/2020/11/mid/10", map[string]string{":year": "2020", ":month": "11", ":day": "10"}})
routers = append(routers, testinfo{"/?:year/:month/mid/:day/?:hour", "/11/mid/10", map[string]string{":month": "11", ":day": "10"}})
routers = make([]testInfo, 0)
// match example
routers = append(routers, matchTestInfo("/topic/?:auth:int", "/topic", nil))
routers = append(routers, matchTestInfo("/topic/?:auth:int", "/topic/123", map[string]string{":auth": "123"}))
routers = append(routers, matchTestInfo("/topic/:id/?:auth", "/topic/1", map[string]string{":id": "1"}))
routers = append(routers, matchTestInfo("/topic/:id/?:auth", "/topic/1/2", map[string]string{":id": "1", ":auth": "2"}))
routers = append(routers, matchTestInfo("/topic/:id/?:auth:int", "/topic/1", map[string]string{":id": "1"}))
routers = append(routers, matchTestInfo("/topic/:id/?:auth:int", "/topic/1/123", map[string]string{":id": "1", ":auth": "123"}))
routers = append(routers, matchTestInfo("/:id", "/123", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/hello/?:id", "/hello", map[string]string{":id": ""}))
routers = append(routers, matchTestInfo("/", "/", nil))
routers = append(routers, matchTestInfo("/customer/login", "/customer/login", nil))
routers = append(routers, matchTestInfo("/customer/login", "/customer/login.json", map[string]string{":ext": "json"}))
routers = append(routers, matchTestInfo("/*", "/http://customer/123/", map[string]string{":splat": "http://customer/123/"}))
routers = append(routers, matchTestInfo("/*", "/customer/2009/12/11", map[string]string{":splat": "customer/2009/12/11"}))
routers = append(routers, matchTestInfo("/aa/*/bb", "/aa/2009/bb", map[string]string{":splat": "2009"}))
routers = append(routers, matchTestInfo("/cc/*/dd", "/cc/2009/11/dd", map[string]string{":splat": "2009/11"}))
routers = append(routers, matchTestInfo("/cc/:id/*", "/cc/2009/11/dd", map[string]string{":id": "2009", ":splat": "11/dd"}))
routers = append(routers, matchTestInfo("/ee/:year/*/ff", "/ee/2009/11/ff", map[string]string{":year": "2009", ":splat": "11"}))
routers = append(routers, matchTestInfo("/thumbnail/:size/uploads/*", "/thumbnail/100x100/uploads/items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg", map[string]string{":size": "100x100", ":splat": "items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg"}))
routers = append(routers, matchTestInfo("/*.*", "/nice/api.json", map[string]string{":path": "nice/api", ":ext": "json"}))
routers = append(routers, matchTestInfo("/:name/*.*", "/nice/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}))
routers = append(routers, matchTestInfo("/:name/test/*.*", "/nice/test/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}))
routers = append(routers, matchTestInfo("/dl/:width:int/:height:int/*.*", "/dl/48/48/05ac66d9bda00a3acf948c43e306fc9a.jpg", map[string]string{":width": "48", ":height": "48", ":ext": "jpg", ":path": "05ac66d9bda00a3acf948c43e306fc9a"}))
routers = append(routers, matchTestInfo("/v1/shop/:id:int", "/v1/shop/123", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(a)", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(b)", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(c)", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/:year:int/:month:int/:id/:endid", "/1111/111/aaa/aaa", map[string]string{":year": "1111", ":month": "111", ":id": "aaa", ":endid": "aaa"}))
routers = append(routers, matchTestInfo("/v1/shop/:id/:name", "/v1/shop/123/nike", map[string]string{":id": "123", ":name": "nike"}))
routers = append(routers, matchTestInfo("/v1/shop/:id/account", "/v1/shop/123/account", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/v1/shop/:name:string", "/v1/shop/nike", map[string]string{":name": "nike"}))
routers = append(routers, matchTestInfo("/v1/shop/:id([0-9]+)", "/v1/shop//123", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/v1/shop/:id([0-9]+)_:name", "/v1/shop/123_nike", map[string]string{":id": "123", ":name": "nike"}))
routers = append(routers, matchTestInfo("/v1/shop/:id(.+)_cms.html", "/v1/shop/123_cms.html", map[string]string{":id": "123"}))
routers = append(routers, matchTestInfo("/v1/shop/cms_:id(.+)_:page(.+).html", "/v1/shop/cms_123_1.html", map[string]string{":id": "123", ":page": "1"}))
routers = append(routers, matchTestInfo("/v1/:v/cms/aaa_:id(.+)_:page(.+).html", "/v1/2/cms/aaa_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}))
routers = append(routers, matchTestInfo("/v1/:v/cms_:id(.+)_:page(.+).html", "/v1/2/cms_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}))
routers = append(routers, matchTestInfo("/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", "/v1/2_cms/ttt_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}))
routers = append(routers, matchTestInfo("/api/projects/:pid/members/?:mid", "/api/projects/1/members", map[string]string{":pid": "1"}))
routers = append(routers, matchTestInfo("/api/projects/:pid/members/?:mid", "/api/projects/1/members/2", map[string]string{":pid": "1", ":mid": "2"}))
routers = append(routers, matchTestInfo("/?:year/?:month/?:day", "/2020/11/10", map[string]string{":year": "2020", ":month": "11", ":day": "10"}))
routers = append(routers, matchTestInfo("/?:year/?:month/?:day", "/2020/11", map[string]string{":year": "2020", ":month": "11"}))
routers = append(routers, matchTestInfo("/?:year", "/2020", map[string]string{":year": "2020"}))
routers = append(routers, matchTestInfo("/?:year([0-9]+)/?:month([0-9]+)/mid/?:day([0-9]+)/?:hour([0-9]+)", "/2020/11/mid/10/24", map[string]string{":year": "2020", ":month": "11", ":day": "10", ":hour": "24"}))
routers = append(routers, matchTestInfo("/?:year/?:month/mid/?:day/?:hour", "/2020/mid/10", map[string]string{":year": "2020", ":day": "10"}))
routers = append(routers, matchTestInfo("/?:year/?:month/mid/?:day/?:hour", "/2020/11/mid", map[string]string{":year": "2020", ":month": "11"}))
routers = append(routers, matchTestInfo("/?:year/?:month/mid/?:day/?:hour", "/mid/10/24", map[string]string{":day": "10", ":hour": "24"}))
routers = append(routers, matchTestInfo("/?:year([0-9]+)/:month([0-9]+)/mid/:day([0-9]+)/?:hour([0-9]+)", "/2020/11/mid/10/24", map[string]string{":year": "2020", ":month": "11", ":day": "10", ":hour": "24"}))
routers = append(routers, matchTestInfo("/?:year/:month/mid/:day/?:hour", "/11/mid/10/24", map[string]string{":month": "11", ":day": "10"}))
routers = append(routers, matchTestInfo("/?:year/:month/mid/:day/?:hour", "/2020/11/mid/10", map[string]string{":year": "2020", ":month": "11", ":day": "10"}))
routers = append(routers, matchTestInfo("/?:year/:month/mid/:day/?:hour", "/11/mid/10", map[string]string{":month": "11", ":day": "10"}))
// not match example
// https://github.com/beego/beego/v2/issues/3865
routers = append(routers, notMatchTestInfo("/read_:id:int\\.htm", "/read_222htm"))
routers = append(routers, notMatchTestInfo("/read_:id:int\\.htm", "/read_222_htm"))
routers = append(routers, notMatchTestInfo("/read_:id:int\\.htm", " /read_262shtm"))
}
func TestTreeRouters(t *testing.T) {
for _, r := range routers {
shouldMatch := r.shouldMatchOrNot
tr := NewTree()
tr.AddRouter(r.url, "astaxie")
tr.AddRouter(r.pattern, "astaxie")
ctx := context.NewContext()
obj := tr.Match(r.requesturl, ctx)
obj := tr.Match(r.requestUrl, ctx)
if !shouldMatch {
if obj != nil {
t.Fatal("pattern:", r.pattern, ", should not match", r.requestUrl)
} else {
return
}
}
if obj == nil || obj.(string) != "astaxie" {
t.Fatal(r.url+" can't get obj, Expect ", r.requesturl)
t.Fatal("pattern:", r.pattern+", can't match obj, Expect ", r.requestUrl)
}
if r.params != nil {
for k, v := range r.params {
if vv := ctx.Input.Param(k); vv != v {
t.Fatal("The Rule: " + r.url + "\nThe RequestURL:" + r.requesturl + "\nThe Key is " + k + ", The Value should be: " + v + ", but get: " + vv)
t.Fatal("The Rule: " + r.pattern + "\nThe RequestURL:" + r.requestUrl + "\nThe Key is " + k + ", The Value should be: " + v + ", but get: " + vv)
} else if vv == "" && v != "" {
t.Fatal(r.url + " " + r.requesturl + " get param empty:" + k)
t.Fatal(r.pattern + " " + r.requestUrl + " get param empty:" + k)
}
}
}
@@ -258,7 +290,6 @@ func TestAddTree5(t *testing.T) {
t.Fatal("url /v1/shop/ need match router /v1/shop/ ")
}
}
func TestSplitPath(t *testing.T) {
a := splitPath("")
if len(a) != 0 {
@@ -303,6 +334,7 @@ func TestSplitSegment(t *testing.T) {
":id([0-9]+)": {true, []string{":id"}, `([0-9]+)`},
":id([0-9]+)_:name": {true, []string{":id", ":name"}, `([0-9]+)_(.+)`},
":id(.+)_cms.html": {true, []string{":id"}, `(.+)_cms.html`},
":id(.+)_cms\\.html": {true, []string{":id"}, `(.+)_cms\.html`},
"cms_:id(.+)_:page(.+).html": {true, []string{":id", ":page"}, `cms_(.+)_(.+).html`},
`:app(a|b|c)`: {true, []string{":app"}, `(a|b|c)`},
`:app\((a|b|c)\)`: {true, []string{":app"}, `(.+)\((a|b|c)\)`},