diff --git a/bind.go b/bind.go index 8138618..511e782 100644 --- a/bind.go +++ b/bind.go @@ -24,7 +24,7 @@ type ( binder struct{} ) -//Bind decode req.Body or form-value to struct +// Bind decode req.Body or form-value to struct func (b *binder) Bind(i interface{}, ctx Context) (err error) { req := ctx.Request() ctype := req.Header.Get(HeaderContentType) @@ -38,22 +38,22 @@ func (b *binder) Bind(i interface{}, ctx Context) (err error) { err = json.Unmarshal(ctx.Request().PostBody(), i) case strings.HasPrefix(ctype, MIMEApplicationXML): err = xml.Unmarshal(ctx.Request().PostBody(), i) - //case strings.HasPrefix(ctype, MIMEApplicationForm), strings.HasPrefix(ctype, MIMEMultipartForm), - // strings.HasPrefix(ctype, MIMETextHTML): - // err = reflects.ConvertMapToStruct(defaultTagName, i, ctx.FormValues()) + // case strings.HasPrefix(ctype, MIMEApplicationForm), strings.HasPrefix(ctype, MIMEMultipartForm), + // strings.HasPrefix(ctype, MIMETextHTML): + // err = reflects.ConvertMapToStruct(defaultTagName, i, ctx.FormValues()) default: - //check is use json tag, fixed for issue #91 + // check is use json tag, fixed for issue #91 tagName := defaultTagName if ctx.HttpServer().ServerConfig().EnabledBindUseJsonTag { tagName = jsonTagName } - //no check content type for fixed issue #6 + // no check content type for fixed issue #6 err = reflects.ConvertMapToStruct(tagName, i, ctx.Request().FormValues()) } return err } -//BindJsonBody default use json decode req.Body to struct +// BindJsonBody default use json decode req.Body to struct func (b *binder) BindJsonBody(i interface{}, ctx Context) (err error) { if ctx.Request().PostBody() == nil { err = errors.New("request body can't be empty") diff --git a/bind_test.go b/bind_test.go index 6eb4d95..370365b 100644 --- a/bind_test.go +++ b/bind_test.go @@ -13,7 +13,7 @@ type Person struct { Legs []string } -//json +// json func TestBinder_Bind_json(t *testing.T) { binder := newBinder() @@ -22,14 +22,14 @@ func TestBinder_Bind_json(t *testing.T) { t.Error("binder can not be nil!") } - //init DotServer + // init DotServer app := New() if app == nil { t.Error("app can not be nil!") } - //expected + // expected expected := &Person{ Hair: "Brown", HasGlass: true, @@ -37,7 +37,7 @@ func TestBinder_Bind_json(t *testing.T) { Legs: []string{"Left", "Right"}, } - //init param + // init param param := &InitContextParam{ t, expected, @@ -45,17 +45,17 @@ func TestBinder_Bind_json(t *testing.T) { test.ToJson, } - //init param + // init param context := initContext(param) - //actual + // actual person := &Person{} err := binder.Bind(person, context) - //check error must nil + // check error must nil test.Nil(t, err) - //check expected + // check expected test.Equal(t, expected, person) t.Log("person:", person) @@ -63,7 +63,7 @@ func TestBinder_Bind_json(t *testing.T) { } -//json +// json func TestBinder_Bind_json_error(t *testing.T) { binder := newBinder() @@ -72,14 +72,14 @@ func TestBinder_Bind_json_error(t *testing.T) { t.Error("binder can not be nil!") } - //init DotServer + // init DotServer app := New() if app == nil { t.Error("app can not be nil!") } - //expected + // expected expected := &Person{ Hair: "Brown", HasGlass: true, @@ -87,7 +87,7 @@ func TestBinder_Bind_json_error(t *testing.T) { Legs: []string{"Left", "Right"}, } - //init param + // init param param := &InitContextParam{ t, expected, @@ -95,18 +95,18 @@ func TestBinder_Bind_json_error(t *testing.T) { test.ToJson, } - //init param + // init param context := initContext(param) - //actual + // actual person := &Person{} err := binder.Bind(person, context) - //check error must not nil + // check error must not nil test.NotNil(t, err) } -//xml +// xml func TestBinder_Bind_xml(t *testing.T) { binder := newBinder() @@ -115,14 +115,14 @@ func TestBinder_Bind_xml(t *testing.T) { t.Error("binder can not be nil!") } - //init DotServer + // init DotServer app := New() if app == nil { t.Error("app can not be nil!") } - //expected + // expected expected := &Person{ Hair: "Brown", HasGlass: true, @@ -136,17 +136,17 @@ func TestBinder_Bind_xml(t *testing.T) { test.ToXML, } - //init param + // init param context := initContext(param) - //actual + // actual person := &Person{} err := binder.Bind(person, context) - //check error must nil + // check error must nil test.Nil(t, err) - //check expected + // check expected test.Equal(t, expected, person) t.Log("person:", person) @@ -154,7 +154,7 @@ func TestBinder_Bind_xml(t *testing.T) { } -//xml +// xml func TestBinder_Bind_xml_error(t *testing.T) { binder := newBinder() @@ -163,14 +163,14 @@ func TestBinder_Bind_xml_error(t *testing.T) { t.Error("binder can not be nil!") } - //init DotServer + // init DotServer app := New() if app == nil { t.Error("app can not be nil!") } - //expected + // expected expected := &Person{ Hair: "Brown", HasGlass: true, @@ -184,18 +184,18 @@ func TestBinder_Bind_xml_error(t *testing.T) { test.ToXML, } - //init param + // init param context := initContext(param) - //actual + // actual person := &Person{} err := binder.Bind(person, context) - //check error must not nil + // check error must not nil test.NotNil(t, err) } -//else +// else func TestBinder_Bind_default(t *testing.T) { binder := newBinder() @@ -204,14 +204,14 @@ func TestBinder_Bind_default(t *testing.T) { t.Error("binder can not be nil!") } - //init DotServer + // init DotServer app := New() if app == nil { t.Error("app can not be nil!") } - //expected + // expected expected := &Person{ Hair: "Brown", HasGlass: true, @@ -225,7 +225,7 @@ func TestBinder_Bind_default(t *testing.T) { test.ToDefault, } - //init param + // init param context := initContext(param) form := make(map[string][]string) @@ -235,15 +235,15 @@ func TestBinder_Bind_default(t *testing.T) { form["Legs"] = []string{"Left", "Right"} context.request.Form = form - //actual + // actual person := &Person{} err := binder.Bind(person, context) - //check error must nil + // check error must nil test.Nil(t, err) - //check expected + // check expected test.Equal(t, expected, person) t.Log("person:", person) @@ -251,7 +251,7 @@ func TestBinder_Bind_default(t *testing.T) { } -//else +// else func TestBinder_Bind_default_error(t *testing.T) { binder := newBinder() @@ -260,14 +260,14 @@ func TestBinder_Bind_default_error(t *testing.T) { t.Error("binder can not be nil!") } - //init DotServer + // init DotServer app := New() if app == nil { t.Error("app can not be nil!") } - //expected + // expected expected := &Person{ Hair: "Brown", HasGlass: true, @@ -281,7 +281,7 @@ func TestBinder_Bind_default_error(t *testing.T) { test.ToDefault, } - //init param + // init param context := initContext(param) form := make(map[string][]string) @@ -291,18 +291,18 @@ func TestBinder_Bind_default_error(t *testing.T) { form["Legs"] = []string{"Left", "Right"} context.request.Form = form - //actual + // actual person := &Person{} err := binder.Bind(person, context) - //check error must not nil + // check error must not nil test.NotNil(t, err) } -//default -//TODO:content type is null but body not null,is it right?? +// default +// TODO:content type is null but body not null,is it right?? func TestBinder_Bind_ContentTypeNull(t *testing.T) { binder := newBinder() @@ -311,14 +311,14 @@ func TestBinder_Bind_ContentTypeNull(t *testing.T) { t.Error("binder can not be nil!") } - //init DotServer + // init DotServer app := New() if app == nil { t.Error("app can not be nil!") } - //expected + // expected expected := &Person{ Hair: "Brown", HasGlass: true, @@ -332,13 +332,13 @@ func TestBinder_Bind_ContentTypeNull(t *testing.T) { test.ToXML, } - //init param + // init param context := initContext(param) - //actual + // actual person := &Person{} err := binder.Bind(person, context) - //check error must nil? + // check error must nil? test.Nil(t, err) } diff --git a/cache/redis/cache_redis.go b/cache/redis/cache_redis.go index 4d621da..e91ea5e 100644 --- a/cache/redis/cache_redis.go +++ b/cache/redis/cache_redis.go @@ -13,7 +13,7 @@ var ( // RedisCache is redis cache adapter. // it contains serverIp for redis conn. type RedisCache struct { - serverURL string //connection string, like "redis://:password@10.0.1.11:6379/0" + serverURL string // connection string, like "redis://:password@10.0.1.11:6379/0" } // NewRedisCache returns a new *RedisCache. diff --git a/cache/runtime/cache_runtime.go b/cache/runtime/cache_runtime.go index 061c3e8..78fec40 100644 --- a/cache/runtime/cache_runtime.go +++ b/cache/runtime/cache_runtime.go @@ -21,7 +21,7 @@ type RuntimeItem struct { ttl time.Duration } -//check item is expire +// check item is expire func (mi *RuntimeItem) isExpire() bool { // 0 means forever if mi.ttl == 0 { @@ -36,7 +36,7 @@ type RuntimeCache struct { sync.RWMutex gcInterval time.Duration items *sync.Map - //items map[string]*RuntimeItem + // items map[string]*RuntimeItem } // NewRuntimeCache returns a new *RuntimeCache. @@ -127,9 +127,9 @@ func (ca *RuntimeCache) Incr(key string) (int64, error) { ca.Lock() itemObj, ok := ca.items.Load(key) if !ok { - //if not exists, auto set new with 0 + // if not exists, auto set new with 0 ca.initValue(key, ZeroInt64, 0) - //reload + // reload itemObj, _ = ca.items.Load(key) } @@ -162,9 +162,9 @@ func (ca *RuntimeCache) Decr(key string) (int64, error) { ca.Lock() itemObj, ok := ca.items.Load(key) if !ok { - //if not exists, auto set new with 0 + // if not exists, auto set new with 0 ca.initValue(key, ZeroInt64, 0) - //reload + // reload itemObj, _ = ca.items.Load(key) } @@ -220,7 +220,7 @@ func (ca *RuntimeCache) Delete(key string) error { ca.Lock() defer ca.Unlock() if _, ok := ca.items.Load(key); !ok { - //if not exists, we think it's success + // if not exists, we think it's success return nil } ca.items.Delete(key) diff --git a/config/configs.go b/config/configs.go index eff1075..637a5b1 100644 --- a/config/configs.go +++ b/config/configs.go @@ -27,49 +27,49 @@ type ( // OfflineNode dotweb app offline config OfflineNode struct { - Offline bool `xml:"offline,attr"` //是否维护,默认false - OfflineText string `xml:"offlinetext,attr"` //当设置为维护,默认显示内容,如果设置url,优先url - OfflineUrl string `xml:"offlineurl,attr"` //当设置为维护,默认维护页地址,如果设置url,优先url + Offline bool `xml:"offline,attr"` // maintenance mode, default false + OfflineText string `xml:"offlinetext,attr"` // text to display when Offline is true, OfflineUrl is used if set + OfflineUrl string `xml:"offlineurl,attr"` // maintenance page url } // AppNode dotweb app global config AppNode struct { - LogPath string `xml:"logpath,attr"` //文件方式日志目录,如果为空,默认当前目录 - EnabledLog bool `xml:"enabledlog,attr"` //是否启用日志记录 - RunMode string `xml:"runmode,attr"` //运行模式,目前支持development、production - PProfPort int `xml:"pprofport,attr"` //pprof-server 端口,不能与主Server端口相同 - EnabledPProf bool `xml:"enabledpprof,attr"` //是否启用pprof server,默认不启用 + LogPath string `xml:"logpath,attr"` // path of log files, use current directory if empty + EnabledLog bool `xml:"enabledlog,attr"` // enable logging + RunMode string `xml:"runmode,attr"` // run mode, currently supports [development, production] + PProfPort int `xml:"pprofport,attr"` // pprof-server port, cann't be same as server port + EnabledPProf bool `xml:"enabledpprof,attr"` // enable pprof server, default is false } // ServerNode dotweb app's httpserver config ServerNode struct { - EnabledListDir bool `xml:"enabledlistdir,attr"` //设置是否启用目录浏览,仅对Router.ServerFile有效,若设置该项,则可以浏览目录文件,默认不开启 - EnabledRequestID bool `xml:"enabledrequestid,attr"` //设置是否启用唯一请求ID,默认不开启,开启后使用32位UUID - EnabledGzip bool `xml:"enabledgzip,attr"` //是否启用gzip - EnabledAutoHEAD bool `xml:"enabledautohead,attr"` //设置是否自动启用Head路由,若设置该项,则会为除Websocket\HEAD外所有路由方式默认添加HEAD路由,默认不开启 - EnabledAutoOPTIONS bool //设置是否自动启用Options路由,若设置该项,则会为除Websocket\Options外所有路由方式默认添加Options路由,默认不开启 - EnabledAutoCORS bool `xml:"enabledautocors,attr"` //设置是否自动跨域支持,若设置,默认“GET, POST, PUT, DELETE, OPTIONS”全部请求均支持跨域 - EnabledIgnoreFavicon bool `xml:"enabledignorefavicon,attr"` //设置是否忽略favicon.ico请求,若设置,网站将把所有favicon.ico请求直接空返回 - EnabledBindUseJsonTag bool `xml:"enabledbindusejsontag,attr"` //设置bind是否启用json标签,默认不启用,若设置,bind自动识别json tag,忽略form tag - EnabledStaticFileMiddleware bool //The flag which enabled or disabled middleware for static-file route - Port int `xml:"port,attr"` //端口 - EnabledTLS bool `xml:"enabledtls,attr"` //是否启用TLS模式 - TLSCertFile string `xml:"tlscertfile,attr"` //TLS模式下Certificate证书文件地址 - TLSKeyFile string `xml:"tlskeyfile,attr"` //TLS模式下秘钥文件地址 - IndexPage string `xml:"indexpage,attr"` //默认index页面 - EnabledDetailRequestData bool `xml:"enableddetailrequestdata,attr"` //设置状态数据是否启用详细页面统计,默认不启用,请特别对待,如果站点url过多,会导致数据量过大 - VirtualPath string //virtual path when deploy on no root path + EnabledListDir bool `xml:"enabledlistdir,attr"` // enable listing of directories, only valid for Router.ServerFile, default is false + EnabledRequestID bool `xml:"enabledrequestid,attr"` // enable uniq request ID, default is false, 32-bit UUID is used if enabled + EnabledGzip bool `xml:"enabledgzip,attr"` // enable gzip + EnabledAutoHEAD bool `xml:"enabledautohead,attr"` // ehanble HEAD routing, default is false, will add HEAD routing for all routes except for websocket and HEAD + EnabledAutoOPTIONS bool // enable OPTIONS routing, default is false, will add OPTIONS routing for all routes except for websocket and OPTIONS + EnabledAutoCORS bool `xml:"enabledautocors,attr"` // enable automatic CORS, if set, all [GET, POST, PUT, DELETE, OPTIONS] requests will allow CORS + EnabledIgnoreFavicon bool `xml:"enabledignorefavicon,attr"` // ignore favicon.ico request, return empty reponse if set + EnabledBindUseJsonTag bool `xml:"enabledbindusejsontag,attr"` // allow Bind to use JSON tag, default is false, Bind will use json tag automatically and ignore form tag + EnabledStaticFileMiddleware bool // The flag which enabled or disabled middleware for static-file route + Port int `xml:"port,attr"` // port + EnabledTLS bool `xml:"enabledtls,attr"` // enable TLS + TLSCertFile string `xml:"tlscertfile,attr"` // certifications file for TLS + TLSKeyFile string `xml:"tlskeyfile,attr"` // keys file for TLS + IndexPage string `xml:"indexpage,attr"` // default index page + EnabledDetailRequestData bool `xml:"enableddetailrequestdata,attr"` // enable detailed statics for requests, default is false. Please use with care, it will have performance issues if the site have lots of URLs + VirtualPath string // virtual path when deploy on no root path } // SessionNode dotweb app's session config SessionNode struct { - EnabledSession bool `xml:"enabled,attr"` //启用Session - SessionMode string `xml:"mode,attr"` //session mode,now support runtime、redis - CookieName string `xml:"cookiename,attr"` //custom cookie name which sessionid store, default is dotweb_sessionId - Timeout int64 `xml:"timeout,attr"` //session time-out period, with second - ServerIP string `xml:"serverip,attr"` //remote session server url - BackupServerUrl string `xml:"backupserverurl,attr"` //backup remote session server url - StoreKeyPre string `xml:"storekeypre,attr"` //remote session StoreKeyPre + EnabledSession bool `xml:"enabled,attr"` // enable session + SessionMode string `xml:"mode,attr"` // session mode,now support runtime、redis + CookieName string `xml:"cookiename,attr"` // custom cookie name which sessionid store, default is dotweb_sessionId + Timeout int64 `xml:"timeout,attr"` // session time-out period, with second + ServerIP string `xml:"serverip,attr"` // remote session server url + BackupServerUrl string `xml:"backupserverurl,attr"` // backup remote session server url + StoreKeyPre string `xml:"storekeypre,attr"` // remote session StoreKeyPre } // RouterNode dotweb app's router config @@ -78,7 +78,7 @@ type ( Path string `xml:"path,attr"` HandlerName string `xml:"handler,attr"` Middlewares []*MiddlewareNode `xml:"middleware"` - IsUse bool `xml:"isuse,attr"` //是否启用,默认false + IsUse bool `xml:"isuse,attr"` // enable router, default is false } // GroupNode dotweb app's group router config @@ -86,13 +86,13 @@ type ( Path string `xml:"path,attr"` Routers []*RouterNode `xml:"router"` Middlewares []*MiddlewareNode `xml:"middleware"` - IsUse bool `xml:"isuse,attr"` //是否启用,默认false + IsUse bool `xml:"isuse,attr"` // enable group, default is false } // MiddlewareNode dotweb app's middleware config MiddlewareNode struct { Name string `xml:"name,attr"` - IsUse bool `xml:"isuse,attr"` //是否启用,默认false + IsUse bool `xml:"isuse,attr"` // enable middleware, default is false } ) @@ -164,8 +164,8 @@ func NewSessionNode() *SessionNode { return config } -//init config file -//If an exception occurs, will be panic it +// init config file +// If an exception occurs, will be panic it func MustInitConfig(configFile string, confType ...interface{}) *Config { conf, err := InitConfig(configFile, confType...) if err != nil { @@ -174,15 +174,14 @@ func MustInitConfig(configFile string, confType ...interface{}) *Config { return conf } -//初始化配置文件 -//如果发生异常,返回异常 +// InitConfig initialize the config with configFile func InitConfig(configFile string, confType ...interface{}) (config *Config, err error) { - //检查配置文件有效性 - //1、按绝对路径检查 - //2、尝试在当前进程根目录下寻找 - //3、尝试在当前进程根目录/config/ 下寻找 - //fixed for issue #15 读取配置文件路径 + // Validity check + // 1. Try read as absolute path + // 2. Try the current working directory + // 3. Try $PWD/config + // fixed for issue #15 config file path realFile := configFile if !file.Exist(realFile) { realFile = file.GetCurrentDirectory() + "/" + configFile @@ -236,7 +235,7 @@ func InitConfig(configFile string, confType ...interface{}) (config *Config, err } config.ConfigSet = tmpConfigSetMap - //deal config default value + // deal config default value dealConfigDefaultSet(config) return config, nil @@ -249,13 +248,13 @@ func dealConfigDefaultSet(c *Config) { func initConfig(configFile string, ctType string, parser func([]byte, interface{}) error) (*Config, error) { content, err := ioutil.ReadFile(configFile) if err != nil { - return nil, errors.New("DotWeb:Config:initConfig 当前cType:" + ctType + " 配置文件[" + configFile + "]无法解析 - " + err.Error()) + return nil, errors.New("DotWeb:Config:initConfig current cType:" + ctType + " config file [" + configFile + "] cannot be parsed - " + err.Error()) } var config *Config err = parser(content, &config) if err != nil { - return nil, errors.New("DotWeb:Config:initConfig 当前cType:" + ctType + " 配置文件[" + configFile + "]解析失败 - " + err.Error()) + return nil, errors.New("DotWeb:Config:initConfig current cType:" + ctType + " config file [" + configFile + "] cannot be parsed - " + err.Error()) } return config, nil } diff --git a/config/configs_test.go b/config/configs_test.go index 3153f15..0f9a818 100644 --- a/config/configs_test.go +++ b/config/configs_test.go @@ -1,6 +1,6 @@ package config -//运行以下用例需要在edit configuration中将working dir改成dotweb目录下,不能在当前目录 +// 运行以下用例需要在edit configuration中将working dir改成dotweb目录下,不能在当前目录 import ( "testing" @@ -18,8 +18,8 @@ func TestInitConfig(t *testing.T) { test.Equal(t, 4, conf.ConfigSet.Len()) } -//该测试方法报错... -//是xml问题还是代码问题? +// 该测试方法报错... +// 是xml问题还是代码问题? func TestInitConfigWithXml(t *testing.T) { conf, err := InitConfig("example/config/dotweb.conf", "xml") diff --git a/config/configset.go b/config/configset.go index 18ce8ad..8dbb8e3 100644 --- a/config/configset.go +++ b/config/configset.go @@ -9,14 +9,14 @@ import ( ) type ( - // ConfigSet 单元配置组,包含一系列单元配置节点 + // ConfigSet set of config nodes ConfigSet struct { XMLName xml.Name `xml:"config" json:"-" yaml:"-"` Name string `xml:"name,attr"` ConfigSetNodes []*ConfigSetNode `xml:"set"` } - // ConfigSetNode update for issue #16 配置文件 + // ConfigSetNode update for issue #16 config file ConfigSetNode struct { Key string `xml:"key,attr"` Value string `xml:"value,attr"` @@ -54,7 +54,7 @@ func parseConfigSetFile(configFile string, confType string) (core.ConcurrenceMap err = UnmarshalYaml(content, set) } if err != nil { - return nil, errors.New("DotWeb:Config:parseConfigSetFile 配置文件[" + configFile + ", " + confType + "]无法解析 - " + err.Error()) + return nil, errors.New("DotWeb:Config:parseConfigSetFile config file[" + configFile + ", " + confType + "]cannot be parsed - " + err.Error()) } item := core.NewConcurrenceMap() for _, s := range set.ConfigSetNodes { diff --git a/config/defaults.go b/config/defaults.go index df03187..f87a39b 100644 --- a/config/defaults.go +++ b/config/defaults.go @@ -2,6 +2,6 @@ package config const ( - //default timeout Millisecond for per request handler + // default timeout Millisecond for per request handler DefaultRequestTimeOut = 30000 ) diff --git a/consts.go b/consts.go index f66a6e6..d95ba42 100644 --- a/consts.go +++ b/consts.go @@ -1,12 +1,12 @@ package dotweb -//Global define +// Global define const ( // Version current version Version = "1.5.9.1" ) -//Log define +// Log define const ( LogTarget_Default = "dotweb_default" LogTarget_HttpRequest = "dotweb_request" @@ -19,7 +19,7 @@ const ( LogLevel_Error = "error" ) -//Http define +// Http define const ( CharsetUTF8 = "charset=utf-8" DefaultServerName = "dotweb" diff --git a/context.go b/context.go index 9c648f5..307532a 100644 --- a/context.go +++ b/context.go @@ -95,7 +95,7 @@ type ( HttpContext struct { context context.Context - //暂未启用 + // Reserved cancle context.CancelFunc middlewareStep string request *Request @@ -106,7 +106,7 @@ type ( hijackConn *HijackConn isWebSocket bool isHijack bool - isEnd bool //表示当前处理流程是否需要终止 + isEnd bool // indicating whether the current process should be terminated httpServer *HttpServer sessionID string innerItems core.ConcurrenceMap @@ -117,7 +117,7 @@ type ( } ) -//reset response attr +// reset response attr func (ctx *HttpContext) reset(res *Response, r *Request, server *HttpServer, node RouterNode, params Params, handler HttpHandle) { ctx.request = r ctx.response = res @@ -134,7 +134,7 @@ func (ctx *HttpContext) reset(res *Response, r *Request, server *HttpServer, nod ctx.Items().Set(ItemKeyHandleStartTime, time.Now()) } -//release all field +// release all field func (ctx *HttpContext) release() { ctx.request = nil ctx.response = nil @@ -263,7 +263,7 @@ func (ctx *HttpContext) Items() core.ConcurrenceMap { } // AppSetConfig get appset from config file -// update for issue #16 配置文件 +// update for issue #16 Config file func (ctx *HttpContext) ConfigSet() core.ReadonlyMap { return ctx.HttpServer().DotApp.Config.ConfigSet } @@ -280,11 +280,11 @@ func (ctx *HttpContext) ViewData() core.ConcurrenceMap { // Session get session state in current context func (ctx *HttpContext) Session() (state *session.SessionState) { if ctx.httpServer == nil { - //return nil, errors.New("no effective http-server") + // return nil, errors.New("no effective http-server") panic("no effective http-server") } if !ctx.httpServer.SessionConfig().EnabledSession { - //return nil, errors.New("http-server not enabled session") + // return nil, errors.New("http-server not enabled session") panic("http-server not enabled session") } state, _ = ctx.httpServer.sessionManager.GetSessionState(ctx.sessionID) @@ -322,9 +322,7 @@ func (ctx *HttpContext) Redirect(code int, targetUrl string) error { return ctx.response.Redirect(code, targetUrl) } -/* -* 根据指定key获取在Get请求中对应参数值 - */ +// QueryString returns request parameters according to key func (ctx *HttpContext) QueryString(key string) string { return ctx.request.QueryString(key) } @@ -357,16 +355,14 @@ func (ctx *HttpContext) QueryInt64(key string) int64 { return val } -/* -* 根据指定key获取包括在post、put和get内的值 - */ +// FormValue returns the first value for the named component of the query. +// POST and PUT body parameters take precedence over URL query string values. func (ctx *HttpContext) FormValue(key string) string { return ctx.request.FormValue(key) } -/* -* 根据指定key获取包括在post、put内的值 - */ +// PostFormValue returns the first value for the named component of the POST, +// PATCH, or PUT request body. URL query parameters are ignored. func (ctx *HttpContext) PostFormValue(key string) string { return ctx.request.PostFormValue(key) } @@ -451,7 +447,7 @@ func (ctx *HttpContext) RemoteIP() string { // SetCookieValue write cookie for name & value & maxAge // default path = "/" // default domain = current domain -// default maxAge = 0 //seconds +// default maxAge = 0 // seconds // seconds=0 means no 'Max-Age' attribute specified. // seconds<0 means delete cookie now, equivalently 'Max-Age: 0' // seconds>0 means Max-Age attribute present and given in seconds @@ -522,7 +518,7 @@ func (ctx *HttpContext) ViewC(code int, name string) error { // Write write code and content content to response func (ctx *HttpContext) Write(code int, content []byte) (int, error) { if ctx.IsHijack() { - //TODO:hijack mode, status-code set default 200 + // TODO:hijack mode, status-code set default 200 return ctx.hijackConn.WriteBlob(content) } else { return ctx.response.Write(code, content) @@ -609,7 +605,7 @@ func (ctx *HttpContext) WriteJsonp(callback string, i interface{}) error { func (ctx *HttpContext) WriteJsonpBlob(callback string, b []byte) error { var err error ctx.response.SetContentType(MIMEApplicationJavaScriptCharsetUTF8) - //特殊处理,如果为hijack,需要先行WriteBlob头部 + // For jihack context, write header first if ctx.IsHijack() { if _, err = ctx.hijackConn.WriteBlob([]byte(ctx.hijackConn.header + "\r\n")); err != nil { return err diff --git a/context_test.go b/context_test.go index 4fba7af..1c020ba 100644 --- a/context_test.go +++ b/context_test.go @@ -14,7 +14,7 @@ type Animal struct { HasMouth bool } -//normal write +// normal write func TestWrite(t *testing.T) { param := &InitContextParam{ t, @@ -23,7 +23,7 @@ func TestWrite(t *testing.T) { test.ToDefault, } - //init param + // init param context := initResponseContext(param) exceptedObject := &Animal{ @@ -34,26 +34,27 @@ func TestWrite(t *testing.T) { animalJson, err := json.Marshal(exceptedObject) test.Nil(t, err) - //call function + // call function status := http.StatusNotFound _, contextErr := context.Write(status, animalJson) test.Nil(t, contextErr) - //check result + // check result - //header + // header contentType := context.response.header.Get(HeaderContentType) - //因writer中的header方法调用过http.Header默认设置 + + // check the default value test.Contains(t, CharsetUTF8, contentType) test.Equal(t, status, context.response.Status) - //body + // body body := string(context.response.body) test.Equal(t, string(animalJson), body) } -//normal write string +// normal write string func TestWriteString(t *testing.T) { param := &InitContextParam{ t, @@ -62,7 +63,7 @@ func TestWriteString(t *testing.T) { test.ToDefault, } - //init param + // init param context := initResponseContext(param) exceptedObject := &Animal{ @@ -73,22 +74,20 @@ func TestWriteString(t *testing.T) { animalJson, err := json.Marshal(exceptedObject) test.Nil(t, err) - //call function - //这里是一个interface数组,用例需要小心. + // call function + // 这里是一个interface数组,用例需要小心. contextErr := context.WriteString(string(animalJson)) test.Nil(t, contextErr) - //header + // header contentType := context.response.header.Get(HeaderContentType) - //因writer中的header方法调用过http.Header默认设置 + // 因writer中的header方法调用过http.Header默认设置 test.Contains(t, CharsetUTF8, contentType) test.Equal(t, defaultHttpCode, context.response.Status) - //body + // body body := string(context.response.body) - //fmt.Printf("%T",context.response.body) - test.Equal(t, string(animalJson), body) } @@ -100,7 +99,7 @@ func TestWriteJson(t *testing.T) { test.ToDefault, } - //init param + // init param context := initResponseContext(param) exceptedObject := &Animal{ @@ -111,23 +110,23 @@ func TestWriteJson(t *testing.T) { animalJson, err := json.Marshal(exceptedObject) test.Nil(t, err) - //call function + // call function contextErr := context.WriteJson(exceptedObject) test.Nil(t, contextErr) - //header + // header contentType := context.response.header.Get(HeaderContentType) - //因writer中的header方法调用过http.Header默认设置 + // 因writer中的header方法调用过http.Header默认设置 test.Equal(t, MIMEApplicationJSONCharsetUTF8, contentType) test.Equal(t, defaultHttpCode, context.response.Status) - //body + // body body := string(context.response.body) test.Equal(t, string(animalJson), body) } -//normal jsonp +// normal jsonp func TestWriteJsonp(t *testing.T) { param := &InitContextParam{ t, @@ -136,7 +135,7 @@ func TestWriteJsonp(t *testing.T) { test.ToDefault, } - //init param + // init param context := initResponseContext(param) exceptedObject := &Animal{ @@ -146,18 +145,18 @@ func TestWriteJsonp(t *testing.T) { callback := "jsonCallBack" - //call function + // call function err := context.WriteJsonp(callback, exceptedObject) test.Nil(t, err) - //check result + // check result - //header + // header contentType := context.response.header.Get(HeaderContentType) test.Equal(t, MIMEApplicationJavaScriptCharsetUTF8, contentType) test.Equal(t, defaultHttpCode, context.response.Status) - //body + // body body := string(context.response.body) animalJson, err := json.Marshal(exceptedObject) diff --git a/core/concurrenceMap.go b/core/concurrenceMap.go index 26f0b57..1406b0c 100644 --- a/core/concurrenceMap.go +++ b/core/concurrenceMap.go @@ -64,7 +64,7 @@ func NewReadonlyMap() ReadonlyMap { } } -// Set 以key、value置入ItemMap +// Set put key, value into ItemMap func (ctx *ItemMap) Set(key string, value interface{}) error { ctx.Lock() ctx.innerMap[key] = value @@ -72,7 +72,7 @@ func (ctx *ItemMap) Set(key string, value interface{}) error { return nil } -// Get 读取指定key在ItemMap中的内容 +// Get returns value of specified key func (ctx *ItemMap) Get(key string) (value interface{}, exists bool) { ctx.RLock() value, exists = ctx.innerMap[key] @@ -100,8 +100,8 @@ func (ctx *ItemMap) Once(key string) (value interface{}, exists bool) { return value, exists } -// GetString 读取指定key在ConcurrenceMap中的内容,以string格式输出 -// 如果不存在key,返回空字符串 +// GetString returns value as string specified by key +// return empty string if key not exists func (ctx *ItemMap) GetString(key string) string { value, exists := ctx.Get(key) if !exists { @@ -110,8 +110,8 @@ func (ctx *ItemMap) GetString(key string) string { return fmt.Sprint(value) } -// GetInt 读取指定key在ConcurrenceMap中的内容,以int格式输出 -// 如果不存在key,或者转换失败,返回0 +// GetInt returns value as int specified by key +// return 0 if key not exists func (ctx *ItemMap) GetInt(key string) int { value, exists := ctx.Get(key) if !exists { @@ -120,8 +120,8 @@ func (ctx *ItemMap) GetInt(key string) int { return value.(int) } -// GetUInt64 读取指定key在ConcurrenceMap中的内容,以uint64格式输出 -// 如果不存在key,或者转换失败,返回0 +// GetUInt64 returns value as uint64 specified by key +// return 0 if key not exists or value cannot be converted to int64 func (ctx *ItemMap) GetUInt64(key string) uint64 { value, exists := ctx.Get(key) if !exists { @@ -130,8 +130,8 @@ func (ctx *ItemMap) GetUInt64(key string) uint64 { return value.(uint64) } -// GetTimeDuration 读取指定key在ConcurrenceMap中的内容,以time.Duration格式输出 -// 如果不存在key,或者转换失败,返回0 +// GetTimeDuration returns value as time.Duration specified by key +// return 0 if key not exists or value cannot be converted to time.Duration func (ctx *ItemMap) GetTimeDuration(key string) time.Duration { timeDuration, err := time.ParseDuration(ctx.GetString(key)) if err != nil { diff --git a/core/concurrenceMap_test.go b/core/concurrenceMap_test.go index c25c7d2..7887f37 100644 --- a/core/concurrenceMap_test.go +++ b/core/concurrenceMap_test.go @@ -66,9 +66,9 @@ func TestItemContext_Current(t *testing.T) { } -//性能测试 +// 性能测试 -//基准测试 +// 基准测试 func BenchmarkItemContext_Set_1(b *testing.B) { var num uint64 = 1 for i := 0; i < b.N; i++ { @@ -76,7 +76,7 @@ func BenchmarkItemContext_Set_1(b *testing.B) { } } -//并发效率 +// 并发效率 func BenchmarkItemContext_Set_Parallel(b *testing.B) { b.RunParallel(func(pb *testing.PB) { var num uint64 = 1 @@ -86,7 +86,7 @@ func BenchmarkItemContext_Set_Parallel(b *testing.B) { }) } -//基准测试 +// 基准测试 func BenchmarkItemContext_Get_1(b *testing.B) { ic.Set("foo", "bar") for i := 0; i < b.N; i++ { @@ -94,7 +94,7 @@ func BenchmarkItemContext_Get_1(b *testing.B) { } } -//并发效率 +// 并发效率 func BenchmarkItemContext_Get_Parallel(b *testing.B) { ic.Set("foo", "bar") b.RunParallel(func(pb *testing.PB) { diff --git a/core/hideReaddirFS.go b/core/hideReaddirFS.go index d64b838..79c75f5 100644 --- a/core/hideReaddirFS.go +++ b/core/hideReaddirFS.go @@ -5,12 +5,12 @@ import ( "os" ) -//FileSystem with hide Readdir +// FileSystem with hide Readdir type HideReaddirFS struct { FileSystem http.FileSystem } -//File with hide Readdir +// File with hide Readdir type hideReaddirFile struct { http.File } diff --git a/core/state.go b/core/state.go index 354866e..d9b8f52 100644 --- a/core/state.go +++ b/core/state.go @@ -52,59 +52,54 @@ func init() { go time.AfterFunc(time.Duration(defaultCheckTimeMinutes)*time.Minute, GlobalState.checkAndRemoveIntervalData) } -//pool定义 type pool struct { requestInfo sync.Pool errorInfo sync.Pool httpCodeInfo sync.Pool } -//http request count info +// http request count info type RequestInfo struct { URL string Code int Num uint64 } -//error count info +// error count info type ErrorInfo struct { URL string ErrMsg string Num uint64 } -//服务器状态信息 +// Server state type ServerStateInfo struct { - //服务启动时间 ServerStartTime time.Time - //是否启用详细请求数据统计 fixed #63 状态数据,当url较多时,导致内存占用过大 + // enable detailed request statistics, fixes #63 request statistics, high memory usage when URL number is high EnabledDetailRequestData bool - //该运行期间总访问次数 - TotalRequestCount uint64 - //当前活跃的请求数 + TotalRequestCount uint64 + // active request count CurrentRequestCount uint64 - //单位时间内请求数据 - 按分钟为单位 + // request statistics per minute IntervalRequestData *ItemMap - //明细请求页面数据 - 以不带参数的访问url为key + // detailed request statistics, the key is url without parameters DetailRequestURLData *ItemMap - //该运行期间异常次数 - TotalErrorCount uint64 - //单位时间内异常次数 - 按分钟为单位 + TotalErrorCount uint64 + // request error statistics per minute IntervalErrorData *ItemMap - //明细异常页面数据 - 以不带参数的访问url为key + // detailed request error statistics, the key is url without parameters DetailErrorPageData *ItemMap - //明细异常数据 - 以不带参数的访问url为key + // detailed error statistics, the key is url without parameters DetailErrorData *ItemMap - //明细Http状态码数据 - 以HttpCode为key,例如200、500等 + // detailed reponse statistics of http code, the key is HttpCode, e.g. 200, 500 etc. DetailHTTPCodeData *ItemMap dataChan_Request chan *RequestInfo dataChan_Error chan *ErrorInfo - //对象池 - infoPool *pool + infoPool *pool } -//ShowHtmlData show server state data html-string format +// ShowHtmlData show server state data html-string format func (state *ServerStateInfo) ShowHtmlData(version string) string { data := "
" data += "HostInfo : " + sysx.GetHostName() @@ -148,34 +143,34 @@ func (state *ServerStateInfo) ShowHtmlData(version string) string { return data } -//QueryIntervalRequestData query request count by query time +// QueryIntervalRequestData query request count by query time func (state *ServerStateInfo) QueryIntervalRequestData(queryKey string) uint64 { return state.IntervalRequestData.GetUInt64(queryKey) } -//QueryIntervalErrorData query error count by query time +// QueryIntervalErrorData query error count by query time func (state *ServerStateInfo) QueryIntervalErrorData(queryKey string) uint64 { return state.IntervalErrorData.GetUInt64(queryKey) } -//AddRequestCount 增加请求数 +// AddRequestCount add request count func (state *ServerStateInfo) AddRequestCount(page string, code int, num uint64) { state.addRequestData(page, code, num) } -//AddCurrentRequest 增加请求数 +// AddCurrentRequest increment current request count func (state *ServerStateInfo) AddCurrentRequest(num uint64) uint64 { atomic.AddUint64(&state.CurrentRequestCount, num) return state.CurrentRequestCount } -//SubCurrentRequest 消除请求数 +// SubCurrentRequest subtract current request count func (state *ServerStateInfo) SubCurrentRequest(num uint64) uint64 { atomic.AddUint64(&state.CurrentRequestCount, ^uint64(num-1)) return state.CurrentRequestCount } -//AddErrorCount 增加错误数 +// AddErrorCount add error count func (state *ServerStateInfo) AddErrorCount(page string, err error, num uint64) uint64 { atomic.AddUint64(&state.TotalErrorCount, num) state.addErrorData(page, err, num) @@ -183,7 +178,7 @@ func (state *ServerStateInfo) AddErrorCount(page string, err error, num uint64) } func (state *ServerStateInfo) addRequestData(page string, code int, num uint64) { - //get from pool + // get from pool info := state.infoPool.requestInfo.Get().(*RequestInfo) info.URL = page info.Code = code @@ -192,7 +187,7 @@ func (state *ServerStateInfo) addRequestData(page string, code int, num uint64) } func (state *ServerStateInfo) addErrorData(page string, err error, num uint64) { - //get from pool + // get from pool info := state.infoPool.errorInfo.Get().(*ErrorInfo) info.URL = page info.ErrMsg = err.Error() @@ -200,7 +195,7 @@ func (state *ServerStateInfo) addErrorData(page string, err error, num uint64) { state.dataChan_Error <- info } -//处理日志内部函数 +// handle logging func (state *ServerStateInfo) handleInfo() { for { select { @@ -209,59 +204,59 @@ func (state *ServerStateInfo) handleInfo() { if strings.Index(info.URL, "/dotweb/") != 0 { atomic.AddUint64(&state.TotalRequestCount, info.Num) } - //fixed #63 状态数据,当url较多时,导致内存占用过大 + // fixes #63 request statistics, high memory usage when URL number is high if state.EnabledDetailRequestData { - //ignore 404 request + // ignore 404 request if info.Code != http.StatusNotFound { - //set detail url data + // set detail url data key := strings.ToLower(info.URL) val := state.DetailRequestURLData.GetUInt64(key) state.DetailRequestURLData.Set(key, val+info.Num) } } - //set interval data + // set interval data key := time.Now().Format(minuteTimeLayout) val := state.IntervalRequestData.GetUInt64(key) state.IntervalRequestData.Set(key, val+info.Num) - //set code data + // set code data key = strconv.Itoa(info.Code) val = state.DetailHTTPCodeData.GetUInt64(key) state.DetailHTTPCodeData.Set(key, val+info.Num) - //put info obj + // put info obj state.infoPool.requestInfo.Put(info) } case info := <-state.dataChan_Error: { - //set detail error page data + // set detail error page data key := strings.ToLower(info.URL) val := state.DetailErrorPageData.GetUInt64(key) state.DetailErrorPageData.Set(key, val+info.Num) - //set detail error data + // set detail error data key = info.ErrMsg val = state.DetailErrorData.GetUInt64(key) state.DetailErrorData.Set(key, val+info.Num) - //set interval data + // set interval data key = time.Now().Format(minuteTimeLayout) val = state.IntervalErrorData.GetUInt64(key) state.IntervalErrorData.Set(key, val+info.Num) - //put info obj + // put info obj state.infoPool.errorInfo.Put(info) } } } } -//check and remove need to remove interval data with request and error +// check and remove need to remove interval data with request and error func (state *ServerStateInfo) checkAndRemoveIntervalData() { var needRemoveKey []string now, _ := time.Parse(minuteTimeLayout, time.Now().Format(minuteTimeLayout)) - //check IntervalRequestData + // check IntervalRequestData state.IntervalRequestData.RLock() if state.IntervalRequestData.Len() > defaultReserveMinutes { for k := range state.IntervalRequestData.GetCurrentMap() { @@ -275,12 +270,12 @@ func (state *ServerStateInfo) checkAndRemoveIntervalData() { } } state.IntervalRequestData.RUnlock() - //remove keys + // remove keys for _, v := range needRemoveKey { state.IntervalRequestData.Remove(v) } - //check IntervalErrorData + // check IntervalErrorData needRemoveKey = []string{} state.IntervalErrorData.RLock() if state.IntervalErrorData.Len() > defaultReserveMinutes { @@ -295,7 +290,7 @@ func (state *ServerStateInfo) checkAndRemoveIntervalData() { } } state.IntervalErrorData.RUnlock() - //remove keys + // remove keys for _, v := range needRemoveKey { state.IntervalErrorData.Remove(v) } diff --git a/dotweb.go b/dotweb.go index 5e1ade0..097b4c8 100644 --- a/dotweb.go +++ b/dotweb.go @@ -64,14 +64,14 @@ const ( // RunMode_Production app runmode in production mode RunMode_Production = "production" - //StartMode_New app startmode in New mode + // StartMode_New app startmode in New mode StartMode_New = "New" - //StartMode_Classic app startmode in Classic mode + // StartMode_Classic app startmode in Classic mode StartMode_Classic = "Classic" ) -//New create and return DotApp instance -//default run mode is RunMode_Production +// New create and return DotApp instance +// default run mode is RunMode_Production func New() *DotWeb { app := &DotWeb{ HttpServer: NewHttpServer(), @@ -83,14 +83,14 @@ func New() *DotWeb { middlewareMutex: new(sync.RWMutex), StartMode: StartMode_New, } - //set default run mode = RunMode_Production + // set default run mode = RunMode_Production app.Config.App.RunMode = RunMode_Production app.HttpServer.setDotApp(app) - //add default httphandler with middlewares - //fixed for issue #100 + // add default httphandler with middlewares + // fixed for issue #100 app.Use(&xMiddleware{}) - //init logger + // init logger logger.InitLog() return app @@ -110,7 +110,7 @@ func Classic(logPath string) *DotWeb { } app.SetEnabledLog(true) - //print logo + // print logo printDotLogo() logger.Logger().Debug("DotWeb Start New AppServer", LogTarget_HttpServer) @@ -256,14 +256,14 @@ func (app *DotWeb) SetLogger(log logger.AppLog) { // SetLogPath set log root path func (app *DotWeb) SetLogPath(path string) { logger.SetLogPath(path) - //fixed #74 dotweb.SetEnabledLog 无效 + // fixed #74 dotweb.SetEnabledLog 无效 app.Config.App.LogPath = path } // SetEnabledLog set enabled log flag func (app *DotWeb) SetEnabledLog(enabledLog bool) { logger.SetEnabledLog(enabledLog) - //fixed #74 dotweb.SetEnabledLog 无效 + // fixed #74 dotweb.SetEnabledLog 无效 app.Config.App.EnabledLog = enabledLog } @@ -287,7 +287,7 @@ func (app *DotWeb) Start() error { if app.Config == nil { return errors.New("no config exists") } - //start server + // start server port := app.Config.Server.Port if port <= 0 { port = DefaultHTTPPort @@ -321,14 +321,14 @@ func (app *DotWeb) ListenAndServe(addr string) error { app.IncludeDotwebGroup() } - //special, if run mode is not develop, auto stop mock + // special, if run mode is not develop, auto stop mock if app.RunMode() != RunMode_Development { if app.Mock != nil { logger.Logger().Debug("DotWeb Mock RunMode is not DevelopMode, Auto stop mock", LogTarget_HttpServer) } app.Mock = nil } - //output run mode + // output run mode logger.Logger().Debug("DotWeb RunMode is "+app.RunMode(), LogTarget_HttpServer) if app.HttpServer.ServerConfig().EnabledTLS { @@ -343,13 +343,13 @@ func (app *DotWeb) ListenAndServe(addr string) error { // init App Config func (app *DotWeb) initAppConfig() { config := app.Config - //log config + // log config if config.App.LogPath != "" { logger.SetLogPath(config.App.LogPath) } logger.SetEnabledLog(config.App.EnabledLog) - //run mode config + // run mode config if app.Config.App.RunMode != RunMode_Development && app.Config.App.RunMode != RunMode_Production { app.Config.App.RunMode = RunMode_Development } @@ -371,7 +371,7 @@ func (app *DotWeb) initAppConfig() { // init register config's Middleware func (app *DotWeb) initRegisterConfigMiddleware() { config := app.Config - //register app's middleware + // register app's middleware for _, m := range config.Middlewares { if !m.IsUse { continue @@ -385,12 +385,12 @@ func (app *DotWeb) initRegisterConfigMiddleware() { // init register config's route func (app *DotWeb) initRegisterConfigRoute() { config := app.Config - //load router and register + // load router and register for _, r := range config.Routers { - //fmt.Println("config.Routers ", i, " ", config.Routers[i]) + // fmt.Println("config.Routers ", i, " ", config.Routers[i]) if h, isok := app.HttpServer.Router().GetHandler(r.HandlerName); isok && r.IsUse { node := app.HttpServer.Router().RegisterRoute(strings.ToUpper(r.Method), r.Path, h) - //use middleware + // use middleware for _, m := range r.Middlewares { if !m.IsUse { continue @@ -406,13 +406,13 @@ func (app *DotWeb) initRegisterConfigRoute() { // init register config's route func (app *DotWeb) initRegisterConfigGroup() { config := app.Config - //support group + // support group for _, v := range config.Groups { if !v.IsUse { continue } g := app.HttpServer.Group(v.Path) - //use middleware + // use middleware for _, m := range v.Middlewares { if !m.IsUse { continue @@ -421,11 +421,11 @@ func (app *DotWeb) initRegisterConfigGroup() { g.Use(mf()) } } - //init group's router + // init group's router for _, r := range v.Routers { if h, isok := app.HttpServer.Router().GetHandler(r.HandlerName); isok && r.IsUse { node := g.RegisterRoute(strings.ToUpper(r.Method), r.Path, h) - //use middleware + // use middleware for _, m := range r.Middlewares { if !m.IsUse { continue @@ -442,7 +442,7 @@ func (app *DotWeb) initRegisterConfigGroup() { // init bind app's middleware to router node func (app *DotWeb) initBindMiddleware() { router := app.HttpServer.Router().(*router) - //bind app middlewares + // bind app middlewares for fullExpress, _ := range router.allRouterExpress { expresses := strings.Split(fullExpress, routerExpressSplit) if len(expresses) < 2 { @@ -469,7 +469,7 @@ func (app *DotWeb) initBindMiddleware() { } } - //bind group middlewares + // bind group middlewares for _, g := range app.HttpServer.groups { xg := g.(*xGroup) if len(xg.middlewares) <= 0 { @@ -522,23 +522,23 @@ func (app *DotWeb) initServerEnvironment() { app.SetMethodNotAllowedHandle(app.DefaultMethodNotAllowedHandler) } - //init session manager + // init session manager if app.HttpServer.SessionConfig().EnabledSession { if app.HttpServer.SessionConfig().SessionMode == "" { - //panic("no set SessionConfig, but set enabledsession true") + // panic("no set SessionConfig, but set enabledsession true") logger.Logger().Warn("not set SessionMode, but set enabledsession true, now will use default runtime session", LogTarget_HttpServer) app.HttpServer.SetSessionConfig(session.NewDefaultRuntimeConfig()) } app.HttpServer.InitSessionManager() } - //if cache not set, create default runtime cache + // if cache not set, create default runtime cache if app.Cache() == nil { app.cache = cache.NewRuntimeCache() } - //if renderer not set, create inner renderer - //if is develop mode, it will use nocache mode + // if renderer not set, create inner renderer + // if is develop mode, it will use nocache mode if app.HttpServer.Renderer() == nil { if app.RunMode() == RunMode_Development { app.HttpServer.SetRenderer(NewInnerRendererNoCache()) @@ -547,14 +547,14 @@ func (app *DotWeb) initServerEnvironment() { } } - //start pprof server + // start pprof server if app.Config.App.EnabledPProf { logger.Logger().Debug("DotWeb:StartPProfServer["+strconv.Itoa(app.Config.App.PProfPort)+"] Begin", LogTarget_HttpServer) go func() { err := http.ListenAndServe(":"+strconv.Itoa(app.Config.App.PProfPort), nil) if err != nil { logger.Logger().Error("DotWeb:StartPProfServer["+strconv.Itoa(app.Config.App.PProfPort)+"] error: "+err.Error(), LogTarget_HttpServer) - //panic the error + // panic the error panic(err) } }() @@ -564,7 +564,7 @@ func (app *DotWeb) initServerEnvironment() { // DefaultHTTPErrorHandler default exception handler func (app *DotWeb) DefaultHTTPErrorHandler(ctx Context, err error) { ctx.Response().Header().Set(HeaderContentType, CharsetUTF8) - //if in development mode, output the error info + // if in development mode, output the error info if app.IsDevelopmentMode() { stack := string(debug.Stack()) ctx.WriteStringC(http.StatusInternalServerError, fmt.Sprintln(err)+stack) @@ -597,7 +597,7 @@ func (app *DotWeb) Close() error { return app.HttpServer.stdServer.Close() } -// Shutdown stops server the gracefully. +// Shutdown stops server gracefully. // It internally calls `http.Server#Shutdown()`. func (app *DotWeb) Shutdown(ctx context.Context) error { return app.HttpServer.stdServer.Shutdown(ctx) @@ -608,8 +608,8 @@ func HTTPNotFound(ctx Context) { http.NotFound(ctx.Response().Writer(), ctx.Request().Request) } -//query pprof debug info -//key:heap goroutine threadcreate block +// query pprof debug info +// key:heap goroutine threadcreate block func initPProf(ctx Context) error { querykey := ctx.GetRouterName("key") runtime.GC() diff --git a/feature.go b/feature.go index 4f76bfd..50ca301 100644 --- a/feature.go +++ b/feature.go @@ -18,7 +18,7 @@ func init() { FeatureTools = new(xFeatureTools) } -//set CROS config on HttpContext +// set CROS config on HttpContext func (f *xFeatureTools) SetCROSConfig(ctx *HttpContext, c *feature.CROSConfig) { ctx.Response().SetHeader(HeaderAccessControlAllowOrigin, c.AllowedOrigins) ctx.Response().SetHeader(HeaderAccessControlAllowMethods, c.AllowedMethods) @@ -27,7 +27,7 @@ func (f *xFeatureTools) SetCROSConfig(ctx *HttpContext, c *feature.CROSConfig) { ctx.Response().SetHeader(HeaderP3P, c.AllowedP3P) } -//set CROS config on HttpContext +// set CROS config on HttpContext func (f *xFeatureTools) SetSession(httpCtx *HttpContext) { sessionId, err := httpCtx.HttpServer().GetSessionManager().GetClientSessionID(httpCtx.Request().Request) if err == nil && sessionId != "" { @@ -56,19 +56,19 @@ func (f *xFeatureTools) SetGzip(httpCtx *HttpContext) { // doFeatures do features... func (f *xFeatureTools) InitFeatures(server *HttpServer, httpCtx *HttpContext) { - //gzip + // gzip if server.ServerConfig().EnabledGzip { FeatureTools.SetGzip(httpCtx) } - //session - //if exists client-sessionid, use it - //if not exists client-sessionid, new one + // session + // if exists client-sessionid, use it + // if not exists client-sessionid, new one if server.SessionConfig().EnabledSession { FeatureTools.SetSession(httpCtx) } - //处理 cros feature + // CROS handling if server.Features.CROSConfig != nil { c := server.Features.CROSConfig if c.EnabledCROS { diff --git a/feature/cors.go b/feature/cors.go index 2ce964a..ea9f41f 100644 --- a/feature/cors.go +++ b/feature/cors.go @@ -1,6 +1,6 @@ package feature -//CROS配置 +// CROS settings type CROSConfig struct { EnabledCROS bool AllowedOrigins string diff --git a/feature/features.go b/feature/features.go index 7b6e55c..323a6ef 100644 --- a/feature/features.go +++ b/feature/features.go @@ -10,7 +10,7 @@ func NewFeature() *Feature { } } -//set Enabled CROS true, with default config +// SetEnabledCROS enable CROS, with default config func (f *Feature) SetEnabledCROS() *CROSConfig { if f.CROSConfig == nil { f.CROSConfig = NewCORSConfig() @@ -20,7 +20,7 @@ func (f *Feature) SetEnabledCROS() *CROSConfig { return f.CROSConfig } -//set Disabled CROS false +// SetDisabledCROS disable CROS func (f *Feature) SetDisabledCROS() { if f.CROSConfig == nil { f.CROSConfig = NewCORSConfig() diff --git a/framework/crypto/cryptos.go b/framework/crypto/cryptos.go index d260690..6fd8b48 100644 --- a/framework/crypto/cryptos.go +++ b/framework/crypto/cryptos.go @@ -8,14 +8,14 @@ import ( "io" ) -//获取MD5值 +// GetMd5String compute the md5 sum as string func GetMd5String(s string) string { h := md5.New() h.Write([]byte(s)) return hex.EncodeToString(h.Sum(nil)) } -//创建指定长度的随机字符串 +// GetRandString returns randominzed string with given length func GetRandString(len int) string { b := make([]byte, len) diff --git a/framework/crypto/des/des.go b/framework/crypto/des/des.go index 92768ac..a12f28c 100644 --- a/framework/crypto/des/des.go +++ b/framework/crypto/des/des.go @@ -7,21 +7,21 @@ import ( "errors" ) -//ECB PKCS5Padding +// ECB PKCS5Padding func PKCS5Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } -//ECB PKCS5UnPadding +// ECB PKCS5UnPadding func PKCS5UnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] } -//ECB Des加密 +// ECB Des encrypt func ECBEncrypt(origData, key []byte) ([]byte, error) { if len(origData) < 1 || len(key) < 1 { return nil, errors.New("wrong data or key") @@ -38,7 +38,7 @@ func ECBEncrypt(origData, key []byte) ([]byte, error) { return crypted, nil } -//ECB Des解密 +// ECB Des decrypt func ECBDecrypt(crypted, key []byte) ([]byte, error) { if len(crypted) < 1 || len(key) < 1 { return nil, errors.New("wrong data or key") @@ -54,7 +54,7 @@ func ECBDecrypt(crypted, key []byte) ([]byte, error) { return origData, nil } -//[golang ECB 3DES Encrypt] +// [golang ECB 3DES Encrypt] func TripleEcbDesEncrypt(origData, key []byte) ([]byte, error) { tkey := make([]byte, 24, 24) copy(tkey, key) @@ -84,7 +84,7 @@ func TripleEcbDesEncrypt(origData, key []byte) ([]byte, error) { return out, nil } -//[golang ECB 3DES Decrypt] +// [golang ECB 3DES Decrypt] func TripleEcbDesDecrypt(crypted, key []byte) ([]byte, error) { tkey := make([]byte, 24, 24) copy(tkey, key) diff --git a/framework/crypto/uuid/uuid.go b/framework/crypto/uuid/uuid.go index 30ac884..5bf4e24 100644 --- a/framework/crypto/uuid/uuid.go +++ b/framework/crypto/uuid/uuid.go @@ -219,11 +219,6 @@ func (u UUID) String() string { func (u UUID) String32() string { buf := make([]byte, 32) - //hex.Encode(buf[0:8], u[0:4]) - //hex.Encode(buf[8:12], u[4:6]) - //hex.Encode(buf[12:16], u[6:8]) - //hex.Encode(buf[16:20], u[8:10]) - //hex.Encode(buf[20:], u[10:]) hex.Encode(buf[0:], u[0:]) return string(buf) diff --git a/framework/exception/exception.go b/framework/exception/exception.go index cdce595..d4e17aa 100644 --- a/framework/exception/exception.go +++ b/framework/exception/exception.go @@ -6,12 +6,9 @@ import ( "runtime/debug" ) -//统一异常处理 +// CatchError is the unified exception handler func CatchError(title string, logtarget string, err interface{}) (errmsg string) { errmsg = fmt.Sprintln(err) - //buf := make([]byte, 4096) - //n := runtime.Stack(buf, true) - //stack := string(buf[:n]) stack := string(debug.Stack()) os.Stdout.Write([]byte(title + " error! => " + errmsg + " => " + stack)) return title + " error! => " + errmsg + " => " + stack diff --git a/framework/file/file.go b/framework/file/file.go index 3d704eb..a78fbfa 100644 --- a/framework/file/file.go +++ b/framework/file/file.go @@ -16,7 +16,7 @@ func GetCurrentDirectory() string { return strings.Replace(dir, "\\", "/", -1) } -//check filename is exist +// check filename exists func Exist(filename string) bool { _, err := os.Stat(filename) return err == nil || os.IsExist(err) diff --git a/framework/hystrix/hystrix.go b/framework/hystrix/hystrix.go index 6f7b41f..0b44dd7 100644 --- a/framework/hystrix/hystrix.go +++ b/framework/hystrix/hystrix.go @@ -8,9 +8,9 @@ import ( const ( status_Hystrix = 1 status_Alive = 2 - DefaultCheckHystrixInterval = 10 //unit is Second - DefaultCheckAliveInterval = 60 //unit is Second - DefaultCleanHistoryInterval = 60 * 5 //unit is Second + DefaultCheckHystrixInterval = 10 // unit is Second + DefaultCheckAliveInterval = 60 // unit is Second + DefaultCleanHistoryInterval = 60 * 5 // unit is Second DefaultMaxFailedNumber = 100 DefaultReserveMinutes = 30 ) @@ -157,7 +157,7 @@ func (h *StandHystrix) doCleanHistoryCounter() { return true }) for _, k := range needRemoveKey { - //fmt.Println(time.Now(), "hystrix doCleanHistoryCounter remove key",k) + // fmt.Println(time.Now(), "hystrix doCleanHistoryCounter remove key",k) h.counters.Delete(k) } time.AfterFunc(time.Duration(DefaultCleanHistoryInterval)*time.Second, h.doCleanHistoryCounter) diff --git a/framework/json/jsonutil.go b/framework/json/jsonutil.go index 5d0e8d6..b98a63e 100644 --- a/framework/json/jsonutil.go +++ b/framework/json/jsonutil.go @@ -4,7 +4,7 @@ import ( "encoding/json" ) -//将传入对象转换为json字符串 +// GetJsonString marshals the object as string func GetJsonString(obj interface{}) string { resByte, err := json.Marshal(obj) if err != nil { @@ -13,7 +13,7 @@ func GetJsonString(obj interface{}) string { return string(resByte) } -//将传入对象转换为json字符串 +// Marshal marshals the value as string func Marshal(v interface{}) (string, error) { resByte, err := json.Marshal(v) if err != nil { @@ -23,7 +23,7 @@ func Marshal(v interface{}) (string, error) { } } -//将传入的json字符串转换为对象 +// Unmarshal converts the jsonstring into value func Unmarshal(jsonstring string, v interface{}) error { return json.Unmarshal([]byte(jsonstring), v) } diff --git a/framework/redis/redisutil.go b/framework/redis/redisutil.go index aa09699..eeb3082 100644 --- a/framework/redis/redisutil.go +++ b/framework/redis/redisutil.go @@ -1,7 +1,7 @@ // redisclient -// Package redisutil 命令的使用方式参考 -// http://doc.redisfans.com/index.html +// Package redisutil, for detailed usage, reference +// http:// doc.redisfans.com/index.html package redisutil import ( @@ -21,7 +21,7 @@ var ( ) const ( - defaultTimeout = 60 * 10 //默认10分钟 + defaultTimeout = 60 * 10 // defaults to 10 minutes ) func init() { @@ -29,8 +29,8 @@ func init() { mapMutex = new(sync.RWMutex) } -// 重写生成连接池方法 -// redisURL: connection string, like "redis://:password@10.0.1.11:6379/0" +// returns new connection pool +// redisURL: connection string, like "redis:// :password@10.0.1.11:6379/0" func newPool(redisURL string) *redis.Pool { return &redis.Pool{ @@ -43,7 +43,7 @@ func newPool(redisURL string) *redis.Pool { } } -// GetRedisClient 获取指定Address的RedisClient +// GetRedisClient returns the RedisClient of specified address func GetRedisClient(address string) *RedisClient { var redis *RedisClient var mok bool @@ -59,38 +59,32 @@ func GetRedisClient(address string) *RedisClient { return redis } -// GetObj 获取指定key的内容, interface{} +// GetObj returns the content specified by key func (rc *RedisClient) GetObj(key string) (interface{}, error) { - // 从连接池里面获得一个连接 conn := rc.pool.Get() - // 连接完关闭,其实没有关闭,是放回池里,也就是队列里面,等待下一个重用 defer conn.Close() reply, errDo := conn.Do("GET", key) return reply, errDo } -// Get 获取指定key的内容, string +// Get returns the content as string specified by key func (rc *RedisClient) Get(key string) (string, error) { val, err := redis.String(rc.GetObj(key)) return val, err } -// Exists 检查指定key是否存在 +// Exists whether key exists func (rc *RedisClient) Exists(key string) (bool, error) { - // 从连接池里面获得一个连接 conn := rc.pool.Get() - // 连接完关闭,其实没有关闭,是放回池里,也就是队列里面,等待下一个重用 defer conn.Close() reply, errDo := redis.Bool(conn.Do("EXISTS", key)) return reply, errDo } -// Del 删除指定key +// Del deletes specified key func (rc *RedisClient) Del(key string) (int64, error) { - // 从连接池里面获得一个连接 conn := rc.pool.Get() - // 连接完关闭,其实没有关闭,是放回池里,也就是队列里面,等待下一个重用 defer conn.Close() reply, errDo := conn.Do("DEL", key) if errDo == nil && reply == nil { @@ -100,7 +94,7 @@ func (rc *RedisClient) Del(key string) (int64, error) { return val, err } -// INCR 对存储在指定key的数值执行原子的加1操作 +// INCR atomically increment the value by 1 specified by key func (rc *RedisClient) INCR(key string) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -112,7 +106,7 @@ func (rc *RedisClient) INCR(key string) (int, error) { return val, err } -// DECR 对存储在指定key的数值执行原子的减1操作 +// DECR atomically decrement the value by 1 specified by key func (rc *RedisClient) DECR(key string) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -124,8 +118,8 @@ func (rc *RedisClient) DECR(key string) (int, error) { return val, err } -// Append 如果 key 已经存在并且是一个字符串, APPEND 命令将 value 追加到 key 原来的值的末尾。 -// 如果 key 不存在, APPEND 就简单地将给定 key 设为 value ,就像执行 SET key value 一样。 +// Append appends the string to original value specivied by key. +// if key does not exists, it behaves like Set func (rc *RedisClient) Append(key string, val interface{}) (interface{}, error) { conn := rc.pool.Get() defer conn.Close() @@ -137,7 +131,7 @@ func (rc *RedisClient) Append(key string, val interface{}) (interface{}, error) return val, err } -// Set 设置指定Key/Value +// Set put key/value into redis func (rc *RedisClient) Set(key string, val interface{}) (interface{}, error) { conn := rc.pool.Get() defer conn.Close() @@ -145,7 +139,7 @@ func (rc *RedisClient) Set(key string, val interface{}) (interface{}, error) { return val, err } -// Expire 设置指定key的过期时间 +// Expire specifies the expire duration for key func (rc *RedisClient) Expire(key string, timeOutSeconds int64) (int64, error) { conn := rc.pool.Get() defer conn.Close() @@ -153,7 +147,7 @@ func (rc *RedisClient) Expire(key string, timeOutSeconds int64) (int64, error) { return val, err } -// SetWithExpire 设置指定key的内容 +// SetWithExpire set the key/value with specified duration func (rc *RedisClient) SetWithExpire(key string, val interface{}, timeOutSeconds int64) (interface{}, error) { conn := rc.pool.Get() defer conn.Close() @@ -161,8 +155,8 @@ func (rc *RedisClient) SetWithExpire(key string, val interface{}, timeOutSeconds return val, err } -// SetNX 将 key 的值设为 value ,当且仅当 key 不存在。 -// 若给定的 key 已经存在,则 SETNX 不做任何动作。 成功返回1, 失败返回0 +// SetNX sets key/value only if key does not exists, +// it does nothing if key already exists. returns 1 on success, 0 on failure func (rc *RedisClient) SetNX(key, value string) (interface{}, error) { conn := rc.pool.Get() defer conn.Close() @@ -171,9 +165,9 @@ func (rc *RedisClient) SetNX(key, value string) (interface{}, error) { return val, err } -//****************** hash 集合 *********************** +// ****************** hash set *********************** -// HGet 获取指定hash的内容 +// HGet returns content specified by hashID and field func (rc *RedisClient) HGet(hashID string, field string) (string, error) { conn := rc.pool.Get() defer conn.Close() @@ -185,7 +179,7 @@ func (rc *RedisClient) HGet(hashID string, field string) (string, error) { return val, err } -// HGetAll 获取指定hash的所有内容 +// HGetAll returns all content specified by hashID func (rc *RedisClient) HGetAll(hashID string) (map[string]string, error) { conn := rc.pool.Get() defer conn.Close() @@ -193,7 +187,7 @@ func (rc *RedisClient) HGetAll(hashID string) (map[string]string, error) { return reply, err } -// HSet 设置指定hash的内容 +// HSet set content with hashID and field func (rc *RedisClient) HSet(hashID string, field string, val string) error { conn := rc.pool.Get() defer conn.Close() @@ -201,7 +195,8 @@ func (rc *RedisClient) HSet(hashID string, field string, val string) error { return err } -// HSetNX 设置指定hash的内容, 如果field不存在, 该操作无效 +// HSetNX set content with hashID and field, if the field does not exists, +// this operation has no effect func (rc *RedisClient) HSetNX(hashID, field, value string) (interface{}, error) { conn := rc.pool.Get() defer conn.Close() @@ -210,7 +205,7 @@ func (rc *RedisClient) HSetNX(hashID, field, value string) (interface{}, error) return val, err } -// HExist 返回hash里面field是否存在 +// HExist returns if the field exists in specified hashID func (rc *RedisClient) HExist(hashID string, field string) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -218,7 +213,7 @@ func (rc *RedisClient) HExist(hashID string, field string) (int, error) { return val, err } -// HIncrBy 增加 key 指定的哈希集中指定字段的数值 +// HIncrBy increment the value specified by hashID and field func (rc *RedisClient) HIncrBy(hashID string, field string, increment int) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -226,7 +221,7 @@ func (rc *RedisClient) HIncrBy(hashID string, field string, increment int) (int, return val, err } -// HLen 返回哈希表 key 中域的数量, 当 key 不存在时,返回0 +// HLen returns count of fileds in hashID, returns 0 if hashID does not exists func (rc *RedisClient) HLen(hashID string) (int64, error) { conn := rc.pool.Get() defer conn.Close() @@ -235,7 +230,8 @@ func (rc *RedisClient) HLen(hashID string) (int64, error) { return val, err } -// HDel 设置指定hashset的内容, 如果field不存在, 该操作无效, 返回0 +// HDel delete content in hashset, if the field does not exists, this operation +// returns 0 and have no effect func (rc *RedisClient) HDel(args ...interface{}) (int64, error) { conn := rc.pool.Get() defer conn.Close() @@ -244,7 +240,8 @@ func (rc *RedisClient) HDel(args ...interface{}) (int64, error) { return val, err } -// HVals 返回哈希表 key 中所有域的值, 当 key 不存在时,返回空 +// HVals return all the values in all fields specified by hashID, returns empty +// if hashID does not exists func (rc *RedisClient) HVals(hashID string) (interface{}, error) { conn := rc.pool.Get() defer conn.Close() @@ -253,9 +250,9 @@ func (rc *RedisClient) HVals(hashID string) (interface{}, error) { return val, err } -//****************** list *********************** +// ****************** list *********************** -//将所有指定的值插入到存于 key 的列表的头部 +// LPush insert the values into front of the list func (rc *RedisClient) LPush(key string, value ...interface{}) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -339,7 +336,8 @@ func (rc *RedisClient) BLPop(key ...interface{}) (map[string]string, error) { return val, err } -//删除,并获得该列表中的最后一个元素,或阻塞,直到有一个可用 +// BRPop returns the last element in the list and delete it. It blocks if the +// list is empty func (rc *RedisClient) BRPop(key ...interface{}) (map[string]string, error) { conn := rc.pool.Get() defer conn.Close() @@ -389,10 +387,10 @@ func (rc *RedisClient) LPop(key string) (string, error) { return val, err } -//****************** set 集合 *********************** +// ****************** set *********************** -// SAdd 将一个或多个 member 元素加入到集合 key 当中,已经存在于集合的 member 元素将被忽略。 -// 假如 key 不存在,则创建一个只包含 member 元素作成员的集合。 +// SAdd add one or multiple members in to the set, creates a new set with key +// if it does not exists func (rc *RedisClient) SAdd(key string, member ...interface{}) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -401,10 +399,8 @@ func (rc *RedisClient) SAdd(key string, member ...interface{}) (int, error) { return val, err } -// SCard 返回集合 key 的基数(集合中元素的数量)。 -// 返回值: -// 集合的基数。 -// 当 key 不存在时,返回 0 +// SCard returns cardinality of the set(count of elements). +// returns 0 when set does not exist func (rc *RedisClient) SCard(key string) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -412,9 +408,8 @@ func (rc *RedisClient) SCard(key string) (int, error) { return val, err } -// SPop 移除并返回集合中的一个随机元素。 -// 如果只想获取一个随机元素,但不想该元素从集合中被移除的话,可以使用 SRANDMEMBER 命令。 -// count 为 返回的随机元素的数量 +// SPop return and remove a random element from the set, +// use SRandMember if the element should not be removed func (rc *RedisClient) SPop(key string) (string, error) { conn := rc.pool.Get() defer conn.Close() @@ -422,9 +417,7 @@ func (rc *RedisClient) SPop(key string) (string, error) { return val, err } -// SRandMember 如果命令执行时,只提供了 key 参数,那么返回集合中的一个随机元素。 -// 该操作和 SPOP 相似,但 SPOP 将随机元素从集合中移除并返回,而 SRANDMEMBER 则仅仅返回随机元素,而不对集合进行任何改动。 -// count 为 返回的随机元素的数量 +// SRandMember returns random count elements from set func (rc *RedisClient) SRandMember(key string, count int) ([]string, error) { conn := rc.pool.Get() defer conn.Close() @@ -432,9 +425,7 @@ func (rc *RedisClient) SRandMember(key string, count int) ([]string, error) { return val, err } -// SRem 移除集合 key 中的一个或多个 member 元素,不存在的 member 元素会被忽略。 -// 当 key 不是集合类型,返回一个错误。 -// 在 Redis 2.4 版本以前, SREM 只接受单个 member 值。 +// SRem remove multiple elements from set func (rc *RedisClient) SRem(key string, member ...interface{}) (int, error) { conn := rc.pool.Get() defer conn.Close() @@ -510,9 +501,9 @@ func (rc *RedisClient) SUnionStore(destination string, key ...interface{}) (int, return val, err } -//****************** 全局操作 *********************** +// ****************** Global functions *********************** -// Ping 测试一个连接是否可用 +// Ping tests the client is ready for use func (rc *RedisClient) Ping() (string, error) { conn := rc.pool.Get() defer conn.Close() @@ -520,7 +511,7 @@ func (rc *RedisClient) Ping() (string, error) { return val, err } -// DBSize 返回当前数据库的 key 的数量 +// DBSize returns count of keys in the database func (rc *RedisClient) DBSize() (int64, error) { conn := rc.pool.Get() defer conn.Close() @@ -529,16 +520,16 @@ func (rc *RedisClient) DBSize() (int64, error) { return val, err } -// FlushDB 删除当前数据库里面的所有数据 -// 这个命令永远不会出现失败 +// FlushDB remove all data in the database +// this command never fails func (rc *RedisClient) FlushDB() { conn := rc.pool.Get() defer conn.Close() conn.Do("FLUSHALL") } -// GetConn 返回一个从连接池获取的redis连接, -// 需要手动释放redis连接 +// GetConn returns a connection from the pool, +// user is responsible for closing this connection func (rc *RedisClient) GetConn() redis.Conn { return rc.pool.Get() } diff --git a/framework/reflects/reflects.go b/framework/reflects/reflects.go index 15fc23f..e70da81 100644 --- a/framework/reflects/reflects.go +++ b/framework/reflects/reflects.go @@ -6,7 +6,7 @@ import ( "strconv" ) -//convert map to struct +// convert map to struct func ConvertMapToStruct(tagName string, ptr interface{}, form map[string][]string) error { typ := reflect.TypeOf(ptr).Elem() val := reflect.ValueOf(ptr).Elem() diff --git a/hijack.go b/hijack.go index d952998..5bb094f 100644 --- a/hijack.go +++ b/hijack.go @@ -5,7 +5,7 @@ import ( "net" ) -//hijack conn +// hijack conn type HijackConn struct { ReadWriter *bufio.ReadWriter Conn net.Conn diff --git a/logger/logger.go b/logger/logger.go index 4625501..f25f5ba 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -42,7 +42,7 @@ func Logger() AppLog { return appLog } -//SetLogPath set log path +// SetLogPath set log path func SetLogger(logger AppLog) { appLog = logger logger.SetLogPath(DefaultLogPath) @@ -56,7 +56,7 @@ func SetLogPath(path string) { } } -//SetEnabledLog set enabled log +// SetEnabledLog set enabled log func SetEnabledLog(isLog bool) { EnabledLog = isLog if appLog != nil { @@ -64,7 +64,7 @@ func SetEnabledLog(isLog bool) { } } -//SetEnabledConsole set enabled Console output +// SetEnabledConsole set enabled Console output func SetEnabledConsole(enabled bool) { EnabledConsole = enabled if appLog != nil { @@ -80,16 +80,16 @@ func InitLog() { appLog = NewXLog() } - SetLogPath(DefaultLogPath) //set default log path - SetEnabledLog(EnabledLog) //set default enabled log - SetEnabledConsole(EnabledConsole) //set default enabled console output + SetLogPath(DefaultLogPath) // set default log path + SetEnabledLog(EnabledLog) // set default enabled log + SetEnabledConsole(EnabledConsole) // set default enabled console output } -//日志内容 -// fileName 文件名字 -// line 调用行号 -// fullPath 文件全路径 -// funcName 那个方法进行调用 +// Log content +// fileName source file name +// line line number in source file +// fullPath full path of source file +// funcName function name of caller type logContext struct { fileName string line int @@ -97,15 +97,15 @@ type logContext struct { funcName string } -//打印 -// skip=0 runtime.Caller 的调用者. -// skip=1 runtime/proc.c 的 runtime.main -// skip=2 runtime/proc.c 的 runtime.goexit +// priting +// skip=0 runtime.Caller +// skip=1 runtime/proc.c: runtime.main +// skip=2 runtime/proc.c: runtime.goexit // -//Go的普通程序的启动顺序: -//1.runtime.goexit 为真正的函数入口(并不是main.main) -//2.然后 runtime.goexit 调用 runtime.main 函数 -//3.最终 runtime.main 调用用户编写的 main.main 函数 +// Process startup procedure of a go program: +// 1.runtime.goexit is the actual entry point(NOT main.main) +// 2.then runtime.goexit calls runtime.main +// 3.finally runtime.main calls user defined main.main func callerInfo(skip int) (ctx *logContext, err error) { pc, file, line, ok := runtime.Caller(skip) if !ok { diff --git a/logger/xlog.go b/logger/xlog.go index c9d113b..11f0e02 100644 --- a/logger/xlog.go +++ b/logger/xlog.go @@ -26,7 +26,7 @@ type xLog struct { enabledConsole bool } -//create new xLog +// NewXLog create new xLog func NewXLog() *xLog { l := &xLog{logChan_Custom: make(chan chanLog, 10000)} go l.handleCustom() @@ -85,26 +85,26 @@ func (l *xLog) log(log string, logTarget string, logLevel string, isRaw bool) { } } -//SetLogPath set log path +// SetLogPath set log path func (l *xLog) SetLogPath(rootPath string) { - //设置日志根目录 + // set root path of the log file l.logRootPath = rootPath if !strings.HasSuffix(l.logRootPath, "/") { l.logRootPath = l.logRootPath + "/" } } -//SetEnabledLog set enabled log +// SetEnabledLog set enabled log func (l *xLog) SetEnabledLog(enabledLog bool) { l.enabledLog = enabledLog } -//SetEnabledConsole set enabled Console output +// SetEnabledConsole set enabled Console output func (l *xLog) SetEnabledConsole(enabled bool) { l.enabledConsole = enabled } -//处理日志内部函数 +// custom handling of the log func (l *xLog) handleCustom() { for { log := <-l.logChan_Custom @@ -132,7 +132,7 @@ func (l *xLog) writeLog(chanLog chanLog, level string) { func writeFile(logFile string, log string) { pathDir := filepath.Dir(logFile) if !file.Exist(pathDir) { - //create path + // create path err := os.MkdirAll(pathDir, 0777) if err != nil { fmt.Println("xlog.writeFile create path error ", err) diff --git a/middleware.go b/middleware.go index 792026e..348474d 100644 --- a/middleware.go +++ b/middleware.go @@ -15,10 +15,8 @@ const ( type MiddlewareFunc func() Middleware -//middleware执行优先级: -//优先级1:app级别middleware -//优先级2:group级别middleware -//优先级3:router级别middleware +// middleware execution priority: +// app > group > router // Middleware middleware interface type Middleware interface { @@ -30,7 +28,7 @@ type Middleware interface { ExistsExcludeRouter(router string) bool } -//middleware 基础类,应用可基于此实现完整Moddleware +// BaseMiddleware is the base struct, user defined middleware should extend this type BaseMiddlware struct { next Middleware excludeRouters map[string]struct{} @@ -63,7 +61,7 @@ func (bm *BaseMiddlware) Next(ctx Context) error { return httpCtx.Handler()(ctx) } } else { - //check exclude config + // check exclude config if ctx.RouterNode().Node().hasExcludeMiddleware && bm.next.HasExclude() { if bm.next.ExistsExcludeRouter(ctx.RouterNode().Node().fullPath) { return bm.next.Next(ctx) @@ -121,7 +119,6 @@ func (x *xMiddleware) Handle(ctx Context) error { return x.Next(ctx) } -//请求日志中间件 type RequestLogMiddleware struct { BaseMiddlware } @@ -153,7 +150,7 @@ func (m *RequestLogMiddleware) Handle(ctx Context) error { return err } -//get default log string +// get default log string func logContext(ctx Context, timetaken uint64) string { var reqbytelen, resbytelen, method, proto, status, userip string if ctx != nil { @@ -176,7 +173,6 @@ func logContext(ctx Context, timetaken uint64) string { return log } -// TimeoutHookMiddleware 超时钩子中间件 type TimeoutHookMiddleware struct { BaseMiddlware HookHandle StandardHandle @@ -193,7 +189,7 @@ func (m *TimeoutHookMiddleware) Handle(ctx Context) error { begin = beginVal.(time.Time) } } - //Do next + // Do next err := m.Next(ctx) if m.HookHandle != nil { realDuration := time.Now().Sub(begin) diff --git a/module.go b/module.go index 1b0fbf6..ccf8159 100644 --- a/module.go +++ b/module.go @@ -4,9 +4,9 @@ package dotweb // it will be no effect when websocket request or use offline mode type HttpModule struct { Name string - //响应请求时作为 HTTP 执行管线链中的第一个事件发生 + // OnBeginRequest is the first event in the execution chain OnBeginRequest func(Context) - //响应请求时作为 HTTP 执行管线链中的最后一个事件发生。 + // OnEndRequest is the last event in the execution chain OnEndRequest func(Context) } diff --git a/render.go b/render.go index 45e142e..f4b6830 100644 --- a/render.go +++ b/render.go @@ -73,7 +73,7 @@ func (r *innerRenderer) parseFiles(fileNames ...string) (*template.Template, err var t *template.Template var exists bool if r.enabledCache { - //check from chach + // check from chach t, exists = r.parseFilesFromCache(filesCacheKey) } if !exists { diff --git a/request.go b/request.go index c918516..e7c252f 100644 --- a/request.go +++ b/request.go @@ -19,7 +19,7 @@ type Request struct { requestID string } -//reset response attr +// reset response attr func (req *Request) reset(r *http.Request, ctx *HttpContext) { req.Request = r req.isReadBody = false @@ -44,17 +44,17 @@ func (req *Request) RequestID() string { return req.requestID } -// QueryStrings 返回Get请求方式下查询字符串map表示 +// QueryStrings parses RawQuery and returns the corresponding values. func (req *Request) QueryStrings() url.Values { return req.URL.Query() } -// RawQuery 获取原始查询字符串 +// RawQuery returns the original query string func (req *Request) RawQuery() string { return req.URL.RawQuery } -// QueryString 根据指定key获取在Get请求中对应参数值 +// QueryString returns the first value associated with the given key. func (req *Request) QueryString(key string) string { return req.URL.Query().Get(key) } diff --git a/response.go b/response.go index 810c4cb..ce7bca5 100644 --- a/response.go +++ b/response.go @@ -54,7 +54,7 @@ func (r *Response) SetWriter(w http.ResponseWriter) *Response { return r } -//HttpCode return http code format int +// HttpCode return http code format int func (r *Response) HttpCode() int { return r.Status } @@ -104,7 +104,7 @@ func (r *Response) Write(code int, b []byte) (n int, err error) { return } -//stop current response +// End stop current response func (r *Response) End() { r.isEnd = true } @@ -123,7 +123,7 @@ func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) { return r.writer.(http.Hijacker).Hijack() } -//reset response attr +// reset response attr func (r *Response) reset(w http.ResponseWriter) { r.writer = w r.header = w.Header() @@ -133,7 +133,7 @@ func (r *Response) reset(w http.ResponseWriter) { r.committed = false } -//reset response attr +// reset response attr func (r *Response) release() { r.writer = nil r.header = nil @@ -143,7 +143,8 @@ func (r *Response) release() { r.committed = false } -/*gzipResponseWriter*/ +// WriteHeader sends an HTTP response header with the provided +// status code. func (w *gzipResponseWriter) WriteHeader(code int) { if code == http.StatusNoContent { // Issue #489 w.ResponseWriter.Header().Del(HeaderContentEncoding) @@ -151,6 +152,7 @@ func (w *gzipResponseWriter) WriteHeader(code int) { w.ResponseWriter.WriteHeader(code) } +// Write do write data func (w *gzipResponseWriter) Write(b []byte) (int, error) { if w.Header().Get(HeaderContentType) == "" { w.Header().Set(HeaderContentType, http.DetectContentType(b)) @@ -158,10 +160,12 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) { return w.Writer.Write(b) } +// Flush do flush func (w *gzipResponseWriter) Flush() { w.Writer.(*gzip.Writer).Flush() } +// Hijack do hijack func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.ResponseWriter.(http.Hijacker).Hijack() } diff --git a/router.go b/router.go index 260decc..aac3403 100644 --- a/router.go +++ b/router.go @@ -232,7 +232,7 @@ func (r *router) ServeHTTP(ctx *HttpContext) { // Try to fix the request path if r.RedirectFixedPath { fixedPath, found := root.findCaseInsensitivePath( - //file.CleanPath(path), + // file.CleanPath(path), paths.Clean(path), r.RedirectTrailingSlash, ) @@ -269,19 +269,18 @@ func (r *router) ServeHTTP(ctx *HttpContext) { } } -//wrap HttpHandle to Handle +// wrap HttpHandle to Handle func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandle { return func(httpCtx *HttpContext) { httpCtx.handler = handler - //do features + // do features FeatureTools.InitFeatures(r.server, httpCtx) - //hijack处理 + // hijack handling if isHijack { _, hijack_err := httpCtx.Hijack() if hijack_err != nil { - //输出内容 httpCtx.Response().WriteHeader(http.StatusInternalServerError) httpCtx.Response().Header().Set(HeaderContentType, CharsetUTF8) httpCtx.WriteString(hijack_err.Error()) @@ -294,14 +293,14 @@ func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandl if err := recover(); err != nil { errmsg = exception.CatchError("HttpServer::RouterHandle", LogTarget_HttpServer, err) - //handler the exception + // handler the exception if r.server.DotApp.ExceptionHandler != nil { r.server.DotApp.ExceptionHandler(httpCtx, fmt.Errorf("%v", err)) } - //if set enabledLog, take the error log + // if set enabledLog, take the error log if logger.EnabledLog { - //记录访问日志 + // record access log headinfo := fmt.Sprintln(httpCtx.Response().Header()) logJson := LogJson{ RequestUrl: httpCtx.Request().RequestURI, @@ -312,19 +311,19 @@ func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandl logger.Logger().Error(logString, LogTarget_HttpServer) } - //增加错误计数 + // Increment error count core.GlobalState.AddErrorCount(httpCtx.Request().Path(), fmt.Errorf("%v", err), 1) } FeatureTools.ReleaseFeatures(r.server, httpCtx) - //cancle Context + // cancle Context if httpCtx.cancle != nil { httpCtx.cancle() } }() - //do mock, special, mock will ignore all middlewares + // do mock, special, mock will ignore all middlewares if r.server.DotApp.Mock != nil && r.server.DotApp.Mock.CheckNeedMock(httpCtx) { r.server.DotApp.Mock.Do(httpCtx) if httpCtx.isEnd { @@ -332,13 +331,8 @@ func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandl } } - //处理用户handle + // process user defined handle var ctxErr error - //if len(r.server.DotApp.Middlewares) > 0 { - // ctxErr = r.server.DotApp.Middlewares[0].Handle(httpCtx) - //} else { - // ctxErr = handler(httpCtx) - //} if len(httpCtx.routerNode.AppMiddlewares()) > 0 { ctxErr = httpCtx.routerNode.AppMiddlewares()[0].Handle(httpCtx) @@ -347,10 +341,10 @@ func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandl } if ctxErr != nil { - //handler the exception + // handler the exception if r.server.DotApp.ExceptionHandler != nil { r.server.DotApp.ExceptionHandler(httpCtx, ctxErr) - //增加错误计数 + // increment error count core.GlobalState.AddErrorCount(httpCtx.Request().Path(), ctxErr, 1) } } @@ -358,7 +352,7 @@ func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandl } } -//wrap fileHandler to httprouter.Handle +// wrap fileHandler to httprouter.Handle func (r *router) wrapFileHandle(fileHandler http.Handler) RouterHandle { return func(httpCtx *HttpContext) { httpCtx.handler = transStaticFileHandler(fileHandler) @@ -444,15 +438,15 @@ func (r *router) RegisterRoute(routeMethod string, path string, handle HttpHandl return nil } - //websocket mode,use default httpserver + // websocket mode,use default httpserver if routeMethod == RouteMethod_WebSocket { http.Handle(realPath, websocket.Handler(r.wrapWebSocketHandle(handle))) } else { - //hijack mode,use get and isHijack = true + // hijack mode,use get and isHijack = true if routeMethod == RouteMethod_HiJack { r.add(RouteMethod_GET, realPath, r.wrapRouterHandle(handle, true)) } else if routeMethod == RouteMethod_Any { - //All GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS mode + // All GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS mode r.add(RouteMethod_HEAD, realPath, r.wrapRouterHandle(handle, false)) r.add(RouteMethod_GET, realPath, r.wrapRouterHandle(handle, false)) r.add(RouteMethod_POST, realPath, r.wrapRouterHandle(handle, false)) @@ -461,18 +455,18 @@ func (r *router) RegisterRoute(routeMethod string, path string, handle HttpHandl r.add(RouteMethod_PATCH, realPath, r.wrapRouterHandle(handle, false)) r.add(RouteMethod_OPTIONS, realPath, r.wrapRouterHandle(handle, false)) } else { - //Single GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS mode + // Single GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS mode r.add(routeMethod, realPath, r.wrapRouterHandle(handle, false)) node = r.getNode(routeMethod, realPath) } } logger.Logger().Debug("DotWeb:Router:RegisterRoute success ["+routeMethod+"] ["+realPath+"] ["+handleName+"]", LogTarget_HttpServer) - //if set auto-head, add head router - //only enabled in hijack\GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS + // if set auto-head, add head router + // only enabled in hijack\GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS if r.server.ServerConfig().EnabledAutoHEAD { if routeMethod == RouteMethod_WebSocket { - //Nothing to do + // Nothing to do } else if routeMethod == RouteMethod_HiJack { r.add(RouteMethod_HEAD, realPath, r.wrapRouterHandle(handle, true)) logger.Logger().Debug("DotWeb:Router:RegisterRoute AutoHead success ["+RouteMethod_HEAD+"] ["+realPath+"] ["+handleName+"]", LogTarget_HttpServer) @@ -482,11 +476,11 @@ func (r *router) RegisterRoute(routeMethod string, path string, handle HttpHandl } } - //if set auto-options, add options router - //only enabled in hijack\GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS + // if set auto-options, add options router + // only enabled in hijack\GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS if r.server.ServerConfig().EnabledAutoOPTIONS { if routeMethod == RouteMethod_WebSocket { - //Nothing to do + // Nothing to do } else if routeMethod == RouteMethod_HiJack { r.add(RouteMethod_OPTIONS, realPath, r.wrapRouterHandle(handle, true)) logger.Logger().Debug("DotWeb:Router:RegisterRoute AutoOPTIONS success ["+RouteMethod_OPTIONS+"] ["+realPath+"] ["+handleName+"]", LogTarget_HttpServer) @@ -509,7 +503,7 @@ func (r *router) ServerFile(path string, fileroot string) RouterNode { if len(realPath) < 2 { panic("path length must be greater than or equal to 2") } - if realPath[len(realPath)-2:] == "/*" { //fixed for #125 + if realPath[len(realPath)-2:] == "/*" { // fixed for #125 realPath = realPath + "filepath" } if len(realPath) < 10 || realPath[len(realPath)-10:] != "/*filepath" { @@ -556,7 +550,7 @@ func (r *router) add(method, path string, handle RouterHandle, m ...Middleware) root = new(Node) r.Nodes[method] = root } - //fmt.Println("Handle => ", method, " - ", *root, " - ", path) + // fmt.Println("Handle => ", method, " - ", *root, " - ", path) outnode = root.addRoute(path, handle, m...) outnode.fullPath = path r.allRouterExpress[method+routerExpressSplit+path] = struct{}{} @@ -601,10 +595,10 @@ func (r *router) allowed(path, reqMethod string) (allow string) { return } -//wrap HttpHandle to websocket.Handle +// wrap HttpHandle to websocket.Handle func (r *router) wrapWebSocketHandle(handler HttpHandle) websocket.Handler { return func(ws *websocket.Conn) { - //get from pool + // get from pool req := r.server.pool.request.Get().(*Request) httpCtx := r.server.pool.context.Get().(*HttpContext) httpCtx.reset(nil, req, r.server, nil, nil, handler) @@ -620,7 +614,7 @@ func (r *router) wrapWebSocketHandle(handler HttpHandle) websocket.Handler { if err := recover(); err != nil { errmsg = exception.CatchError("httpserver::WebsocketHandle", LogTarget_HttpServer, err) - //记录访问日志 + // record access log headinfo := fmt.Sprintln(httpCtx.webSocket.Request().Header) logJson := LogJson{ RequestUrl: httpCtx.webSocket.Request().RequestURI, @@ -630,17 +624,17 @@ func (r *router) wrapWebSocketHandle(handler HttpHandle) websocket.Handler { logString := jsonutil.GetJsonString(logJson) logger.Logger().Error(logString, LogTarget_HttpServer) - //增加错误计数 + // increment error count core.GlobalState.AddErrorCount(httpCtx.Request().Path(), fmt.Errorf("%v", err), 1) } timetaken := int64(time.Now().Sub(startTime) / time.Millisecond) - //HttpServer Logging + // HttpServer Logging logger.Logger().Debug(httpCtx.Request().Url()+" "+logWebsocketContext(httpCtx, timetaken), LogTarget_HttpRequest) - //release request + // release request req.release() r.server.pool.request.Put(req) - //release context + // release context httpCtx.release() r.server.pool.context.Put(httpCtx) }() @@ -662,7 +656,7 @@ func (r *router) existsRouter(method, path string) bool { return exists } -//get default log string +// get default log string func logWebsocketContext(ctx Context, timetaken int64) string { var reqbytelen, resbytelen, method, proto, status, userip string if ctx != nil { diff --git a/router_test.go b/router_test.go index 7746b92..d6e9a9b 100644 --- a/router_test.go +++ b/router_test.go @@ -25,7 +25,6 @@ func TestRouter_ServeHTTP(t *testing.T) { r.ServeHTTP(context) } -// func TestWrapRouterHandle(t *testing.T) { param := &InitContextParam{ t, @@ -39,7 +38,7 @@ func TestWrapRouterHandle(t *testing.T) { app := New() server := app.HttpServer router := server.Router().(*router) - //use default config + // use default config server.SetSessionConfig(session.NewDefaultRuntimeConfig()) handle := router.wrapRouterHandle(Index, false) @@ -58,7 +57,7 @@ func TestLogWebsocketContext(t *testing.T) { log := logWebsocketContext(context, time.Now().Unix()) t.Log("logContext:", log) - //test.NotNil(t,log) + // test.NotNil(t,log) test.Equal(t, "", "") } diff --git a/server.go b/server.go index 2ff8c76..420c9af 100644 --- a/server.go +++ b/server.go @@ -24,7 +24,6 @@ const ( ) type ( - //HttpServer定义 HttpServer struct { stdServer *http.Server router Router @@ -39,10 +38,9 @@ type ( render Renderer offline bool Features *feature.Feature - virtualPath string //virtual path when deploy on no root path + virtualPath string // virtual path when deploy on no root path } - //pool定义 pool struct { request sync.Pool response sync.Pool @@ -74,7 +72,7 @@ func NewHttpServer() *HttpServer { binder: newBinder(), Features: &feature.Feature{}, } - //设置router + // setup router server.router = NewRouter(server) server.stdServer = &http.Server{Handler: server} return server @@ -82,13 +80,13 @@ func NewHttpServer() *HttpServer { // initConfig init config from app config func (server *HttpServer) initConfig() { - //CROS Config + // CROS Config if server.ServerConfig().EnabledAutoCORS { server.Features.SetEnabledCROS() } server.SetEnabledGzip(server.ServerConfig().EnabledGzip) - //VirtualPath config + // VirtualPath config if server.virtualPath == "" { server.virtualPath = server.ServerConfig().VirtualPath } @@ -133,7 +131,7 @@ func (server *HttpServer) ListenAndServe(addr string) error { // ListenAndServeTLS always returns a non-nil error. func (server *HttpServer) ListenAndServeTLS(addr string, certFile, keyFile string) error { server.stdServer.Addr = addr - //check tls config + // check tls config if !file.Exist(certFile) { logger.Logger().Error("DotWeb:HttpServer ListenAndServeTLS ["+addr+","+certFile+","+keyFile+"] error => Server EnabledTLS is true, but TLSCertFile not exists", LogTarget_HttpServer) panic("Server EnabledTLS is true, but TLSCertFile not exists") @@ -151,19 +149,18 @@ func (server *HttpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { core.GlobalState.AddCurrentRequest(1) defer core.GlobalState.SubCurrentRequest(1) - //针对websocket与调试信息特殊处理 + // special handling for websocket and debugging if checkIsWebSocketRequest(req) { http.DefaultServeMux.ServeHTTP(w, req) - //增加状态计数 core.GlobalState.AddRequestCount(req.URL.Path, defaultHttpCode, 1) } else { - //设置header信息 + // setup header w.Header().Set(HeaderServer, DefaultServerName) - //处理维护 + // maintenance mode if server.IsOffline() { server.DotApp.OfflineServer.ServeHTTP(w, req) } else { - //get from pool + // get from pool response := server.pool.response.Get().(*Response) request := server.pool.request.Get().(*Request) httpCtx := server.pool.context.Get().(*HttpContext) @@ -171,7 +168,7 @@ func (server *HttpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { response.reset(w) request.reset(req, httpCtx) - //处理前置Module集合 + // process OnBeginRequest of modules for _, module := range server.Modules { if module.OnBeginRequest != nil { module.OnBeginRequest(httpCtx) @@ -182,23 +179,21 @@ func (server *HttpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { server.Router().ServeHTTP(httpCtx) } - //处理后置Module集合 + // process OnEndRequest of modules for _, module := range server.Modules { if module.OnEndRequest != nil { module.OnEndRequest(httpCtx) } } - //增加状态计数 core.GlobalState.AddRequestCount(httpCtx.Request().Path(), httpCtx.Response().HttpCode(), 1) - - //release response + // release response response.release() server.pool.response.Put(response) - //release request + // release request request.release() server.pool.request.Put(request) - //release context + // release context httpCtx.release() server.pool.context.Put(httpCtx) } @@ -240,7 +235,7 @@ func (server *HttpServer) IndexPage() string { // SetSessionConfig set session store config func (server *HttpServer) SetSessionConfig(storeConfig *session.StoreConfig) { - //sync session config + // sync session config server.SessionConfig().Timeout = storeConfig.Maxlifetime server.SessionConfig().SessionMode = storeConfig.StoreName server.SessionConfig().ServerIP = storeConfig.ServerIP @@ -261,10 +256,10 @@ func (server *HttpServer) InitSessionManager() { storeConfig.CookieName = server.SessionConfig().CookieName if server.sessionManager == nil { - //设置Session + // setup session server.lock_session.Lock() if manager, err := session.NewDefaultSessionManager(storeConfig); err != nil { - //panic error with create session manager + // panic error with create session manager panic(err.Error()) } else { server.sessionManager = manager @@ -274,7 +269,7 @@ func (server *HttpServer) InitSessionManager() { logger.Logger().Debug("DotWeb:HttpServer InitSessionManager ["+jsonutil.GetJsonString(storeConfig)+"]", LogTarget_HttpServer) } -// setDotApp 关联当前HttpServer实例对应的DotServer实例 +// setDotApp associates the dotApp to the current HttpServer func (server *HttpServer) setDotApp(dotApp *DotWeb) { server.DotApp = dotApp } @@ -401,25 +396,25 @@ func (server *HttpServer) SetEnabledRequestID(isEnabled bool) { logger.Logger().Debug("DotWeb:HttpServer SetEnabledRequestID ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer) } -// SetEnabledListDir 设置是否允许目录浏览,默认为false +// SetEnabledListDir set whether to allow listing of directories, default is false func (server *HttpServer) SetEnabledListDir(isEnabled bool) { server.ServerConfig().EnabledListDir = isEnabled logger.Logger().Debug("DotWeb:HttpServer SetEnabledListDir ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer) } -// SetEnabledSession 设置是否启用Session,默认为false +// SetEnabledSession set whether to enable session, default is false func (server *HttpServer) SetEnabledSession(isEnabled bool) { server.SessionConfig().EnabledSession = isEnabled logger.Logger().Debug("DotWeb:HttpServer SetEnabledSession ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer) } -// SetEnabledGzip 设置是否启用gzip,默认为false +// SetEnabledGzip set whether to enable gzip, default is false func (server *HttpServer) SetEnabledGzip(isEnabled bool) { server.ServerConfig().EnabledGzip = isEnabled logger.Logger().Debug("DotWeb:HttpServer SetEnabledGzip ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer) } -// SetEnabledBindUseJsonTag 设置bind是否启用json标签,默认为false, fixed for issue #91 +// SetEnabledBindUseJsonTag set whethr to enable json tab on Bind, default is false func (server *HttpServer) SetEnabledBindUseJsonTag(isEnabled bool) { server.ServerConfig().EnabledBindUseJsonTag = isEnabled logger.Logger().Debug("DotWeb:HttpServer SetEnabledBindUseJsonTag ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer) @@ -455,7 +450,7 @@ func (server *HttpServer) SetEnabledStaticFileMiddleware(isEnabled bool) { logger.Logger().Debug("DotWeb:HttpServer SetEnabledStaticFileMiddleware ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer) } -// RegisterModule 添加处理模块 +// RegisterModule add HttpModule func (server *HttpServer) RegisterModule(module *HttpModule) { server.Modules = append(server.Modules, module) logger.Logger().Debug("DotWeb:HttpServer RegisterModule ["+module.Name+"]", LogTarget_HttpServer) @@ -467,8 +462,8 @@ type LogJson struct { HttpBody string } -//check request is the websocket request -//check Connection contains upgrade +// check request is the websocket request +// check Connection contains upgrade func checkIsWebSocketRequest(req *http.Request) bool { if strings.Index(strings.ToLower(req.Header.Get("Connection")), "upgrade") >= 0 { return true @@ -476,7 +471,7 @@ func checkIsWebSocketRequest(req *http.Request) bool { return false } -//check request is startwith /debug/ +// check request is startwith /debug/ func checkIsDebugRequest(req *http.Request) bool { if strings.Index(req.RequestURI, "/debug/") == 0 { return true diff --git a/server_test.go b/server_test.go index 3289c29..c1fb01c 100644 --- a/server_test.go +++ b/server_test.go @@ -7,7 +7,7 @@ import ( "github.com/devfeel/dotweb/test" ) -//check httpServer +// check httpServer func TestNewHttpServer(t *testing.T) { server := NewHttpServer() @@ -24,27 +24,25 @@ func TestNewHttpServer(t *testing.T) { test.NotNil(t, server.pool.response) test.Equal(t, false, server.IsOffline()) - //t.Log("is offline:",server.IsOffline()) + // t.Log("is offline:",server.IsOffline()) } -//session manager用来设置gc? -//总感觉和名字不是太匹配 func TestSesionConfig(t *testing.T) { server := NewHttpServer() server.DotApp = New() - //use default config + // use default config server.SetSessionConfig(session.NewDefaultRuntimeConfig()) - //init + // init server.InitSessionManager() - //get session + // get session sessionManager := server.GetSessionManager() - //EnabledSession flag is false + // EnabledSession flag is false test.Nil(t, sessionManager) - //switch EnabledSession flag + // switch EnabledSession flag server.SessionConfig().EnabledSession = true sessionManager = server.GetSessionManager() diff --git a/servers/offlineserver.go b/servers/offlineserver.go index 1e45994..38d643c 100644 --- a/servers/offlineserver.go +++ b/servers/offlineserver.go @@ -27,15 +27,14 @@ func (server *OfflineServer) SetOffline(offline bool, offlineText string, offlin server.offlineText = offlineText } -//ServeHTTP makes the httprouter implement the http.Handler interface. +// ServeHTTP makes the httprouter implement the http.Handler interface. func (server *OfflineServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { - //处理维护 + // maintenance mode if server.offline { - //url优先 + // prefer url if server.offlineUrl != "" { http.Redirect(w, req, server.offlineUrl, http.StatusMovedPermanently) } else { - //输出内容 if server.offlineText == "" { server.offlineText = DefaultOfflineText } diff --git a/servers/server.go b/servers/server.go index e24e377..7eb93b0 100644 --- a/servers/server.go +++ b/servers/server.go @@ -3,10 +3,10 @@ package servers import "net/http" type Server interface { - //ServeHTTP make sure request can be handled correctly + // ServeHTTP make sure request can be handled correctly ServeHTTP(w http.ResponseWriter, req *http.Request) - //SetOffline set server offline config + // SetOffline set server offline config SetOffline(offline bool, offlineText string, offlineUrl string) - //IsOffline check server is set offline state + // IsOffline check server is set offline state IsOffline() bool } diff --git a/session/session.go b/session/session.go index 7c6d457..6d3b5e8 100644 --- a/session/session.go +++ b/session/session.go @@ -12,8 +12,8 @@ import ( ) const ( - DefaultSessionGCLifeTime = 60 //second - DefaultSessionMaxLifeTime = 20 * 60 //second + DefaultSessionGCLifeTime = 60 // second + DefaultSessionMaxLifeTime = 20 * 60 // second DefaultSessionCookieName = "dotweb_sessionId" DefaultSessionLength = 20 SessionMode_Runtime = "runtime" @@ -28,18 +28,18 @@ type ( SessionExist(sessionId string) bool SessionUpdate(state *SessionState) error SessionRemove(sessionId string) error - SessionCount() int //get all active session length - SessionGC() int //gc session and return out of date state num + SessionCount() int // get all active session length + SessionGC() int // gc session and return out of date state num } - //session config info + // session config info StoreConfig struct { StoreName string - Maxlifetime int64 //session life time, with second - CookieName string //custom cookie name which sessionid store - ServerIP string //if use redis, connection string, like "redis://:password@10.0.1.11:6379/0" - BackupServerUrl string //if use redis, if ServerIP is down, use this server, like "redis://:password@10.0.1.11:6379/0" - StoreKeyPre string //if use redis, set custom redis key-pre; default is dotweb:session: + Maxlifetime int64 // session life time, with second + CookieName string // custom cookie name which sessionid store + ServerIP string // if use redis, connection string, like "redis://:password@10.0.1.11:6379/0" + BackupServerUrl string // if use redis, if ServerIP is down, use this server, like "redis://:password@10.0.1.11:6379/0" + StoreKeyPre string // if use redis, set custom redis key-pre; default is dotweb:session: } SessionManager struct { @@ -50,7 +50,7 @@ type ( } ) -//create new session store with store config +// GetSessionStore create new session store with store config func GetSessionStore(config *StoreConfig) SessionStore { switch config.StoreName { case SessionMode_Runtime: @@ -68,23 +68,23 @@ func GetSessionStore(config *StoreConfig) SessionStore { return nil } -//create new store with default config and use runtime store +// NewDefaultRuntimeConfig create new store with default config and use runtime store func NewDefaultRuntimeConfig() *StoreConfig { return NewStoreConfig(SessionMode_Runtime, DefaultSessionMaxLifeTime, "", "") } -//create new store with default config and use redis store +// NewDefaultRedisConfig create new store with default config and use redis store func NewDefaultRedisConfig(serverIp string) *StoreConfig { return NewStoreConfig(SessionMode_Redis, DefaultSessionMaxLifeTime, serverIp, "") } -//create new store with config and use redis store -//must set serverIp and storeKeyPre +// NewRedisConfig create new store with config and use redis store +// must set serverIp and storeKeyPre func NewRedisConfig(serverIp string, storeKeyPre string) *StoreConfig { return NewStoreConfig(SessionMode_Redis, DefaultSessionMaxLifeTime, serverIp, storeKeyPre) } -//create new store config +// NewStoreConfig create new store config func NewStoreConfig(storeName string, maxlifetime int64, serverIp string, storeKeyPre string) *StoreConfig { return &StoreConfig{ StoreName: storeName, @@ -94,12 +94,12 @@ func NewStoreConfig(storeName string, maxlifetime int64, serverIp string, storeK } } -//create new session manager with default config info +// NewDefaultSessionManager create new session manager with default config info func NewDefaultSessionManager(config *StoreConfig) (*SessionManager, error) { return NewSessionManager(DefaultSessionGCLifeTime, config) } -//create new seesion manager +// NewSessionManager create new seesion manager func NewSessionManager(gcLifetime int64, config *StoreConfig) (*SessionManager, error) { if gcLifetime <= 0 { gcLifetime = DefaultSessionGCLifeTime @@ -112,7 +112,7 @@ func NewSessionManager(gcLifetime int64, config *StoreConfig) (*SessionManager, GCLifetime: gcLifetime, storeConfig: config, } - //开启GC + // enable GC go func() { time.AfterFunc(time.Duration(manager.GCLifetime)*time.Second, func() { manager.GC() }) }() @@ -130,8 +130,8 @@ func (manager *SessionManager) StoreConfig() *StoreConfig { return manager.storeConfig } -//get session id from client -//default mode is from cookie +// GetClientSessionID get session id from client +// default mode is from cookie func (manager *SessionManager) GetClientSessionID(req *http.Request) (string, error) { cookie, err := req.Cookie(manager.storeConfig.CookieName) if err != nil { @@ -140,8 +140,8 @@ func (manager *SessionManager) GetClientSessionID(req *http.Request) (string, er if cookie.Value == "" { return "", nil } - //TODO: check client validity - //check ip & agent + // TODO: check client validity + // check ip & agent return url.QueryUnescape(cookie.Value) } @@ -153,7 +153,7 @@ func (manager *SessionManager) GetSessionState(sessionId string) (session *Sessi return session, nil } -//GC loop gc session data +// GC loop gc session data func (manager *SessionManager) GC() { num := manager.store.SessionGC() if num > 0 { diff --git a/session/sessionstate.go b/session/sessionstate.go index 324f9fc..55274ab 100644 --- a/session/sessionstate.go +++ b/session/sessionstate.go @@ -17,11 +17,11 @@ func init() { } } -//session state +// session state type SessionState struct { - sessionId string //session id - timeAccessed time.Time //last access time - values map[interface{}]interface{} //session store + sessionId string // session id + timeAccessed time.Time // last access time + values map[interface{}]interface{} // session store lock *sync.RWMutex store SessionStore } diff --git a/session/store_redis.go b/session/store_redis.go index dd7532a..99cd17a 100644 --- a/session/store_redis.go +++ b/session/store_redis.go @@ -20,12 +20,12 @@ type RedisStore struct { hystrix hystrix.Hystrix lock *sync.RWMutex // locker maxlifetime int64 - serverIp string //connection string, like "redis://:password@10.0.1.11:6379/0" - backupServerUrl string //backup connection string, like "redis://:password@10.0.1.11:6379/0" - storeKeyPre string //set custom redis key-pre; default is dotweb:session: + serverIp string // connection string, like "redis://:password@10.0.1.11:6379/0" + backupServerUrl string // backup connection string, like "redis://:password@10.0.1.11:6379/0" + storeKeyPre string // set custom redis key-pre; default is dotweb:session: } -//create new redis store +// create new redis store func NewRedisStore(config *StoreConfig) (*RedisStore, error) { store := &RedisStore{ lock: new(sync.RWMutex), @@ -36,7 +36,7 @@ func NewRedisStore(config *StoreConfig) (*RedisStore, error) { store.hystrix = hystrix.NewHystrix(store.checkRedisAlive, nil) store.hystrix.SetMaxFailedNumber(HystrixErrorCount) store.hystrix.Do() - //init redis key-pre + // init redis key-pre if config.StoreKeyPre == "" { store.storeKeyPre = defaultRedisKeyPre } else { @@ -109,13 +109,13 @@ func (store *RedisStore) sessionReExpire(state *SessionState) error { return err } -//SessionUpdate update session state in store +// SessionUpdate update session state in store func (store *RedisStore) SessionUpdate(state *SessionState) error { defer func() { - //ignore error + // ignore error if err := recover(); err != nil { fmt.Println("SessionUpdate-Redis error", err) - //TODO deal panic err + // TODO deal panic err } }() redisClient := store.getRedisClient() @@ -182,7 +182,7 @@ func (store *RedisStore) checkConnErrorAndNeedRetry(err error) bool { strings.Index(err.Error(), "No connection could be made because the target machine actively refused it") >= 0 || strings.Index(err.Error(), "A connection attempt failed because the connected party did not properly respond after a period of time") >= 0 { store.hystrix.GetCounter().Inc(1) - //if is hystrix, not to retry, because in getReadRedisClient already use backUp redis + // if is hystrix, not to retry, because in getReadRedisClient already use backUp redis if store.hystrix.IsHystrix() { return false } diff --git a/session/store_runtime.go b/session/store_runtime.go index a66984e..16a8eca 100644 --- a/session/store_runtime.go +++ b/session/store_runtime.go @@ -33,7 +33,7 @@ func (store *RuntimeStore) SessionRead(sessionId string) (*SessionState, error) } store.lock.RUnlock() - //if sessionId of state not exist, create a new state + // if sessionId of state not exist, create a new state state := NewSessionState(store, sessionId, make(map[interface{}]interface{})) store.lock.Lock() element := store.list.PushFront(state) @@ -52,18 +52,18 @@ func (store *RuntimeStore) SessionExist(sessionId string) bool { return false } -//SessionUpdate update session state in store +// SessionUpdate update session state in store func (store *RuntimeStore) SessionUpdate(state *SessionState) error { store.lock.RLock() - if element, ok := store.sessions[state.sessionId]; ok { //state has exist + if element, ok := store.sessions[state.sessionId]; ok { // state has exist go store.SessionAccess(state.sessionId) store.lock.RUnlock() - element.Value.(*SessionState).values = state.values //only assist update whole session state + element.Value.(*SessionState).values = state.values // only assist update whole session state return nil } store.lock.RUnlock() - //if sessionId of state not exist, create a new state + // if sessionId of state not exist, create a new state new_state := NewSessionState(store, state.sessionId, state.values) store.lock.Lock() new_element := store.list.PushFront(new_state) diff --git a/tree.go b/tree.go index b0e5ca0..43756e4 100644 --- a/tree.go +++ b/tree.go @@ -56,7 +56,7 @@ type Node struct { priority uint32 } -//Use registers a middleware +// Use registers a middleware func (n *Node) Use(m ...Middleware) *Node { if len(m) <= 0 { return n diff --git a/uploadfile.go b/uploadfile.go index 6f9185d..2d77eaa 100644 --- a/uploadfile.go +++ b/uploadfile.go @@ -16,7 +16,7 @@ const randFileNameLength = 12 type UploadFile struct { File multipart.File Header *multipart.FileHeader - fileExt string //file extensions + fileExt string // file extensions fileName string randomFileName string fileSize int64 @@ -28,7 +28,7 @@ func NewUploadFile(file multipart.File, header *multipart.FileHeader) *UploadFil Header: header, fileName: header.Filename, randomFileName: cryptos.GetRandString(randFileNameLength) + filepath.Ext(header.Filename), - fileExt: filepath.Ext(header.Filename), //update for issue #99 + fileExt: filepath.Ext(header.Filename), // update for issue #99 } } diff --git a/uploadfile_test.go b/uploadfile_test.go index 1530ebb..7c91b2f 100644 --- a/uploadfile_test.go +++ b/uploadfile_test.go @@ -4,10 +4,7 @@ import ( "testing" ) -// 以下为功能测试 - func Test_NewUploadFile_1(t *testing.T) { - // } func Test_FileName_1(t *testing.T) { @@ -22,7 +19,7 @@ func Test_SaveFile_1(t *testing.T) { // } -//GetFileExt +// GetFileExt func Test_GetFileExt_1(t *testing.T) { // } diff --git a/utils_test.go b/utils_test.go index 983439a..95e7bff 100644 --- a/utils_test.go +++ b/utils_test.go @@ -11,7 +11,7 @@ import ( "testing" ) -//common init context +// common init context func initContext(param *InitContextParam) *HttpContext { httpRequest := &http.Request{} context := &HttpContext{ @@ -26,7 +26,7 @@ func initContext(param *InitContextParam) *HttpContext { header["Accept-Encoding"] = []string{"gzip, deflate"} header["Accept-Language"] = []string{"en-us"} header["Foo"] = []string{"Bar", "two"} - //specify json + // specify json header["Content-Type"] = []string{param.contentType} context.request.Header = header @@ -37,7 +37,7 @@ func initContext(param *InitContextParam) *HttpContext { return context } -//init response context +// init response context func initResponseContext(param *InitContextParam) *HttpContext { context := &HttpContext{ response: &Response{}, @@ -56,7 +56,7 @@ func initResponseContext(param *InitContextParam) *HttpContext { return context } -//init request and response context +// init request and response context func initAllContext(param *InitContextParam) *HttpContext { context := &HttpContext{ response: &Response{}, @@ -73,7 +73,7 @@ func initAllContext(param *InitContextParam) *HttpContext { header["Accept-Encoding"] = []string{"gzip, deflate"} header["Accept-Language"] = []string{"en-us"} header["Foo"] = []string{"Bar", "two"} - //specify json + // specify json header["Content-Type"] = []string{param.contentType} context.request.Header = header @@ -88,18 +88,7 @@ func initAllContext(param *InitContextParam) *HttpContext { body := format(jsonStr) context.request.Request.Body = body - //var buf1 bytes.Buffer - //w := io.MultiWriter(&buf1) - w := &httpWriter{} - //gzip 开关 - /* - gw, _ := gzip.NewWriterLevel(w, DefaultGzipLevel) - writer := &gzipResponseWriter{ - ResponseWriter: w, - Writer: &gzipResponseWriter{Writer: gw, ResponseWriter: w}, - } - */ context.response = NewResponse(w) diff --git a/version.MD b/version.MD index 2f8b019..458723b 100644 --- a/version.MD +++ b/version.MD @@ -1,5 +1,10 @@ ## dotweb版本记录: +#### Version 1.5.9.3 +* Translate Chinse to English +* Update by @yangbor +* 2018-12-28 10:00 + #### Version 1.5.9.2 * Fix typo and translate Chinse to English * Reformat code diff --git a/websocket.go b/websocket.go index 9f123f5..154df7e 100644 --- a/websocket.go +++ b/websocket.go @@ -10,17 +10,17 @@ type WebSocket struct { Conn *websocket.Conn } -//get http request +// Request get http request func (ws *WebSocket) Request() *http.Request { return ws.Conn.Request() } -//send message from websocket.conn +// SendMessage send message from websocket.conn func (ws *WebSocket) SendMessage(msg string) error { return websocket.Message.Send(ws.Conn, msg) } -//read message from websocket.conn +// ReadMessage read message from websocket.conn func (ws *WebSocket) ReadMessage() (string, error) { str := "" err := websocket.Message.Receive(ws.Conn, &str)