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)
- Lint: use golangci-lint. [4619](https://github.com/beego/beego/pull/4619)
- 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)
- 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)
- 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)
@ -49,10 +47,8 @@
- 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)
- 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)
- 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)
## Fix Sonar
@ -66,11 +62,17 @@
## Fix lint and format code
- [4651](https://github.com/beego/beego/pull/4651)
- [4644](https://github.com/beego/beego/pull/4644)
- [4645](https://github.com/beego/beego/pull/4645)
- [4646](https://github.com/beego/beego/pull/4646)
- [4647](https://github.com/beego/beego/pull/4647)
- [4648](https://github.com/beego/beego/pull/4648)
- [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)

View File

@ -45,9 +45,7 @@ var beeAdminApp *adminApp
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool
func init() {
FilterMonitorFunc = func(string, string, time.Duration, string, int) bool { return true }
}
func list(root string, p interface{}, m M) {
@ -84,7 +82,6 @@ type adminApp struct {
// Route adds http.HandlerFunc to adminApp with url pattern.
func (admin *adminApp) Run() {
// if len(task.AdminTaskList) > 0 {
// 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).
// it's in "/task" pattern in admin module.
func (a *adminController) TaskStatus() {
rw, req := a.Ctx.ResponseWriter, a.Ctx.Request
data := make(map[interface{}]interface{})
@ -91,11 +90,11 @@ func (a *adminController) TaskStatus() {
cmd := admin.GetCommand("task", "run")
res := cmd.Execute(taskname)
if res.IsSuccess() {
data["Message"] = []string{"success",
data["Message"] = []string{
"success",
template.HTMLEscapeString(fmt.Sprintf("%s run success,Now the Status is <br>%s",
taskname, res.Content.(string)))}
taskname, res.Content.(string))),
}
} else {
data["Message"] = []string{"error", template.HTMLEscapeString(fmt.Sprintf("%s", res.Error))}
}
@ -104,7 +103,7 @@ func (a *adminController) TaskStatus() {
// List Tasks
content := make(M)
resultList := admin.GetCommand("task", "list").Execute().Content.([][]string)
var fields = []string{
fields := []string{
"Task Name",
"Task Spec",
"Task Status",
@ -238,14 +237,12 @@ func (a *adminController) ListConf() {
data["Title"] = "Routers"
writeTemplate(rw, data, routerAndFilterTpl, defaultScriptsTpl)
case "filter":
var (
content = M{
"Fields": []string{
"Router Pattern",
"Filter Function",
},
}
)
content := M{
"Fields": []string{
"Router Pattern",
"Filter Function",
},
}
filterTypeData := BeeApp.reportFilter()
@ -287,7 +284,6 @@ func buildHealthCheckResponseList(healthCheckResults *[][]string) []map[string]i
}
return response
}
// PrintTree print all routers

View File

@ -14,11 +14,9 @@ import (
"github.com/beego/beego/v2/core/admin"
)
type SampleDatabaseCheck struct {
}
type SampleDatabaseCheck struct{}
type SampleCacheCheck struct {
}
type SampleCacheCheck struct{}
func (dc *SampleDatabaseCheck) Check() error {
return nil
@ -111,7 +109,6 @@ func TestWriteJSON(t *testing.T) {
decodedBody := []int{}
err := json.NewDecoder(w.Body).Decode(&decodedBody)
if err != nil {
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") {
t.Errorf("Expected 'database' in generated template.")
}
}
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)
}
}
}
}
func TestHealthCheckHandlerReturnsJSON(t *testing.T) {
admin.AddHealthCheck("database", &SampleDatabaseCheck{})
admin.AddHealthCheck("cache", &SampleCacheCheck{})
@ -245,5 +238,4 @@ func TestHealthCheckHandlerReturnsJSON(t *testing.T) {
assert.Equal(t, expectedResponseBody[0], database)
assert.Equal(t, expectedResponseBody[1], cache)
}

View File

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

View File

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

View File

@ -156,7 +156,7 @@ func init() {
if err != nil {
panic(err)
}
var filename = "app.conf"
filename := "app.conf"
if os.Getenv("BEEGO_RUNMODE") != "" {
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
// but for 2.x, we use Unmarshaler method
func assignConfig(ac config.Configer) error {
parseConfigForV1(ac)
err := ac.Unmarshaler("", BConfig)
@ -422,7 +421,6 @@ func assignSingleConfig(p interface{}, ac config.Configer) {
// do nothing here
}
}
}
// 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.FailNow()
}
}
func TestAssignConfig_03(t *testing.T) {

View File

@ -131,14 +131,12 @@ var (
}
)
var (
encoderMap = map[string]acceptEncoder{ // all the other compress methods will ignore
"gzip": gzipCompressEncoder,
"deflate": deflateCompressEncoder,
"*": gzipCompressEncoder, // * means any compress will accept,we prefer gzip
"identity": noneCompressEncoder, // identity means none-compress
}
)
var encoderMap = map[string]acceptEncoder{ // all the other compress methods will ignore
"gzip": gzipCompressEncoder,
"deflate": deflateCompressEncoder,
"*": gzipCompressEncoder, // * means any compress will accept,we prefer gzip
"identity": noneCompressEncoder, // identity means none-compress
}
// 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) {
@ -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) {
var outputWriter resetWriter
var err error
var ce = noneCompressEncoder
ce := noneCompressEncoder
if cf, ok := encoderMap[encoding]; ok {
ce = cf

View File

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

View File

@ -63,7 +63,7 @@ func (output *BeegoOutput) Header(key, val string) {
// Sends out response body directly.
func (output *BeegoOutput) Body(content []byte) error {
var encoding string
var buf = &bytes.Buffer{}
buf := &bytes.Buffer{}
if output.EnableGzip {
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)
}
type boolParser struct {
}
type boolParser struct{}
func (p boolParser) parse(value string, toType reflect.Type) (interface{}, error) {
return strconv.ParseBool(value)
}
type stringParser struct {
}
type stringParser struct{}
func (p stringParser) parse(value string, toType reflect.Type) (interface{}, error) {
return value, nil
}
type intParser struct {
}
type intParser struct{}
func (p intParser) parse(value string, toType reflect.Type) (interface{}, error) {
return strconv.Atoi(value)
}
type floatParser struct {
}
type floatParser struct{}
func (p floatParser) parse(value string, toType reflect.Type) (interface{}, error) {
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)
}
type timeParser struct {
}
type timeParser struct{}
func (p timeParser) parse(value string, toType reflect.Type) (result interface{}, err error) {
result, err = time.Parse(time.RFC3339, value)
@ -101,8 +96,7 @@ func (p timeParser) parse(value string, toType reflect.Type) (result interface{}
return
}
type jsonParser struct {
}
type jsonParser struct{}
func (p jsonParser) parse(value string, toType reflect.Type) (interface{}, error) {
pResult := reflect.New(toType)

View File

@ -13,7 +13,6 @@ type testDefinition struct {
}
func Test_Parsers(t *testing.T) {
// ints
checkParser(testDefinition{"1", 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})
// pointers
var someInt = 1
someInt := 1
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)
}
func checkParser(def testDefinition, t *testing.T, methodParam ...MethodParam) {

View File

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

View File

@ -141,7 +141,7 @@ func TestAdditionalViewPaths(t *testing.T) {
dir2file := "file2.tpl"
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 {
t.Fatal(err)
} else {
@ -149,7 +149,6 @@ func TestAdditionalViewPaths(t *testing.T) {
f.WriteString(content)
f.Close()
}
}
genFile(dir1, dir1file, `<div>{{.Content}}</div>`)
genFile(dir2, dir2file, `<html>{{.Content}}</html>`)
@ -216,7 +215,6 @@ func TestBindNoContentType(t *testing.T) {
}
func TestBindXML(t *testing.T) {
var s struct {
Foo string `xml:"foo"`
}

View File

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

View File

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

View File

@ -9,8 +9,8 @@ import (
"github.com/beego/beego/v2/server/web/session"
)
//Session maintain session for web service
//Session new a session storage and store it into webContext.Context
// Session maintain session for web service
// Session new a session storage and store it into webContext.Context
func Session(providerType session.ProviderType, options ...session.ManagerConfigOpt) web.FilterChain {
sessionConfig := session.NewManagerConfig(options...)
sessionManager, _ := session.NewManager(string(providerType), sessionConfig)
@ -25,7 +25,7 @@ func Session(providerType session.ProviderType, options ...session.ManagerConfig
if sess, err := sessionManager.SessionStart(ctx.ResponseWriter, ctx.Request); err != nil {
logs.Error(`init session error:%s`, err.Error())
} else {
//release session at the end of request
// release session at the end of request
defer sess.SessionRelease(context.Background(), ctx.ResponseWriter)
ctx.Input.CruSession = sess
}

View File

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

View File

@ -6,8 +6,7 @@ import (
"path/filepath"
)
type FileSystem struct {
}
type FileSystem struct{}
func (d FileSystem) Open(name string) (http.File, error) {
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
// and directories are filtered by walkFn.
func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error {
f, err := fs.Open(root)
if err != nil {
return err

View File

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

View File

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

View File

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

View File

@ -82,8 +82,7 @@ type FilterHandler interface {
}
// default log filter static file will not show
type logFilter struct {
}
type logFilter struct{}
func (l *logFilter) Filter(ctx *beecontext.Context) bool {
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) {
opts = append(opts, WithCaseSensitive(p.cfg.RouterCaseSensitive))
p.filterChains = append(p.filterChains, filterChainConfig{
pattern: pattern,
@ -957,7 +955,6 @@ func (p *ControllerRegister) execFilter(context *beecontext.Context, urlPath str
// Implement http.Handler interface.
func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
ctx := p.GetContext()
ctx.Reset(rw, r)
@ -1295,7 +1292,7 @@ func (p *ControllerRegister) handleParamResponse(context *beecontext.Context, ex
// FindRouter Find Router info for URL
func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) {
var urlPath = context.Input.URL()
urlPath := context.Input.URL()
if !p.cfg.RouterCaseSensitive {
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"))
}
type TestControllerWithInterface struct {
}
type TestControllerWithInterface struct{}
func (m TestControllerWithInterface) Ping() {
fmt.Println("pong")
@ -248,7 +247,6 @@ func TestAutoExtFunc(t *testing.T) {
}
func TestEscape(t *testing.T) {
r, _ := http.NewRequest("GET", "/search/%E4%BD%A0%E5%A5%BD", nil)
w := httptest.NewRecorder()
@ -265,7 +263,6 @@ func TestEscape(t *testing.T) {
}
func TestRouteOk(t *testing.T) {
r, _ := http.NewRequest("GET", "/person/anderson/thomas?learn=kungfu", nil)
w := httptest.NewRecorder()
@ -279,7 +276,6 @@ func TestRouteOk(t *testing.T) {
}
func TestManyRoute(t *testing.T) {
r, _ := http.NewRequest("GET", "/beego32-12.html", nil)
w := httptest.NewRecorder()
@ -296,7 +292,6 @@ func TestManyRoute(t *testing.T) {
// Test for issue #1669
func TestEmptyResponse(t *testing.T) {
r, _ := http.NewRequest("GET", "/beego-empty.html", nil)
w := httptest.NewRecorder()
@ -839,7 +834,6 @@ func TestRouterSessionSet(t *testing.T) {
if w.Header().Get("Set-Cookie") == "" {
t.Errorf("TestRotuerSessionSet failed")
}
}
func TestRouterRouterGet(t *testing.T) {
@ -1019,7 +1013,7 @@ func TestRouterAddRouterMethodPanicInvalidMethod(t *testing.T) {
message := "not support http method: " + strings.ToUpper(method)
defer func() {
err := recover()
if err != nil { //产生了panic异常
if err != nil { // 产生了panic异常
errStr, ok := err.(string)
if ok && errStr == message {
return
@ -1037,7 +1031,7 @@ func TestRouterAddRouterMethodPanicNotAMethod(t *testing.T) {
message := "not a method"
defer func() {
err := recover()
if err != nil { //产生了panic异常
if err != nil { // 产生了panic异常
errStr, ok := err.(string)
if ok && errStr == message {
return
@ -1055,7 +1049,7 @@ func TestRouterAddRouterMethodPanicNotPublicMethod(t *testing.T) {
message := "ping is not a public method"
defer func() {
err := recover()
if err != nil { //产生了panic异常
if err != nil { // 产生了panic异常
errStr, ok := err.(string)
if ok && errStr == message {
return
@ -1073,7 +1067,7 @@ func TestRouterAddRouterMethodPanicNotImplementInterface(t *testing.T) {
message := "web.TestControllerWithInterface is not implemented ControllerInterface"
defer func() {
err := recover()
if err != nil { //产生了panic异常
if err != nil { // 产生了panic异常
errStr, ok := err.(string)
if ok && errStr == message {
return
@ -1091,7 +1085,7 @@ func TestRouterAddRouterPointerMethodPanicNotImplementInterface(t *testing.T) {
message := "web.TestControllerWithInterface is not implemented ControllerInterface"
defer func() {
err := recover()
if err != nil { //产生了panic异常
if err != nil { // 产生了panic异常
errStr, ok := err.(string)
if ok && errStr == message {
return

View File

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

View File

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

View File

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

View File

@ -43,8 +43,10 @@ import (
"github.com/beego/beego/v2/server/web/session"
)
var mempder = &MemProvider{}
var client *memcache.Client
var (
mempder = &MemProvider{}
client *memcache.Client
)
// SessionStore memcache session store
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",
b, time.Now().Format(time.RFC3339), st.sid)
}
// Provider postgresql session provider

View File

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

View File

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

View File

@ -90,11 +90,9 @@ func TestRedisSentinel(t *testing.T) {
}
sess.SessionRelease(nil, w)
}
func TestProvider_SessionInit(t *testing.T) {
savePath := `
{ "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)
st.lock.Unlock()
if err == nil {
cookie := &http.Cookie{Name: cookiepder.config.CookieName,
cookie := &http.Cookie{
Name: cookiepder.config.CookieName,
Value: url.QueryEscape(encodedCookie),
Path: "/",
HttpOnly: true,
Secure: cookiepder.config.Secure,
MaxAge: cookiepder.config.Maxage}
MaxAge: cookiepder.config.Maxage,
}
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))
var f *os.File
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 {
SLogger.Println(err)
return
@ -140,23 +140,32 @@ func (fp *FileProvider) SessionRead(ctx context.Context, sid string) (Store, err
filepder.lock.Lock()
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 {
SLogger.Println(err.Error())
}
_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
var f *os.File
if err == nil {
f, err = os.OpenFile(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), os.O_RDWR, 0777)
} else if os.IsNotExist(err) {
f, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
} else {
_, err = os.Stat(sidPath)
switch {
case err == nil:
f, err = os.OpenFile(sidPath, os.O_RDWR, 0o777)
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
}
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{}
b, err := ioutil.ReadAll(f)
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)
}
err = os.MkdirAll(newPath, 0755)
err = os.MkdirAll(newPath, 0o755)
if err != nil {
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.Chtimes(newSidFile, time.Now(), time.Now())
ss := &FileSessionStore{sid: sid, values: kv}

View File

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

View File

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

View File

@ -58,84 +58,84 @@ func CfgSessionIdPrefix(prefix string) ManagerConfigOpt {
}
}
//CfgSetCookie whether set `Set-Cookie` header in HTTP response
// CfgSetCookie whether set `Set-Cookie` header in HTTP response
func CfgSetCookie(enable bool) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.EnableSetCookie = enable
}
}
//CfgGcLifeTime set session gc lift time
// CfgGcLifeTime set session gc lift time
func CfgGcLifeTime(lifeTime int64) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.Gclifetime = lifeTime
}
}
//CfgMaxLifeTime set session lift time
// CfgMaxLifeTime set session lift time
func CfgMaxLifeTime(lifeTime int64) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.Maxlifetime = lifeTime
}
}
//CfgGcLifeTime set session lift time
// CfgGcLifeTime set session lift time
func CfgCookieLifeTime(lifeTime int) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.CookieLifeTime = lifeTime
}
}
//CfgProviderConfig configure session provider
// CfgProviderConfig configure session provider
func CfgProviderConfig(providerConfig string) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.ProviderConfig = providerConfig
}
}
//CfgDomain set cookie domain
// CfgDomain set cookie domain
func CfgDomain(domain string) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.Domain = domain
}
}
//CfgSessionIdInHTTPHeader enable session id in http header
// CfgSessionIdInHTTPHeader enable session id in http header
func CfgSessionIdInHTTPHeader(enable bool) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.EnableSidInHTTPHeader = enable
}
}
//CfgSetSessionNameInHTTPHeader set key of session id in http header
// CfgSetSessionNameInHTTPHeader set key of session id in http header
func CfgSetSessionNameInHTTPHeader(name string) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.SessionNameInHTTPHeader = name
}
}
//EnableSidInURLQuery enable session id in query string
// EnableSidInURLQuery enable session id in query string
func CfgEnableSidInURLQuery(enable bool) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.EnableSidInURLQuery = enable
}
}
//DisableHTTPOnly set HTTPOnly for http.Cookie
// DisableHTTPOnly set HTTPOnly for http.Cookie
func CfgHTTPOnly(HTTPOnly bool) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.DisableHTTPOnly = !HTTPOnly
}
}
//CfgSecure set Secure for http.Cookie
// CfgSecure set Secure for http.Cookie
func CfgSecure(Enable bool) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.Secure = Enable
}
}
//CfgSameSite set http.SameSite
// CfgSameSite set http.SameSite
func CfgSameSite(sameSite http.SameSite) ManagerConfigOpt {
return func(config *ManagerConfig) {
config.CookieSameSite = sameSite

View File

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

View File

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

View File

@ -65,7 +65,6 @@ func (m *URLMap) AddStatistics(requestMethod, requestURL, requestController stri
}
m.urlmap[requestURL][requestMethod] = nb
}
} else {
if m.LengthLimit > 0 && m.LengthLimit <= len(m.urlmap) {
return
@ -89,7 +88,7 @@ func (m *URLMap) GetMap() map[string]interface{} {
m.lock.RLock()
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
content := make(map[string]interface{})

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -119,7 +119,6 @@ func init() {
routers = append(routers, notMatchTestInfo(abcSuffix, "/abc/suffix.html/a"))
routers = append(routers, matchTestInfo(abcSuffix, "/abc/suffix/a", nil))
routers = append(routers, notMatchTestInfo(abcSuffix, "/abc.j/suffix/a"))
}
func TestTreeRouters(t *testing.T) {
@ -303,6 +302,7 @@ 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 {
@ -331,7 +331,6 @@ func TestSplitPath(t *testing.T) {
}
func TestSplitSegment(t *testing.T) {
items := map[string]struct {
isReg bool
params []string

View File

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