mirror of
https://gitee.com/johng/gf.git
synced 2024-11-30 03:07:45 +08:00
Merge branch 'master' of https://github.com/gogf/gf into gjson_example
This commit is contained in:
commit
3a1cd3d588
@ -171,10 +171,13 @@ func (r *Ring) Link(s *Ring) *Ring {
|
||||
//
|
||||
func (r *Ring) Unlink(n int) *Ring {
|
||||
r.mu.Lock()
|
||||
r.ring = r.ring.Unlink(n)
|
||||
resultRing := r.ring.Unlink(n)
|
||||
r.dirty.Set(true)
|
||||
r.mu.Unlock()
|
||||
return r
|
||||
resultGRing := New(resultRing.Len())
|
||||
resultGRing.ring = resultRing
|
||||
resultGRing.dirty.Set(true)
|
||||
return resultGRing
|
||||
}
|
||||
|
||||
// RLockIteratorNext iterates and locks reading forward
|
||||
|
@ -7,6 +7,7 @@
|
||||
package gring_test
|
||||
|
||||
import (
|
||||
"container/ring"
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/container/gring"
|
||||
@ -137,3 +138,48 @@ func TestRing_Slice(t *testing.T) {
|
||||
t.Assert(array4, g.Slice{1, 5, 4, 3, 2})
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/1394
|
||||
func Test_Issue1394(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// gring.
|
||||
gRing := gring.New(10)
|
||||
for i := 0; i < 10; i++ {
|
||||
gRing.Put(i)
|
||||
}
|
||||
t.Logf("the length:%d", gRing.Len())
|
||||
gRingResult := gRing.Unlink(6)
|
||||
for i := 0; i < 10; i++ {
|
||||
t.Log(gRing.Val())
|
||||
gRing = gRing.Next()
|
||||
}
|
||||
t.Logf("the ring length:%d", gRing.Len())
|
||||
t.Logf("the result length:%d", gRingResult.Len())
|
||||
|
||||
// stdring
|
||||
stdRing := ring.New(10)
|
||||
for i := 0; i < 10; i++ {
|
||||
stdRing.Value = i
|
||||
stdRing = stdRing.Next()
|
||||
}
|
||||
t.Logf("the length:%d", stdRing.Len())
|
||||
stdRingResult := stdRing.Unlink(6)
|
||||
for i := 0; i < 10; i++ {
|
||||
t.Log(stdRing.Value)
|
||||
stdRing = stdRing.Next()
|
||||
}
|
||||
t.Logf("the ring length:%d", stdRing.Len())
|
||||
t.Logf("the result length:%d", stdRingResult.Len())
|
||||
|
||||
// Assertion.
|
||||
t.Assert(gRing.Len(), stdRing.Len())
|
||||
t.Assert(gRingResult.Len(), stdRingResult.Len())
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
t.Assert(stdRing.Value, gRing.Val())
|
||||
stdRing = stdRing.Next()
|
||||
gRing = gRing.Next()
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
@ -134,11 +134,12 @@ func (d *DriverMssql) parseSql(sql string) string {
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
index := 0
|
||||
keyword := strings.TrimSpace(res[index][0])
|
||||
keyword = strings.ToUpper(keyword)
|
||||
var (
|
||||
index = 0
|
||||
keyword = strings.TrimSpace(res[index][0])
|
||||
)
|
||||
index++
|
||||
switch keyword {
|
||||
switch strings.ToUpper(keyword) {
|
||||
case "SELECT":
|
||||
// LIMIT statement checks.
|
||||
if len(res) < 2 ||
|
||||
@ -150,9 +151,11 @@ func (d *DriverMssql) parseSql(sql string) string {
|
||||
break
|
||||
}
|
||||
// ORDER BY statement checks.
|
||||
selectStr := ""
|
||||
orderStr := ""
|
||||
haveOrder := gregex.IsMatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql)
|
||||
var (
|
||||
selectStr = ""
|
||||
orderStr = ""
|
||||
haveOrder = gregex.IsMatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql)
|
||||
)
|
||||
if haveOrder {
|
||||
queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql)
|
||||
if len(queryExpr) != 4 ||
|
||||
@ -283,7 +286,7 @@ LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id
|
||||
LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id =0
|
||||
WHERE d.name='%s'
|
||||
ORDER BY a.id,a.colorder`,
|
||||
strings.ToUpper(table),
|
||||
table,
|
||||
)
|
||||
structureSql, _ = gregex.ReplaceString(`[\n\r\s]+`, " ", gstr.Trim(structureSql))
|
||||
result, err = d.DoGetAll(ctx, link, structureSql)
|
||||
@ -294,8 +297,8 @@ ORDER BY a.id,a.colorder`,
|
||||
for i, m := range result {
|
||||
fields[strings.ToLower(m["Field"].String())] = &gdb.TableField{
|
||||
Index: i,
|
||||
Name: strings.ToLower(m["Field"].String()),
|
||||
Type: strings.ToLower(m["Type"].String()),
|
||||
Name: m["Field"].String(),
|
||||
Type: m["Type"].String(),
|
||||
Null: m["Null"].Bool(),
|
||||
Key: m["Key"].String(),
|
||||
Default: m["Default"].Val(),
|
||||
|
@ -13,13 +13,12 @@
|
||||
package pgsql
|
||||
|
||||
import (
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"github.com/gogf/gf/v2/container/gmap"
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
@ -180,7 +179,7 @@ FROM pg_attribute a
|
||||
left join information_schema.columns ic on ic.column_name = a.attname and ic.table_name = c.relname
|
||||
WHERE c.relname = '%s' and a.attisdropped is false and a.attnum > 0
|
||||
ORDER BY a.attnum`,
|
||||
strings.ToLower(table),
|
||||
table,
|
||||
)
|
||||
)
|
||||
if link, err = d.SlaveLink(useSchema); err != nil {
|
||||
|
@ -42,7 +42,7 @@ type Model struct {
|
||||
filter bool // Filter data and where key-value pairs according to the fields of the table.
|
||||
distinct string // Force the query to only return distinct results.
|
||||
lockInfo string // Lock for update or in shared lock.
|
||||
cacheEnabled bool // Enable sql result cache feature.
|
||||
cacheEnabled bool // Enable sql result cache feature, which is mainly for indicating cache duration(especially 0) usage.
|
||||
cacheOption CacheOption // Cache option for query statement.
|
||||
unscoped bool // Disables soft deleting features when select/delete operations.
|
||||
safe bool // If true, it clones and returns a new model object whenever operation done; or else it changes the attribute of current model.
|
||||
|
@ -504,6 +504,7 @@ func (m *Model) Having(having interface{}, args ...interface{}) *Model {
|
||||
// doGetAllBySql does the select statement on the database.
|
||||
func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, err error) {
|
||||
var (
|
||||
ok bool
|
||||
ctx = m.GetCtx()
|
||||
cacheKey = ""
|
||||
cacheObj = m.db.GetCache()
|
||||
@ -512,20 +513,18 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e
|
||||
if m.cacheEnabled && m.tx == nil {
|
||||
cacheKey = m.cacheOption.Name
|
||||
if len(cacheKey) == 0 {
|
||||
cacheKey = "gcache:" + gmd5.MustEncryptString(sql+", @PARAMS:"+gconv.String(args))
|
||||
cacheKey = "GCache:" + gmd5.MustEncryptString(sql+", @PARAMS:"+gconv.String(args))
|
||||
}
|
||||
if v, _ := cacheObj.Get(ctx, cacheKey); !v.IsNil() {
|
||||
if result, ok := v.Val().(Result); ok {
|
||||
if result, ok = v.Val().(Result); ok {
|
||||
// In-memory cache.
|
||||
return result, nil
|
||||
}
|
||||
// Other cache, it needs conversion.
|
||||
if err = json.UnmarshalUseNumber(v.Bytes(), &result); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
// Other cache, it needs conversion.
|
||||
var result Result
|
||||
if err = json.UnmarshalUseNumber(v.Bytes(), &result); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result, nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -535,7 +534,7 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e
|
||||
// Cache the result.
|
||||
if cacheKey != "" && err == nil {
|
||||
if m.cacheOption.Duration < 0 {
|
||||
if _, err := cacheObj.Remove(ctx, cacheKey); err != nil {
|
||||
if _, err = cacheObj.Remove(ctx, cacheKey); err != nil {
|
||||
intlog.Errorf(m.GetCtx(), `%+v`, err)
|
||||
}
|
||||
} else {
|
||||
@ -543,7 +542,7 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e
|
||||
if result.IsEmpty() && m.cacheOption.Force {
|
||||
result = Result{}
|
||||
}
|
||||
if err := cacheObj.Set(ctx, cacheKey, result, m.cacheOption.Duration); err != nil {
|
||||
if err = cacheObj.Set(ctx, cacheKey, result, m.cacheOption.Duration); err != nil {
|
||||
intlog.Errorf(m.GetCtx(), `%+v`, err)
|
||||
}
|
||||
}
|
||||
|
@ -156,7 +156,13 @@ func (m *Model) doWithScanStruct(pointer interface{}) error {
|
||||
if parsedTagOutput.Order != "" {
|
||||
model = model.Order(parsedTagOutput.Order)
|
||||
}
|
||||
err = model.Fields(fieldKeys).Where(relatedSourceName, relatedTargetValue).Scan(bindToReflectValue)
|
||||
// With cache feature.
|
||||
if m.cacheEnabled && m.cacheOption.Name == "" {
|
||||
model = model.Cache(m.cacheOption)
|
||||
}
|
||||
err = model.Fields(fieldKeys).
|
||||
Where(relatedSourceName, relatedTargetValue).
|
||||
Scan(bindToReflectValue)
|
||||
// It ignores sql.ErrNoRows in with feature.
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return err
|
||||
@ -263,7 +269,10 @@ func (m *Model) doWithScanStructs(pointer interface{}) error {
|
||||
if parsedTagOutput.Order != "" {
|
||||
model = model.Order(parsedTagOutput.Order)
|
||||
}
|
||||
|
||||
// With cache feature.
|
||||
if m.cacheEnabled && m.cacheOption.Name == "" {
|
||||
model = model.Cache(m.cacheOption)
|
||||
}
|
||||
err = model.Fields(fieldKeys).
|
||||
Where(relatedSourceName, relatedTargetValue).
|
||||
ScanList(pointer, fieldName, parsedTagOutput.With)
|
||||
|
@ -13,25 +13,19 @@
|
||||
// Redis Chinese Documentation: http://redisdoc.com/
|
||||
package gredis
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
)
|
||||
|
||||
// New creates and returns a redis client.
|
||||
// It creates a default redis adapter of go-redis.
|
||||
func New(config ...*Config) (*Redis, error) {
|
||||
if len(config) > 0 {
|
||||
if len(config) > 0 && config[0] != nil {
|
||||
// Redis client with go redis implements adapter from given configuration.
|
||||
return &Redis{adapter: NewAdapterGoRedis(config[0])}, nil
|
||||
}
|
||||
configFromGlobal, ok := GetConfig()
|
||||
if !ok {
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeMissingConfiguration,
|
||||
`configuration not found for creating Redis client`,
|
||||
)
|
||||
// Redis client with go redis implements adapter from package configuration.
|
||||
if configFromGlobal, ok := GetConfig(); ok {
|
||||
return &Redis{adapter: NewAdapterGoRedis(configFromGlobal)}, nil
|
||||
}
|
||||
return &Redis{adapter: NewAdapterGoRedis(configFromGlobal)}, nil
|
||||
// Redis client with empty adapter.
|
||||
return &Redis{}, nil
|
||||
}
|
||||
|
||||
// NewWithAdapter creates and returns a redis client with given adapter.
|
||||
|
@ -28,6 +28,7 @@ const (
|
||||
defaultPoolIdleTimeout = 10 * time.Second
|
||||
defaultPoolWaitTimeout = 10 * time.Second
|
||||
defaultPoolMaxLifeTime = 30 * time.Second
|
||||
defaultMaxRetries = -1
|
||||
)
|
||||
|
||||
// NewAdapterGoRedis creates and returns a redis adapter using go-redis.
|
||||
@ -37,6 +38,7 @@ func NewAdapterGoRedis(config *Config) *AdapterGoRedis {
|
||||
Addrs: gstr.SplitAndTrim(config.Address, ","),
|
||||
Password: config.Pass,
|
||||
DB: config.Db,
|
||||
MaxRetries: defaultMaxRetries,
|
||||
MinIdleConns: config.MinIdle,
|
||||
MaxConnAge: config.MaxConnLifetime,
|
||||
IdleTimeout: config.IdleTimeout,
|
||||
@ -90,4 +92,10 @@ func fillWithDefaultConfiguration(config *Config) {
|
||||
if config.MaxConnLifetime == 0 {
|
||||
config.MaxConnLifetime = defaultPoolMaxLifeTime
|
||||
}
|
||||
if config.WriteTimeout == 0 {
|
||||
config.WriteTimeout = -1
|
||||
}
|
||||
if config.ReadTimeout == 0 {
|
||||
config.ReadTimeout = -1
|
||||
}
|
||||
}
|
||||
|
@ -30,7 +30,7 @@ type Config struct {
|
||||
IdleTimeout time.Duration `json:"idleTimeout"` // Maximum idle time for connection (default is 10 seconds, not allowed to be set to 0)
|
||||
WaitTimeout time.Duration `json:"waitTimeout"` // Timed out duration waiting to get a connection from the connection pool.
|
||||
DialTimeout time.Duration `json:"dialTimeout"` // Dial connection timeout for TCP.
|
||||
ReadTimeout time.Duration `json:"readTimeout"` // Read timeout for TCP.
|
||||
ReadTimeout time.Duration `json:"readTimeout"` // Read timeout for TCP. DO NOT set it if not necessary.
|
||||
WriteTimeout time.Duration `json:"writeTimeout"` // Write timeout for TCP.
|
||||
MasterName string `json:"masterName"` // Used in Redis Sentinel mode.
|
||||
TLS bool `json:"tls"` // Specifies whether TLS should be used when connecting to the server.
|
||||
|
@ -46,6 +46,12 @@ func (r *Redis) Conn(ctx context.Context) (*RedisConn, error) {
|
||||
if r == nil {
|
||||
return nil, gerror.NewCode(gcode.CodeInvalidParameter, errorNilRedis)
|
||||
}
|
||||
if r.adapter == nil {
|
||||
return nil, gerror.NewCodef(
|
||||
gcode.CodeMissingConfiguration,
|
||||
`redis adapter not initialized, missing configuration or adapter register?`,
|
||||
)
|
||||
}
|
||||
conn, err := r.adapter.Conn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -67,8 +73,8 @@ func (r *Redis) Do(ctx context.Context, command string, args ...interface{}) (*g
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if err := conn.Close(ctx); err != nil {
|
||||
intlog.Errorf(ctx, `%+v`, err)
|
||||
if closeErr := conn.Close(ctx); closeErr != nil {
|
||||
intlog.Errorf(ctx, `%+v`, closeErr)
|
||||
}
|
||||
}()
|
||||
return conn.Do(ctx, command, args...)
|
||||
|
@ -44,8 +44,8 @@ func Test_Gzip_UnGzip(t *testing.T) {
|
||||
|
||||
func Test_Gzip_UnGzip_File(t *testing.T) {
|
||||
srcPath := gdebug.TestDataPath("gzip", "file.txt")
|
||||
dstPath1 := gfile.TempDir(gtime.TimestampNanoStr(), "gzip.zip")
|
||||
dstPath2 := gfile.TempDir(gtime.TimestampNanoStr(), "file.txt")
|
||||
dstPath1 := gfile.Temp(gtime.TimestampNanoStr(), "gzip.zip")
|
||||
dstPath2 := gfile.Temp(gtime.TimestampNanoStr(), "file.txt")
|
||||
|
||||
// Compress.
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
|
@ -29,7 +29,7 @@ func Test_ZipPath(t *testing.T) {
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// unzip to temporary dir.
|
||||
tempDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
t.Assert(gfile.Mkdir(tempDirPath), nil)
|
||||
t.Assert(gcompress.UnZipFile(dstPath, tempDirPath), nil)
|
||||
defer gfile.Remove(tempDirPath)
|
||||
@ -44,7 +44,7 @@ func Test_ZipPath(t *testing.T) {
|
||||
var (
|
||||
srcPath1 = gdebug.TestDataPath("zip", "path1", "1.txt")
|
||||
srcPath2 = gdebug.TestDataPath("zip", "path2", "2.txt")
|
||||
dstPath = gfile.TempDir(gtime.TimestampNanoStr(), "zip.zip")
|
||||
dstPath = gfile.Temp(gtime.TimestampNanoStr(), "zip.zip")
|
||||
)
|
||||
if p := gfile.Dir(dstPath); !gfile.Exists(p) {
|
||||
t.Assert(gfile.Mkdir(p), nil)
|
||||
@ -57,7 +57,7 @@ func Test_ZipPath(t *testing.T) {
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// unzip to another temporary dir.
|
||||
tempDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
t.Assert(gfile.Mkdir(tempDirPath), nil)
|
||||
err = gcompress.UnZipFile(dstPath, tempDirPath)
|
||||
t.Assert(err, nil)
|
||||
@ -77,7 +77,7 @@ func Test_ZipPath(t *testing.T) {
|
||||
var (
|
||||
srcPath1 = gdebug.TestDataPath("zip", "path1")
|
||||
srcPath2 = gdebug.TestDataPath("zip", "path2", "2.txt")
|
||||
dstPath = gfile.TempDir(gtime.TimestampNanoStr(), "zip.zip")
|
||||
dstPath = gfile.Temp(gtime.TimestampNanoStr(), "zip.zip")
|
||||
)
|
||||
if p := gfile.Dir(dstPath); !gfile.Exists(p) {
|
||||
t.Assert(gfile.Mkdir(p), nil)
|
||||
@ -90,7 +90,7 @@ func Test_ZipPath(t *testing.T) {
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
// unzip to another temporary dir.
|
||||
tempDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
t.Assert(gfile.Mkdir(tempDirPath), nil)
|
||||
err = gcompress.UnZipFile(dstPath, tempDirPath)
|
||||
t.Assert(err, nil)
|
||||
@ -121,7 +121,7 @@ func Test_ZipPath(t *testing.T) {
|
||||
t.Assert(gfile.Exists(dstPath), true)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
tempDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(tempDirPath)
|
||||
t.Assert(err, nil)
|
||||
|
||||
@ -157,7 +157,7 @@ func Test_ZipPath(t *testing.T) {
|
||||
t.Assert(gfile.Exists(dstPath), true)
|
||||
defer gfile.Remove(dstPath)
|
||||
|
||||
tempDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(tempDirPath)
|
||||
t.Assert(err, nil)
|
||||
|
||||
@ -196,7 +196,7 @@ func Test_ZipPathWriter(t *testing.T) {
|
||||
t.Assert(err, nil)
|
||||
t.AssertGT(writer.Len(), 0)
|
||||
|
||||
tempDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(tempDirPath)
|
||||
t.Assert(err, nil)
|
||||
|
||||
|
@ -180,19 +180,18 @@ func parseDBConfigNode(value interface{}) *gdb.ConfigNode {
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
node := &gdb.ConfigNode{}
|
||||
err := gconv.Struct(nodeMap, node)
|
||||
var (
|
||||
node = &gdb.ConfigNode{}
|
||||
err = gconv.Struct(nodeMap, node)
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// Be compatible with old version.
|
||||
if _, v := gutil.MapPossibleItemByKey(nodeMap, "LinkInfo"); v != nil {
|
||||
node.Link = gconv.String(v)
|
||||
}
|
||||
// Find possible `Link` configuration content.
|
||||
if _, v := gutil.MapPossibleItemByKey(nodeMap, "Link"); v != nil {
|
||||
node.Link = gconv.String(v)
|
||||
}
|
||||
// Parse link syntax.
|
||||
// Parse `Link` configuration syntax.
|
||||
if node.Link != "" && node.Type == "" {
|
||||
match, _ := gregex.MatchString(`([a-z]+):(.+)`, node.Link)
|
||||
if len(match) == 3 {
|
||||
|
@ -18,9 +18,7 @@ const (
|
||||
|
||||
// HttpClient returns an instance of http client with specified name.
|
||||
func HttpClient(name ...interface{}) *gclient.Client {
|
||||
var (
|
||||
instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name)
|
||||
)
|
||||
var instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name)
|
||||
return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
|
||||
return gclient.New()
|
||||
}).(*gclient.Client)
|
||||
|
@ -11,7 +11,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gredis"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/internal/intlog"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
@ -25,6 +25,7 @@ const (
|
||||
// Note that it panics if any error occurs duration instance creating.
|
||||
func Redis(name ...string) *gredis.Redis {
|
||||
var (
|
||||
err error
|
||||
ctx = context.Background()
|
||||
group = gredis.DefaultGroupName
|
||||
)
|
||||
@ -37,35 +38,33 @@ func Redis(name ...string) *gredis.Redis {
|
||||
if _, ok := gredis.GetConfig(group); ok {
|
||||
return gredis.Instance(group)
|
||||
}
|
||||
// Or else, it parses the default configuration file and returns a new redis instance.
|
||||
var (
|
||||
configMap map[string]interface{}
|
||||
)
|
||||
|
||||
if configData, err := Config().Data(ctx); err != nil {
|
||||
panic(gerror.Wrap(err, `retrieving redis configuration failed`))
|
||||
} else {
|
||||
if _, v := gutil.MapPossibleItemByKey(configData, configNodeNameRedis); v != nil {
|
||||
if Config().Available(ctx) {
|
||||
var (
|
||||
configMap map[string]interface{}
|
||||
redisConfig *gredis.Config
|
||||
redisClient *gredis.Redis
|
||||
)
|
||||
if configMap, err = Config().Data(ctx); err != nil {
|
||||
intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
|
||||
}
|
||||
if _, v := gutil.MapPossibleItemByKey(configMap, configNodeNameRedis); v != nil {
|
||||
configMap = gconv.Map(v)
|
||||
}
|
||||
}
|
||||
|
||||
if len(configMap) > 0 {
|
||||
if v, ok := configMap[group]; ok {
|
||||
redisConfig, err := gredis.ConfigFromMap(gconv.Map(v))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
if len(configMap) > 0 {
|
||||
if v, ok := configMap[group]; ok {
|
||||
if redisConfig, err = gredis.ConfigFromMap(gconv.Map(v)); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
intlog.Printf(ctx, `missing configuration for redis group "%s"`, group)
|
||||
}
|
||||
redisClient, err := gredis.New(redisConfig)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return redisClient
|
||||
} else {
|
||||
panic(fmt.Sprintf(`missing configuration for redis group "%s"`, group))
|
||||
intlog.Print(ctx, `missing configuration for redis: "redis" node not found`)
|
||||
}
|
||||
} else {
|
||||
panic(`missing configuration for redis: "redis" node not found`)
|
||||
if redisClient, err = gredis.New(redisConfig); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return redisClient
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
@ -17,15 +17,16 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
frameCoreComponentNameServer = "gf.core.component.server"
|
||||
configNodeNameServer = "server"
|
||||
configNodeNameServerSecondary = "httpserver"
|
||||
frameCoreComponentNameServer = "gf.core.component.server" // Prefix for HTTP server instance.
|
||||
configNodeNameServer = "server" // General version configuration item name.
|
||||
configNodeNameServerSecondary = "httpserver" // New version configuration item name support from v2.
|
||||
)
|
||||
|
||||
// Server returns an instance of http server with specified name.
|
||||
// Note that it panics if any error occurs duration instance creating.
|
||||
func Server(name ...interface{}) *ghttp.Server {
|
||||
var (
|
||||
err error
|
||||
ctx = context.Background()
|
||||
instanceName = ghttp.DefaultServerName
|
||||
instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameServer, name)
|
||||
@ -34,57 +35,67 @@ func Server(name ...interface{}) *ghttp.Server {
|
||||
instanceName = gconv.String(name[0])
|
||||
}
|
||||
return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
|
||||
s := ghttp.GetServer(instanceName)
|
||||
// It ignores returned error to avoid file no found error while it's not necessary.
|
||||
var (
|
||||
serverConfigMap map[string]interface{}
|
||||
serverLoggerConfigMap map[string]interface{}
|
||||
configNodeName string
|
||||
)
|
||||
if configData, _ := Config().Data(ctx); len(configData) > 0 {
|
||||
if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameServer); v != "" {
|
||||
configNodeName = v
|
||||
server := ghttp.GetServer(instanceName)
|
||||
if Config().Available(ctx) {
|
||||
// Server initialization from configuration.
|
||||
var (
|
||||
configMap map[string]interface{}
|
||||
serverConfigMap map[string]interface{}
|
||||
serverLoggerConfigMap map[string]interface{}
|
||||
configNodeName string
|
||||
)
|
||||
if configMap, err = Config().Data(ctx); err != nil {
|
||||
intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
|
||||
}
|
||||
if configNodeName == "" {
|
||||
if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameServerSecondary); v != "" {
|
||||
// Find possible server configuration item by possible names.
|
||||
if len(configMap) > 0 {
|
||||
if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameServer); v != "" {
|
||||
configNodeName = v
|
||||
}
|
||||
if configNodeName == "" {
|
||||
if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameServerSecondary); v != "" {
|
||||
configNodeName = v
|
||||
}
|
||||
}
|
||||
}
|
||||
// Server configuration.
|
||||
serverConfigMap = Config().MustGet(
|
||||
ctx,
|
||||
fmt.Sprintf(`%s.%s`, configNodeName, server.GetName()),
|
||||
).Map()
|
||||
if len(serverConfigMap) == 0 {
|
||||
serverConfigMap = Config().MustGet(ctx, configNodeName).Map()
|
||||
}
|
||||
if len(serverConfigMap) > 0 {
|
||||
if err = server.SetConfigWithMap(serverConfigMap); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
// The configuration is not necessary, so it just prints internal logs.
|
||||
intlog.Printf(
|
||||
ctx,
|
||||
`missing configuration from configuration component for HTTP server "%s"`,
|
||||
instanceName,
|
||||
)
|
||||
}
|
||||
// Server logger configuration checks.
|
||||
serverLoggerConfigMap = Config().MustGet(
|
||||
ctx,
|
||||
fmt.Sprintf(`%s.%s.%s`, configNodeName, server.GetName(), configNodeNameLogger),
|
||||
).Map()
|
||||
if len(serverLoggerConfigMap) > 0 {
|
||||
if err = server.Logger().SetConfigWithMap(serverLoggerConfigMap); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Server configuration.
|
||||
certainConfigNodeName := fmt.Sprintf(`%s.%s`, configNodeName, s.GetName())
|
||||
if v, _ := Config().Get(ctx, certainConfigNodeName); !v.IsEmpty() {
|
||||
serverConfigMap = v.Map()
|
||||
}
|
||||
if len(serverConfigMap) == 0 {
|
||||
if v, _ := Config().Get(ctx, configNodeName); !v.IsEmpty() {
|
||||
serverConfigMap = v.Map()
|
||||
}
|
||||
}
|
||||
if len(serverConfigMap) > 0 {
|
||||
if err := s.SetConfigWithMap(serverConfigMap); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
// The configuration is not necessary, so it just prints internal logs.
|
||||
intlog.Printf(ctx, `missing configuration from configuration component for HTTP server "%s"`, instanceName)
|
||||
}
|
||||
if s.GetName() == "" || s.GetName() == ghttp.DefaultServerName {
|
||||
s.SetName(instanceName)
|
||||
}
|
||||
// Server logger configuration checks.
|
||||
serverLoggerNodeName := fmt.Sprintf(`%s.%s.%s`, configNodeName, s.GetName(), configNodeNameLogger)
|
||||
if v, _ := Config().Get(ctx, serverLoggerNodeName); !v.IsEmpty() {
|
||||
serverLoggerConfigMap = v.Map()
|
||||
}
|
||||
if len(serverLoggerConfigMap) > 0 {
|
||||
if err := s.Logger().SetConfigWithMap(serverLoggerConfigMap); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// The server name is necessary. It sets a default server name is it is not configured.
|
||||
if server.GetName() == "" || server.GetName() == ghttp.DefaultServerName {
|
||||
server.SetName(instanceName)
|
||||
}
|
||||
// As it might use template feature,
|
||||
// it initializes the view instance as well.
|
||||
_ = getViewInstance()
|
||||
return s
|
||||
return server
|
||||
}).(*ghttp.Server)
|
||||
}
|
||||
|
@ -10,6 +10,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/internal/intlog"
|
||||
"github.com/gogf/gf/v2/os/gview"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
@ -35,6 +36,7 @@ func View(name ...string) *gview.View {
|
||||
|
||||
func getViewInstance(name ...string) *gview.View {
|
||||
var (
|
||||
err error
|
||||
ctx = context.Background()
|
||||
instanceName = gview.DefaultName
|
||||
)
|
||||
@ -42,27 +44,27 @@ func getViewInstance(name ...string) *gview.View {
|
||||
instanceName = name[0]
|
||||
}
|
||||
view := gview.Instance(instanceName)
|
||||
// To avoid file no found error while it's not necessary.
|
||||
var (
|
||||
configMap map[string]interface{}
|
||||
configNodeName = configNodeNameViewer
|
||||
)
|
||||
if configData, _ := Config().Data(ctx); len(configData) > 0 {
|
||||
if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameViewer); v != "" {
|
||||
configNodeName = v
|
||||
if Config().Available(ctx) {
|
||||
var (
|
||||
configMap map[string]interface{}
|
||||
configNodeName = configNodeNameViewer
|
||||
)
|
||||
if configMap, err = Config().Data(ctx); err != nil {
|
||||
intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
|
||||
}
|
||||
}
|
||||
if v, _ := Config().Get(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)); !v.IsEmpty() {
|
||||
configMap = v.Map()
|
||||
}
|
||||
if len(configMap) == 0 {
|
||||
if v, _ := Config().Get(ctx, configNodeName); !v.IsEmpty() {
|
||||
configMap = v.Map()
|
||||
if len(configMap) > 0 {
|
||||
if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameViewer); v != "" {
|
||||
configNodeName = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(configMap) > 0 {
|
||||
if err := view.SetConfigWithMap(configMap); err != nil {
|
||||
panic(err)
|
||||
configMap = Config().MustGet(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)).Map()
|
||||
if len(configMap) == 0 {
|
||||
configMap = Config().MustGet(ctx, configNodeName).Map()
|
||||
}
|
||||
if len(configMap) > 0 {
|
||||
if err = view.SetConfigWithMap(configMap); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return view
|
||||
|
@ -40,7 +40,7 @@ func Test_Config2(t *testing.T) {
|
||||
// relative path
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var err error
|
||||
dirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(dirPath)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(dirPath)
|
||||
@ -64,7 +64,7 @@ func Test_Config2(t *testing.T) {
|
||||
// relative path, config folder
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var err error
|
||||
dirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(dirPath)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(dirPath)
|
||||
@ -90,7 +90,7 @@ func Test_Config2(t *testing.T) {
|
||||
func Test_Config3(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var err error
|
||||
dirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(dirPath)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(dirPath)
|
||||
@ -114,7 +114,7 @@ func Test_Config3(t *testing.T) {
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var err error
|
||||
dirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(dirPath)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(dirPath)
|
||||
@ -140,7 +140,7 @@ func Test_Config3(t *testing.T) {
|
||||
func Test_Config4(t *testing.T) {
|
||||
// absolute path
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := fmt.Sprintf(`%s/%d`, gfile.TempDir(), gtime.TimestampNano())
|
||||
path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano())
|
||||
file := fmt.Sprintf(`%s/%s`, path, "config.toml")
|
||||
err := gfile.PutContents(file, configContent)
|
||||
t.Assert(err, nil)
|
||||
@ -155,7 +155,7 @@ func Test_Config4(t *testing.T) {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := fmt.Sprintf(`%s/%d/config`, gfile.TempDir(), gtime.TimestampNano())
|
||||
path := fmt.Sprintf(`%s/%d/config`, gfile.Temp(), gtime.TimestampNano())
|
||||
file := fmt.Sprintf(`%s/%s`, path, "config.toml")
|
||||
err := gfile.PutContents(file, configContent)
|
||||
t.Assert(err, nil)
|
||||
@ -169,7 +169,7 @@ func Test_Config4(t *testing.T) {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := fmt.Sprintf(`%s/%d`, gfile.TempDir(), gtime.TimestampNano())
|
||||
path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano())
|
||||
file := fmt.Sprintf(`%s/%s`, path, "test.toml")
|
||||
err := gfile.PutContents(file, configContent)
|
||||
t.Assert(err, nil)
|
||||
@ -184,7 +184,7 @@ func Test_Config4(t *testing.T) {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := fmt.Sprintf(`%s/%d/config`, gfile.TempDir(), gtime.TimestampNano())
|
||||
path := fmt.Sprintf(`%s/%d/config`, gfile.Temp(), gtime.TimestampNano())
|
||||
file := fmt.Sprintf(`%s/%s`, path, "test.toml")
|
||||
err := gfile.PutContents(file, configContent)
|
||||
t.Assert(err, nil)
|
||||
|
@ -24,7 +24,7 @@ func Test_Database(t *testing.T) {
|
||||
)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var err error
|
||||
dirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(dirPath)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(dirPath)
|
||||
|
@ -25,7 +25,7 @@ func Test_Redis(t *testing.T) {
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var err error
|
||||
dirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(dirPath)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(dirPath)
|
||||
|
@ -36,7 +36,7 @@ func Test_View(t *testing.T) {
|
||||
t.Assert(b, "中国人")
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := fmt.Sprintf(`%s/%d`, gfile.TempDir(), gtime.TimestampNano())
|
||||
path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano())
|
||||
tpl := fmt.Sprintf(`%s/%s`, path, "t.tpl")
|
||||
err := gfile.PutContents(tpl, `{{"我是中国人" | substr 2 -1}}`)
|
||||
t.Assert(err, nil)
|
||||
|
@ -316,7 +316,7 @@ func Test_Client_File_And_Param(t *testing.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
s.BindHandler("/", func(r *ghttp.Request) {
|
||||
tmpPath := gfile.TempDir(guid.S())
|
||||
tmpPath := gfile.Temp(guid.S())
|
||||
err := gfile.Mkdir(tmpPath)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(tmpPath)
|
||||
|
@ -16,6 +16,16 @@ func (r *Request) SetParam(key string, value interface{}) {
|
||||
r.paramsMap[key] = value
|
||||
}
|
||||
|
||||
// SetParamMap sets custom parameter with key-value pair map.
|
||||
func (r *Request) SetParamMap(data map[string]interface{}) {
|
||||
if r.paramsMap == nil {
|
||||
r.paramsMap = make(map[string]interface{})
|
||||
}
|
||||
for k, v := range data {
|
||||
r.paramsMap[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// GetParam returns custom parameter with given name `key`.
|
||||
// It returns `def` if `key` does not exist.
|
||||
// It returns nil if `def` is not passed.
|
||||
|
@ -31,7 +31,7 @@ func ExampleUploadFile_Save() {
|
||||
return
|
||||
}
|
||||
file.Filename = "MyCustomFileName.txt"
|
||||
fileName, err := file.Save(gfile.TempDir())
|
||||
fileName, err := file.Save(gfile.Temp())
|
||||
if err != nil {
|
||||
r.Response.Write(err)
|
||||
return
|
||||
|
@ -124,7 +124,7 @@ func Test_ClientMaxBodySize_File(t *testing.T) {
|
||||
c := g.Client()
|
||||
c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
|
||||
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
data := make([]byte, 512)
|
||||
for i := 0; i < 512; i++ {
|
||||
data[i] = 'a'
|
||||
@ -142,7 +142,7 @@ func Test_ClientMaxBodySize_File(t *testing.T) {
|
||||
c := g.Client()
|
||||
c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
|
||||
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
data := make([]byte, 1056)
|
||||
for i := 0; i < 1056; i++ {
|
||||
data[i] = 'a'
|
||||
|
@ -24,7 +24,7 @@ import (
|
||||
|
||||
func Test_Log(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
logDir := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
logDir := gfile.Temp(gtime.TimestampNanoStr())
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
s.BindHandler("/hello", func(r *ghttp.Request) {
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
)
|
||||
|
||||
func Test_Params_File_Single(t *testing.T) {
|
||||
dstDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dstDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
s.BindHandler("/upload/single", func(r *ghttp.Request) {
|
||||
@ -76,7 +76,7 @@ func Test_Params_File_Single(t *testing.T) {
|
||||
}
|
||||
|
||||
func Test_Params_File_CustomName(t *testing.T) {
|
||||
dstDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dstDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
s.BindHandler("/upload/single", func(r *ghttp.Request) {
|
||||
@ -113,7 +113,7 @@ func Test_Params_File_CustomName(t *testing.T) {
|
||||
}
|
||||
|
||||
func Test_Params_File_Batch(t *testing.T) {
|
||||
dstDirPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dstDirPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
s.BindHandler("/upload/batch", func(r *ghttp.Request) {
|
||||
|
@ -527,3 +527,50 @@ func Test_Params_Struct_Validation(t *testing.T) {
|
||||
t.Assert(c.PostContent(ctx, "/", `id=1`), `The name field is required`)
|
||||
})
|
||||
}
|
||||
|
||||
// https://github.com/gogf/gf/issues/1488
|
||||
func Test_Params_Parse_Issue1488(t *testing.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
s.Group("/", func(group *ghttp.RouterGroup) {
|
||||
group.ALL("/", func(r *ghttp.Request) {
|
||||
type Request struct {
|
||||
Type []int `p:"type"`
|
||||
Keyword string `p:"keyword"`
|
||||
Limit int `p:"per_page" d:"10"`
|
||||
Page int `p:"page" d:"1"`
|
||||
Order string
|
||||
CreatedAtLte string
|
||||
CreatedAtGte string
|
||||
CreatorID []int
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
r.SetParamMap(g.Map{
|
||||
"type[]": 0,
|
||||
"keyword": "",
|
||||
"t_start": "",
|
||||
"t_end": "",
|
||||
"reserve_at_start": "",
|
||||
"reserve_at_end": "",
|
||||
"user_name": "",
|
||||
"flag": "",
|
||||
"per_page": 6,
|
||||
})
|
||||
var parsed Request
|
||||
_ = r.Parse(&parsed)
|
||||
r.Response.Write(parsed.Page, parsed.Limit)
|
||||
}
|
||||
})
|
||||
})
|
||||
s.SetPort(p)
|
||||
s.SetDumpRouterMap(false)
|
||||
s.Start()
|
||||
defer s.Shutdown()
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
c := g.Client()
|
||||
c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
|
||||
t.Assert(c.GetContent(ctx, "/", ``), `16161616161616161616`)
|
||||
})
|
||||
}
|
||||
|
@ -26,7 +26,7 @@ func Test_Static_ServerRoot(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
defer gfile.Remove(path)
|
||||
gfile.PutContents(path+"/index.htm", "index")
|
||||
s.SetServerRoot(path)
|
||||
@ -86,7 +86,7 @@ func Test_Static_Folder_Forbidden(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
defer gfile.Remove(path)
|
||||
gfile.PutContents(path+"/test.html", "test")
|
||||
s.SetServerRoot(path)
|
||||
@ -107,7 +107,7 @@ func Test_Static_IndexFolder(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
defer gfile.Remove(path)
|
||||
gfile.PutContents(path+"/test.html", "test")
|
||||
s.SetIndexFolder(true)
|
||||
@ -130,7 +130,7 @@ func Test_Static_IndexFiles1(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
defer gfile.Remove(path)
|
||||
gfile.PutContents(path+"/index.html", "index")
|
||||
gfile.PutContents(path+"/test.html", "test")
|
||||
@ -152,7 +152,7 @@ func Test_Static_IndexFiles2(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
defer gfile.Remove(path)
|
||||
gfile.PutContents(path+"/test.html", "test")
|
||||
s.SetIndexFiles([]string{"index.html", "test.html"})
|
||||
@ -174,8 +174,8 @@ func Test_Static_AddSearchPath1(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.TempDir(), p, p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.Temp(), p, p)
|
||||
defer gfile.Remove(path1)
|
||||
defer gfile.Remove(path2)
|
||||
gfile.PutContents(path2+"/test.html", "test")
|
||||
@ -197,8 +197,8 @@ func Test_Static_AddSearchPath2(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.TempDir(), p, p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.Temp(), p, p)
|
||||
defer gfile.Remove(path1)
|
||||
defer gfile.Remove(path2)
|
||||
gfile.PutContents(path1+"/test.html", "test1")
|
||||
@ -221,8 +221,8 @@ func Test_Static_AddStaticPath(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.TempDir(), p, p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d`, gfile.Temp(), p, p)
|
||||
defer gfile.Remove(path1)
|
||||
defer gfile.Remove(path2)
|
||||
gfile.PutContents(path1+"/test.html", "test1")
|
||||
@ -246,8 +246,8 @@ func Test_Static_AddStaticPath_Priority(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d/test`, gfile.TempDir(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d/test`, gfile.TempDir(), p, p)
|
||||
path1 := fmt.Sprintf(`%s/ghttp/static/test/%d/test`, gfile.Temp(), p)
|
||||
path2 := fmt.Sprintf(`%s/ghttp/static/test/%d/%d/test`, gfile.Temp(), p, p)
|
||||
defer gfile.Remove(path1)
|
||||
defer gfile.Remove(path2)
|
||||
gfile.PutContents(path1+"/test.html", "test1")
|
||||
@ -271,7 +271,7 @@ func Test_Static_Rewrite(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p, _ := gtcp.GetFreePort()
|
||||
s := g.Server(p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.TempDir(), p)
|
||||
path := fmt.Sprintf(`%s/ghttp/static/test/%d`, gfile.Temp(), p)
|
||||
defer gfile.Remove(path)
|
||||
gfile.PutContents(path+"/test1.html", "test1")
|
||||
gfile.PutContents(path+"/test2.html", "test2")
|
||||
|
@ -11,7 +11,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/container/gmap"
|
||||
"github.com/gogf/gf/v2/container/gvar"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
@ -24,7 +23,6 @@ import (
|
||||
// Config is the configuration management object.
|
||||
type Config struct {
|
||||
adapter Adapter
|
||||
dataMap *gmap.StrAnyMap
|
||||
}
|
||||
|
||||
const (
|
||||
@ -39,7 +37,6 @@ func New() (*Config, error) {
|
||||
}
|
||||
return &Config{
|
||||
adapter: adapterFile,
|
||||
dataMap: gmap.NewStrAnyMap(true),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@ -47,7 +44,6 @@ func New() (*Config, error) {
|
||||
func NewWithAdapter(adapter Adapter) *Config {
|
||||
return &Config{
|
||||
adapter: adapter,
|
||||
dataMap: gmap.NewStrAnyMap(true),
|
||||
}
|
||||
}
|
||||
|
||||
@ -103,13 +99,6 @@ func (c *Config) Available(ctx context.Context, resource ...string) (ok bool) {
|
||||
return c.adapter.Available(ctx, resource...)
|
||||
}
|
||||
|
||||
// Set sets value with specified `pattern`.
|
||||
// It supports hierarchical data access by char separator, which is '.' in default.
|
||||
// It is commonly used for updates certain configuration value in runtime.
|
||||
func (c *Config) Set(ctx context.Context, pattern string, value interface{}) {
|
||||
c.dataMap.Set(pattern, value)
|
||||
}
|
||||
|
||||
// Get retrieves and returns value by specified `pattern`.
|
||||
// It returns all values of current Json object if `pattern` is given empty or string ".".
|
||||
// It returns nil if no value found by `pattern`.
|
||||
@ -120,17 +109,15 @@ func (c *Config) Get(ctx context.Context, pattern string, def ...interface{}) (*
|
||||
err error
|
||||
value interface{}
|
||||
)
|
||||
if value = c.dataMap.Get(pattern); value == nil {
|
||||
value, err = c.adapter.Get(ctx, pattern)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == nil {
|
||||
if len(def) > 0 {
|
||||
return gvar.New(def[0]), nil
|
||||
}
|
||||
return nil, nil
|
||||
value, err = c.adapter.Get(ctx, pattern)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == nil {
|
||||
if len(def) > 0 {
|
||||
return gvar.New(def[0]), nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
return gvar.New(value), nil
|
||||
}
|
||||
@ -181,19 +168,7 @@ func (c *Config) GetWithCmd(ctx context.Context, pattern string, def ...interfac
|
||||
|
||||
// Data retrieves and returns all configuration data as map type.
|
||||
func (c *Config) Data(ctx context.Context) (data map[string]interface{}, err error) {
|
||||
adapterData, err := c.adapter.Data(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data = make(map[string]interface{})
|
||||
for k, v := range adapterData {
|
||||
data[k] = v
|
||||
}
|
||||
c.dataMap.Iterator(func(k string, v interface{}) bool {
|
||||
data[k] = v
|
||||
return true
|
||||
})
|
||||
return
|
||||
return c.adapter.Data(ctx)
|
||||
}
|
||||
|
||||
// MustGet acts as function Get, but it panics if error occurs.
|
||||
|
@ -253,28 +253,26 @@ func (c *AdapterFile) getJson(fileName ...string) (configJson *gjson.Json, err e
|
||||
} else {
|
||||
configJson, err = gjson.LoadContent(content, true)
|
||||
}
|
||||
if err == nil {
|
||||
configJson.SetViolenceCheck(c.violenceCheck)
|
||||
// Add monitor for this configuration file,
|
||||
// any changes of this file will refresh its cache in Config object.
|
||||
if filePath != "" && !gres.Contains(filePath) {
|
||||
_, err = gfsnotify.Add(filePath, func(event *gfsnotify.Event) {
|
||||
c.jsonMap.Remove(usedFileName)
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return configJson
|
||||
}
|
||||
if err != nil {
|
||||
if filePath != "" {
|
||||
err = gerror.Wrapf(err, `load config file "%s" failed`, filePath)
|
||||
} else {
|
||||
err = gerror.Wrap(err, `load configuration failed`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
configJson.SetViolenceCheck(c.violenceCheck)
|
||||
// Add monitor for this configuration file,
|
||||
// any changes of this file will refresh its cache in Config object.
|
||||
if filePath != "" && !gres.Contains(filePath) {
|
||||
_, err = gfsnotify.Add(filePath, func(event *gfsnotify.Event) {
|
||||
c.jsonMap.Remove(usedFileName)
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return configJson
|
||||
})
|
||||
if result != nil {
|
||||
return result.(*gjson.Json), err
|
||||
|
@ -146,29 +146,10 @@ func Test_SetFileName(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestCfg_Set(t *testing.T) {
|
||||
config := `log-path = "logs"`
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gcfg.DefaultConfigFile
|
||||
err := gfile.PutContents(path, config)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
|
||||
adapterFile, err := gcfg.NewAdapterFile()
|
||||
t.AssertNil(err)
|
||||
t.Assert(adapterFile.MustGet(ctx, "log-path"), "logs")
|
||||
|
||||
c := gcfg.NewWithAdapter(adapterFile)
|
||||
c.Set(ctx, "log-path", "custom-logs")
|
||||
t.Assert(err, nil)
|
||||
t.Assert(c.MustGet(ctx, "log-path"), "custom-logs")
|
||||
})
|
||||
}
|
||||
|
||||
func TestCfg_Get_WrongConfigFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var err error
|
||||
configPath := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
configPath := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gfile.Mkdir(configPath)
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(configPath)
|
||||
|
@ -433,12 +433,12 @@ func ExtName(path string) string {
|
||||
return strings.TrimLeft(Ext(path), ".")
|
||||
}
|
||||
|
||||
// TempDir retrieves and returns the temporary directory of current system.
|
||||
// Temp retrieves and returns the temporary directory of current system.
|
||||
// It returns "/tmp" is current in *nix system, or else it returns os.TempDir().
|
||||
//
|
||||
// The optional parameter `names` specifies the sub-folders/sub-files,
|
||||
// which will be joined with current system separator and returned with the path.
|
||||
func TempDir(names ...string) string {
|
||||
func Temp(names ...string) string {
|
||||
path := tempDir
|
||||
for _, name := range names {
|
||||
path += Separator + name
|
||||
|
@ -17,7 +17,7 @@ func ExampleGetContentsWithCache() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_cache")
|
||||
tempDir = gfile.Temp("gfile_example_cache")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
|
@ -16,7 +16,7 @@ func ExampleGetContents() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -35,7 +35,7 @@ func ExampleGetBytes() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -54,7 +54,7 @@ func ExamplePutContents() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -73,7 +73,7 @@ func ExamplePutBytes() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -91,7 +91,7 @@ func ExamplePutContentsAppend() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -117,7 +117,7 @@ func ExamplePutBytesAppend() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -142,7 +142,7 @@ func ExampleGetNextCharOffsetByPath() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -161,7 +161,7 @@ func ExampleGetBytesTilCharByPath() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -179,7 +179,7 @@ func ExampleGetBytesByTwoOffsetsByPath() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -197,7 +197,7 @@ func ExampleReadLines() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -220,7 +220,7 @@ func ExampleReadLinesBytes() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_content")
|
||||
tempDir = gfile.Temp("gfile_example_content")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
|
@ -16,7 +16,7 @@ func ExampleCopy() {
|
||||
// init
|
||||
var (
|
||||
srcFileName = "gflie_example.txt"
|
||||
srcTempDir = gfile.TempDir("gfile_example_copy_src")
|
||||
srcTempDir = gfile.Temp("gfile_example_copy_src")
|
||||
srcTempFile = gfile.Join(srcTempDir, srcFileName)
|
||||
|
||||
// copy file
|
||||
@ -24,7 +24,7 @@ func ExampleCopy() {
|
||||
dstTempFile = gfile.Join(srcTempDir, dstFileName)
|
||||
|
||||
// copy dir
|
||||
dstTempDir = gfile.TempDir("gfile_example_copy_dst")
|
||||
dstTempDir = gfile.Temp("gfile_example_copy_dst")
|
||||
)
|
||||
|
||||
// write contents
|
||||
|
@ -17,7 +17,7 @@ func ExampleReplaceFile() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_replace")
|
||||
tempDir = gfile.Temp("gfile_example_replace")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -41,7 +41,7 @@ func ExampleReplaceFileFunc() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_replace")
|
||||
tempDir = gfile.Temp("gfile_example_replace")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -69,7 +69,7 @@ func ExampleReplaceDir() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_replace")
|
||||
tempDir = gfile.Temp("gfile_example_replace")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -94,7 +94,7 @@ func ExampleReplaceDirFunc() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_replace")
|
||||
tempDir = gfile.Temp("gfile_example_replace")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
|
@ -16,7 +16,7 @@ func ExampleScanDir() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_scan_dir")
|
||||
tempDir = gfile.Temp("gfile_example_scan_dir")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
|
||||
tempSubDir = gfile.Join(tempDir, "sub_dir")
|
||||
@ -43,7 +43,7 @@ func ExampleScanDirFile() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_scan_dir_file")
|
||||
tempDir = gfile.Temp("gfile_example_scan_dir_file")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
|
||||
tempSubDir = gfile.Join(tempDir, "sub_dir")
|
||||
@ -69,7 +69,7 @@ func ExampleScanDirFunc() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_scan_dir_func")
|
||||
tempDir = gfile.Temp("gfile_example_scan_dir_func")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
|
||||
tempSubDir = gfile.Join(tempDir, "sub_dir")
|
||||
@ -100,7 +100,7 @@ func ExampleScanDirFileFunc() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_scan_dir_file_func")
|
||||
tempDir = gfile.Temp("gfile_example_scan_dir_file_func")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
|
||||
fileName1 = "gflie_example_ignores.txt"
|
||||
|
@ -16,7 +16,7 @@ func ExampleSearch() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_search")
|
||||
tempDir = gfile.Temp("gfile_example_search")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
|
@ -16,7 +16,7 @@ func ExampleSize() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_size")
|
||||
tempDir = gfile.Temp("gfile_example_size")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -32,7 +32,7 @@ func ExampleSizeFormat() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_size")
|
||||
tempDir = gfile.Temp("gfile_example_size")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
@ -48,7 +48,7 @@ func ExampleReadableSize() {
|
||||
// init
|
||||
var (
|
||||
fileName = "gflie_example.txt"
|
||||
tempDir = gfile.TempDir("gfile_example_size")
|
||||
tempDir = gfile.Temp("gfile_example_size")
|
||||
tempFile = gfile.Join(tempDir, fileName)
|
||||
)
|
||||
|
||||
|
@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
func ExampleMTime() {
|
||||
t := gfile.MTime(gfile.TempDir())
|
||||
t := gfile.MTime(gfile.Temp())
|
||||
fmt.Println(t)
|
||||
|
||||
// May Output:
|
||||
@ -21,7 +21,7 @@ func ExampleMTime() {
|
||||
}
|
||||
|
||||
func ExampleMTimestamp() {
|
||||
t := gfile.MTimestamp(gfile.TempDir())
|
||||
t := gfile.MTimestamp(gfile.Temp())
|
||||
fmt.Println(t)
|
||||
|
||||
// May Output:
|
||||
@ -29,7 +29,7 @@ func ExampleMTimestamp() {
|
||||
}
|
||||
|
||||
func ExampleMTimestampMilli() {
|
||||
t := gfile.MTimestampMilli(gfile.TempDir())
|
||||
t := gfile.MTimestampMilli(gfile.Temp())
|
||||
fmt.Println(t)
|
||||
|
||||
// May Output:
|
||||
|
@ -16,7 +16,7 @@ import (
|
||||
func ExampleMkdir() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.TempDir("gfile_example_basic_dir")
|
||||
path = gfile.Temp("gfile_example_basic_dir")
|
||||
)
|
||||
|
||||
// Creates directory
|
||||
@ -32,7 +32,7 @@ func ExampleMkdir() {
|
||||
func ExampleCreate() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
dataByte = make([]byte, 50)
|
||||
)
|
||||
// Check whether the file exists
|
||||
@ -66,7 +66,7 @@ func ExampleCreate() {
|
||||
func ExampleOpen() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
dataByte = make([]byte, 4096)
|
||||
)
|
||||
// Open file or directory with READONLY model
|
||||
@ -85,7 +85,7 @@ func ExampleOpen() {
|
||||
func ExampleOpenFile() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
dataByte = make([]byte, 4096)
|
||||
)
|
||||
// Opens file/directory with custom `flag` and `perm`
|
||||
@ -111,7 +111,7 @@ func ExampleOpenFile() {
|
||||
func ExampleOpenWithFlag() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
dataByte = make([]byte, 4096)
|
||||
)
|
||||
|
||||
@ -138,7 +138,7 @@ func ExampleOpenWithFlag() {
|
||||
func ExampleJoin() {
|
||||
// init
|
||||
var (
|
||||
dirPath = gfile.TempDir("gfile_example_basic_dir")
|
||||
dirPath = gfile.Temp("gfile_example_basic_dir")
|
||||
filePath = "file1"
|
||||
)
|
||||
|
||||
@ -154,7 +154,7 @@ func ExampleJoin() {
|
||||
func ExampleExists() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
// Checks whether given `path` exist.
|
||||
joinString := gfile.Exists(path)
|
||||
@ -168,8 +168,8 @@ func ExampleExists() {
|
||||
func ExampleIsDir() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.TempDir("gfile_example_basic_dir")
|
||||
filePath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Temp("gfile_example_basic_dir")
|
||||
filePath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
// Checks whether given `path` a directory.
|
||||
fmt.Println(gfile.IsDir(path))
|
||||
@ -191,7 +191,7 @@ func ExamplePwd() {
|
||||
func ExampleChdir() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
// Get current working directory
|
||||
fmt.Println(gfile.Pwd())
|
||||
@ -210,8 +210,8 @@ func ExampleChdir() {
|
||||
func ExampleIsFile() {
|
||||
// init
|
||||
var (
|
||||
filePath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
dirPath = gfile.TempDir("gfile_example_basic_dir")
|
||||
filePath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
dirPath = gfile.Temp("gfile_example_basic_dir")
|
||||
)
|
||||
// Checks whether given `path` a file, which means it's not a directory.
|
||||
fmt.Println(gfile.IsFile(filePath))
|
||||
@ -225,7 +225,7 @@ func ExampleIsFile() {
|
||||
func ExampleStat() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
// Get a FileInfo describing the named file.
|
||||
stat, _ := gfile.Stat(path)
|
||||
@ -248,8 +248,8 @@ func ExampleStat() {
|
||||
func ExampleMove() {
|
||||
// init
|
||||
var (
|
||||
srcPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
dstPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file2")
|
||||
srcPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
dstPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file2")
|
||||
)
|
||||
// Check is file
|
||||
fmt.Println(gfile.IsFile(dstPath))
|
||||
@ -270,8 +270,8 @@ func ExampleMove() {
|
||||
func ExampleRename() {
|
||||
// init
|
||||
var (
|
||||
srcPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file2")
|
||||
dstPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
srcPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file2")
|
||||
dstPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
// Check is file
|
||||
fmt.Println(gfile.IsFile(dstPath))
|
||||
@ -292,7 +292,7 @@ func ExampleRename() {
|
||||
func ExampleDirNames() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.TempDir("gfile_example_basic_dir")
|
||||
path = gfile.Temp("gfile_example_basic_dir")
|
||||
)
|
||||
// Get sub-file names of given directory `path`.
|
||||
dirNames, _ := gfile.DirNames(path)
|
||||
@ -353,7 +353,7 @@ func ExampleIsWritable() {
|
||||
func ExampleChmod() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
|
||||
// Get a FileInfo describing the named file.
|
||||
@ -380,7 +380,7 @@ func ExampleChmod() {
|
||||
func ExampleAbs() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
|
||||
// Get an absolute representation of path.
|
||||
@ -393,8 +393,8 @@ func ExampleAbs() {
|
||||
func ExampleRealPath() {
|
||||
// init
|
||||
var (
|
||||
realPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
worryPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "worryFile")
|
||||
realPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
worryPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "worryFile")
|
||||
)
|
||||
|
||||
// fetch an absolute representation of path.
|
||||
@ -462,7 +462,7 @@ func ExampleName() {
|
||||
func ExampleDir() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
|
||||
// Get all but the last element of path, typically the path's directory.
|
||||
@ -475,7 +475,7 @@ func ExampleDir() {
|
||||
func ExampleIsEmpty() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
|
||||
// Check whether the `path` is empty
|
||||
@ -525,7 +525,7 @@ func ExampleTempDir() {
|
||||
)
|
||||
|
||||
// fetch an absolute representation of path.
|
||||
path := gfile.TempDir(fileName)
|
||||
path := gfile.Temp(fileName)
|
||||
|
||||
fmt.Println(path)
|
||||
|
||||
@ -536,7 +536,7 @@ func ExampleTempDir() {
|
||||
func ExampleRemove() {
|
||||
// init
|
||||
var (
|
||||
path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
|
||||
path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1")
|
||||
)
|
||||
|
||||
// Checks whether given `path` a file, which means it's not a directory.
|
||||
|
@ -50,8 +50,8 @@ func Test_CopyFile(t *testing.T) {
|
||||
})
|
||||
// Content replacement.
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
src := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dst := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
src := gfile.Temp(gtime.TimestampNanoStr())
|
||||
dst := gfile.Temp(gtime.TimestampNanoStr())
|
||||
srcContent := "1"
|
||||
dstContent := "1"
|
||||
t.Assert(gfile.PutContents(src, srcContent), nil)
|
||||
@ -111,8 +111,8 @@ func Test_CopyDir(t *testing.T) {
|
||||
})
|
||||
// Content replacement.
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
src := gfile.TempDir(gtime.TimestampNanoStr(), gtime.TimestampNanoStr())
|
||||
dst := gfile.TempDir(gtime.TimestampNanoStr(), gtime.TimestampNanoStr())
|
||||
src := gfile.Temp(gtime.TimestampNanoStr(), gtime.TimestampNanoStr())
|
||||
dst := gfile.Temp(gtime.TimestampNanoStr(), gtime.TimestampNanoStr())
|
||||
defer func() {
|
||||
gfile.Remove(src)
|
||||
gfile.Remove(dst)
|
||||
|
@ -610,9 +610,9 @@ func Test_ExtName(t *testing.T) {
|
||||
func Test_TempDir(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
if gfile.Separator != "/" || !gfile.Exists("/tmp") {
|
||||
t.Assert(gfile.TempDir(), os.TempDir())
|
||||
t.Assert(gfile.Temp(), os.TempDir())
|
||||
} else {
|
||||
t.Assert(gfile.TempDir(), "/tmp")
|
||||
t.Assert(gfile.Temp(), "/tmp")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -147,7 +147,7 @@ func stop(testFile string) {
|
||||
|
||||
func Test_ConcurrentOS(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
defer gfile.Remove(path)
|
||||
f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666)
|
||||
t.Assert(err, nil)
|
||||
@ -178,7 +178,7 @@ func Test_ConcurrentOS(t *testing.T) {
|
||||
})
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
defer gfile.Remove(path)
|
||||
f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666)
|
||||
t.Assert(err, nil)
|
||||
@ -199,7 +199,7 @@ func Test_ConcurrentOS(t *testing.T) {
|
||||
t.Assert(gstr.Count(gfile.GetContents(path), "@1234567890#"), 2000)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
defer gfile.Remove(path)
|
||||
f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666)
|
||||
t.Assert(err, nil)
|
||||
@ -227,7 +227,7 @@ func Test_ConcurrentOS(t *testing.T) {
|
||||
})
|
||||
// DATA RACE
|
||||
// gtest.C(t, func(t *gtest.T) {
|
||||
// path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
// path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
// defer gfile.Remove(path)
|
||||
// f1, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666)
|
||||
// t.Assert(err, nil)
|
||||
@ -265,7 +265,7 @@ func Test_ConcurrentOS(t *testing.T) {
|
||||
|
||||
func Test_ConcurrentGFPool(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
defer gfile.Remove(path)
|
||||
f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666)
|
||||
t.Assert(err, nil)
|
||||
@ -287,7 +287,7 @@ func Test_ConcurrentGFPool(t *testing.T) {
|
||||
})
|
||||
// DATA RACE
|
||||
// gtest.C(t, func(t *gtest.T) {
|
||||
// path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
// path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
// defer gfile.Remove(path)
|
||||
// f1, err := gfpool.Open(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND, 0666)
|
||||
// t.Assert(err, nil)
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
func TestWatcher_AddOnce(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
value := gtype.New()
|
||||
path := gfile.TempDir(gconv.String(gtime.TimestampNano()))
|
||||
path := gfile.Temp(gconv.String(gtime.TimestampNano()))
|
||||
err := gfile.PutContents(path, "init")
|
||||
t.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
@ -57,8 +57,8 @@ func TestWatcher_AddOnce(t *testing.T) {
|
||||
|
||||
func TestWatcher_AddRemove(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path1 := gfile.TempDir() + gfile.Separator + gconv.String(gtime.TimestampNano())
|
||||
path2 := gfile.TempDir() + gfile.Separator + gconv.String(gtime.TimestampNano()) + "2"
|
||||
path1 := gfile.Temp() + gfile.Separator + gconv.String(gtime.TimestampNano())
|
||||
path2 := gfile.Temp() + gfile.Separator + gconv.String(gtime.TimestampNano()) + "2"
|
||||
gfile.PutContents(path1, "1")
|
||||
defer func() {
|
||||
gfile.Remove(path1)
|
||||
@ -89,7 +89,7 @@ func TestWatcher_AddRemove(t *testing.T) {
|
||||
})
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path1 := gfile.TempDir() + gfile.Separator + gconv.String(gtime.TimestampNano())
|
||||
path1 := gfile.Temp() + gfile.Separator + gconv.String(gtime.TimestampNano())
|
||||
gfile.PutContents(path1, "1")
|
||||
defer func() {
|
||||
gfile.Remove(path1)
|
||||
@ -124,7 +124,7 @@ func TestWatcher_AddRemove(t *testing.T) {
|
||||
|
||||
func TestWatcher_Callback1(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path1 := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path1 := gfile.Temp(gtime.TimestampNanoStr())
|
||||
gfile.PutContents(path1, "1")
|
||||
defer func() {
|
||||
gfile.Remove(path1)
|
||||
@ -154,7 +154,7 @@ func TestWatcher_Callback1(t *testing.T) {
|
||||
func TestWatcher_Callback2(t *testing.T) {
|
||||
// multiple callbacks
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path1 := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path1 := gfile.Temp(gtime.TimestampNanoStr())
|
||||
t.Assert(gfile.PutContents(path1, "1"), nil)
|
||||
defer func() {
|
||||
gfile.Remove(path1)
|
||||
@ -198,7 +198,7 @@ func TestWatcher_WatchFolderWithoutRecursively(t *testing.T) {
|
||||
var (
|
||||
err error
|
||||
array = garray.New(true)
|
||||
dirPath = gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dirPath = gfile.Temp(gtime.TimestampNanoStr())
|
||||
)
|
||||
err = gfile.Mkdir(dirPath)
|
||||
t.AssertNil(err)
|
||||
|
@ -276,21 +276,14 @@ func (l *Logger) printToStdout(ctx context.Context, input *HandlerInput) *bytes.
|
||||
if l.config.StdoutPrint {
|
||||
var (
|
||||
err error
|
||||
buffer = input.getRealBuffer(true)
|
||||
buffer = input.getRealBuffer(!l.config.StdoutColorDisabled)
|
||||
)
|
||||
if l.config.StdoutColorDisabled {
|
||||
// Output to stdout without color.
|
||||
if _, err = os.Stdout.Write(buffer.Bytes()); err != nil {
|
||||
intlog.Errorf(ctx, `%+v`, err)
|
||||
}
|
||||
} else {
|
||||
// This will lose color in Windows os system.
|
||||
// if _, err := os.Stdout.Write(input.getRealBuffer(true).Bytes()); err != nil {
|
||||
// This will lose color in Windows os system.
|
||||
// if _, err := os.Stdout.Write(input.getRealBuffer(true).Bytes()); err != nil {
|
||||
|
||||
// This will print color in Windows os system.
|
||||
if _, err = fmt.Fprint(color.Output, buffer.String()); err != nil {
|
||||
intlog.Errorf(ctx, `%+v`, err)
|
||||
}
|
||||
// This will print color in Windows os system.
|
||||
if _, err = fmt.Fprint(color.Output, buffer.String()); err != nil {
|
||||
intlog.Errorf(ctx, `%+v`, err)
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
|
@ -193,7 +193,7 @@ func (l *Logger) GetCtxKeys() []interface{} {
|
||||
}
|
||||
|
||||
// SetWriter sets the customized logging `writer` for logging.
|
||||
// The `writer` object should implements the io.Writer interface.
|
||||
// The `writer` object should implement the io.Writer interface.
|
||||
// Developer can use customized logging `writer` to redirect logging output to another service,
|
||||
// eg: kafka, mysql, mongodb, etc.
|
||||
func (l *Logger) SetWriter(writer io.Writer) {
|
||||
@ -254,7 +254,12 @@ func (l *Logger) SetHandlers(handlers ...Handler) {
|
||||
l.config.Handlers = handlers
|
||||
}
|
||||
|
||||
// SetWriterColorEnable sets the file logging with color
|
||||
// SetWriterColorEnable enables file/writer logging with color.
|
||||
func (l *Logger) SetWriterColorEnable(enabled bool) {
|
||||
l.config.WriterColorEnable = enabled
|
||||
}
|
||||
|
||||
// SetStdoutColorDisabled disables stdout logging with color.
|
||||
func (l *Logger) SetStdoutColorDisabled(disabled bool) {
|
||||
l.config.StdoutColorDisabled = disabled
|
||||
}
|
||||
|
@ -30,7 +30,7 @@ func Test_To(t *testing.T) {
|
||||
|
||||
func Test_Path(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -48,7 +48,7 @@ func Test_Path(t *testing.T) {
|
||||
func Test_Cat(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
cat := "category"
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -65,7 +65,7 @@ func Test_Cat(t *testing.T) {
|
||||
|
||||
func Test_Level(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -82,7 +82,7 @@ func Test_Level(t *testing.T) {
|
||||
|
||||
func Test_Skip(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -101,7 +101,7 @@ func Test_Skip(t *testing.T) {
|
||||
|
||||
func Test_Stack(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -120,7 +120,7 @@ func Test_Stack(t *testing.T) {
|
||||
|
||||
func Test_StackWithFilter(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -136,7 +136,7 @@ func Test_StackWithFilter(t *testing.T) {
|
||||
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -154,7 +154,7 @@ func Test_StackWithFilter(t *testing.T) {
|
||||
|
||||
func Test_Header(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -167,7 +167,7 @@ func Test_Header(t *testing.T) {
|
||||
t.Assert(gstr.Count(content, "1 2 3"), 1)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -183,7 +183,7 @@ func Test_Header(t *testing.T) {
|
||||
|
||||
func Test_Line(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -199,7 +199,7 @@ func Test_Line(t *testing.T) {
|
||||
//t.Assert(gstr.Contains(content, gfile.Separator), true)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -217,7 +217,7 @@ func Test_Line(t *testing.T) {
|
||||
|
||||
func Test_Async(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
@ -235,7 +235,7 @@ func Test_Async(t *testing.T) {
|
||||
})
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
path := gfile.Temp(gtime.TimestampNanoStr())
|
||||
file := fmt.Sprintf(`%d.log`, gtime.TimestampNano())
|
||||
|
||||
err := gfile.Mkdir(path)
|
||||
|
@ -27,7 +27,7 @@ var (
|
||||
func Test_Rotate_Size(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
l := glog.New()
|
||||
p := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
p := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err := l.SetConfigWithMap(g.Map{
|
||||
"Path": p,
|
||||
"File": "access.log",
|
||||
@ -66,7 +66,7 @@ func Test_Rotate_Size(t *testing.T) {
|
||||
func Test_Rotate_Expire(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
l := glog.New()
|
||||
p := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
p := gfile.Temp(gtime.TimestampNanoStr())
|
||||
err := l.SetConfigWithMap(g.Map{
|
||||
"Path": p,
|
||||
"File": "access.log",
|
||||
|
@ -60,7 +60,7 @@ func Test_Concurrent(t *testing.T) {
|
||||
l := glog.New()
|
||||
s := "@1234567890#"
|
||||
f := "test.log"
|
||||
p := gfile.TempDir(gtime.TimestampNanoStr())
|
||||
p := gfile.Temp(gtime.TimestampNanoStr())
|
||||
t.Assert(l.SetPath(p), nil)
|
||||
defer gfile.Remove(p)
|
||||
wg := sync.WaitGroup{}
|
||||
|
@ -57,7 +57,7 @@ func init() {
|
||||
if homePath, _ := gfile.Home(); homePath != "" {
|
||||
availablePaths = append(availablePaths, gfile.Join(homePath, ".config"))
|
||||
}
|
||||
availablePaths = append(availablePaths, gfile.TempDir())
|
||||
availablePaths = append(availablePaths, gfile.Temp())
|
||||
for _, availablePath := range availablePaths {
|
||||
checkPath := gfile.Join(availablePath, defaultFolderNameForProcComm)
|
||||
if !gfile.Exists(checkPath) && gfile.Mkdir(checkPath) != nil {
|
||||
|
@ -24,7 +24,7 @@ func Test_PackToGoFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gdebug.TestDataPath("files")
|
||||
goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "testdata.go")
|
||||
goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "testdata.go")
|
||||
pkgName = "testdata"
|
||||
err = gres.PackToGoFile(srcPath, goFilePath, pkgName)
|
||||
)
|
||||
@ -52,7 +52,7 @@ func Test_PackToFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gdebug.TestDataPath("files")
|
||||
dstPath = gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dstPath = gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gres.PackToFile(srcPath, dstPath)
|
||||
)
|
||||
t.Assert(err, nil)
|
||||
@ -70,7 +70,7 @@ func Test_PackMulti(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gdebug.TestDataPath("files")
|
||||
goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "data.go")
|
||||
goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "data.go")
|
||||
pkgName = "data"
|
||||
array, err = gfile.ScanDir(srcPath, "*", false)
|
||||
)
|
||||
@ -85,7 +85,7 @@ func Test_PackWithPrefix1(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gdebug.TestDataPath("files")
|
||||
goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "testdata.go")
|
||||
goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "testdata.go")
|
||||
pkgName = "testdata"
|
||||
err = gres.PackToGoFile(srcPath, goFilePath, pkgName, "www/gf-site/test")
|
||||
)
|
||||
@ -98,7 +98,7 @@ func Test_PackWithPrefix2(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
srcPath = gdebug.TestDataPath("files")
|
||||
goFilePath = gfile.TempDir(gtime.TimestampNanoStr(), "testdata.go")
|
||||
goFilePath = gfile.Temp(gtime.TimestampNanoStr(), "testdata.go")
|
||||
pkgName = "testdata"
|
||||
err = gres.PackToGoFile(srcPath, goFilePath, pkgName, "/var/www/gf-site/test")
|
||||
)
|
||||
@ -237,7 +237,7 @@ func Test_Export(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
src = `template`
|
||||
dst = gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dst = gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gres.Export(src, dst)
|
||||
)
|
||||
defer gfile.Remove(dst)
|
||||
@ -252,7 +252,7 @@ func Test_Export(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
src = `template`
|
||||
dst = gfile.TempDir(gtime.TimestampNanoStr())
|
||||
dst = gfile.Temp(gtime.TimestampNanoStr())
|
||||
err = gres.Export(src, dst, gres.ExportOption{
|
||||
RemovePrefix: `template`,
|
||||
})
|
||||
|
@ -38,7 +38,7 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultStorageFilePath = gfile.TempDir("gsessions")
|
||||
DefaultStorageFilePath = gfile.Temp("gsessions")
|
||||
DefaultStorageFileCryptoKey = []byte("Session storage file crypto key!")
|
||||
)
|
||||
|
||||
|
@ -18,9 +18,15 @@ type Type struct {
|
||||
|
||||
// Field contains information of a struct field .
|
||||
type Field struct {
|
||||
Value reflect.Value // The underlying value of the field.
|
||||
Field reflect.StructField // The underlying field of the field.
|
||||
TagValue string // Retrieved tag value. There might be more than one tags in the field, but only one can be retrieved according to calling function rules.
|
||||
Value reflect.Value // The underlying value of the field.
|
||||
Field reflect.StructField // The underlying field of the field.
|
||||
|
||||
// Retrieved tag name. It depends TagValue.
|
||||
TagName string
|
||||
|
||||
// Retrieved tag value.
|
||||
// There might be more than one tags in the field, but only one can be retrieved according to calling function rules.
|
||||
TagValue string
|
||||
}
|
||||
|
||||
// FieldsInput is the input parameter struct type for function Fields.
|
||||
|
@ -180,7 +180,8 @@ func getFieldValuesByTagPriority(pointer interface{}, priority []string, tagMap
|
||||
return nil, err
|
||||
}
|
||||
var (
|
||||
tagValue = ""
|
||||
tagName string
|
||||
tagValue string
|
||||
tagFields = make([]Field, 0)
|
||||
)
|
||||
for _, field := range fields {
|
||||
@ -190,6 +191,7 @@ func getFieldValuesByTagPriority(pointer interface{}, priority []string, tagMap
|
||||
}
|
||||
tagValue = ""
|
||||
for _, p := range priority {
|
||||
tagName = p
|
||||
tagValue = field.Tag(p)
|
||||
if tagValue != "" && tagValue != "-" {
|
||||
break
|
||||
@ -201,6 +203,7 @@ func getFieldValuesByTagPriority(pointer interface{}, priority []string, tagMap
|
||||
continue
|
||||
}
|
||||
tagField := field
|
||||
tagField.TagName = tagName
|
||||
tagField.TagValue = tagValue
|
||||
tagFields = append(tagFields, tagField)
|
||||
}
|
||||
|
@ -80,7 +80,7 @@ func (view *View) Parse(ctx context.Context, file string, params ...Params) (res
|
||||
}
|
||||
// Monitor template files changes using fsnotify asynchronously.
|
||||
if resource == nil {
|
||||
if _, err := gfsnotify.AddOnce("gview.Parse:"+folder, folder, func(event *gfsnotify.Event) {
|
||||
if _, err = gfsnotify.AddOnce("gview.Parse:"+folder, folder, func(event *gfsnotify.Event) {
|
||||
// CLEAR THEM ALL.
|
||||
view.fileCacheMap.Clear()
|
||||
templates.Clear()
|
||||
@ -137,11 +137,11 @@ func (view *View) Parse(ctx context.Context, file string, params ...Params) (res
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := newTpl.Execute(buffer, variables); err != nil {
|
||||
if err = newTpl.Execute(buffer, variables); err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
if err := tpl.(*texttpl.Template).Execute(buffer, variables); err != nil {
|
||||
if err = tpl.(*texttpl.Template).Execute(buffer, variables); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
@ -222,7 +222,7 @@ func Test_FuncInclude(t *testing.T) {
|
||||
layout = `{{include "header.html" .}}
|
||||
{{include "main.html" .}}
|
||||
{{include "footer.html" .}}`
|
||||
templatePath = gfile.TempDir("template")
|
||||
templatePath = gfile.Temp("template")
|
||||
)
|
||||
|
||||
gfile.Mkdir(templatePath)
|
||||
@ -294,7 +294,7 @@ func Test_ParseContent(t *testing.T) {
|
||||
func Test_HotReload(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
dirPath := gfile.Join(
|
||||
gfile.TempDir(),
|
||||
gfile.Temp(),
|
||||
"testdata",
|
||||
"template-"+gconv.String(gtime.TimestampNano()),
|
||||
)
|
||||
|
@ -34,8 +34,8 @@ var (
|
||||
}
|
||||
|
||||
// StructTagPriority defines the default priority tags for Map*/Struct* functions.
|
||||
// Note, the "gconv", "param", "params" tags are used by old version of package.
|
||||
// It is strongly recommended using short tag "c" or "p" instead in the future.
|
||||
// Note, the `gconv/param/params` tags are used by old version of package.
|
||||
// It is strongly recommended using short tag `c/p` instead in the future.
|
||||
StructTagPriority = []string{"gconv", "param", "params", "c", "p", "json"}
|
||||
)
|
||||
|
||||
|
@ -248,6 +248,12 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string
|
||||
// orm:"id, priority"
|
||||
// orm:"name, with:uid=id"
|
||||
tagMap[attributeName] = utils.RemoveSymbols(strings.Split(tagName, ",")[0])
|
||||
|
||||
// If tag and attribute values both exist in `paramsMap`,
|
||||
// it then uses the tag value overwriting the attribute value in `paramsMap`.
|
||||
if paramsMap[tagName] != nil && paramsMap[attributeName] != nil {
|
||||
paramsMap[attributeName] = paramsMap[tagName]
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
@ -269,7 +275,7 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string
|
||||
// string cases and chars like '-'/'_'/'.'/' '.
|
||||
|
||||
// Matching the parameters to struct tag names.
|
||||
// The `tagV` is the attribute name of the struct.
|
||||
// The `attrKey` is the attribute name of the struct.
|
||||
for attrKey, cmpKey := range tagMap {
|
||||
if strings.EqualFold(checkName, cmpKey) {
|
||||
attrName = attrKey
|
||||
@ -297,12 +303,12 @@ func doStruct(params interface{}, pointer interface{}, mapping map[string]string
|
||||
continue
|
||||
}
|
||||
// If the attribute name is already checked converting, then skip it.
|
||||
if _, ok := doneMap[attrName]; ok {
|
||||
if _, ok = doneMap[attrName]; ok {
|
||||
continue
|
||||
}
|
||||
// Mark it done.
|
||||
doneMap[attrName] = struct{}{}
|
||||
if err := bindVarToStructAttr(pointerElemReflectValue, attrName, mapV, mapping); err != nil {
|
||||
if err = bindVarToStructAttr(pointerElemReflectValue, attrName, mapV, mapping); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user