Skip to content

Commit e2f777a

Browse files
committed
Utils switches to github.com/henrylee2cn/goutil
1 parent 4ea43e0 commit e2f777a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+312
-6635
lines changed

README.md

+8-8
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,16 @@ HTTPS/HTTP2(Let's Encrypt TLS on UNIX socket) | `unix_letsencrypt`
7272
HTTP(UNIX socket) | `unix_http`
7373
HTTPS/HTTP2(TLS on UNIX socket) | `unix_https`
7474

75-
- Support single-service & single-listener, single-service & multi-listener, multi-service & multi-listener and so on. The configuration of multiple services is independent of each other.
75+
- Support single-service & single-listener, single-service & multi-listener, multi-service & multi-listener and so on. The config of multiple services is independent of each other.
7676
- The high-performance router based on `httprouter` supports both chain and tree registration styles; supports flexible static file router (such as DirFS, RenderFS, MarkdownFS, etc.).
7777
- Support graceful shutdown and rebooting, provide fay tools which has new projects, hot compilation , meta programming function.
7878
- Use the most powerful `pongo2` as the HTML rendering engine.
7979
- Support near-LRU memory caching. (mainly used for static file cache)
8080
- Support cross-platform color log system, and has two output interface(console and file).
8181
- Support session management.
82-
- Support global gzip compression configuration.
82+
- Support global gzip compression config.
8383
- Support XSRF security filtering.
84-
- Most features try to use simple ini configurations to avoid unnecessary recompilation, and these profiles can be automatically assigned default values.
84+
- Most features try to use simple ini configs to avoid unnecessary recompilation, and these profiles can be automatically assigned default values.
8585
- Provide `gorm`, ` xorm`, `sqlx`, ` directSQL`, `Websocket`, ` ini`, `http client` and many other commonly used expansion packages.
8686

8787
![faygo handler multi-usage](https://github.com/henrylee2cn/faygo/raw/master/doc/MultiUsage.png)
@@ -281,22 +281,22 @@ kill -USR2 [pid]
281281

282282
## Configuration
283283

284-
- Each instance of the application has a single configuration (file name format `config/{appname}[_{version}].ini`). Refer to the following:
284+
- Each instance of the application has a single config (file name format `config/{appname}[_{version}].ini`). Refer to the following:
285285

286286
```
287287
net_types = http|https # List of network type: http | https | unix_http | unix_https | letsencrypt | unix_letsencrypt
288288
addrs = 0.0.0.0:80|0.0.0.0:443 # List of multiple listening addresses
289289
tls_certfile = # TLS certificate file path
290290
tls_keyfile = # TLS key file path
291291
letsencrypt_dir = # Let's Encrypt TLS certificate cache directory
292-
unix_filemode = 438 # File permissions for UNIX listener (438 equivalent to 0666)
292+
unix_filemode = 0666 # File permissions for UNIX listener, requires octal number
293293
read_timeout = 0s # Maximum duration for reading the full; ns|µs|ms|s|m|h request (including body)
294294
write_timeout = 0s # Maximum duration for writing the full; ns|µs|ms|s|m|h response (including body)
295295
multipart_maxmemory_mb = 32 # Maximum size of memory that can be used when receiving uploaded files
296296
slow_response_threshold= 0s # When response time > slow_response_threshold, log level = 'WARNING'; 0 means not limited; ns|µs|ms|s|m|h
297297
print_body = false # Form requests are printed in JSON format, but other types are printed as-is
298298
299-
[router] # Routing configuration section
299+
[router] # Routing config section
300300
redirect_trailing_slash = true # Automatic redirection (for example, `/foo/` -> `/foo`)
301301
redirect_fixed_path = true # Tries to fix the current request path, if no handle is registered for it
302302
handle_method_not_allowed = true # Returns 405 if the requested method does not exist, otherwise returns 404
@@ -313,7 +313,7 @@ expire_second = 3600 # Expire of XSRF token
313313
enable = false # Whether enabled or not
314314
provider = memory # Data storage
315315
name = faygosessionID # The client stores the name of the cookie
316-
provider_config = # According to the different engine settings different configuration information
316+
provider_config = # According to the different engine settings different config information
317317
cookie_life_second = 0 # The default value is 0, which is the lifetime of the browser
318318
gc_life_second = 300 # The interval between triggering the GC
319319
max_life_second = 3600 # The session max lefetime
@@ -336,7 +336,7 @@ license = # The license used by the API
336336
license_url = # The URL of the protocol content page
337337
```
338338

339-
- Only one global configuration is applied (`config/__global__.ini`). Refer to the following:
339+
- Only one global config is applied (`config/__global__.ini`). Refer to the following:
340340

341341
```
342342
[cache] # Cache section

README_ZH.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ addrs = 0.0.0.0:80|0.0.0.0:443 # 多个监听地址列表
292292
tls_certfile = # TLS证书文件路径
293293
tls_keyfile = # TLS密钥文件路径
294294
letsencrypt_dir = # Let's Encrypt TLS证书缓存目录
295-
unix_filemode = 438 # UNIX listener的文件权限(438即0666)
295+
unix_filemode = 0666 # UNIX listener的文件权限,要求使用八进制
296296
read_timeout = 0s # 读取请求数据超时;ns|µs|ms|s|m|h
297297
write_timeout = 0s # 写入响应数据超时;ns|µs|ms|s|m|h
298298
multipart_maxmemory_mb = 32 # 接收上传文件时允许使用的最大内存

config.go

+29-21
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,30 @@ import (
1919
"math"
2020
"os"
2121
"sort"
22+
"strconv"
2223
"strings"
2324
"sync/atomic"
2425
"time"
2526
)
2627

2728
type (
28-
// GlobalConfig is global configuration
29+
// GlobalConfig is global config
2930
GlobalConfig struct {
3031
Cache CacheConfig `ini:"cache" comment:"Cache section"`
3132
Gzip GzipConfig `ini:"gzip" comment:"Whether enabled or not"`
3233
Log LogConfig `ini:"log" comment:"Whether enabled or not console logger"`
3334
warnMsg string `int:"-"`
3435
}
35-
// Config is the configuration information for each web instance
36+
// Config is the config information for each web instance
3637
Config struct {
3738
// RunMode string `ini:"run_mode" comment:"run mode: dev|prod"`
3839
NetTypes []string `ini:"net_types" delim:"|" comment:"List of network type: http|https|unix_http|unix_https|letsencrypt|unix_letsencrypt"`
3940
Addrs []string `ini:"addrs" delim:"|" comment:"List of multiple listening addresses"`
4041
TLSCertFile string `ini:"tls_certfile" comment:"TLS certificate file path"`
4142
TLSKeyFile string `ini:"tls_keyfile" comment:"TLS key file path"`
4243
LetsencryptDir string `ini:"letsencrypt_dir" comment:"Let's Encrypt TLS certificate cache directory"`
43-
UNIXFileMode os.FileMode `ini:"unix_filemode" comment:"File permissions for UNIX listener (438 equivalent to 0666)"`
44+
UNIXFileMode string `ini:"unix_filemode" comment:"File permissions for UNIX listener, requires octal number"`
45+
unixFileMode os.FileMode `ini:"-"`
4446
// Maximum duration for reading the full request (including body).
4547
//
4648
// This also limits the maximum duration for idle keep-alive
@@ -54,15 +56,15 @@ type (
5456
WriteTimeout time.Duration `ini:"write_timeout" comment:"Maximum duration for writing the full response (including body); ns|µs|ms|s|m|h"`
5557
MultipartMaxMemoryMB int64 `ini:"multipart_maxmemory_mb" comment:"Maximum size of memory that can be used when receiving uploaded files"`
5658
multipartMaxMemory int64 `ini:"-"`
57-
Router RouterConfig `ini:"router" comment:"Routing configuration section"`
59+
Router RouterConfig `ini:"router" comment:"Routing config section"`
5860
XSRF XSRFConfig `ini:"xsrf" comment:"XSRF security section"`
5961
Session SessionConfig `ini:"session" comment:"Session section"`
6062
SlowResponseThreshold time.Duration `ini:"slow_response_threshold" comment:"When response time > slow_response_threshold, log level = 'WARNING'; 0 means not limited; ns|µs|ms|s|m|h"`
6163
slowResponseThreshold time.Duration `ini:"-"`
6264
PrintBody bool `ini:"print_body" comment:"Form requests are printed in JSON format, but other types are printed as-is"`
6365
APIdoc APIdocConfig `ini:"apidoc" comment:"API documentation section"`
6466
}
65-
// RouterConfig is the configuration about router
67+
// RouterConfig is the config about router
6668
RouterConfig struct {
6769
// Enables automatic redirection if the current route can't be matched but a
6870
// handler for the path with (without) the trailing slash exists.
@@ -93,7 +95,7 @@ type (
9395
DefaultUpload bool `ini:"default_upload" comment:"Automatically register the default router: /upload/*filepath"`
9496
DefaultStatic bool `ini:"default_static" comment:"Automatically register the default router: /static/*filepath"`
9597
}
96-
// GzipConfig is the configuration about gzip
98+
// GzipConfig is the config about gzip
9799
GzipConfig struct {
98100
// if EnableGzip, compress response content.
99101
Enable bool `ini:"enable" comment:"Whether enabled or not"`
@@ -107,7 +109,7 @@ type (
107109
Methods []string `ini:"methods" delim:"|" comment:"List of HTTP methods to compress. If not set, only GET requests are compressed."`
108110
// StaticExtensionsToGzip []string
109111
}
110-
// CacheConfig is the configuration about cache
112+
// CacheConfig is the config about cache
111113
CacheConfig struct {
112114
// Whether to enable caching static files
113115
Enable bool `ini:"enable" comment:"Whether enabled or not"`
@@ -121,18 +123,18 @@ type (
121123
// ExpireSecond <= 0 (second) means no expire, but it can be evicted when cache is full.
122124
ExpireSecond int `ini:"expire_second" comment:"Maximum duration for caching"`
123125
}
124-
// XSRFConfig is the configuration about XSRF filter
126+
// XSRFConfig is the config about XSRF filter
125127
XSRFConfig struct {
126128
Enable bool `ini:"enable" comment:"Whether enabled or not"`
127129
Key string `ini:"key" comment:"Encryption key"`
128130
ExpireSecond int `ini:"expire_second" comment:"Expire of XSRF token"`
129131
}
130-
// SessionConfig is the configuration about session
132+
// SessionConfig is the config about session
131133
SessionConfig struct {
132134
Enable bool `ini:"enable" comment:"Whether enabled or not"`
133135
Provider string `ini:"provider" comment:"Data storage"`
134136
Name string `ini:"name" comment:"The client stores the name of the cookie"`
135-
ProviderConfig string `ini:"provider_config" comment:"According to the different engine settings different configuration information"`
137+
ProviderConfig string `ini:"provider_config" comment:"According to the different engine settings different config information"`
136138
CookieLifeSecond int `ini:"cookie_life_second" comment:"The default value is 0, which is the lifetime of the browser"`
137139
GcLifeSecond int64 `ini:"gc_life_second" comment:"The interval between triggering the GC"`
138140
MaxLifeSecond int64 `ini:"max_life_second" comment:"The session max lefetime"`
@@ -142,15 +144,15 @@ type (
142144
NameInHttpHeader string `ini:"name_in_header" comment:"The name of the header when the session ID is written to the header"`
143145
EnableSidInUrlQuery bool `ini:"enable_sid_in_urlquery" comment:"Whether to write the session ID to the URL Query params"`
144146
}
145-
// LogConfig is the configuration about log
147+
// LogConfig is the config about log
146148
LogConfig struct {
147149
ConsoleEnable bool `ini:"console_enable" comment:"Whether enabled or not console logger"`
148150
ConsoleLevel string `ini:"console_level" comment:"Console logger level: critical|error|warning|notice|info|debug"`
149151
FileEnable bool `ini:"file_enable" comment:"Whether enabled or not file logger"`
150152
FileLevel string `ini:"file_level" comment:"File logger level: critical|error|warning|notice|info|debug"`
151153
AsyncLen int `ini:"async_len" comment:"The length of asynchronous buffer, 0 means synchronization"`
152154
}
153-
// APIdocConfig is the configuration about API doc
155+
// APIdocConfig is the config about API doc
154156
APIdocConfig struct {
155157
Enable bool `ini:"enable" comment:"Whether enabled or not"`
156158
Path string `ini:"path" comment:"The URL path"`
@@ -174,7 +176,7 @@ const (
174176
defaultMultipartMaxMemoryMB = 32
175177
defaultPort = 8080
176178

177-
// The path for the configuration files
179+
// The path for the config files
178180
CONFIG_DIR = "./config/"
179181
// global config file name
180182
GLOBAL_CONFIG_FILE = "__global___.ini"
@@ -209,12 +211,12 @@ var globalConfig = func() GlobalConfig {
209211

210212
err := SyncINI(
211213
&background,
212-
func(existed bool, mustSave func() error) error {
214+
func(onecUpdateFunc func() error) error {
213215
if !(background.Log.ConsoleEnable || background.Log.FileEnable) {
214216
background.Log.ConsoleEnable = true
215217
background.warnMsg = "config: log::enable_console and log::enable_file can not be disabled at the same time, so automatically open console log."
216218
}
217-
return mustSave()
219+
return onecUpdateFunc()
218220
},
219221
filename,
220222
)
@@ -235,7 +237,7 @@ func newConfig(filename string) Config {
235237
// RunMode: RUNMODE_DEV,
236238
NetTypes: []string{NETTYPE_HTTP},
237239
Addrs: []string{addr},
238-
UNIXFileMode: 0666,
240+
UNIXFileMode: "0666",
239241
MultipartMaxMemoryMB: defaultMultipartMaxMemoryMB,
240242
Router: RouterConfig{
241243
RedirectTrailingSlash: true,
@@ -278,33 +280,39 @@ func newConfig(filename string) Config {
278280

279281
err := SyncINI(
280282
&background,
281-
func(existed bool, mustSave func() error) error {
283+
func(onecUpdateFunc func() error) error {
282284
// switch background.RunMode {
283285
// case RUNMODE_DEV, RUNMODE_PROD:
284286
// default:
285287
// panic("Please set a valid config item run_mode, refer to the following:\ndev|prod")
286288
// }
287289
if len(background.NetTypes) != len(background.Addrs) {
288-
panic("The number of configuration items `net_types` and `addrs` must be equal")
290+
panic("The number of config items `net_types` and `addrs` must be equal")
289291
}
290292
if len(background.NetTypes) == 0 {
291-
panic("The number of configuration items `net_types` and `addrs` must be greater than zero")
293+
panic("The number of config items `net_types` and `addrs` must be greater than zero")
292294
}
293295
for _, t := range background.NetTypes {
294296
switch t {
295297
case NETTYPE_HTTP, NETTYPE_UNIX_HTTP, NETTYPE_HTTPS, NETTYPE_UNIX_HTTPS, NETTYPE_LETSENCRYPT, NETTYPE_UNIX_LETSENCRYPT:
296298
default:
297-
panic("Please set a valid config item `net_types`, refer to the following:" + __netTypes__ + "\n")
299+
panic("Please set a valid config item `net_types`, refer to the following:" + __netTypes__)
298300
}
299301
}
302+
fileMode, err := strconv.ParseUint(background.UNIXFileMode, 8, 32)
303+
if err != nil {
304+
panic("The config item `unix_filemode` is not a valid octal number:" + background.UNIXFileMode)
305+
}
306+
background.unixFileMode = os.FileMode(fileMode)
307+
background.UNIXFileMode = fmt.Sprintf("%#o", fileMode)
300308
background.multipartMaxMemory = background.MultipartMaxMemoryMB * MB
301309
if background.SlowResponseThreshold <= 0 {
302310
background.slowResponseThreshold = time.Duration(math.MaxInt64)
303311
} else {
304312
background.slowResponseThreshold = background.SlowResponseThreshold
305313
}
306314
background.APIdoc.Comb()
307-
return mustSave()
315+
return onecUpdateFunc()
308316
},
309317
filename,
310318
)

context.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import (
2828

2929
"github.com/henrylee2cn/faygo/logging"
3030
"github.com/henrylee2cn/faygo/session"
31-
"github.com/henrylee2cn/faygo/utils"
3231
)
3332

3433
// Headers
@@ -152,7 +151,7 @@ func (ctx *Context) XSRFToken(specifiedExpiration ...int) string {
152151
token, ok := ctx.SecureCookieParam(ctx.frame.config.XSRF.Key, "_xsrf")
153152
if !ok {
154153
ctx._xsrfTokenReset = true
155-
token = utils.RandomString(32)
154+
token = RandomString(32)
156155
if len(specifiedExpiration) > 0 && specifiedExpiration[0] > 0 {
157156
ctx.xsrfExpire = specifiedExpiration[0]
158157
} else if ctx.xsrfExpire == 0 {

context_input.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ import (
3636
"strings"
3737

3838
"github.com/henrylee2cn/faygo/apiware"
39-
"github.com/henrylee2cn/faygo/utils"
4039
)
4140

4241
// Regexes for checking the accept headers
@@ -566,7 +565,7 @@ func (ctx *Context) SaveFile(key string, cover bool, newfname ...string) (savedF
566565
// If the file with the same name exists, add the suffix of the serial number
567566
idx := strings.LastIndex(fullname, filepath.Ext(fullname))
568567
_fullname := fullname
569-
for i := 2; utils.FileExists(_fullname) && !cover; i++ {
568+
for i := 2; FileExists(_fullname) && !cover; i++ {
570569
_fullname = fmt.Sprintf("%s(%d)%s", fullname[:idx], i, fullname[idx:])
571570
}
572571
fullname = _fullname
@@ -642,7 +641,7 @@ func (ctx *Context) SaveFiles(key string, cover bool, newfname ...string) (saved
642641
if num >= 2 {
643642
_fullname = fmt.Sprintf("%s(%d)%s", fullname[:idx], num, fullname[idx:])
644643
}
645-
for utils.FileExists(_fullname) && !cover {
644+
for FileExists(_fullname) && !cover {
646645
num++
647646
_fullname = fmt.Sprintf("%s(%d)%s", fullname[:idx], num, fullname[idx:])
648647
}

0 commit comments

Comments
 (0)