format code

This commit is contained in:
Ming Deng
2020-12-14 12:22:44 +08:00
parent 181a5b6ef6
commit d4da82ef77
51 changed files with 174 additions and 183 deletions

View File

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

View File

@@ -222,7 +222,7 @@ func (r *Response) Write(p []byte) (int, error) {
// and sets `Started` to true.
func (r *Response) WriteHeader(code int) {
if r.Status > 0 {
//prevent multiple response.WriteHeader calls
// prevent multiple response.WriteHeader calls
return
}
r.Status = code

View File

@@ -288,7 +288,7 @@ func (output *BeegoOutput) Download(file string, filename ...string) {
} else {
fName = filepath.Base(file)
}
//https://tools.ietf.org/html/rfc6266#section-4.3
// https://tools.ietf.org/html/rfc6266#section-4.3
fn := url.PathEscape(fName)
if fName == fn {
fn = "filename=" + fn

View File

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

View File

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

View File

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

View File

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

View File

@@ -46,7 +46,7 @@ func TestGetInt8(t *testing.T) {
if val != 40 {
t.Errorf("TestGetInt8 expect 40,get %T,%v", val, val)
}
//Output: int8
// Output: int8
}
func TestGetInt16(t *testing.T) {

View File

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

View File

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

View File

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

View File

@@ -138,7 +138,7 @@ func NewServer(addr string, handler http.Handler) (srv *Server) {
},
state: StateInit,
Network: "tcp",
terminalChan: make(chan error), //no cache channel
terminalChan: make(chan error), // no cache channel
}
srv.Server = &http.Server{
Addr: addr,

View File

@@ -189,8 +189,8 @@ func (n *Namespace) Include(cList ...ControllerInterface) *Namespace {
// Namespace add nest Namespace
// usage:
//ns := beego.NewNamespace(“/v1”).
//Namespace(
// ns := beego.NewNamespace(“/v1”).
// Namespace(
// beego.NewNamespace("/shop").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("shopinfo"))
@@ -203,7 +203,7 @@ func (n *Namespace) Include(cList ...ControllerInterface) *Namespace {
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("crminfo"))
// }),
//)
// )
func (n *Namespace) Namespace(ns ...*Namespace) *Namespace {
for _, ni := range ns {
for k, v := range ni.handlers.routers {

View File

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

View File

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

View File

@@ -44,12 +44,12 @@ import (
// Store contains all data for one session process with specific id.
type Store interface {
Set(ctx context.Context, key, value interface{}) error //set session value
Get(ctx context.Context, key interface{}) interface{} //get session value
Delete(ctx context.Context, key interface{}) error //delete session value
SessionID(ctx context.Context) string //back current sessionID
Set(ctx context.Context, key, value interface{}) error // set session value
Get(ctx context.Context, key interface{}) interface{} // get session value
Delete(ctx context.Context, key interface{}) error // delete session value
SessionID(ctx context.Context) string // back current sessionID
SessionRelease(ctx context.Context, w http.ResponseWriter) // release the resource & save data to provider & return the data
Flush(ctx context.Context) error //delete all data
Flush(ctx context.Context) error // delete all data
}
// Provider contains global session methods and saved SessionStores.
@@ -60,7 +60,7 @@ type Provider interface {
SessionExist(ctx context.Context, sid string) (bool, error)
SessionRegenerate(ctx context.Context, oldsid, sid string) (Store, error)
SessionDestroy(ctx context.Context, sid string) error
SessionAll(ctx context.Context) int //get all active session
SessionAll(ctx context.Context) int // get all active session
SessionGC(ctx context.Context)
}
@@ -82,7 +82,7 @@ func Register(name string, provide Provider) {
provides[name] = provide
}
//GetProvider
// GetProvider
func GetProvider(name string) (Provider, error) {
provider, ok := provides[name]
if !ok {
@@ -308,7 +308,7 @@ func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Reque
cookie, err := r.Cookie(manager.config.CookieName)
if err != nil || cookie.Value == "" {
//delete old cookie
// delete old cookie
session, err = manager.provider.SessionRead(nil, sid)
if err != nil {
return nil, err

View File

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

View File

@@ -35,7 +35,7 @@ type Statistics struct {
// URLMap contains several statistics struct to log different data
type URLMap struct {
lock sync.RWMutex
LengthLimit int //limit the urlmap's length if it's equal to 0 there's no limit
LengthLimit int // limit the urlmap's length if it's equal to 0 there's no limit
urlmap map[string]map[string]*Statistics
}

View File

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

View File

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

View File

@@ -117,7 +117,7 @@ func TestRelativeTemplate(t *testing.T) {
assert.Nil(t, err)
dir := filepath.Join(wkdir, "_beeTmp")
//Just add dir to known viewPaths
// Just add dir to known viewPaths
if err := AddViewPath(dir); err != nil {
t.Fatal(err)
}

View File

@@ -50,7 +50,7 @@ func notMatchTestInfo(pattern, url string) testInfo {
func init() {
routers = make([]testInfo, 0)
//match example
// match example
routers = append(routers, matchTestInfo("/topic/?:auth:int", "/topic", nil))
routers = append(routers, matchTestInfo("/topic/?:auth:int", "/topic/123", map[string]string{":auth": "123"}))
routers = append(routers, matchTestInfo("/topic/:id/?:auth", "/topic/1", map[string]string{":id": "1"}))
@@ -91,7 +91,7 @@ func init() {
routers = append(routers, matchTestInfo("/api/projects/:pid/members/?:mid", "/api/projects/1/members", map[string]string{":pid": "1"}))
routers = append(routers, matchTestInfo("/api/projects/:pid/members/?:mid", "/api/projects/1/members/2", map[string]string{":pid": "1", ":mid": "2"}))
//not match example
// not match example
// https://github.com/beego/beego/v2/issues/3865
routers = append(routers, notMatchTestInfo("/read_:id:int\\.htm", "/read_222htm"))
@@ -324,7 +324,7 @@ func TestSplitSegment(t *testing.T) {
":id([0-9]+)": {true, []string{":id"}, `([0-9]+)`},
":id([0-9]+)_:name": {true, []string{":id", ":name"}, `([0-9]+)_(.+)`},
":id(.+)_cms.html": {true, []string{":id"}, `(.+)_cms.html`},
":id(.+)_cms\\.html": {true, []string{":id"}, `(.+)_cms\.html`},
":id(.+)_cms\\.html": {true, []string{":id"}, `(.+)_cms\.html`},
"cms_:id(.+)_:page(.+).html": {true, []string{":id", ":page"}, `cms_(.+)_(.+).html`},
`:app(a|b|c)`: {true, []string{":app"}, `(a|b|c)`},
`:app\((a|b|c)\)`: {true, []string{":app"}, `(.+)\((a|b|c)\)`},