Merge pull request #4656 from Loyalsoldier/server-fix-lint

Fix lint and format code in server dir
This commit is contained in:
Ming Deng 2021-06-11 21:13:21 +08:00 committed by GitHub
commit f79dfcff8d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 159 additions and 204 deletions

View File

@ -5,10 +5,8 @@
- Infra: use dependabot to update dependencies. [4623](https://github.com/beego/beego/pull/4623) - Infra: use dependabot to update dependencies. [4623](https://github.com/beego/beego/pull/4623)
- Lint: use golangci-lint. [4619](https://github.com/beego/beego/pull/4619) - Lint: use golangci-lint. [4619](https://github.com/beego/beego/pull/4619)
- Chore: format code. [4615](https://github.com/beego/beego/pull/4615) - Chore: format code. [4615](https://github.com/beego/beego/pull/4615)
- Fix lint and format code in client/httplib dir [4652](https://github.com/beego/beego/pull/4652)
- Test on Go v1.15.x & v1.16.x. [4614](https://github.com/beego/beego/pull/4614) - Test on Go v1.15.x & v1.16.x. [4614](https://github.com/beego/beego/pull/4614)
- Env: non-empty GOBIN & GOPATH. [4613](https://github.com/beego/beego/pull/4613) - Env: non-empty GOBIN & GOPATH. [4613](https://github.com/beego/beego/pull/4613)
- Fix lint and format code in client/orm dir [4653](https://github.com/beego/beego/pull/4653)
- Chore: update dependencies. [4611](https://github.com/beego/beego/pull/4611) - Chore: update dependencies. [4611](https://github.com/beego/beego/pull/4611)
- Update orm_test.go/TestInsertOrUpdate with table-driven. [4609](https://github.com/beego/beego/pull/4609) - Update orm_test.go/TestInsertOrUpdate with table-driven. [4609](https://github.com/beego/beego/pull/4609)
- Add: Resp() method for web.Controller. [4588](https://github.com/beego/beego/pull/4588) - Add: Resp() method for web.Controller. [4588](https://github.com/beego/beego/pull/4588)
@ -49,10 +47,8 @@
- Feature issue #4402 finish router get example. [4416](https://github.com/beego/beego/pull/4416) - Feature issue #4402 finish router get example. [4416](https://github.com/beego/beego/pull/4416)
- Proposal: Add Bind() method for `web.Controller` [4491](https://github.com/beego/beego/issues/4579) - Proposal: Add Bind() method for `web.Controller` [4491](https://github.com/beego/beego/issues/4579)
- Optimize AddAutoPrefix: only register one router in case-insensitive mode. [4582](https://github.com/beego/beego/pull/4582) - Optimize AddAutoPrefix: only register one router in case-insensitive mode. [4582](https://github.com/beego/beego/pull/4582)
- Fix lint and format code in task dir [4655](https://github.com/beego/beego/pull/4655)
- Init exceptMethod by using reflection. [4583](https://github.com/beego/beego/pull/4583) - Init exceptMethod by using reflection. [4583](https://github.com/beego/beego/pull/4583)
- Deprecated BeeMap and replace all usage with `sync.map` [4616](https://github.com/beego/beego/pull/4616) - Deprecated BeeMap and replace all usage with `sync.map` [4616](https://github.com/beego/beego/pull/4616)
- Fix lint and format code in core dir [4654](https://github.com/beego/beego/pull/4654)
- TaskManager support graceful shutdown [4635](https://github.com/beego/beego/pull/4635) - TaskManager support graceful shutdown [4635](https://github.com/beego/beego/pull/4635)
## Fix Sonar ## Fix Sonar
@ -66,11 +62,17 @@
## Fix lint and format code ## Fix lint and format code
- [4651](https://github.com/beego/beego/pull/4651)
- [4644](https://github.com/beego/beego/pull/4644) - [4644](https://github.com/beego/beego/pull/4644)
- [4645](https://github.com/beego/beego/pull/4645) - [4645](https://github.com/beego/beego/pull/4645)
- [4646](https://github.com/beego/beego/pull/4646) - [4646](https://github.com/beego/beego/pull/4646)
- [4647](https://github.com/beego/beego/pull/4647) - [4647](https://github.com/beego/beego/pull/4647)
- [4648](https://github.com/beego/beego/pull/4648) - [4648](https://github.com/beego/beego/pull/4648)
- [4649](https://github.com/beego/beego/pull/4649) - [4649](https://github.com/beego/beego/pull/4649)
- [4651](https://github.com/beego/beego/pull/4651)
- [4652](https://github.com/beego/beego/pull/4652)
- [4653](https://github.com/beego/beego/pull/4653)
- [4654](https://github.com/beego/beego/pull/4654)
- [4655](https://github.com/beego/beego/pull/4655)
- [4656](https://github.com/beego/beego/pull/4656)
- [4660](https://github.com/beego/beego/pull/4660) - [4660](https://github.com/beego/beego/pull/4660)

View File

@ -45,9 +45,7 @@ var beeAdminApp *adminApp
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool var FilterMonitorFunc func(string, string, time.Duration, string, int) bool
func init() { func init() {
FilterMonitorFunc = func(string, string, time.Duration, string, int) bool { return true } FilterMonitorFunc = func(string, string, time.Duration, string, int) bool { return true }
} }
func list(root string, p interface{}, m M) { func list(root string, p interface{}, m M) {
@ -84,7 +82,6 @@ type adminApp struct {
// Route adds http.HandlerFunc to adminApp with url pattern. // Route adds http.HandlerFunc to adminApp with url pattern.
func (admin *adminApp) Run() { func (admin *adminApp) Run() {
// if len(task.AdminTaskList) > 0 { // if len(task.AdminTaskList) > 0 {
// task.StartTask() // task.StartTask()
// } // }

View File

@ -79,7 +79,6 @@ func (a *adminController) PrometheusMetrics() {
// TaskStatus is a http.Handler with running task status (task name, status and the last execution). // TaskStatus is a http.Handler with running task status (task name, status and the last execution).
// it's in "/task" pattern in admin module. // it's in "/task" pattern in admin module.
func (a *adminController) TaskStatus() { func (a *adminController) TaskStatus() {
rw, req := a.Ctx.ResponseWriter, a.Ctx.Request rw, req := a.Ctx.ResponseWriter, a.Ctx.Request
data := make(map[interface{}]interface{}) data := make(map[interface{}]interface{})
@ -91,11 +90,11 @@ func (a *adminController) TaskStatus() {
cmd := admin.GetCommand("task", "run") cmd := admin.GetCommand("task", "run")
res := cmd.Execute(taskname) res := cmd.Execute(taskname)
if res.IsSuccess() { if res.IsSuccess() {
data["Message"] = []string{
data["Message"] = []string{"success", "success",
template.HTMLEscapeString(fmt.Sprintf("%s run success,Now the Status is <br>%s", template.HTMLEscapeString(fmt.Sprintf("%s run success,Now the Status is <br>%s",
taskname, res.Content.(string)))} taskname, res.Content.(string))),
}
} else { } else {
data["Message"] = []string{"error", template.HTMLEscapeString(fmt.Sprintf("%s", res.Error))} data["Message"] = []string{"error", template.HTMLEscapeString(fmt.Sprintf("%s", res.Error))}
} }
@ -104,7 +103,7 @@ func (a *adminController) TaskStatus() {
// List Tasks // List Tasks
content := make(M) content := make(M)
resultList := admin.GetCommand("task", "list").Execute().Content.([][]string) resultList := admin.GetCommand("task", "list").Execute().Content.([][]string)
var fields = []string{ fields := []string{
"Task Name", "Task Name",
"Task Spec", "Task Spec",
"Task Status", "Task Status",
@ -238,14 +237,12 @@ func (a *adminController) ListConf() {
data["Title"] = "Routers" data["Title"] = "Routers"
writeTemplate(rw, data, routerAndFilterTpl, defaultScriptsTpl) writeTemplate(rw, data, routerAndFilterTpl, defaultScriptsTpl)
case "filter": case "filter":
var ( content := M{
content = M{
"Fields": []string{ "Fields": []string{
"Router Pattern", "Router Pattern",
"Filter Function", "Filter Function",
}, },
} }
)
filterTypeData := BeeApp.reportFilter() filterTypeData := BeeApp.reportFilter()
@ -287,7 +284,6 @@ func buildHealthCheckResponseList(healthCheckResults *[][]string) []map[string]i
} }
return response return response
} }
// PrintTree print all routers // PrintTree print all routers

View File

@ -14,11 +14,9 @@ import (
"github.com/beego/beego/v2/core/admin" "github.com/beego/beego/v2/core/admin"
) )
type SampleDatabaseCheck struct { type SampleDatabaseCheck struct{}
}
type SampleCacheCheck struct { type SampleCacheCheck struct{}
}
func (dc *SampleDatabaseCheck) Check() error { func (dc *SampleDatabaseCheck) Check() error {
return nil return nil
@ -111,7 +109,6 @@ func TestWriteJSON(t *testing.T) {
decodedBody := []int{} decodedBody := []int{}
err := json.NewDecoder(w.Body).Decode(&decodedBody) err := json.NewDecoder(w.Body).Decode(&decodedBody)
if err != nil { if err != nil {
t.Fatal("Could not decode response body into slice.") t.Fatal("Could not decode response body into slice.")
} }
@ -147,7 +144,6 @@ func TestHealthCheckHandlerDefault(t *testing.T) {
if !strings.Contains(w.Body.String(), "database") { if !strings.Contains(w.Body.String(), "database") {
t.Errorf("Expected 'database' in generated template.") t.Errorf("Expected 'database' in generated template.")
} }
} }
func TestBuildHealthCheckResponseList(t *testing.T) { func TestBuildHealthCheckResponseList(t *testing.T) {
@ -180,13 +176,10 @@ func TestBuildHealthCheckResponseList(t *testing.T) {
t.Errorf("expected %s to be in the response %v", field, response) t.Errorf("expected %s to be in the response %v", field, response)
} }
} }
} }
} }
func TestHealthCheckHandlerReturnsJSON(t *testing.T) { func TestHealthCheckHandlerReturnsJSON(t *testing.T) {
admin.AddHealthCheck("database", &SampleDatabaseCheck{}) admin.AddHealthCheck("database", &SampleDatabaseCheck{})
admin.AddHealthCheck("cache", &SampleCacheCheck{}) admin.AddHealthCheck("cache", &SampleCacheCheck{})
@ -245,5 +238,4 @@ func TestHealthCheckHandlerReturnsJSON(t *testing.T) {
assert.Equal(t, expectedResponseBody[0], database) assert.Equal(t, expectedResponseBody[0], database)
assert.Equal(t, expectedResponseBody[1], cache) assert.Equal(t, expectedResponseBody[1], cache)
} }

View File

@ -33,9 +33,7 @@ type M map[string]interface{}
// Hook function to run // Hook function to run
type hookfunc func() error type hookfunc func() error
var ( var hooks = make([]hookfunc, 0) // hook function slice to store the hookfunc
hooks = make([]hookfunc, 0) // hook function slice to store the hookfunc
)
// AddAPPStartHook is used to register the hookfunc // AddAPPStartHook is used to register the hookfunc
// The hookfuncs will run in beego.Run() // The hookfuncs will run in beego.Run()
@ -50,7 +48,6 @@ func AddAPPStartHook(hf ...hookfunc) {
// beego.Run(":8089") // beego.Run(":8089")
// beego.Run("127.0.0.1:8089") // beego.Run("127.0.0.1:8089")
func Run(params ...string) { func Run(params ...string) {
if len(params) > 0 && params[0] != "" { if len(params) > 0 && params[0] != "" {
BeeApp.Run(params[0]) BeeApp.Run(params[0])
} }

View File

@ -73,9 +73,7 @@ import (
"github.com/beego/beego/v2/server/web/context" "github.com/beego/beego/v2/server/web/context"
) )
var ( var defaultChars = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
defaultChars = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
)
const ( const (
// default captcha attributes // default captcha attributes
@ -199,7 +197,7 @@ func (c *Captcha) VerifyReq(req *http.Request) bool {
// Verify direct verify id and challenge string // Verify direct verify id and challenge string
func (c *Captcha) Verify(id string, challenge string) (success bool) { func (c *Captcha) Verify(id string, challenge string) (success bool) {
if len(challenge) == 0 || len(id) == 0 { if challenge == "" || id == "" {
return return
} }
@ -243,7 +241,7 @@ func NewCaptcha(urlPrefix string, store Storage) *Captcha {
cpt.StdWidth = stdWidth cpt.StdWidth = stdWidth
cpt.StdHeight = stdHeight cpt.StdHeight = stdHeight
if len(urlPrefix) == 0 { if urlPrefix == "" {
urlPrefix = defaultURLPrefix urlPrefix = defaultURLPrefix
} }

View File

@ -156,7 +156,7 @@ func init() {
if err != nil { if err != nil {
panic(err) panic(err)
} }
var filename = "app.conf" filename := "app.conf"
if os.Getenv("BEEGO_RUNMODE") != "" { if os.Getenv("BEEGO_RUNMODE") != "" {
filename = os.Getenv("BEEGO_RUNMODE") + ".app.conf" filename = os.Getenv("BEEGO_RUNMODE") + ".app.conf"
} }
@ -304,7 +304,6 @@ func parseConfig(appConfigPath string) (err error) {
// For 1.x, it use assignSingleConfig to parse the file // For 1.x, it use assignSingleConfig to parse the file
// but for 2.x, we use Unmarshaler method // but for 2.x, we use Unmarshaler method
func assignConfig(ac config.Configer) error { func assignConfig(ac config.Configer) error {
parseConfigForV1(ac) parseConfigForV1(ac)
err := ac.Unmarshaler("", BConfig) err := ac.Unmarshaler("", BConfig)
@ -422,7 +421,6 @@ func assignSingleConfig(p interface{}, ac config.Configer) {
// do nothing here // do nothing here
} }
} }
} }
// LoadAppConfig allow developer to apply a config file // LoadAppConfig allow developer to apply a config file

View File

@ -105,7 +105,6 @@ func TestAssignConfig_02(t *testing.T) {
t.Log(_BConfig.Log.FileLineNum) t.Log(_BConfig.Log.FileLineNum)
t.FailNow() t.FailNow()
} }
} }
func TestAssignConfig_03(t *testing.T) { func TestAssignConfig_03(t *testing.T) {

View File

@ -131,14 +131,12 @@ var (
} }
) )
var ( var encoderMap = map[string]acceptEncoder{ // all the other compress methods will ignore
encoderMap = map[string]acceptEncoder{ // all the other compress methods will ignore
"gzip": gzipCompressEncoder, "gzip": gzipCompressEncoder,
"deflate": deflateCompressEncoder, "deflate": deflateCompressEncoder,
"*": gzipCompressEncoder, // * means any compress will accept,we prefer gzip "*": gzipCompressEncoder, // * means any compress will accept,we prefer gzip
"identity": noneCompressEncoder, // identity means none-compress "identity": noneCompressEncoder, // identity means none-compress
} }
)
// WriteFile reads from file and writes to writer by the specific encoding(gzip/deflate) // WriteFile reads from file and writes to writer by the specific encoding(gzip/deflate)
func WriteFile(encoding string, writer io.Writer, file *os.File) (bool, string, error) { func WriteFile(encoding string, writer io.Writer, file *os.File) (bool, string, error) {
@ -159,7 +157,7 @@ func WriteBody(encoding string, writer io.Writer, content []byte) (bool, string,
func writeLevel(encoding string, writer io.Writer, reader io.Reader, level int) (bool, string, error) { func writeLevel(encoding string, writer io.Writer, reader io.Reader, level int) (bool, string, error) {
var outputWriter resetWriter var outputWriter resetWriter
var err error var err error
var ce = noneCompressEncoder ce := noneCompressEncoder
if cf, ok := encoderMap[encoding]; ok { if cf, ok := encoderMap[encoding]; ok {
ce = cf ce = cf

View File

@ -203,8 +203,8 @@ func TestParams(t *testing.T) {
if val := inp.Param("p2"); val != "val2_ver2" { if val := inp.Param("p2"); val != "val2_ver2" {
t.Fatalf("Input.Param wrong value: %s, expected %s", val, "val1_ver2") t.Fatalf("Input.Param wrong value: %s, expected %s", val, "val1_ver2")
} }
} }
func BenchmarkQuery(b *testing.B) { func BenchmarkQuery(b *testing.B) {
beegoInput := NewInput() beegoInput := NewInput()
beegoInput.Context = NewContext() beegoInput.Context = NewContext()

View File

@ -63,7 +63,7 @@ func (output *BeegoOutput) Header(key, val string) {
// Sends out response body directly. // Sends out response body directly.
func (output *BeegoOutput) Body(content []byte) error { func (output *BeegoOutput) Body(content []byte) error {
var encoding string var encoding string
var buf = &bytes.Buffer{} buf := &bytes.Buffer{}
if output.EnableGzip { if output.EnableGzip {
encoding = ParseEncoding(output.Context.Request) encoding = ParseEncoding(output.Context.Request)
} }

View File

@ -55,29 +55,25 @@ func (f parserFunc) parse(value string, toType reflect.Type) (interface{}, error
return f(value, toType) return f(value, toType)
} }
type boolParser struct { type boolParser struct{}
}
func (p boolParser) parse(value string, toType reflect.Type) (interface{}, error) { func (p boolParser) parse(value string, toType reflect.Type) (interface{}, error) {
return strconv.ParseBool(value) return strconv.ParseBool(value)
} }
type stringParser struct { type stringParser struct{}
}
func (p stringParser) parse(value string, toType reflect.Type) (interface{}, error) { func (p stringParser) parse(value string, toType reflect.Type) (interface{}, error) {
return value, nil return value, nil
} }
type intParser struct { type intParser struct{}
}
func (p intParser) parse(value string, toType reflect.Type) (interface{}, error) { func (p intParser) parse(value string, toType reflect.Type) (interface{}, error) {
return strconv.Atoi(value) return strconv.Atoi(value)
} }
type floatParser struct { type floatParser struct{}
}
func (p floatParser) parse(value string, toType reflect.Type) (interface{}, error) { func (p floatParser) parse(value string, toType reflect.Type) (interface{}, error) {
if toType.Kind() == reflect.Float32 { if toType.Kind() == reflect.Float32 {
@ -90,8 +86,7 @@ func (p floatParser) parse(value string, toType reflect.Type) (interface{}, erro
return strconv.ParseFloat(value, 64) return strconv.ParseFloat(value, 64)
} }
type timeParser struct { type timeParser struct{}
}
func (p timeParser) parse(value string, toType reflect.Type) (result interface{}, err error) { func (p timeParser) parse(value string, toType reflect.Type) (result interface{}, err error) {
result, err = time.Parse(time.RFC3339, value) result, err = time.Parse(time.RFC3339, value)
@ -101,8 +96,7 @@ func (p timeParser) parse(value string, toType reflect.Type) (result interface{}
return return
} }
type jsonParser struct { type jsonParser struct{}
}
func (p jsonParser) parse(value string, toType reflect.Type) (interface{}, error) { func (p jsonParser) parse(value string, toType reflect.Type) (interface{}, error) {
pResult := reflect.New(toType) pResult := reflect.New(toType)

View File

@ -13,7 +13,6 @@ type testDefinition struct {
} }
func Test_Parsers(t *testing.T) { func Test_Parsers(t *testing.T) {
// ints // ints
checkParser(testDefinition{"1", 1, intParser{}}, t) checkParser(testDefinition{"1", 1, intParser{}}, t)
checkParser(testDefinition{"-1", int64(-1), intParser{}}, t) checkParser(testDefinition{"-1", int64(-1), intParser{}}, t)
@ -48,12 +47,11 @@ func Test_Parsers(t *testing.T) {
checkParser(testDefinition{`["a","b"]`, []string{"a", "b"}, jsonParser{}}, t, MethodParam{in: body}) checkParser(testDefinition{`["a","b"]`, []string{"a", "b"}, jsonParser{}}, t, MethodParam{in: body})
// pointers // pointers
var someInt = 1 someInt := 1
checkParser(testDefinition{`1`, &someInt, ptrParser(intParser{})}, t) checkParser(testDefinition{`1`, &someInt, ptrParser(intParser{})}, t)
var someStruct = struct{ X int }{5} someStruct := struct{ X int }{5}
checkParser(testDefinition{`{"X": 5}`, &someStruct, jsonParser{}}, t) checkParser(testDefinition{`{"X": 5}`, &someStruct, jsonParser{}}, t)
} }
func checkParser(def testDefinition, t *testing.T, methodParam ...MethodParam) { func checkParser(def testDefinition, t *testing.T, methodParam ...MethodParam) {

View File

@ -51,7 +51,7 @@ var (
const ( const (
bytePerKb = 1024 bytePerKb = 1024
copyBufferKb = 32 copyBufferKb = 32
filePerm = 0666 filePerm = 0o666
) )
func init() { func init() {

View File

@ -141,7 +141,7 @@ func TestAdditionalViewPaths(t *testing.T) {
dir2file := "file2.tpl" dir2file := "file2.tpl"
genFile := func(dir string, name string, content string) { genFile := func(dir string, name string, content string) {
os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0777) os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o777)
if f, err := os.Create(filepath.Join(dir, name)); err != nil { if f, err := os.Create(filepath.Join(dir, name)); err != nil {
t.Fatal(err) t.Fatal(err)
} else { } else {
@ -149,7 +149,6 @@ func TestAdditionalViewPaths(t *testing.T) {
f.WriteString(content) f.WriteString(content)
f.Close() f.Close()
} }
} }
genFile(dir1, dir1file, `<div>{{.Content}}</div>`) genFile(dir1, dir1file, `<div>{{.Content}}</div>`)
genFile(dir2, dir2file, `<html>{{.Content}}</html>`) genFile(dir2, dir2file, `<html>{{.Content}}</html>`)
@ -216,7 +215,6 @@ func TestBindNoContentType(t *testing.T) {
} }
func TestBindXML(t *testing.T) { func TestBindXML(t *testing.T) {
var s struct { var s struct {
Foo string `xml:"foo"` Foo string `xml:"foo"`
} }

View File

@ -33,15 +33,15 @@ const unknownRouterPattern = "UnknownRouterPattern"
// FilterChainBuilder is an extension point, // FilterChainBuilder is an extension point,
// when we want to support some configuration, // when we want to support some configuration,
// please use this structure // please use this structure
type FilterChainBuilder struct { type FilterChainBuilder struct{}
}
var summaryVec prometheus.ObserverVec var (
var initSummaryVec sync.Once summaryVec prometheus.ObserverVec
initSummaryVec sync.Once
)
// FilterChain returns a FilterFunc. The filter will records some metrics // FilterChain returns a FilterFunc. The filter will records some metrics
func (builder *FilterChainBuilder) FilterChain(next web.FilterFunc) web.FilterFunc { func (builder *FilterChainBuilder) FilterChain(next web.FilterFunc) web.FilterFunc {
initSummaryVec.Do(func() { initSummaryVec.Do(func() {
summaryVec = builder.buildVec() summaryVec = builder.buildVec()
err := prometheus.Register(summaryVec) err := prometheus.Register(summaryVec)

View File

@ -42,7 +42,6 @@ func TestFilterChain(t *testing.T) {
} }
func TestFilterChainBuilder_report(t *testing.T) { func TestFilterChainBuilder_report(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
r, _ := http.NewRequest("GET", "/prometheus/user", nil) r, _ := http.NewRequest("GET", "/prometheus/user", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()

View File

@ -28,7 +28,6 @@ import (
) )
func TestControllerRegister_InsertFilterChain(t *testing.T) { func TestControllerRegister_InsertFilterChain(t *testing.T) {
InsertFilterChain("/*", func(next FilterFunc) FilterFunc { InsertFilterChain("/*", func(next FilterFunc) FilterFunc {
return func(ctx *context.Context) { return func(ctx *context.Context) {
ctx.Output.Header("filter", "filter-chain") ctx.Output.Header("filter", "filter-chain")

View File

@ -6,8 +6,7 @@ import (
"path/filepath" "path/filepath"
) )
type FileSystem struct { type FileSystem struct{}
}
func (d FileSystem) Open(name string) (http.File, error) { func (d FileSystem) Open(name string) (http.File, error) {
return os.Open(name) return os.Open(name)
@ -17,7 +16,6 @@ func (d FileSystem) Open(name string) (http.File, error) {
// directory in the tree, including root. All errors that arise visiting files // directory in the tree, including root. All errors that arise visiting files
// and directories are filtered by walkFn. // and directories are filtered by walkFn.
func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error { func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error {
f, err := fs.Open(root) f, err := fs.Open(root)
if err != nil { if err != nil {
return err return err

View File

@ -303,8 +303,8 @@ func (srv *Server) fork() (err error) {
} }
runningServersForked = true runningServersForked = true
var files = make([]*os.File, len(runningServers)) files := make([]*os.File, len(runningServers))
var orderArgs = make([]string, len(runningServers)) orderArgs := make([]string, len(runningServers))
for _, srvPtr := range runningServers { for _, srvPtr := range runningServers {
f, _ := srvPtr.ln.(*net.TCPListener).File() f, _ := srvPtr.ln.(*net.TCPListener).File()
files[socketPtrOffsetMap[srvPtr.Server.Addr]] = f files[socketPtrOffsetMap[srvPtr.Server.Addr]] = f

View File

@ -25,7 +25,6 @@ import (
) )
func TestSessionProvider(t *testing.T) { func TestSessionProvider(t *testing.T) {
sp := NewSessionProvider("file") sp := NewSessionProvider("file")
assert.NotNil(t, sp) assert.NotNil(t, sp)

View File

@ -25,7 +25,7 @@ type PolicyFunc func(*context.Context)
// FindPolicy Find Router info for URL // FindPolicy Find Router info for URL
func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc { func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc {
var urlPath = cont.Input.URL() urlPath := cont.Input.URL()
if !BConfig.RouterCaseSensitive { if !BConfig.RouterCaseSensitive {
urlPath = strings.ToLower(urlPath) urlPath = strings.ToLower(urlPath)
} }

View File

@ -82,8 +82,7 @@ type FilterHandler interface {
} }
// default log filter static file will not show // default log filter static file will not show
type logFilter struct { type logFilter struct{}
}
func (l *logFilter) Filter(ctx *beecontext.Context) bool { func (l *logFilter) Filter(ctx *beecontext.Context) bool {
requestPath := path.Clean(ctx.Request.URL.Path) requestPath := path.Clean(ctx.Request.URL.Path)
@ -780,7 +779,6 @@ func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter Filter
// } // }
// } // }
func (p *ControllerRegister) InsertFilterChain(pattern string, chain FilterChain, opts ...FilterOpt) { func (p *ControllerRegister) InsertFilterChain(pattern string, chain FilterChain, opts ...FilterOpt) {
opts = append(opts, WithCaseSensitive(p.cfg.RouterCaseSensitive)) opts = append(opts, WithCaseSensitive(p.cfg.RouterCaseSensitive))
p.filterChains = append(p.filterChains, filterChainConfig{ p.filterChains = append(p.filterChains, filterChainConfig{
pattern: pattern, pattern: pattern,
@ -957,7 +955,6 @@ func (p *ControllerRegister) execFilter(context *beecontext.Context, urlPath str
// Implement http.Handler interface. // Implement http.Handler interface.
func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) { func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
ctx := p.GetContext() ctx := p.GetContext()
ctx.Reset(rw, r) ctx.Reset(rw, r)
@ -1295,7 +1292,7 @@ func (p *ControllerRegister) handleParamResponse(context *beecontext.Context, ex
// FindRouter Find Router info for URL // FindRouter Find Router info for URL
func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) { func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) {
var urlPath = context.Input.URL() urlPath := context.Input.URL()
if !p.cfg.RouterCaseSensitive { if !p.cfg.RouterCaseSensitive {
urlPath = strings.ToLower(urlPath) urlPath = strings.ToLower(urlPath)
} }

View File

@ -34,8 +34,7 @@ func (ptc *PrefixTestController) PrefixList() {
ptc.Ctx.Output.Body([]byte("i am list in prefix test")) ptc.Ctx.Output.Body([]byte("i am list in prefix test"))
} }
type TestControllerWithInterface struct { type TestControllerWithInterface struct{}
}
func (m TestControllerWithInterface) Ping() { func (m TestControllerWithInterface) Ping() {
fmt.Println("pong") fmt.Println("pong")
@ -248,7 +247,6 @@ func TestAutoExtFunc(t *testing.T) {
} }
func TestEscape(t *testing.T) { func TestEscape(t *testing.T) {
r, _ := http.NewRequest("GET", "/search/%E4%BD%A0%E5%A5%BD", nil) r, _ := http.NewRequest("GET", "/search/%E4%BD%A0%E5%A5%BD", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@ -265,7 +263,6 @@ func TestEscape(t *testing.T) {
} }
func TestRouteOk(t *testing.T) { func TestRouteOk(t *testing.T) {
r, _ := http.NewRequest("GET", "/person/anderson/thomas?learn=kungfu", nil) r, _ := http.NewRequest("GET", "/person/anderson/thomas?learn=kungfu", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@ -279,7 +276,6 @@ func TestRouteOk(t *testing.T) {
} }
func TestManyRoute(t *testing.T) { func TestManyRoute(t *testing.T) {
r, _ := http.NewRequest("GET", "/beego32-12.html", nil) r, _ := http.NewRequest("GET", "/beego32-12.html", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@ -296,7 +292,6 @@ func TestManyRoute(t *testing.T) {
// Test for issue #1669 // Test for issue #1669
func TestEmptyResponse(t *testing.T) { func TestEmptyResponse(t *testing.T) {
r, _ := http.NewRequest("GET", "/beego-empty.html", nil) r, _ := http.NewRequest("GET", "/beego-empty.html", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@ -839,7 +834,6 @@ func TestRouterSessionSet(t *testing.T) {
if w.Header().Get("Set-Cookie") == "" { if w.Header().Get("Set-Cookie") == "" {
t.Errorf("TestRotuerSessionSet failed") t.Errorf("TestRotuerSessionSet failed")
} }
} }
func TestRouterRouterGet(t *testing.T) { func TestRouterRouterGet(t *testing.T) {

View File

@ -37,12 +37,10 @@ import (
"github.com/beego/beego/v2/server/web/grace" "github.com/beego/beego/v2/server/web/grace"
) )
var (
// BeeApp is an application instance // BeeApp is an application instance
// If you are using single server, you could use this // If you are using single server, you could use this
// But if you need multiple servers, do not use this // But if you need multiple servers, do not use this
BeeApp *HttpServer var BeeApp *HttpServer
)
func init() { func init() {
// create beego application // create beego application
@ -80,7 +78,6 @@ type MiddleWare func(http.Handler) http.Handler
// Run beego application. // Run beego application.
func (app *HttpServer) Run(addr string, mws ...MiddleWare) { func (app *HttpServer) Run(addr string, mws ...MiddleWare) {
initBeforeHTTPRun() initBeforeHTTPRun()
// init... // init...
@ -234,7 +231,6 @@ func (app *HttpServer) Run(addr string, mws ...MiddleWare) {
endRunning <- true endRunning <- true
} }
}() }()
} }
if app.Cfg.Listen.EnableHTTP { if app.Cfg.Listen.EnableHTTP {
go func() { go func() {
@ -864,21 +860,21 @@ func printTree(resultList *[][]string, t *Tree) {
for _, l := range t.leaves { for _, l := range t.leaves {
if v, ok := l.runObject.(*ControllerInfo); ok { if v, ok := l.runObject.(*ControllerInfo); ok {
if v.routerType == routerTypeBeego { if v.routerType == routerTypeBeego {
var result = []string{ result := []string{
template.HTMLEscapeString(v.pattern), template.HTMLEscapeString(v.pattern),
template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)), template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)),
template.HTMLEscapeString(v.controllerType.String()), template.HTMLEscapeString(v.controllerType.String()),
} }
*resultList = append(*resultList, result) *resultList = append(*resultList, result)
} else if v.routerType == routerTypeRESTFul { } else if v.routerType == routerTypeRESTFul {
var result = []string{ result := []string{
template.HTMLEscapeString(v.pattern), template.HTMLEscapeString(v.pattern),
template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)), template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)),
"", "",
} }
*resultList = append(*resultList, result) *resultList = append(*resultList, result)
} else if v.routerType == routerTypeHandler { } else if v.routerType == routerTypeHandler {
var result = []string{ result := []string{
template.HTMLEscapeString(v.pattern), template.HTMLEscapeString(v.pattern),
"", "",
"", "",
@ -904,7 +900,7 @@ func (app *HttpServer) reportFilter() M {
if bf := app.Handlers.filters[k]; len(bf) > 0 { if bf := app.Handlers.filters[k]; len(bf) > 0 {
resultList := new([][]string) resultList := new([][]string)
for _, f := range bf { for _, f := range bf {
var result = []string{ result := []string{
// void xss // void xss
template.HTMLEscapeString(f.pattern), template.HTMLEscapeString(f.pattern),
template.HTMLEscapeString(utils.GetFuncName(f.filterFunc)), template.HTMLEscapeString(utils.GetFuncName(f.filterFunc)),

View File

@ -23,12 +23,10 @@ import (
) )
func TestNewHttpServerWithCfg(t *testing.T) { func TestNewHttpServerWithCfg(t *testing.T) {
BConfig.AppName = "Before" BConfig.AppName = "Before"
svr := NewHttpServerWithCfg(BConfig) svr := NewHttpServerWithCfg(BConfig)
svr.Cfg.AppName = "hello" svr.Cfg.AppName = "hello"
assert.Equal(t, "hello", BConfig.AppName) assert.Equal(t, "hello", BConfig.AppName)
} }
func TestServerRouterGet(t *testing.T) { func TestServerRouterGet(t *testing.T) {

View File

@ -186,6 +186,7 @@ func (lp *Provider) SessionGC(context.Context) {
func (lp *Provider) SessionAll(context.Context) int { func (lp *Provider) SessionAll(context.Context) int {
return 0 return 0
} }
func init() { func init() {
session.Register("ledis", ledispder) session.Register("ledis", ledispder)
} }

View File

@ -43,8 +43,10 @@ import (
"github.com/beego/beego/v2/server/web/session" "github.com/beego/beego/v2/server/web/session"
) )
var mempder = &MemProvider{} var (
var client *memcache.Client mempder = &MemProvider{}
client *memcache.Client
)
// SessionStore memcache session store // SessionStore memcache session store
type SessionStore struct { type SessionStore struct {

View File

@ -123,7 +123,6 @@ func (st *SessionStore) SessionRelease(ctx context.Context, w http.ResponseWrite
} }
st.c.Exec("UPDATE session set session_data=$1, session_expiry=$2 where session_key=$3", st.c.Exec("UPDATE session set session_data=$1, session_expiry=$2 where session_key=$3",
b, time.Now().Format(time.RFC3339), st.sid) b, time.Now().Format(time.RFC3339), st.sid)
} }
// Provider postgresql session provider // Provider postgresql session provider

View File

@ -101,7 +101,6 @@ func TestRedis(t *testing.T) {
} }
func TestProvider_SessionInit(t *testing.T) { func TestProvider_SessionInit(t *testing.T) {
savePath := ` savePath := `
{ "save_path": "my save path", "idle_timeout": "3s"} { "save_path": "my save path", "idle_timeout": "3s"}
` `

View File

@ -23,7 +23,6 @@ import (
) )
func TestProvider_SessionInit(t *testing.T) { func TestProvider_SessionInit(t *testing.T) {
savePath := ` savePath := `
{ "save_path": "my save path", "idle_timeout": "3s"} { "save_path": "my save path", "idle_timeout": "3s"}
` `

View File

@ -90,11 +90,9 @@ func TestRedisSentinel(t *testing.T) {
} }
sess.SessionRelease(nil, w) sess.SessionRelease(nil, w)
} }
func TestProvider_SessionInit(t *testing.T) { func TestProvider_SessionInit(t *testing.T) {
savePath := ` savePath := `
{ "save_path": "my save path", "idle_timeout": "3s"} { "save_path": "my save path", "idle_timeout": "3s"}
` `

View File

@ -79,12 +79,14 @@ func (st *CookieSessionStore) SessionRelease(ctx context.Context, w http.Respons
encodedCookie, err := encodeCookie(cookiepder.block, cookiepder.config.SecurityKey, cookiepder.config.SecurityName, st.values) encodedCookie, err := encodeCookie(cookiepder.block, cookiepder.config.SecurityKey, cookiepder.config.SecurityName, st.values)
st.lock.Unlock() st.lock.Unlock()
if err == nil { if err == nil {
cookie := &http.Cookie{Name: cookiepder.config.CookieName, cookie := &http.Cookie{
Name: cookiepder.config.CookieName,
Value: url.QueryEscape(encodedCookie), Value: url.QueryEscape(encodedCookie),
Path: "/", Path: "/",
HttpOnly: true, HttpOnly: true,
Secure: cookiepder.config.Secure, Secure: cookiepder.config.Secure,
MaxAge: cookiepder.config.Maxage} MaxAge: cookiepder.config.Maxage,
}
http.SetCookie(w, cookie) http.SetCookie(w, cookie)
} }
} }

View File

@ -91,7 +91,7 @@ func (fs *FileSessionStore) SessionRelease(ctx context.Context, w http.ResponseW
_, err = os.Stat(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid)) _, err = os.Stat(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid))
var f *os.File var f *os.File
if err == nil { if err == nil {
f, err = os.OpenFile(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid), os.O_RDWR, 0777) f, err = os.OpenFile(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid), os.O_RDWR, 0o777)
if err != nil { if err != nil {
SLogger.Println(err) SLogger.Println(err)
return return
@ -140,23 +140,32 @@ func (fp *FileProvider) SessionRead(ctx context.Context, sid string) (Store, err
filepder.lock.Lock() filepder.lock.Lock()
defer filepder.lock.Unlock() defer filepder.lock.Unlock()
err := os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0755) sessionPath := filepath.Join(fp.savePath, string(sid[0]), string(sid[1]))
sidPath := filepath.Join(sessionPath, sid)
err := os.MkdirAll(sessionPath, 0o755)
if err != nil { if err != nil {
SLogger.Println(err.Error()) SLogger.Println(err.Error())
} }
_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
var f *os.File var f *os.File
if err == nil { _, err = os.Stat(sidPath)
f, err = os.OpenFile(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), os.O_RDWR, 0777) switch {
} else if os.IsNotExist(err) { case err == nil:
f, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid)) f, err = os.OpenFile(sidPath, os.O_RDWR, 0o777)
} else { if err != nil {
return nil, err
}
case os.IsNotExist(err):
f, err = os.Create(sidPath)
if err != nil {
return nil, err
}
default:
return nil, err return nil, err
} }
defer f.Close() defer f.Close()
os.Chtimes(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), time.Now(), time.Now()) os.Chtimes(sidPath, time.Now(), time.Now())
var kv map[interface{}]interface{} var kv map[interface{}]interface{}
b, err := ioutil.ReadAll(f) b, err := ioutil.ReadAll(f)
if err != nil { if err != nil {
@ -236,7 +245,7 @@ func (fp *FileProvider) SessionRegenerate(ctx context.Context, oldsid, sid strin
return nil, fmt.Errorf("newsid %s exist", newSidFile) return nil, fmt.Errorf("newsid %s exist", newSidFile)
} }
err = os.MkdirAll(newPath, 0755) err = os.MkdirAll(newPath, 0o755)
if err != nil { if err != nil {
SLogger.Println(err.Error()) SLogger.Println(err.Error())
} }
@ -263,7 +272,7 @@ func (fp *FileProvider) SessionRegenerate(ctx context.Context, oldsid, sid strin
} }
} }
ioutil.WriteFile(newSidFile, b, 0777) ioutil.WriteFile(newSidFile, b, 0o777)
os.Remove(oldSidFile) os.Remove(oldSidFile)
os.Chtimes(newSidFile, time.Now(), time.Now()) os.Chtimes(newSidFile, time.Now(), time.Now())
ss := &FileSessionStore{sid: sid, values: kv} ss := &FileSessionStore{sid: sid, values: kv}

View File

@ -23,14 +23,14 @@ import (
"time" "time"
) )
const sid = "Session_id" const (
const sidNew = "Session_id_new" sid = "Session_id"
const sessionPath = "./_session_runtime" sidNew = "Session_id_new"
sessionPath = "./_session_runtime"
var (
mutex sync.Mutex
) )
var mutex sync.Mutex
func TestFileProviderSessionInit(t *testing.T) { func TestFileProviderSessionInit(t *testing.T) {
mutex.Lock() mutex.Lock()
defer mutex.Unlock() defer mutex.Unlock()

View File

@ -252,7 +252,8 @@ func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) {
manager.provider.SessionDestroy(nil, sid) manager.provider.SessionDestroy(nil, sid)
if manager.config.EnableSetCookie { if manager.config.EnableSetCookie {
expiration := time.Now() expiration := time.Now()
cookie = &http.Cookie{Name: manager.config.CookieName, cookie = &http.Cookie{
Name: manager.config.CookieName,
Path: "/", Path: "/",
HttpOnly: !manager.config.DisableHTTPOnly, HttpOnly: !manager.config.DisableHTTPOnly,
Expires: expiration, Expires: expiration,
@ -294,7 +295,8 @@ func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Reque
if err != nil { if err != nil {
return nil, err return nil, err
} }
cookie = &http.Cookie{Name: manager.config.CookieName, cookie = &http.Cookie{
Name: manager.config.CookieName,
Value: url.QueryEscape(sid), Value: url.QueryEscape(sid),
Path: "/", Path: "/",
HttpOnly: !manager.config.DisableHTTPOnly, HttpOnly: !manager.config.DisableHTTPOnly,

View File

@ -75,7 +75,7 @@ func serverStaticRouter(ctx *context.Context) {
return return
} }
var enableCompress = BConfig.EnableGzip && isStaticCompress(filePath) enableCompress := BConfig.EnableGzip && isStaticCompress(filePath)
var acceptEncoding string var acceptEncoding string
if enableCompress { if enableCompress {
acceptEncoding = context.ParseEncoding(ctx.Request) acceptEncoding = context.ParseEncoding(ctx.Request)

View File

@ -12,8 +12,10 @@ import (
"testing" "testing"
) )
var currentWorkDir, _ = os.Getwd() var (
var licenseFile = filepath.Join(currentWorkDir, "LICENSE") currentWorkDir, _ = os.Getwd()
licenseFile = filepath.Join(currentWorkDir, "LICENSE")
)
func testOpenFile(encoding string, content []byte, t *testing.T) { func testOpenFile(encoding string, content []byte, t *testing.T) {
fi, _ := os.Stat(licenseFile) fi, _ := os.Stat(licenseFile)
@ -27,6 +29,7 @@ func testOpenFile(encoding string, content []byte, t *testing.T) {
assetOpenFileAndContent(sch, reader, content, t) assetOpenFileAndContent(sch, reader, content, t)
} }
func TestOpenStaticFile_1(t *testing.T) { func TestOpenStaticFile_1(t *testing.T) {
file, _ := os.Open(licenseFile) file, _ := os.Open(licenseFile)
content, _ := ioutil.ReadAll(file) content, _ := ioutil.ReadAll(file)
@ -43,6 +46,7 @@ func TestOpenStaticFileGzip_1(t *testing.T) {
testOpenFile("gzip", content, t) testOpenFile("gzip", content, t)
} }
func TestOpenStaticFileDeflate_1(t *testing.T) { func TestOpenStaticFileDeflate_1(t *testing.T) {
file, _ := os.Open(licenseFile) file, _ := os.Open(licenseFile)
var zipBuf bytes.Buffer var zipBuf bytes.Buffer

View File

@ -65,7 +65,6 @@ func (m *URLMap) AddStatistics(requestMethod, requestURL, requestController stri
} }
m.urlmap[requestURL][requestMethod] = nb m.urlmap[requestURL][requestMethod] = nb
} }
} else { } else {
if m.LengthLimit > 0 && m.LengthLimit <= len(m.urlmap) { if m.LengthLimit > 0 && m.LengthLimit <= len(m.urlmap) {
return return
@ -89,7 +88,7 @@ func (m *URLMap) GetMap() map[string]interface{} {
m.lock.RLock() m.lock.RLock()
defer m.lock.RUnlock() defer m.lock.RUnlock()
var fields = []string{"requestUrl", "method", "times", "used", "max used", "min used", "avg used"} fields := []string{"requestUrl", "method", "times", "used", "max used", "min used", "avg used"}
var resultLists [][]string var resultLists [][]string
content := make(map[string]interface{}) content := make(map[string]interface{})

View File

@ -349,7 +349,6 @@ func _getTemplate(t0 *template.Template, root string, fs http.FileSystem, subMod
} }
} }
} }
} }
return return
} }

View File

@ -56,11 +56,11 @@ func TestTemplate(t *testing.T) {
"index.tpl", "index.tpl",
"blocks/block.tpl", "blocks/block.tpl",
} }
if err := os.MkdirAll(dir, 0777); err != nil { if err := os.MkdirAll(dir, 0o777); err != nil {
t.Fatal(err) t.Fatal(err)
} }
for k, name := range files { for k, name := range files {
dirErr := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0777) dirErr := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o777)
assert.Nil(t, dirErr) assert.Nil(t, dirErr)
if f, err := os.Create(filepath.Join(dir, name)); err != nil { if f, err := os.Create(filepath.Join(dir, name)); err != nil {
t.Fatal(err) t.Fatal(err)
@ -100,6 +100,7 @@ var menu = `<div class="menu">
</ul> </ul>
</div> </div>
` `
var user = `<!DOCTYPE html> var user = `<!DOCTYPE html>
<html> <html>
<head> <head>
@ -124,11 +125,11 @@ func TestRelativeTemplate(t *testing.T) {
"easyui/public/menu.tpl", "easyui/public/menu.tpl",
"easyui/rbac/user.tpl", "easyui/rbac/user.tpl",
} }
if err := os.MkdirAll(dir, 0777); err != nil { if err := os.MkdirAll(dir, 0o777); err != nil {
t.Fatal(err) t.Fatal(err)
} }
for k, name := range files { for k, name := range files {
os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0777) os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o777)
if f, err := os.Create(filepath.Join(dir, name)); err != nil { if f, err := os.Create(filepath.Join(dir, name)); err != nil {
t.Fatal(err) t.Fatal(err)
} else { } else {
@ -232,12 +233,12 @@ func TestTemplateLayout(t *testing.T) {
"add.tpl", "add.tpl",
"layout_blog.tpl", "layout_blog.tpl",
} }
if err := os.MkdirAll(dir, 0777); err != nil { if err := os.MkdirAll(dir, 0o777); err != nil {
t.Fatal(err) t.Fatal(err)
} }
for k, name := range files { for k, name := range files {
dirErr := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0777) dirErr := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o777)
assert.Nil(t, dirErr) assert.Nil(t, dirErr)
if f, err := os.Create(filepath.Join(dir, name)); err != nil { if f, err := os.Create(filepath.Join(dir, name)); err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -54,7 +54,6 @@ func Substr(s string, start, length int) string {
// HTML2str returns escaping text convert from html. // HTML2str returns escaping text convert from html.
func HTML2str(html string) string { func HTML2str(html string) string {
re := regexp.MustCompile(`\<[\S\s]+?\>`) re := regexp.MustCompile(`\<[\S\s]+?\>`)
html = re.ReplaceAllStringFunc(html, strings.ToLower) html = re.ReplaceAllStringFunc(html, strings.ToLower)
@ -255,7 +254,6 @@ func URLFor(endpoint string, values ...interface{}) string {
// AssetsJs returns script tag with src string. // AssetsJs returns script tag with src string.
func AssetsJs(text string) template.HTML { func AssetsJs(text string) template.HTML {
text = "<script src=\"" + text + "\"></script>" text = "<script src=\"" + text + "\"></script>"
return template.HTML(text) return template.HTML(text)
@ -263,7 +261,6 @@ func AssetsJs(text string) template.HTML {
// AssetsCSS returns stylesheet link tag with src string. // AssetsCSS returns stylesheet link tag with src string.
func AssetsCSS(text string) template.HTML { func AssetsCSS(text string) template.HTML {
text = "<link href=\"" + text + "\" rel=\"stylesheet\" />" text = "<link href=\"" + text + "\" rel=\"stylesheet\" />"
return template.HTML(text) return template.HTML(text)
@ -423,8 +420,10 @@ func ParseForm(form url.Values, obj interface{}) error {
return parseFormToStruct(form, objT, objV) return parseFormToStruct(form, objT, objV)
} }
var sliceOfInts = reflect.TypeOf([]int(nil)) var (
var sliceOfStrings = reflect.TypeOf([]string(nil)) sliceOfInts = reflect.TypeOf([]int(nil))
sliceOfStrings = reflect.TypeOf([]string(nil))
)
var unKind = map[reflect.Kind]bool{ var unKind = map[reflect.Kind]bool{
reflect.Uintptr: true, reflect.Uintptr: true,

View File

@ -299,7 +299,6 @@ func TestParseFormTag(t *testing.T) {
if !(name == "name" && !required) { if !(name == "name" && !required) {
t.Errorf("Form Tag containing only name and not required was not correctly parsed.") t.Errorf("Form Tag containing only name and not required was not correctly parsed.")
} }
} }
func TestMapGet(t *testing.T) { func TestMapGet(t *testing.T) {

View File

@ -23,9 +23,7 @@ import (
"github.com/beego/beego/v2/server/web/context" "github.com/beego/beego/v2/server/web/context"
) )
var ( var allowSuffixExt = []string{".json", ".xml", ".html"}
allowSuffixExt = []string{".json", ".xml", ".html"}
)
// Tree has three elements: FixRouter/wildcard/leaves // Tree has three elements: FixRouter/wildcard/leaves
// fixRouter stores Fixed Router // fixRouter stores Fixed Router

View File

@ -119,7 +119,6 @@ func init() {
routers = append(routers, notMatchTestInfo(abcSuffix, "/abc/suffix.html/a")) routers = append(routers, notMatchTestInfo(abcSuffix, "/abc/suffix.html/a"))
routers = append(routers, matchTestInfo(abcSuffix, "/abc/suffix/a", nil)) routers = append(routers, matchTestInfo(abcSuffix, "/abc/suffix/a", nil))
routers = append(routers, notMatchTestInfo(abcSuffix, "/abc.j/suffix/a")) routers = append(routers, notMatchTestInfo(abcSuffix, "/abc.j/suffix/a"))
} }
func TestTreeRouters(t *testing.T) { func TestTreeRouters(t *testing.T) {
@ -303,6 +302,7 @@ func TestAddTree5(t *testing.T) {
t.Fatal("url /v1/shop/ need match router /v1/shop/ ") t.Fatal("url /v1/shop/ need match router /v1/shop/ ")
} }
} }
func TestSplitPath(t *testing.T) { func TestSplitPath(t *testing.T) {
a := splitPath("") a := splitPath("")
if len(a) != 0 { if len(a) != 0 {
@ -331,7 +331,6 @@ func TestSplitPath(t *testing.T) {
} }
func TestSplitSegment(t *testing.T) { func TestSplitSegment(t *testing.T) {
items := map[string]struct { items := map[string]struct {
isReg bool isReg bool
params []string params []string

View File

@ -27,13 +27,14 @@ import (
// that embed parent routers. // that embed parent routers.
// //
const contentRootOriginal = "ok-original-root" const (
const contentLevel1Original = "ok-original-level1" contentRootOriginal = "ok-original-root"
const contentLevel2Original = "ok-original-level2" contentLevel1Original = "ok-original-level1"
contentLevel2Original = "ok-original-level2"
const contentRootReplacement = "ok-replacement-root" contentRootReplacement = "ok-replacement-root"
const contentLevel1Replacement = "ok-replacement-level1" contentLevel1Replacement = "ok-replacement-level1"
const contentLevel2Replacement = "ok-replacement-level2" contentLevel2Replacement = "ok-replacement-level2"
)
// TestPreUnregController will supply content for the original routes, // TestPreUnregController will supply content for the original routes,
// before unregistration // before unregistration
@ -44,9 +45,11 @@ type TestPreUnregController struct {
func (tc *TestPreUnregController) GetFixedRoot() { func (tc *TestPreUnregController) GetFixedRoot() {
tc.Ctx.Output.Body([]byte(contentRootOriginal)) tc.Ctx.Output.Body([]byte(contentRootOriginal))
} }
func (tc *TestPreUnregController) GetFixedLevel1() { func (tc *TestPreUnregController) GetFixedLevel1() {
tc.Ctx.Output.Body([]byte(contentLevel1Original)) tc.Ctx.Output.Body([]byte(contentLevel1Original))
} }
func (tc *TestPreUnregController) GetFixedLevel2() { func (tc *TestPreUnregController) GetFixedLevel2() {
tc.Ctx.Output.Body([]byte(contentLevel2Original)) tc.Ctx.Output.Body([]byte(contentLevel2Original))
} }
@ -60,9 +63,11 @@ type TestPostUnregController struct {
func (tc *TestPostUnregController) GetFixedRoot() { func (tc *TestPostUnregController) GetFixedRoot() {
tc.Ctx.Output.Body([]byte(contentRootReplacement)) tc.Ctx.Output.Body([]byte(contentRootReplacement))
} }
func (tc *TestPostUnregController) GetFixedLevel1() { func (tc *TestPostUnregController) GetFixedLevel1() {
tc.Ctx.Output.Body([]byte(contentLevel1Replacement)) tc.Ctx.Output.Body([]byte(contentLevel1Replacement))
} }
func (tc *TestPostUnregController) GetFixedLevel2() { func (tc *TestPostUnregController) GetFixedLevel2() {
tc.Ctx.Output.Body([]byte(contentLevel2Replacement)) tc.Ctx.Output.Body([]byte(contentLevel2Replacement))
} }
@ -71,8 +76,7 @@ func (tc *TestPostUnregController) GetFixedLevel2() {
// In this case, for a path like "/level1/level2" or "/level1", those actions // In this case, for a path like "/level1/level2" or "/level1", those actions
// should remain intact, and continue to serve the original content. // should remain intact, and continue to serve the original content.
func TestUnregisterFixedRouteRoot(t *testing.T) { func TestUnregisterFixedRouteRoot(t *testing.T) {
method := "GET"
var method = "GET"
handler := NewControllerRegister() handler := NewControllerRegister()
handler.Add("/", &TestPreUnregController{}, WithRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot")) handler.Add("/", &TestPreUnregController{}, WithRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot"))
@ -106,15 +110,13 @@ func TestUnregisterFixedRouteRoot(t *testing.T) {
// Test level 2 (expect no change from the original) // Test level 2 (expect no change from the original)
testHelperFnContentCheck(t, handler, "Test level 2 (expect no change from the original)", method, "/level1/level2", contentLevel2Original) testHelperFnContentCheck(t, handler, "Test level 2 (expect no change from the original)", method, "/level1/level2", contentLevel2Original)
} }
// TestUnregisterFixedRouteLevel1 replaces just the "/level1" fixed route path. // TestUnregisterFixedRouteLevel1 replaces just the "/level1" fixed route path.
// In this case, for a path like "/level1/level2" or "/", those actions // In this case, for a path like "/level1/level2" or "/", those actions
// should remain intact, and continue to serve the original content. // should remain intact, and continue to serve the original content.
func TestUnregisterFixedRouteLevel1(t *testing.T) { func TestUnregisterFixedRouteLevel1(t *testing.T) {
method := "GET"
var method = "GET"
handler := NewControllerRegister() handler := NewControllerRegister()
handler.Add("/", &TestPreUnregController{}, WithRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot")) handler.Add("/", &TestPreUnregController{}, WithRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot"))
@ -156,15 +158,13 @@ func TestUnregisterFixedRouteLevel1(t *testing.T) {
// Test level 2 (expect no change from the original) // Test level 2 (expect no change from the original)
testHelperFnContentCheck(t, handler, "Test level 2 (expect no change from the original)", method, "/level1/level2", contentLevel2Original) testHelperFnContentCheck(t, handler, "Test level 2 (expect no change from the original)", method, "/level1/level2", contentLevel2Original)
} }
// TestUnregisterFixedRouteLevel2 unregisters just the "/level1/level2" fixed // TestUnregisterFixedRouteLevel2 unregisters just the "/level1/level2" fixed
// route path. In this case, for a path like "/level1" or "/", those actions // route path. In this case, for a path like "/level1" or "/", those actions
// should remain intact, and continue to serve the original content. // should remain intact, and continue to serve the original content.
func TestUnregisterFixedRouteLevel2(t *testing.T) { func TestUnregisterFixedRouteLevel2(t *testing.T) {
method := "GET"
var method = "GET"
handler := NewControllerRegister() handler := NewControllerRegister()
handler.Add("/", &TestPreUnregController{}, WithRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot")) handler.Add("/", &TestPreUnregController{}, WithRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot"))
@ -206,7 +206,6 @@ func TestUnregisterFixedRouteLevel2(t *testing.T) {
// Test level 2 (expect change) // Test level 2 (expect change)
testHelperFnContentCheck(t, handler, "Test level 2 (expect change)", method, "/level1/level2", contentLevel2Replacement) testHelperFnContentCheck(t, handler, "Test level 2 (expect change)", method, "/level1/level2", contentLevel2Replacement)
} }
func testHelperFnContentCheck(t *testing.T, handler *ControllerRegister, func testHelperFnContentCheck(t *testing.T, handler *ControllerRegister,