mirror of
https://gitee.com/johng/gf
synced 2026-07-05 13:22:16 +08:00
remove deprecated functions; refract package gjson
This commit is contained in:
@ -17,25 +17,11 @@ func (v *Var) Struct(pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.Struct(v.Val(), pointer, mapping...)
|
||||
}
|
||||
|
||||
// StructDeep maps value of `v` to `pointer` recursively.
|
||||
// The parameter `pointer` should be a pointer to a struct instance.
|
||||
// The parameter `mapping` is used to specify the key-to-attribute mapping rules.
|
||||
// Deprecated, use Struct instead.
|
||||
func (v *Var) StructDeep(pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.StructDeep(v.Val(), pointer, mapping...)
|
||||
}
|
||||
|
||||
// Structs converts and returns `v` as given struct slice.
|
||||
func (v *Var) Structs(pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.Structs(v.Val(), pointer, mapping...)
|
||||
}
|
||||
|
||||
// StructsDeep converts and returns `v` as given struct slice recursively.
|
||||
// Deprecated, use Struct instead.
|
||||
func (v *Var) StructsDeep(pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.StructsDeep(v.Val(), pointer, mapping...)
|
||||
}
|
||||
|
||||
// Scan automatically calls Struct or Structs function according to the type of parameter
|
||||
// `pointer` to implement the converting.
|
||||
//
|
||||
@ -44,14 +30,3 @@ func (v *Var) StructsDeep(pointer interface{}, mapping ...map[string]string) err
|
||||
func (v *Var) Scan(pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.Scan(v.Val(), pointer, mapping...)
|
||||
}
|
||||
|
||||
// ScanDeep automatically calls StructDeep or StructsDeep function according to the type of
|
||||
// parameter `pointer` to implement the converting.
|
||||
//
|
||||
// It calls function StructDeep if `pointer` is type of *struct/**struct to do the converting.
|
||||
// It calls function StructsDeep if `pointer` is type of *[]struct/*[]*struct to do the converting.
|
||||
//
|
||||
// Deprecated, use Scan instead.
|
||||
func (v *Var) ScanDeep(pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.ScanDeep(v.Val(), pointer, mapping...)
|
||||
}
|
||||
|
||||
@ -33,14 +33,6 @@ type DB interface {
|
||||
// Model creation.
|
||||
// ===========================================================================
|
||||
|
||||
// Table function is deprecated, use Model instead.
|
||||
// The DB interface is designed not only for
|
||||
// relational databases but also for NoSQL databases in the future. The name
|
||||
// "Table" is not proper for that purpose any more.
|
||||
// Also see Core.Table.
|
||||
// Deprecated.
|
||||
Table(tableNameOrStruct ...interface{}) *Model
|
||||
|
||||
// Model creates and returns a new ORM model from given schema.
|
||||
// The parameter `table` can be more than one table names, and also alias name, like:
|
||||
// 1. Model names:
|
||||
|
||||
@ -217,19 +217,16 @@ func (c *Core) GetGroup() string {
|
||||
}
|
||||
|
||||
// SetDryRun enables/disables the DryRun feature.
|
||||
// Deprecated, use GetConfig instead.
|
||||
func (c *Core) SetDryRun(enabled bool) {
|
||||
c.config.DryRun = enabled
|
||||
}
|
||||
|
||||
// GetDryRun returns the DryRun value.
|
||||
// Deprecated, use GetConfig instead.
|
||||
func (c *Core) GetDryRun() bool {
|
||||
return c.config.DryRun || allDryRun
|
||||
}
|
||||
|
||||
// GetPrefix returns the table prefix string configured.
|
||||
// Deprecated, use GetConfig instead.
|
||||
func (c *Core) GetPrefix() string {
|
||||
return c.config.Prefix
|
||||
}
|
||||
|
||||
@ -76,13 +76,6 @@ const (
|
||||
defaultFields = "*"
|
||||
)
|
||||
|
||||
// Table is alias of Core.Model.
|
||||
// See Core.Model.
|
||||
// Deprecated, use Model instead.
|
||||
func (c *Core) Table(tableNameQueryOrStruct ...interface{}) *Model {
|
||||
return c.db.Model(tableNameQueryOrStruct...)
|
||||
}
|
||||
|
||||
// Model creates and returns a new ORM model from given schema.
|
||||
// The parameter `tableNameQueryOrStruct` can be more than one table names, and also alias name, like:
|
||||
// 1. Model names:
|
||||
|
||||
@ -236,27 +236,6 @@ func (m *Model) WhereOrNotNull(columns ...string) *Model {
|
||||
return model
|
||||
}
|
||||
|
||||
// And adds "AND" condition to the where statement.
|
||||
// Deprecated, use Where instead.
|
||||
func (m *Model) And(where interface{}, args ...interface{}) *Model {
|
||||
model := m.getModel()
|
||||
if model.whereHolder == nil {
|
||||
model.whereHolder = make([]ModelWhereHolder, 0)
|
||||
}
|
||||
model.whereHolder = append(model.whereHolder, ModelWhereHolder{
|
||||
Operator: whereHolderOperatorAnd,
|
||||
Where: where,
|
||||
Args: args,
|
||||
})
|
||||
return model
|
||||
}
|
||||
|
||||
// Or adds "OR" condition to the where statement.
|
||||
// Deprecated, use WhereOr instead.
|
||||
func (m *Model) Or(where interface{}, args ...interface{}) *Model {
|
||||
return m.WhereOr(where, args...)
|
||||
}
|
||||
|
||||
// Group sets the "GROUP BY" statement for the model.
|
||||
func (m *Model) Group(groupBy ...string) *Model {
|
||||
if len(groupBy) == 0 {
|
||||
@ -350,13 +329,6 @@ func (m *Model) Page(page, limit int) *Model {
|
||||
return model
|
||||
}
|
||||
|
||||
// ForPage is alias of Model.Page.
|
||||
// See Model.Page.
|
||||
// Deprecated, use Page instead.
|
||||
func (m *Model) ForPage(page, limit int) *Model {
|
||||
return m.Page(page, limit)
|
||||
}
|
||||
|
||||
// formatCondition formats where arguments of the model and returns a new condition sql and its arguments.
|
||||
// Note that this function does not change any attribute value of the `m`.
|
||||
//
|
||||
|
||||
@ -150,25 +150,6 @@ func (m *Model) appendFieldsExByStr(fieldsEx string) *Model {
|
||||
return m
|
||||
}
|
||||
|
||||
// Filter marks filtering the fields which does not exist in the fields of the operated table.
|
||||
// Note that this function supports only single table operations.
|
||||
// Deprecated, filter feature is automatically enabled from GoFrame v1.16.0, it is so no longer used.
|
||||
func (m *Model) Filter() *Model {
|
||||
if gstr.Contains(m.tables, " ") {
|
||||
panic("function Filter supports only single table operations")
|
||||
}
|
||||
model := m.getModel()
|
||||
model.filter = true
|
||||
return model
|
||||
}
|
||||
|
||||
// FieldsStr retrieves and returns all fields from the table, joined with char ','.
|
||||
// The optional parameter `prefix` specifies the prefix for each field, eg: FieldsStr("u.").
|
||||
// Deprecated, use GetFieldsStr instead.
|
||||
func (m *Model) FieldsStr(prefix ...string) string {
|
||||
return m.GetFieldsStr(prefix...)
|
||||
}
|
||||
|
||||
// GetFieldsStr retrieves and returns all fields from the table, joined with char ','.
|
||||
// The optional parameter `prefix` specifies the prefix for each field, eg: GetFieldsStr("u.").
|
||||
func (m *Model) GetFieldsStr(prefix ...string) string {
|
||||
@ -198,15 +179,6 @@ func (m *Model) GetFieldsStr(prefix ...string) string {
|
||||
return newFields
|
||||
}
|
||||
|
||||
// FieldsExStr retrieves and returns fields which are not in parameter `fields` from the table,
|
||||
// joined with char ','.
|
||||
// The parameter `fields` specifies the fields that are excluded.
|
||||
// The optional parameter `prefix` specifies the prefix for each field, eg: FieldsExStr("id", "u.").
|
||||
// Deprecated, use GetFieldsExStr instead.
|
||||
func (m *Model) FieldsExStr(fields string, prefix ...string) string {
|
||||
return m.GetFieldsExStr(fields, prefix...)
|
||||
}
|
||||
|
||||
// GetFieldsExStr retrieves and returns fields which are not in parameter `fields` from the table,
|
||||
// joined with char ','.
|
||||
// The parameter `fields` specifies the fields that are excluded.
|
||||
|
||||
@ -15,14 +15,6 @@ const (
|
||||
optionOmitNilData // 64
|
||||
)
|
||||
|
||||
// Option adds extra operation option for the model.
|
||||
// Deprecated, use separate operations instead.
|
||||
func (m *Model) Option(option int) *Model {
|
||||
model := m.getModel()
|
||||
model.option = model.option | option
|
||||
return model
|
||||
}
|
||||
|
||||
// OmitEmpty sets optionOmitEmpty option for the model, which automatically filers
|
||||
// the data and where parameters for `empty` values.
|
||||
func (m *Model) OmitEmpty() *Model {
|
||||
|
||||
@ -20,13 +20,6 @@ import (
|
||||
"github.com/gogf/gf/util/gconv"
|
||||
)
|
||||
|
||||
// Select is alias of Model.All.
|
||||
// See Model.All.
|
||||
// Deprecated, use All instead.
|
||||
func (m *Model) Select(where ...interface{}) (Result, error) {
|
||||
return m.All(where...)
|
||||
}
|
||||
|
||||
// All does "SELECT FROM ..." statement for the model.
|
||||
// It retrieves the records from table and returns the result as slice type.
|
||||
// It returns nil if there's no record retrieved with the given conditions from table.
|
||||
@ -197,15 +190,6 @@ func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error) {
|
||||
return all.Array(), nil
|
||||
}
|
||||
|
||||
// Struct retrieves one record from table and converts it into given struct.
|
||||
// The parameter `pointer` should be type of *struct/**struct. If type **struct is given,
|
||||
// it can create the struct internally during converting.
|
||||
//
|
||||
// Deprecated, use Scan instead.
|
||||
func (m *Model) Struct(pointer interface{}, where ...interface{}) error {
|
||||
return m.doStruct(pointer, where...)
|
||||
}
|
||||
|
||||
// Struct retrieves one record from table and converts it into given struct.
|
||||
// The parameter `pointer` should be type of *struct/**struct. If type **struct is given,
|
||||
// it can create the struct internally during converting.
|
||||
@ -242,15 +226,6 @@ func (m *Model) doStruct(pointer interface{}, where ...interface{}) error {
|
||||
return model.doWithScanStruct(pointer)
|
||||
}
|
||||
|
||||
// Structs retrieves records from table and converts them into given struct slice.
|
||||
// The parameter `pointer` should be type of *[]struct/*[]*struct. It can create and fill the struct
|
||||
// slice internally during converting.
|
||||
//
|
||||
// Deprecated, use Scan instead.
|
||||
func (m *Model) Structs(pointer interface{}, where ...interface{}) error {
|
||||
return m.doStructs(pointer, where...)
|
||||
}
|
||||
|
||||
// Structs retrieves records from table and converts them into given struct slice.
|
||||
// The parameter `pointer` should be type of *[]struct/*[]*struct. It can create and fill the struct
|
||||
// slice internally during converting.
|
||||
|
||||
@ -9,21 +9,21 @@ package gdb
|
||||
import (
|
||||
"database/sql"
|
||||
"github.com/gogf/gf/container/gmap"
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/encoding/gjson"
|
||||
"github.com/gogf/gf/internal/empty"
|
||||
"github.com/gogf/gf/util/gconv"
|
||||
)
|
||||
|
||||
// Json converts `r` to JSON format content.
|
||||
func (r Record) Json() string {
|
||||
content, _ := gparser.VarToJson(r.Map())
|
||||
return string(content)
|
||||
content, _ := gjson.New(r.Map()).ToJsonString()
|
||||
return content
|
||||
}
|
||||
|
||||
// Xml converts `r` to XML format content.
|
||||
func (r Record) Xml(rootTag ...string) string {
|
||||
content, _ := gparser.VarToXml(r.Map(), rootTag...)
|
||||
return string(content)
|
||||
content, _ := gjson.New(r.Map()).ToXmlString(rootTag...)
|
||||
return content
|
||||
}
|
||||
|
||||
// Map converts `r` to map[string]interface{}.
|
||||
|
||||
@ -8,7 +8,7 @@ package gdb
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/container/gvar"
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/encoding/gjson"
|
||||
"github.com/gogf/gf/util/gconv"
|
||||
"math"
|
||||
)
|
||||
@ -51,14 +51,14 @@ func (r Result) Chunk(size int) []Result {
|
||||
|
||||
// Json converts `r` to JSON format content.
|
||||
func (r Result) Json() string {
|
||||
content, _ := gparser.VarToJson(r.List())
|
||||
return string(content)
|
||||
content, _ := gjson.New(r.List()).ToJsonString()
|
||||
return content
|
||||
}
|
||||
|
||||
// Xml converts `r` to XML format content.
|
||||
func (r Result) Xml(rootTag ...string) string {
|
||||
content, _ := gparser.VarToXml(r.List(), rootTag...)
|
||||
return string(content)
|
||||
content, _ := gjson.New(r.List()).ToXmlString(rootTag...)
|
||||
return content
|
||||
}
|
||||
|
||||
// List converts `r` to a List.
|
||||
|
||||
@ -10,7 +10,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/container/garray"
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/text/gstr"
|
||||
"testing"
|
||||
"time"
|
||||
@ -210,7 +209,7 @@ func Test_DB_Insert_WithStructAndSliceAttribute(t *testing.T) {
|
||||
t.AssertNil(err)
|
||||
t.Assert(one["passport"], data["passport"])
|
||||
t.Assert(one["create_time"], data["create_time"])
|
||||
t.Assert(one["nickname"], gparser.MustToJson(data["nickname"]))
|
||||
t.Assert(one["nickname"], gjson.New(data["nickname"]).MustToJson())
|
||||
})
|
||||
}
|
||||
|
||||
@ -785,7 +784,7 @@ func Test_DB_ToJson(t *testing.T) {
|
||||
gtest.AssertNil(err)
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Fields("*").Where("id =? ", 1).Select()
|
||||
result, err := db.Model(table).Fields("*").Where("id =? ", 1).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -814,11 +813,11 @@ func Test_DB_ToJson(t *testing.T) {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
|
||||
t.Assert(users[0].Id, resultJson.GetInt("0.id"))
|
||||
t.Assert(users[0].Passport, resultJson.GetString("0.passport"))
|
||||
t.Assert(users[0].Password, resultJson.GetString("0.password"))
|
||||
t.Assert(users[0].NickName, resultJson.GetString("0.nickname"))
|
||||
t.Assert(users[0].CreateTime, resultJson.GetString("0.create_time"))
|
||||
t.Assert(users[0].Id, resultJson.Get("0.id").Int())
|
||||
t.Assert(users[0].Passport, resultJson.Get("0.passport").String())
|
||||
t.Assert(users[0].Password, resultJson.Get("0.password").String())
|
||||
t.Assert(users[0].NickName, resultJson.Get("0.nickname").String())
|
||||
t.Assert(users[0].CreateTime, resultJson.Get("0.create_time").String())
|
||||
|
||||
result = nil
|
||||
err = result.Structs(&users)
|
||||
@ -925,7 +924,7 @@ func Test_DB_ToStringMap(t *testing.T) {
|
||||
gtest.AssertNil(err)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
id := "1"
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", 1).Select()
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", 1).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -962,7 +961,7 @@ func Test_DB_ToIntMap(t *testing.T) {
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
id := 1
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).Select()
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -998,7 +997,7 @@ func Test_DB_ToUintMap(t *testing.T) {
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
id := 1
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).Select()
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -1036,7 +1035,7 @@ func Test_DB_ToStringRecord(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
id := 1
|
||||
ids := "1"
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).Select()
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -1073,7 +1072,7 @@ func Test_DB_ToIntRecord(t *testing.T) {
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
id := 1
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).Select()
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -1110,7 +1109,7 @@ func Test_DB_ToUintRecord(t *testing.T) {
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
id := 1
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).Select()
|
||||
result, err := db.Model(table).Fields("*").Where("id = ?", id).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -1182,7 +1181,7 @@ func Test_DB_TableField(t *testing.T) {
|
||||
gtest.Assert(n, 1)
|
||||
}
|
||||
|
||||
result, err := db.Model(name).Fields("*").Where("field_int = ?", 2).Select()
|
||||
result, err := db.Model(name).Fields("*").Where("field_int = ?", 2).All()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
@ -1313,14 +1312,14 @@ func Test_Model_InnerJoin(t *testing.T) {
|
||||
|
||||
t.Assert(n, 5)
|
||||
|
||||
result, err := db.Model(table1+" u1").InnerJoin(table2+" u2", "u1.id = u2.id").Order("u1.id").Select()
|
||||
result, err := db.Model(table1+" u1").InnerJoin(table2+" u2", "u1.id = u2.id").Order("u1.id").All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Assert(len(result), 5)
|
||||
|
||||
result, err = db.Model(table1+" u1").InnerJoin(table2+" u2", "u1.id = u2.id").Where("u1.id > ?", 1).Order("u1.id").Select()
|
||||
result, err = db.Model(table1+" u1").InnerJoin(table2+" u2", "u1.id = u2.id").Where("u1.id > ?", 1).Order("u1.id").All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@ -1349,14 +1348,14 @@ func Test_Model_LeftJoin(t *testing.T) {
|
||||
t.Assert(n, 7)
|
||||
}
|
||||
|
||||
result, err := db.Model(table1+" u1").LeftJoin(table2+" u2", "u1.id = u2.id").Select()
|
||||
result, err := db.Model(table1+" u1").LeftJoin(table2+" u2", "u1.id = u2.id").All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Assert(len(result), 10)
|
||||
|
||||
result, err = db.Model(table1+" u1").LeftJoin(table2+" u2", "u1.id = u2.id").Where("u1.id > ? ", 2).Select()
|
||||
result, err = db.Model(table1+" u1").LeftJoin(table2+" u2", "u1.id = u2.id").Where("u1.id > ? ", 2).All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@ -1385,13 +1384,13 @@ func Test_Model_RightJoin(t *testing.T) {
|
||||
|
||||
t.Assert(n, 7)
|
||||
|
||||
result, err := db.Model(table1+" u1").RightJoin(table2+" u2", "u1.id = u2.id").Select()
|
||||
result, err := db.Model(table1+" u1").RightJoin(table2+" u2", "u1.id = u2.id").All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Assert(len(result), 10)
|
||||
|
||||
result, err = db.Model(table1+" u1").RightJoin(table2+" u2", "u1.id = u2.id").Where("u1.id > 2").Select()
|
||||
result, err = db.Model(table1+" u1").RightJoin(table2+" u2", "u1.id = u2.id").Where("u1.id > 2").All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@ -10,13 +10,13 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/encoding/gjson"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/container/garray"
|
||||
"github.com/gogf/gf/container/gmap"
|
||||
"github.com/gogf/gf/debug/gdebug"
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/os/gfile"
|
||||
"github.com/gogf/gf/util/gutil"
|
||||
|
||||
@ -124,7 +124,7 @@ func Test_Model_Insert_WithStructAndSliceAttribute(t *testing.T) {
|
||||
t.AssertNil(err)
|
||||
t.Assert(one["passport"], data["passport"])
|
||||
t.Assert(one["create_time"], data["create_time"])
|
||||
t.Assert(one["nickname"], gparser.MustToJson(data["nickname"]))
|
||||
t.Assert(one["nickname"], gjson.New(data["nickname"]).MustToJson())
|
||||
})
|
||||
}
|
||||
|
||||
@ -465,7 +465,7 @@ func Test_Model_Safe(t *testing.T) {
|
||||
t.AssertNil(err)
|
||||
t.Assert(count, 2)
|
||||
|
||||
md.And("id = ?", 1)
|
||||
md.Where("id = ?", 1)
|
||||
count, err = md.Count()
|
||||
t.AssertNil(err)
|
||||
t.Assert(count, 1)
|
||||
@ -476,7 +476,7 @@ func Test_Model_Safe(t *testing.T) {
|
||||
t.AssertNil(err)
|
||||
t.Assert(count, 2)
|
||||
|
||||
md.And("id = ?", 1)
|
||||
md.Where("id = ?", 1)
|
||||
count, err = md.Count()
|
||||
t.AssertNil(err)
|
||||
t.Assert(count, 2)
|
||||
@ -488,7 +488,7 @@ func Test_Model_Safe(t *testing.T) {
|
||||
t.AssertNil(err)
|
||||
t.Assert(count, 2)
|
||||
|
||||
md.And("id = ?", 1)
|
||||
md.Where("id = ?", 1)
|
||||
count, err = md.Count()
|
||||
t.AssertNil(err)
|
||||
t.Assert(count, 2)
|
||||
@ -882,7 +882,7 @@ func Test_Model_Select(t *testing.T) {
|
||||
table := createInitTable()
|
||||
defer dropTable(table)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Select()
|
||||
result, err := db.Model(table).All()
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(result), TableSize)
|
||||
})
|
||||
@ -1214,7 +1214,7 @@ func Test_Model_OrderBy(t *testing.T) {
|
||||
defer dropTable(table)
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Order("id DESC").Select()
|
||||
result, err := db.Model(table).Order("id DESC").All()
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(result), TableSize)
|
||||
t.Assert(result[0]["nickname"].String(), fmt.Sprintf("name_%d", TableSize))
|
||||
@ -1326,7 +1326,7 @@ func Test_Model_Where(t *testing.T) {
|
||||
result, err := db.Model(table).Where(g.Map{
|
||||
"id": g.Slice{1, 2, 3},
|
||||
"passport": g.Slice{"user_2", "user_3"},
|
||||
}).And("id=? and nickname=?", g.Slice{3, "name_3"}).One()
|
||||
}).Where("id=? and nickname=?", g.Slice{3, "name_3"}).One()
|
||||
t.AssertNil(err)
|
||||
t.AssertGT(len(result), 0)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
@ -1355,22 +1355,22 @@ func Test_Model_Where(t *testing.T) {
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Where("id", 3).And("nickname", "name_3").One()
|
||||
result, err := db.Model(table).Where("id", 3).Where("nickname", "name_3").One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Where("id", 30).Or("nickname", "name_3").One()
|
||||
result, err := db.Model(table).Where("id", 30).WhereOr("nickname", "name_3").One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Where("id", 30).Or("nickname", "name_3").And("id>?", 1).One()
|
||||
result, err := db.Model(table).Where("id", 30).WhereOr("nickname", "name_3").Where("id>?", 1).One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Where("id", 30).Or("nickname", "name_3").And("id>", 1).One()
|
||||
result, err := db.Model(table).Where("id", 30).WhereOr("nickname", "name_3").Where("id>", 1).One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
@ -1653,7 +1653,7 @@ func Test_Model_WherePri(t *testing.T) {
|
||||
result, err := db.Model(table).WherePri(g.Map{
|
||||
"id": g.Slice{1, 2, 3},
|
||||
"passport": g.Slice{"user_2", "user_3"},
|
||||
}).And("id=? and nickname=?", g.Slice{3, "name_3"}).One()
|
||||
}).Where("id=? and nickname=?", g.Slice{3, "name_3"}).One()
|
||||
t.AssertNil(err)
|
||||
t.AssertGT(len(result), 0)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
@ -1662,7 +1662,7 @@ func Test_Model_WherePri(t *testing.T) {
|
||||
result, err := db.Model(table).WherePri(g.Map{
|
||||
"id": g.Slice{1, 2, 3},
|
||||
"passport": g.Slice{"user_2", "user_3"},
|
||||
}).Or("nickname=?", g.Slice{"name_4"}).And("id", 3).One()
|
||||
}).WhereOr("nickname=?", g.Slice{"name_4"}).Where("id", 3).One()
|
||||
t.AssertNil(err)
|
||||
t.AssertGT(len(result), 0)
|
||||
t.Assert(result["id"].Int(), 2)
|
||||
@ -1691,22 +1691,22 @@ func Test_Model_WherePri(t *testing.T) {
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).WherePri("id", 3).And("nickname", "name_3").One()
|
||||
result, err := db.Model(table).WherePri("id", 3).Where("nickname", "name_3").One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).WherePri("id", 30).Or("nickname", "name_3").One()
|
||||
result, err := db.Model(table).WherePri("id", 30).WhereOr("nickname", "name_3").One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).WherePri("id", 30).Or("nickname", "name_3").And("id>?", 1).One()
|
||||
result, err := db.Model(table).WherePri("id", 30).WhereOr("nickname", "name_3").Where("id>?", 1).One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).WherePri("id", 30).Or("nickname", "name_3").And("id>", 1).One()
|
||||
result, err := db.Model(table).WherePri("id", 30).WhereOr("nickname", "name_3").Where("id>", 1).One()
|
||||
t.AssertNil(err)
|
||||
t.Assert(result["id"].Int(), 3)
|
||||
})
|
||||
@ -1887,7 +1887,7 @@ func Test_Model_Offset(t *testing.T) {
|
||||
table := createInitTable()
|
||||
defer dropTable(table)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
result, err := db.Model(table).Limit(2).Offset(5).Order("id").Select()
|
||||
result, err := db.Model(table).Limit(2).Offset(5).Order("id").All()
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(result), 2)
|
||||
t.Assert(result[0]["id"], 6)
|
||||
@ -2208,7 +2208,7 @@ func Test_Model_Option_Where(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
table := createInitTable()
|
||||
defer dropTable(table)
|
||||
r, err := db.Model(table).OmitEmpty().Data("nickname", 1).Where(g.Map{"id": 0, "passport": ""}).And(1).Update()
|
||||
r, err := db.Model(table).OmitEmpty().Data("nickname", 1).Where(g.Map{"id": 0, "passport": ""}).Where(1).Update()
|
||||
t.AssertNil(err)
|
||||
n, _ := r.RowsAffected()
|
||||
t.Assert(n, TableSize)
|
||||
@ -2246,7 +2246,7 @@ func Test_Model_Where_MultiSliceArguments(t *testing.T) {
|
||||
result, err := db.Model(table).Where(g.Map{
|
||||
"id": g.Slice{1, 2, 3},
|
||||
"passport": g.Slice{"user_2", "user_3"},
|
||||
}).Or("nickname=?", g.Slice{"name_4"}).And("id", 3).One()
|
||||
}).WhereOr("nickname=?", g.Slice{"name_4"}).Where("id", 3).One()
|
||||
t.AssertNil(err)
|
||||
t.AssertGT(len(result), 0)
|
||||
t.Assert(result["id"].Int(), 2)
|
||||
@ -2300,26 +2300,6 @@ func Test_Model_FieldsEx_WithReservedWords(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Model_FieldsStr(t *testing.T) {
|
||||
table := createTable()
|
||||
defer dropTable(table)
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
t.Assert(db.Model(table).FieldsStr(), "`id`,`passport`,`password`,`nickname`,`create_time`")
|
||||
t.Assert(db.Model(table).FieldsStr("a."), "`a`.`id`,`a`.`passport`,`a`.`password`,`a`.`nickname`,`a`.`create_time`")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Model_FieldsExStr(t *testing.T) {
|
||||
table := createTable()
|
||||
defer dropTable(table)
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
t.Assert(db.Model(table).FieldsExStr("create_time,nickname"), "`id`,`passport`,`password`")
|
||||
t.Assert(db.Model(table).FieldsExStr("create_time,nickname", "a."), "`a`.`id`,`a`.`passport`,`a`.`password`")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Model_Prefix(t *testing.T) {
|
||||
db := dbPrefix
|
||||
table := fmt.Sprintf(`%s_%d`, TableName, gtime.TimestampNano())
|
||||
|
||||
@ -641,7 +641,7 @@ CREATE TABLE %s (
|
||||
n, _ := r.RowsAffected()
|
||||
t.Assert(n, 3)
|
||||
|
||||
count, err := db.Model(table).Where("id", 1).Or("id", 3).Count()
|
||||
count, err := db.Model(table).Where("id", 1).WhereOr("id", 3).Count()
|
||||
t.AssertNil(err)
|
||||
t.Assert(count, 0)
|
||||
})
|
||||
|
||||
@ -10,21 +10,11 @@ import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/errors/gcode"
|
||||
"github.com/gogf/gf/errors/gerror"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/util/gutil"
|
||||
|
||||
"github.com/gogf/gf/container/gvar"
|
||||
"github.com/gogf/gf/os/gtime"
|
||||
"github.com/gogf/gf/util/gconv"
|
||||
)
|
||||
|
||||
// Value returns the json value.
|
||||
// Deprecated, use Interface instead.
|
||||
func (j *Json) Value() interface{} {
|
||||
return j.Interface()
|
||||
}
|
||||
|
||||
// Interface returns the json value.
|
||||
func (j *Json) Interface() interface{} {
|
||||
j.mu.RLock()
|
||||
@ -34,7 +24,7 @@ func (j *Json) Interface() interface{} {
|
||||
|
||||
// Var returns the json value as *gvar.Var.
|
||||
func (j *Json) Var() *gvar.Var {
|
||||
return gvar.New(j.Value())
|
||||
return gvar.New(j.Interface())
|
||||
}
|
||||
|
||||
// IsNil checks whether the value pointed by <j> is nil.
|
||||
@ -52,7 +42,7 @@ func (j *Json) IsNil() bool {
|
||||
// "list.10", "array.0.name", "array.0.1.id".
|
||||
//
|
||||
// It returns a default value specified by <def> if value for <pattern> is not found.
|
||||
func (j *Json) Get(pattern string, def ...interface{}) interface{} {
|
||||
func (j *Json) Get(pattern string, def ...interface{}) *gvar.Var {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
|
||||
@ -68,47 +58,10 @@ func (j *Json) Get(pattern string, def ...interface{}) interface{} {
|
||||
result = j.getPointerByPatternWithoutViolenceCheck(pattern)
|
||||
}
|
||||
if result != nil {
|
||||
return *result
|
||||
return gvar.New(*result)
|
||||
}
|
||||
if len(def) > 0 {
|
||||
return def[0]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetVar returns a gvar.Var with value by given <pattern>.
|
||||
func (j *Json) GetVar(pattern string, def ...interface{}) *gvar.Var {
|
||||
return gvar.New(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetVars returns []*gvar.Var with value by given <pattern>.
|
||||
func (j *Json) GetVars(pattern string, def ...interface{}) []*gvar.Var {
|
||||
return gvar.New(j.Get(pattern, def...)).Vars()
|
||||
}
|
||||
|
||||
// GetMap retrieves and returns the value by specified <pattern> as map[string]interface{}.
|
||||
func (j *Json) GetMap(pattern string, def ...interface{}) map[string]interface{} {
|
||||
result := j.Get(pattern, def...)
|
||||
if result != nil {
|
||||
return gconv.Map(result)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMapStrStr retrieves and returns the value by specified <pattern> as map[string]string.
|
||||
func (j *Json) GetMapStrStr(pattern string, def ...interface{}) map[string]string {
|
||||
result := j.Get(pattern, def...)
|
||||
if result != nil {
|
||||
return gconv.MapStrStr(result)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMaps retrieves and returns the value by specified <pattern> as []map[string]interface{}.
|
||||
func (j *Json) GetMaps(pattern string, def ...interface{}) []map[string]interface{} {
|
||||
result := j.Get(pattern, def...)
|
||||
if result != nil {
|
||||
return gconv.Maps(result)
|
||||
return gvar.New(def[0])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -116,13 +69,13 @@ func (j *Json) GetMaps(pattern string, def ...interface{}) []map[string]interfac
|
||||
// GetJson gets the value by specified <pattern>,
|
||||
// and converts it to a un-concurrent-safe Json object.
|
||||
func (j *Json) GetJson(pattern string, def ...interface{}) *Json {
|
||||
return New(j.Get(pattern, def...))
|
||||
return New(j.Get(pattern, def...).Val())
|
||||
}
|
||||
|
||||
// GetJsons gets the value by specified <pattern>,
|
||||
// and converts it to a slice of un-concurrent-safe Json object.
|
||||
func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json {
|
||||
array := j.GetArray(pattern, def...)
|
||||
array := j.Get(pattern, def...).Array()
|
||||
if len(array) > 0 {
|
||||
jsonSlice := make([]*Json, len(array))
|
||||
for i := 0; i < len(array); i++ {
|
||||
@ -136,7 +89,7 @@ func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json {
|
||||
// GetJsonMap gets the value by specified <pattern>,
|
||||
// and converts it to a map of un-concurrent-safe Json object.
|
||||
func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json {
|
||||
m := j.GetMap(pattern, def...)
|
||||
m := j.Get(pattern, def...).Map()
|
||||
if len(m) > 0 {
|
||||
jsonMap := make(map[string]*Json, len(m))
|
||||
for k, v := range m {
|
||||
@ -147,126 +100,6 @@ func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetArray retrieves the value by specified <pattern>,
|
||||
// and converts it to a slice of []interface{}.
|
||||
func (j *Json) GetArray(pattern string, def ...interface{}) []interface{} {
|
||||
return gconv.Interfaces(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetString retrieves the value by specified <pattern> and converts it to string.
|
||||
func (j *Json) GetString(pattern string, def ...interface{}) string {
|
||||
return gconv.String(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetBytes retrieves the value by specified <pattern> and converts it to []byte.
|
||||
func (j *Json) GetBytes(pattern string, def ...interface{}) []byte {
|
||||
return gconv.Bytes(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetBool retrieves the value by specified <pattern>,
|
||||
// converts and returns it as bool.
|
||||
// It returns false when value is: "", 0, false, off, nil;
|
||||
// or returns true instead.
|
||||
func (j *Json) GetBool(pattern string, def ...interface{}) bool {
|
||||
return gconv.Bool(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetInt retrieves the value by specified <pattern> and converts it to int.
|
||||
func (j *Json) GetInt(pattern string, def ...interface{}) int {
|
||||
return gconv.Int(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetInt8 retrieves the value by specified <pattern> and converts it to int8.
|
||||
func (j *Json) GetInt8(pattern string, def ...interface{}) int8 {
|
||||
return gconv.Int8(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetInt16 retrieves the value by specified <pattern> and converts it to int16.
|
||||
func (j *Json) GetInt16(pattern string, def ...interface{}) int16 {
|
||||
return gconv.Int16(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetInt32 retrieves the value by specified <pattern> and converts it to int32.
|
||||
func (j *Json) GetInt32(pattern string, def ...interface{}) int32 {
|
||||
return gconv.Int32(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetInt64 retrieves the value by specified <pattern> and converts it to int64.
|
||||
func (j *Json) GetInt64(pattern string, def ...interface{}) int64 {
|
||||
return gconv.Int64(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetUint retrieves the value by specified <pattern> and converts it to uint.
|
||||
func (j *Json) GetUint(pattern string, def ...interface{}) uint {
|
||||
return gconv.Uint(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetUint8 retrieves the value by specified <pattern> and converts it to uint8.
|
||||
func (j *Json) GetUint8(pattern string, def ...interface{}) uint8 {
|
||||
return gconv.Uint8(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetUint16 retrieves the value by specified <pattern> and converts it to uint16.
|
||||
func (j *Json) GetUint16(pattern string, def ...interface{}) uint16 {
|
||||
return gconv.Uint16(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetUint32 retrieves the value by specified <pattern> and converts it to uint32.
|
||||
func (j *Json) GetUint32(pattern string, def ...interface{}) uint32 {
|
||||
return gconv.Uint32(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetUint64 retrieves the value by specified <pattern> and converts it to uint64.
|
||||
func (j *Json) GetUint64(pattern string, def ...interface{}) uint64 {
|
||||
return gconv.Uint64(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetFloat32 retrieves the value by specified <pattern> and converts it to float32.
|
||||
func (j *Json) GetFloat32(pattern string, def ...interface{}) float32 {
|
||||
return gconv.Float32(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetFloat64 retrieves the value by specified <pattern> and converts it to float64.
|
||||
func (j *Json) GetFloat64(pattern string, def ...interface{}) float64 {
|
||||
return gconv.Float64(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetFloats retrieves the value by specified <pattern> and converts it to []float64.
|
||||
func (j *Json) GetFloats(pattern string, def ...interface{}) []float64 {
|
||||
return gconv.Floats(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetInts retrieves the value by specified <pattern> and converts it to []int.
|
||||
func (j *Json) GetInts(pattern string, def ...interface{}) []int {
|
||||
return gconv.Ints(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetStrings retrieves the value by specified <pattern> and converts it to []string.
|
||||
func (j *Json) GetStrings(pattern string, def ...interface{}) []string {
|
||||
return gconv.Strings(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetInterfaces is alias of GetArray.
|
||||
// See GetArray.
|
||||
func (j *Json) GetInterfaces(pattern string, def ...interface{}) []interface{} {
|
||||
return gconv.Interfaces(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetTime retrieves the value by specified <pattern> and converts it to time.Time.
|
||||
func (j *Json) GetTime(pattern string, format ...string) time.Time {
|
||||
return gconv.Time(j.Get(pattern), format...)
|
||||
}
|
||||
|
||||
// GetDuration retrieves the value by specified <pattern> and converts it to time.Duration.
|
||||
func (j *Json) GetDuration(pattern string, def ...interface{}) time.Duration {
|
||||
return gconv.Duration(j.Get(pattern, def...))
|
||||
}
|
||||
|
||||
// GetGTime retrieves the value by specified <pattern> and converts it to *gtime.Time.
|
||||
func (j *Json) GetGTime(pattern string, format ...string) *gtime.Time {
|
||||
return gconv.GTime(j.Get(pattern), format...)
|
||||
}
|
||||
|
||||
// Set sets value with specified <pattern>.
|
||||
// It supports hierarchical data access by char separator, which is '.' in default.
|
||||
func (j *Json) Set(pattern string, value interface{}) error {
|
||||
@ -322,101 +155,22 @@ func (j *Json) Append(pattern string, value interface{}) error {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "invalid variable type of %s", pattern)
|
||||
}
|
||||
|
||||
// GetStruct retrieves the value by specified <pattern> and converts it to specified object
|
||||
// <pointer>. The <pointer> should be the pointer to an object.
|
||||
func (j *Json) GetStruct(pattern string, pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.Struct(j.Get(pattern), pointer, mapping...)
|
||||
}
|
||||
|
||||
// GetStructs converts any slice to given struct slice.
|
||||
func (j *Json) GetStructs(pattern string, pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.Structs(j.Get(pattern), pointer, mapping...)
|
||||
}
|
||||
|
||||
// GetScan automatically calls Struct or Structs function according to the type of parameter
|
||||
// <pointer> to implement the converting..
|
||||
func (j *Json) GetScan(pattern string, pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.Scan(j.Get(pattern), pointer, mapping...)
|
||||
}
|
||||
|
||||
// GetScanDeep automatically calls StructDeep or StructsDeep function according to the type of
|
||||
// parameter <pointer> to implement the converting..
|
||||
func (j *Json) GetScanDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.ScanDeep(j.Get(pattern), pointer, mapping...)
|
||||
}
|
||||
|
||||
// GetMapToMap retrieves the value by specified <pattern> and converts it to specified map variable.
|
||||
// See gconv.MapToMap.
|
||||
func (j *Json) GetMapToMap(pattern string, pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.MapToMap(j.Get(pattern), pointer, mapping...)
|
||||
}
|
||||
|
||||
// GetMapToMaps retrieves the value by specified <pattern> and converts it to specified map slice
|
||||
// variable.
|
||||
// See gconv.MapToMaps.
|
||||
func (j *Json) GetMapToMaps(pattern string, pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.MapToMaps(j.Get(pattern), pointer, mapping...)
|
||||
}
|
||||
|
||||
// GetMapToMapsDeep retrieves the value by specified <pattern> and converts it to specified map slice
|
||||
// variable recursively.
|
||||
// See gconv.MapToMapsDeep.
|
||||
func (j *Json) GetMapToMapsDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.MapToMapsDeep(j.Get(pattern), pointer, mapping...)
|
||||
}
|
||||
|
||||
// Map converts current Json object to map[string]interface{}.
|
||||
// It returns nil if fails.
|
||||
func (j *Json) Map() map[string]interface{} {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.Map(*(j.p))
|
||||
return j.Var().Map()
|
||||
}
|
||||
|
||||
// Array converts current Json object to []interface{}.
|
||||
// It returns nil if fails.
|
||||
func (j *Json) Array() []interface{} {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.Interfaces(*(j.p))
|
||||
}
|
||||
|
||||
// Struct converts current Json object to specified object.
|
||||
// The <pointer> should be a pointer type of *struct.
|
||||
func (j *Json) Struct(pointer interface{}, mapping ...map[string]string) error {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.Struct(*(j.p), pointer, mapping...)
|
||||
}
|
||||
|
||||
// Structs converts current Json object to specified object slice.
|
||||
// The <pointer> should be a pointer type of []struct/*struct.
|
||||
func (j *Json) Structs(pointer interface{}, mapping ...map[string]string) error {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.Structs(*(j.p), pointer, mapping...)
|
||||
return j.Var().Array()
|
||||
}
|
||||
|
||||
// Scan automatically calls Struct or Structs function according to the type of parameter
|
||||
// <pointer> to implement the converting..
|
||||
// <pointer> to implement the converting.
|
||||
func (j *Json) Scan(pointer interface{}, mapping ...map[string]string) error {
|
||||
return gconv.Scan(*(j.p), pointer, mapping...)
|
||||
}
|
||||
|
||||
// MapToMap converts current Json object to specified map variable.
|
||||
// The parameter of <pointer> should be type of *map.
|
||||
func (j *Json) MapToMap(pointer interface{}, mapping ...map[string]string) error {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.MapToMap(*(j.p), pointer, mapping...)
|
||||
}
|
||||
|
||||
// MapToMaps converts current Json object to specified map variable slice.
|
||||
// The parameter of <pointer> should be type of []map/*map.
|
||||
func (j *Json) MapToMaps(pointer interface{}, mapping ...map[string]string) error {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.MapToMaps(*(j.p), pointer, mapping...)
|
||||
return j.Var().Scan(pointer, mapping...)
|
||||
}
|
||||
|
||||
// Dump prints current Json object with more manually readable.
|
||||
|
||||
@ -69,7 +69,7 @@ func (j *Json) MustToJsonIndentString() string {
|
||||
// ========================================================================
|
||||
|
||||
func (j *Json) ToXml(rootTag ...string) ([]byte, error) {
|
||||
return gxml.Encode(j.Map(), rootTag...)
|
||||
return gxml.Encode(j.Var().Map(), rootTag...)
|
||||
}
|
||||
|
||||
func (j *Json) ToXmlString(rootTag ...string) (string, error) {
|
||||
@ -78,7 +78,7 @@ func (j *Json) ToXmlString(rootTag ...string) (string, error) {
|
||||
}
|
||||
|
||||
func (j *Json) ToXmlIndent(rootTag ...string) ([]byte, error) {
|
||||
return gxml.EncodeWithIndent(j.Map(), rootTag...)
|
||||
return gxml.EncodeWithIndent(j.Var().Map(), rootTag...)
|
||||
}
|
||||
|
||||
func (j *Json) ToXmlIndentString(rootTag ...string) (string, error) {
|
||||
|
||||
@ -76,7 +76,7 @@ func Example_conversionGetStruct() {
|
||||
Array []string
|
||||
}
|
||||
users := new(Users)
|
||||
if err := j.GetStruct("users", users); err != nil {
|
||||
if err := j.Get("users").Scan(users); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf(`%+v`, users)
|
||||
@ -101,7 +101,7 @@ func Example_conversionToStruct() {
|
||||
Array []string
|
||||
}
|
||||
users := new(Users)
|
||||
if err := j.Struct(users); err != nil {
|
||||
if err := j.Var().Scan(users); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf(`%+v`, users)
|
||||
|
||||
@ -17,8 +17,8 @@ func Example_dataSetCreate1() {
|
||||
j.Set("score", 99.5)
|
||||
fmt.Printf(
|
||||
"Name: %s, Score: %v\n",
|
||||
j.GetString("name"),
|
||||
j.GetFloat32("score"),
|
||||
j.Get("name").String(),
|
||||
j.Get("score").Float32(),
|
||||
)
|
||||
fmt.Println(j.MustToJsonString())
|
||||
|
||||
@ -54,7 +54,7 @@ func Example_dataSetRuntimeEdit() {
|
||||
panic(err)
|
||||
} else {
|
||||
j.Set("users.list.1.score", 100)
|
||||
fmt.Println("John Score:", j.GetFloat32("users.list.1.score"))
|
||||
fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
|
||||
fmt.Println(j.MustToJsonString())
|
||||
}
|
||||
// Output:
|
||||
|
||||
@ -25,7 +25,7 @@ func Example_patternGet() {
|
||||
if j, err := gjson.DecodeToJson(data); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
fmt.Println("John Score:", j.GetFloat32("users.list.1.score"))
|
||||
fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
|
||||
}
|
||||
// Output:
|
||||
// John Score: 99.5
|
||||
@ -46,7 +46,7 @@ func Example_patternCustomSplitChar() {
|
||||
panic(err)
|
||||
} else {
|
||||
j.SetSplitChar('#')
|
||||
fmt.Println("John Score:", j.GetFloat32("users#list#1#score"))
|
||||
fmt.Println("John Score:", j.Get("users#list#1#score").Float32())
|
||||
}
|
||||
// Output:
|
||||
// John Score: 99.5
|
||||
@ -64,7 +64,7 @@ func Example_patternViolenceCheck() {
|
||||
panic(err)
|
||||
} else {
|
||||
j.SetViolenceCheck(true)
|
||||
fmt.Println("Users Count:", j.GetInt("users.count"))
|
||||
fmt.Println("Users Count:", j.Get("users.count").Int())
|
||||
}
|
||||
// Output:
|
||||
// Users Count: 101
|
||||
@ -73,23 +73,23 @@ func Example_patternViolenceCheck() {
|
||||
func Example_mapSliceChange() {
|
||||
jsonContent := `{"map":{"key":"value"}, "slice":[59,90]}`
|
||||
j, _ := gjson.LoadJson(jsonContent)
|
||||
m := j.GetMap("map")
|
||||
m := j.Get("map").Map()
|
||||
fmt.Println(m)
|
||||
|
||||
// Change the key-value pair.
|
||||
m["key"] = "john"
|
||||
|
||||
// It changes the underlying key-value pair.
|
||||
fmt.Println(j.GetMap("map"))
|
||||
fmt.Println(j.Get("map").Map())
|
||||
|
||||
s := j.GetArray("slice")
|
||||
s := j.Get("slice").Array()
|
||||
fmt.Println(s)
|
||||
|
||||
// Change the value of specified index.
|
||||
s[0] = 100
|
||||
|
||||
// It changes the underlying slice.
|
||||
fmt.Println(j.GetArray("slice"))
|
||||
fmt.Println(j.Get("slice").Array())
|
||||
|
||||
// output:
|
||||
// map[key:value]
|
||||
|
||||
@ -19,9 +19,9 @@ func Test_New(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gjson.New(data)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("a").Array(), g.Slice{1, 2, 3})
|
||||
})
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
@ -82,11 +82,11 @@ func Test_Decode(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("a").Array(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -96,11 +96,11 @@ func Test_SplitChar(t *testing.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
j.SetSplitChar(byte('#'))
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m#k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a#1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m#k").String(), "v")
|
||||
t.Assert(j.Get("a").Array(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a#1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -121,11 +121,11 @@ func Test_GetVar(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.GetVar("n").String(), "123456789")
|
||||
t.Assert(j.GetVar("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.GetVar("a").Interfaces(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.GetVar("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.GetVar("a").Array(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("a").Interfaces(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a").Array(), g.Slice{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
@ -134,9 +134,9 @@ func Test_GetMap(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.GetMap("n"), nil)
|
||||
t.Assert(j.GetMap("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.GetMap("a"), g.Map{"1": "2", "3": nil})
|
||||
t.Assert(j.Get("n").Map(), nil)
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("a").Map(), g.Map{"1": "2", "3": nil})
|
||||
})
|
||||
}
|
||||
|
||||
@ -158,9 +158,9 @@ func Test_GetArray(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.GetArray("n"), g.Array{123456789})
|
||||
t.Assert(j.GetArray("m"), g.Array{g.Map{"k": "v"}})
|
||||
t.Assert(j.GetArray("a"), g.Array{1, 2, 3})
|
||||
t.Assert(j.Get("n").Array(), g.Array{123456789})
|
||||
t.Assert(j.Get("m").Array(), g.Array{g.Map{"k": "v"}})
|
||||
t.Assert(j.Get("a").Array(), g.Array{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
@ -169,10 +169,10 @@ func Test_GetString(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
t.Assert(err, nil)
|
||||
t.AssertEQ(j.GetString("n"), "123456789")
|
||||
t.AssertEQ(j.GetString("m"), `{"k":"v"}`)
|
||||
t.AssertEQ(j.GetString("a"), `[1,2,3]`)
|
||||
t.AssertEQ(j.GetString("i"), "")
|
||||
t.AssertEQ(j.Get("n").String(), "123456789")
|
||||
t.AssertEQ(j.Get("m").String(), `{"k":"v"}`)
|
||||
t.AssertEQ(j.Get("a").String(), `[1,2,3]`)
|
||||
t.AssertEQ(j.Get("i").String(), "")
|
||||
})
|
||||
}
|
||||
|
||||
@ -181,10 +181,10 @@ func Test_GetStrings(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
t.Assert(err, nil)
|
||||
t.AssertEQ(j.GetStrings("n"), g.SliceStr{"123456789"})
|
||||
t.AssertEQ(j.GetStrings("m"), g.SliceStr{`{"k":"v"}`})
|
||||
t.AssertEQ(j.GetStrings("a"), g.SliceStr{"1", "2", "3"})
|
||||
t.AssertEQ(j.GetStrings("i"), nil)
|
||||
t.AssertEQ(j.Get("n").Strings(), g.SliceStr{"123456789"})
|
||||
t.AssertEQ(j.Get("m").Strings(), g.SliceStr{`{"k":"v"}`})
|
||||
t.AssertEQ(j.Get("a").Strings(), g.SliceStr{"1", "2", "3"})
|
||||
t.AssertEQ(j.Get("i").Strings(), nil)
|
||||
})
|
||||
}
|
||||
|
||||
@ -193,9 +193,9 @@ func Test_GetInterfaces(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
t.Assert(err, nil)
|
||||
t.AssertEQ(j.GetInterfaces("n"), g.Array{123456789})
|
||||
t.AssertEQ(j.GetInterfaces("m"), g.Array{g.Map{"k": "v"}})
|
||||
t.AssertEQ(j.GetInterfaces("a"), g.Array{1, 2, 3})
|
||||
t.AssertEQ(j.Get("n").Interfaces(), g.Array{123456789})
|
||||
t.AssertEQ(j.Get("m").Interfaces(), g.Array{g.Map{"k": "v"}})
|
||||
t.AssertEQ(j.Get("a").Interfaces(), g.Array{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
@ -230,7 +230,7 @@ func Test_Append(t *testing.T) {
|
||||
p := gjson.New(nil)
|
||||
p.Append("a.b", 1)
|
||||
p.Append("a.c", 2)
|
||||
t.Assert(p.Get("a"), g.Map{
|
||||
t.Assert(p.Get("a").Map(), g.Map{
|
||||
"b": g.Slice{1},
|
||||
"c": g.Slice{2},
|
||||
})
|
||||
@ -278,36 +278,36 @@ func TestJson_ToJson(t *testing.T) {
|
||||
func TestJson_Default(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gjson.New(nil)
|
||||
t.AssertEQ(j.Get("no", 100), 100)
|
||||
t.AssertEQ(j.GetString("no", 100), "100")
|
||||
t.AssertEQ(j.GetBool("no", "on"), true)
|
||||
t.AssertEQ(j.GetInt("no", 100), 100)
|
||||
t.AssertEQ(j.GetInt8("no", 100), int8(100))
|
||||
t.AssertEQ(j.GetInt16("no", 100), int16(100))
|
||||
t.AssertEQ(j.GetInt32("no", 100), int32(100))
|
||||
t.AssertEQ(j.GetInt64("no", 100), int64(100))
|
||||
t.AssertEQ(j.GetUint("no", 100), uint(100))
|
||||
t.AssertEQ(j.GetUint8("no", 100), uint8(100))
|
||||
t.AssertEQ(j.GetUint16("no", 100), uint16(100))
|
||||
t.AssertEQ(j.GetUint32("no", 100), uint32(100))
|
||||
t.AssertEQ(j.GetUint64("no", 100), uint64(100))
|
||||
t.AssertEQ(j.GetFloat32("no", 123.456), float32(123.456))
|
||||
t.AssertEQ(j.GetFloat64("no", 123.456), float64(123.456))
|
||||
t.AssertEQ(j.GetArray("no", g.Slice{1, 2, 3}), g.Slice{1, 2, 3})
|
||||
t.AssertEQ(j.GetInts("no", g.Slice{1, 2, 3}), g.SliceInt{1, 2, 3})
|
||||
t.AssertEQ(j.GetFloats("no", g.Slice{1, 2, 3}), []float64{1, 2, 3})
|
||||
t.AssertEQ(j.GetMap("no", g.Map{"k": "v"}), g.Map{"k": "v"})
|
||||
t.AssertEQ(j.GetVar("no", 123.456).Float64(), float64(123.456))
|
||||
t.AssertEQ(j.GetJson("no", g.Map{"k": "v"}).Get("k"), "v")
|
||||
t.AssertEQ(j.Get("no", 100).Int(), 100)
|
||||
t.AssertEQ(j.Get("no", 100).String(), "100")
|
||||
t.AssertEQ(j.Get("no", "on").Bool(), true)
|
||||
t.AssertEQ(j.Get("no", 100).Int(), 100)
|
||||
t.AssertEQ(j.Get("no", 100).Int8(), int8(100))
|
||||
t.AssertEQ(j.Get("no", 100).Int16(), int16(100))
|
||||
t.AssertEQ(j.Get("no", 100).Int32(), int32(100))
|
||||
t.AssertEQ(j.Get("no", 100).Int64(), int64(100))
|
||||
t.AssertEQ(j.Get("no", 100).Uint(), uint(100))
|
||||
t.AssertEQ(j.Get("no", 100).Uint8(), uint8(100))
|
||||
t.AssertEQ(j.Get("no", 100).Uint16(), uint16(100))
|
||||
t.AssertEQ(j.Get("no", 100).Uint32(), uint32(100))
|
||||
t.AssertEQ(j.Get("no", 100).Uint64(), uint64(100))
|
||||
t.AssertEQ(j.Get("no", 123.456).Float32(), float32(123.456))
|
||||
t.AssertEQ(j.Get("no", 123.456).Float64(), float64(123.456))
|
||||
t.AssertEQ(j.Get("no", g.Slice{1, 2, 3}).Array(), g.Slice{1, 2, 3})
|
||||
t.AssertEQ(j.Get("no", g.Slice{1, 2, 3}).Ints(), g.SliceInt{1, 2, 3})
|
||||
t.AssertEQ(j.Get("no", g.Slice{1, 2, 3}).Floats(), []float64{1, 2, 3})
|
||||
t.AssertEQ(j.Get("no", g.Map{"k": "v"}).Map(), g.Map{"k": "v"})
|
||||
t.AssertEQ(j.Get("no", 123.456).Float64(), float64(123.456))
|
||||
t.AssertEQ(j.GetJson("no", g.Map{"k": "v"}).Get("k").String(), "v")
|
||||
t.AssertEQ(j.GetJsons("no", g.Slice{
|
||||
g.Map{"k1": "v1"},
|
||||
g.Map{"k2": "v2"},
|
||||
g.Map{"k3": "v3"},
|
||||
})[0].Get("k1"), "v1")
|
||||
})[0].Get("k1").String(), "v1")
|
||||
t.AssertEQ(j.GetJsonMap("no", g.Map{
|
||||
"m1": g.Map{"k1": "v1"},
|
||||
"m2": g.Map{"k2": "v2"},
|
||||
})["m2"].Get("k2"), "v2")
|
||||
})["m2"].Get("k2").String(), "v2")
|
||||
})
|
||||
}
|
||||
|
||||
@ -356,27 +356,27 @@ func Test_Convert2(t *testing.T) {
|
||||
Name string
|
||||
}{}
|
||||
j := gjson.New(`{"name":"gf","time":"2019-06-12"}`)
|
||||
t.Assert(j.Value().(g.Map)["name"], "gf")
|
||||
t.Assert(j.GetMap("name1"), nil)
|
||||
t.Assert(j.Interface().(g.Map)["name"], "gf")
|
||||
t.Assert(j.Get("name1").Map(), nil)
|
||||
t.AssertNE(j.GetJson("name1"), nil)
|
||||
t.Assert(j.GetJsons("name1"), nil)
|
||||
t.Assert(j.GetJsonMap("name1"), nil)
|
||||
t.Assert(j.Contains("name1"), false)
|
||||
t.Assert(j.GetVar("name1").IsNil(), true)
|
||||
t.Assert(j.GetVar("name").IsNil(), false)
|
||||
t.Assert(j.Get("name1").IsNil(), true)
|
||||
t.Assert(j.Get("name").IsNil(), false)
|
||||
t.Assert(j.Len("name1"), -1)
|
||||
t.Assert(j.GetTime("time").Format("2006-01-02"), "2019-06-12")
|
||||
t.Assert(j.GetGTime("time").Format("Y-m-d"), "2019-06-12")
|
||||
t.Assert(j.GetDuration("time").String(), "0s")
|
||||
t.Assert(j.Get("time").Time().Format("2006-01-02"), "2019-06-12")
|
||||
t.Assert(j.Get("time").GTime().Format("Y-m-d"), "2019-06-12")
|
||||
t.Assert(j.Get("time").Duration().String(), "0s")
|
||||
|
||||
err := j.Struct(&name)
|
||||
err := j.Var().Scan(&name)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(name.Name, "gf")
|
||||
//j.Dump()
|
||||
t.Assert(err, nil)
|
||||
|
||||
j = gjson.New(`{"person":{"name":"gf"}}`)
|
||||
err = j.GetStruct("person", &name)
|
||||
err = j.Get("person").Scan(&name)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(name.Name, "gf")
|
||||
|
||||
@ -385,7 +385,7 @@ func Test_Convert2(t *testing.T) {
|
||||
t.Assert(err, nil)
|
||||
|
||||
j = gjson.New(`[1,2,3]`)
|
||||
t.Assert(len(j.Array()), 3)
|
||||
t.Assert(len(j.Var().Array()), 3)
|
||||
})
|
||||
}
|
||||
|
||||
@ -394,10 +394,10 @@ func Test_Basic(t *testing.T) {
|
||||
j := gjson.New(`{"name":"gf","time":"2019-06-12"}`)
|
||||
j.SetViolenceCheck(true)
|
||||
t.Assert(j.Get(""), nil)
|
||||
t.Assert(j.Get(".").(g.Map)["name"], "gf")
|
||||
t.Assert(j.Get(".").(g.Map)["name1"], nil)
|
||||
t.Assert(j.Get(".").Interface().(g.Map)["name"], "gf")
|
||||
t.Assert(j.Get(".").Interface().(g.Map)["name1"], nil)
|
||||
j.SetViolenceCheck(false)
|
||||
t.Assert(j.Get(".").(g.Map)["name"], "gf")
|
||||
t.Assert(j.Get(".").Interface().(g.Map)["name"], "gf")
|
||||
|
||||
err := j.Set("name", "gf1")
|
||||
t.Assert(err, nil)
|
||||
@ -416,7 +416,7 @@ func Test_Basic(t *testing.T) {
|
||||
err = j.Remove("1")
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("0"), 1)
|
||||
t.Assert(len(j.Array()), 2)
|
||||
t.Assert(len(j.Var().Array()), 2)
|
||||
|
||||
j = gjson.New(`[1,2,3]`)
|
||||
// If index 0 is delete, its next item will be at index 0.
|
||||
@ -424,13 +424,13 @@ func Test_Basic(t *testing.T) {
|
||||
t.Assert(j.Remove("0"), nil)
|
||||
t.Assert(j.Remove("0"), nil)
|
||||
t.Assert(j.Get("0"), nil)
|
||||
t.Assert(len(j.Array()), 0)
|
||||
t.Assert(len(j.Var().Array()), 0)
|
||||
|
||||
j = gjson.New(`[1,2,3]`)
|
||||
err = j.Remove("3")
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("0"), 1)
|
||||
t.Assert(len(j.Array()), 3)
|
||||
t.Assert(len(j.Var().Array()), 3)
|
||||
|
||||
j = gjson.New(`[1,2,3]`)
|
||||
err = j.Remove("0.3")
|
||||
@ -464,20 +464,20 @@ func Test_Basic(t *testing.T) {
|
||||
t.Assert(j.Get("Name"), "gf")
|
||||
err = j.Set("Name1", g.Map{"Name": "gf1"})
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("Name1").(g.Map)["Name"], "gf1")
|
||||
t.Assert(j.Get("Name1").Interface().(g.Map)["Name"], "gf1")
|
||||
err = j.Set("Name2", g.Slice{1, 2, 3})
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("Name2").(g.Slice)[0], 1)
|
||||
t.Assert(j.Get("Name2").Interface().(g.Slice)[0], 1)
|
||||
err = j.Set("Name3", name)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("Name3").(g.Map)["Name"], "gf")
|
||||
t.Assert(j.Get("Name3").Interface().(g.Map)["Name"], "gf")
|
||||
err = j.Set("Name4", &name)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("Name4").(g.Map)["Name"], "gf")
|
||||
t.Assert(j.Get("Name4").Interface().(g.Map)["Name"], "gf")
|
||||
arr := [3]int{1, 2, 3}
|
||||
err = j.Set("Name5", arr)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("Name5").(g.Array)[0], 1)
|
||||
t.Assert(j.Get("Name5").Interface().(g.Array)[0], 1)
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
@ -22,11 +22,11 @@ func TestJson_UnmarshalJSON(t *testing.T) {
|
||||
j := gjson.New(nil)
|
||||
err := json.UnmarshalUseNumber(data, j)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Array(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -44,11 +44,11 @@ func TestJson_UnmarshalValue(t *testing.T) {
|
||||
}, &v)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(v.Name, "john")
|
||||
t.Assert(v.Json.Get("n"), "123456789")
|
||||
t.Assert(v.Json.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(v.Json.Get("m.k"), "v")
|
||||
t.Assert(v.Json.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(v.Json.Get("a.1"), 2)
|
||||
t.Assert(v.Json.Get("n").String(), "123456789")
|
||||
t.Assert(v.Json.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(v.Json.Get("m.k").String(), "v")
|
||||
t.Assert(v.Json.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(v.Json.Get("a.1").Int(), 2)
|
||||
})
|
||||
// Map
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
@ -63,10 +63,10 @@ func TestJson_UnmarshalValue(t *testing.T) {
|
||||
}, &v)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(v.Name, "john")
|
||||
t.Assert(v.Json.Get("n"), "123456789")
|
||||
t.Assert(v.Json.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(v.Json.Get("m.k"), "v")
|
||||
t.Assert(v.Json.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(v.Json.Get("a.1"), 2)
|
||||
t.Assert(v.Json.Get("n").String(), "123456789")
|
||||
t.Assert(v.Json.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(v.Json.Get("m.k").String(), "v")
|
||||
t.Assert(v.Json.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(v.Json.Get("a.1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -61,7 +61,7 @@ func Test_MapAttributeConvert(t *testing.T) {
|
||||
Title map[string]interface{}
|
||||
}{}
|
||||
|
||||
err = j.Struct(&tx)
|
||||
err = j.Var().Scan(&tx)
|
||||
gtest.Assert(err, nil)
|
||||
t.Assert(tx.Title, g.Map{
|
||||
"l1": "标签1", "l2": "标签2",
|
||||
@ -76,7 +76,7 @@ func Test_MapAttributeConvert(t *testing.T) {
|
||||
Title map[string]string
|
||||
}{}
|
||||
|
||||
err = j.Struct(&tx)
|
||||
err = j.Var().Scan(&tx)
|
||||
gtest.Assert(err, nil)
|
||||
t.Assert(tx.Title, g.Map{
|
||||
"l1": "标签1", "l2": "标签2",
|
||||
|
||||
@ -21,11 +21,11 @@ func Test_Load_JSON1(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
// JSON
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
@ -34,11 +34,11 @@ func Test_Load_JSON1(t *testing.T) {
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -47,11 +47,11 @@ func Test_Load_JSON2(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789000000000000")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789000000000000")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -61,11 +61,11 @@ func Test_Load_XML(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("doc.n"), "123456789")
|
||||
t.Assert(j.Get("doc.m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("doc.m.k"), "v")
|
||||
t.Assert(j.Get("doc.a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("doc.a.1"), 2)
|
||||
t.Assert(j.Get("doc.n").String(), "123456789")
|
||||
t.Assert(j.Get("doc.m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("doc.m.k").String(), "v")
|
||||
t.Assert(j.Get("doc.a").Slice(), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("doc.a.1").Int(), 2)
|
||||
})
|
||||
// XML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
@ -74,11 +74,11 @@ func Test_Load_XML(t *testing.T) {
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("doc.n"), "123456789")
|
||||
t.Assert(j.Get("doc.m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("doc.m.k"), "v")
|
||||
t.Assert(j.Get("doc.a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("doc.a.1"), 2)
|
||||
t.Assert(j.Get("doc.n").String(), "123456789")
|
||||
t.Assert(j.Get("doc.m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("doc.m.k").String(), "v")
|
||||
t.Assert(j.Get("doc.a").Array(), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("doc.a.1").Int(), 2)
|
||||
})
|
||||
|
||||
// XML
|
||||
@ -114,11 +114,11 @@ m:
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
// YAML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
@ -127,11 +127,11 @@ m:
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -156,11 +156,11 @@ n = 123456789
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gjson.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
// TOML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
@ -169,11 +169,11 @@ n = 123456789
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
t.Assert(j.Get("n").String(), "123456789")
|
||||
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k").String(), "v")
|
||||
t.Assert(j.Get("a").Slice(), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("a.1").Int(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
@ -189,14 +189,14 @@ func Test_Load_TOML2(t *testing.T) {
|
||||
func Test_Load_Basic(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gjson.New(nil)
|
||||
t.Assert(j.Value(), nil)
|
||||
t.Assert(j.Interface(), nil)
|
||||
_, err := gjson.Decode(nil)
|
||||
t.AssertNE(err, nil)
|
||||
_, err = gjson.DecodeToJson(nil)
|
||||
t.AssertNE(err, nil)
|
||||
j, err = gjson.LoadContent(nil)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Value(), nil)
|
||||
t.Assert(j.Interface(), nil)
|
||||
|
||||
j, err = gjson.LoadContent(`{"name": "gf"}`)
|
||||
t.Assert(err, nil)
|
||||
@ -205,7 +205,7 @@ func Test_Load_Basic(t *testing.T) {
|
||||
t.AssertNE(err, nil)
|
||||
|
||||
j = gjson.New(&g.Map{"name": "gf"})
|
||||
t.Assert(j.GetString("name"), "gf")
|
||||
t.Assert(j.Get("name").String(), "gf")
|
||||
|
||||
})
|
||||
}
|
||||
@ -228,19 +228,19 @@ enable=true
|
||||
`
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
json, err := gjson.LoadContent(data)
|
||||
j, err := gjson.LoadContent(data)
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
|
||||
t.Assert(json.GetString("addr.ip"), "127.0.0.1")
|
||||
t.Assert(json.GetString("addr.port"), "9001")
|
||||
t.Assert(json.GetString("addr.enable"), "true")
|
||||
t.Assert(json.GetString("DBINFO.type"), "mysql")
|
||||
t.Assert(json.GetString("DBINFO.user"), "root")
|
||||
t.Assert(json.GetString("DBINFO.password"), "password")
|
||||
t.Assert(j.Get("addr.ip").String(), "127.0.0.1")
|
||||
t.Assert(j.Get("addr.port").String(), "9001")
|
||||
t.Assert(j.Get("addr.enable").String(), "true")
|
||||
t.Assert(j.Get("DBINFO.type").String(), "mysql")
|
||||
t.Assert(j.Get("DBINFO.user").String(), "root")
|
||||
t.Assert(j.Get("DBINFO.password").String(), "password")
|
||||
|
||||
_, err = json.ToIni()
|
||||
_, err = j.ToIni()
|
||||
if err != nil {
|
||||
gtest.Fatal(err)
|
||||
}
|
||||
|
||||
@ -101,12 +101,12 @@ func Test_New_HierarchicalStruct(t *testing.T) {
|
||||
func Test_NewWithOptions(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
data := []byte("[9223372036854775807, 9223372036854775806]")
|
||||
array := gjson.New(data).Array()
|
||||
array := gjson.New(data).Var().Array()
|
||||
t.Assert(array, []uint64{9223372036854776000, 9223372036854776000})
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
data := []byte("[9223372036854775807, 9223372036854775806]")
|
||||
array := gjson.NewWithOptions(data, gjson.Options{StrNumber: true}).Array()
|
||||
array := gjson.NewWithOptions(data, gjson.Options{StrNumber: true}).Var().Array()
|
||||
t.Assert(array, []uint64{9223372036854775807, 9223372036854775806})
|
||||
})
|
||||
}
|
||||
|
||||
@ -20,7 +20,7 @@ func Test_GetScan(t *testing.T) {
|
||||
j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var user *User
|
||||
err := j.GetScan("1", &user)
|
||||
err := j.Get("1").Scan(&user)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(user, &User{
|
||||
Name: "smith",
|
||||
@ -29,7 +29,7 @@ func Test_GetScan(t *testing.T) {
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var users []User
|
||||
err := j.GetScan(".", &users)
|
||||
err := j.Get(".").Scan(&users)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(users, []User{
|
||||
{
|
||||
@ -52,7 +52,7 @@ func Test_GetScanDeep(t *testing.T) {
|
||||
j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var user *User
|
||||
err := j.GetScanDeep("1", &user)
|
||||
err := j.Get("1").Scan(&user)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(user, &User{
|
||||
Name: "smith",
|
||||
@ -61,7 +61,7 @@ func Test_GetScanDeep(t *testing.T) {
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var users []User
|
||||
err := j.GetScanDeep(".", &users)
|
||||
err := j.Get(".").Scan(&users)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(users, []User{
|
||||
{
|
||||
@ -84,7 +84,7 @@ func Test_Scan1(t *testing.T) {
|
||||
j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var users []User
|
||||
err := j.Scan(&users)
|
||||
err := j.Var().Scan(&users)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(users, []User{
|
||||
{
|
||||
@ -107,7 +107,7 @@ func Test_Scan2(t *testing.T) {
|
||||
j := gjson.New(`[{"name":"john", "score":"100"},{"name":"smith", "score":"60"}]`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var users []User
|
||||
err := j.Scan(&users)
|
||||
err := j.Var().Scan(&users)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(users, []User{
|
||||
{
|
||||
@ -198,7 +198,7 @@ func Test_Struct1(t *testing.T) {
|
||||
data := new(UserCollectionAddReq)
|
||||
j, err := gjson.LoadJson(jsonContent)
|
||||
t.Assert(err, nil)
|
||||
err = j.Struct(data)
|
||||
err = j.Scan(data)
|
||||
t.Assert(err, nil)
|
||||
})
|
||||
}
|
||||
@ -226,12 +226,12 @@ func Test_Struct(t *testing.T) {
|
||||
|
||||
j, err := gjson.LoadContent(txt)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.GetString("me.name"), "mikey")
|
||||
t.Assert(j.GetString("items"), "")
|
||||
t.Assert(j.GetBool("items"), false)
|
||||
t.Assert(j.GetArray("items"), nil)
|
||||
t.Assert(j.Get("me.name").String(), "mikey")
|
||||
t.Assert(j.Get("items").String(), "")
|
||||
t.Assert(j.Get("items").Bool(), false)
|
||||
t.Assert(j.Get("items").Array(), nil)
|
||||
m := new(M)
|
||||
err = j.Struct(m)
|
||||
err = j.Scan(m)
|
||||
t.Assert(err, nil)
|
||||
t.AssertNE(m.Me, nil)
|
||||
t.Assert(m.Me["day"], "20009")
|
||||
@ -290,7 +290,7 @@ func Test_Struct_Complicated(t *testing.T) {
|
||||
j, err := gjson.LoadContent(jsonContent)
|
||||
t.Assert(err, nil)
|
||||
var response = new(Response)
|
||||
err = j.Struct(response)
|
||||
err = j.Scan(response)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(len(response.CertList), 3)
|
||||
t.Assert(response.CertList[0].CertID, 2023313)
|
||||
|
||||
@ -1,15 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://gitee.com/johng/gp.
|
||||
|
||||
// Package gparser provides convenient API for accessing/converting variable and JSON/XML/YAML/TOML.
|
||||
package gparser
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/encoding/gjson"
|
||||
)
|
||||
|
||||
// Parser is actually alias of gjson.Json.
|
||||
type Parser = gjson.Json
|
||||
@ -1,139 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://gitee.com/johng/gp.
|
||||
|
||||
package gparser
|
||||
|
||||
// ========================================================================
|
||||
// JSON
|
||||
// ========================================================================
|
||||
|
||||
func VarToJson(value interface{}) ([]byte, error) {
|
||||
return New(value).ToJson()
|
||||
}
|
||||
|
||||
func VarToJsonString(value interface{}) (string, error) {
|
||||
return New(value).ToJsonString()
|
||||
}
|
||||
|
||||
func VarToJsonIndent(value interface{}) ([]byte, error) {
|
||||
return New(value).ToJsonIndent()
|
||||
}
|
||||
|
||||
func VarToJsonIndentString(value interface{}) (string, error) {
|
||||
return New(value).ToJsonIndentString()
|
||||
}
|
||||
|
||||
func MustToJson(value interface{}) []byte {
|
||||
return New(value).MustToJson()
|
||||
}
|
||||
|
||||
func MustToJsonString(value interface{}) string {
|
||||
return New(value).MustToJsonString()
|
||||
}
|
||||
|
||||
func MustToJsonIndent(value interface{}) []byte {
|
||||
return New(value).MustToJsonIndent()
|
||||
}
|
||||
|
||||
func MustToJsonIndentString(value interface{}) string {
|
||||
return New(value).MustToJsonIndentString()
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// XML
|
||||
// ========================================================================
|
||||
|
||||
func VarToXml(value interface{}, rootTag ...string) ([]byte, error) {
|
||||
return NewWithTag(value, "xml").ToXml(rootTag...)
|
||||
}
|
||||
|
||||
func VarToXmlString(value interface{}, rootTag ...string) (string, error) {
|
||||
return NewWithTag(value, "xml").ToXmlString(rootTag...)
|
||||
}
|
||||
|
||||
func VarToXmlIndent(value interface{}, rootTag ...string) ([]byte, error) {
|
||||
return NewWithTag(value, "xml").ToXmlIndent(rootTag...)
|
||||
}
|
||||
|
||||
func VarToXmlIndentString(value interface{}, rootTag ...string) (string, error) {
|
||||
return NewWithTag(value, "xml").ToXmlIndentString(rootTag...)
|
||||
}
|
||||
|
||||
func MustToXml(value interface{}, rootTag ...string) []byte {
|
||||
return NewWithTag(value, "xml").MustToXml(rootTag...)
|
||||
}
|
||||
|
||||
func MustToXmlString(value interface{}, rootTag ...string) string {
|
||||
return NewWithTag(value, "xml").MustToXmlString(rootTag...)
|
||||
}
|
||||
|
||||
func MustToXmlIndent(value interface{}, rootTag ...string) []byte {
|
||||
return NewWithTag(value, "xml").MustToXmlIndent(rootTag...)
|
||||
}
|
||||
|
||||
func MustToXmlIndentString(value interface{}, rootTag ...string) string {
|
||||
return NewWithTag(value, "xml").MustToXmlIndentString(rootTag...)
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// YAML
|
||||
// ========================================================================
|
||||
|
||||
func VarToYaml(value interface{}) ([]byte, error) {
|
||||
return NewWithTag(value, "yaml").ToYaml()
|
||||
}
|
||||
|
||||
func VarToYamlString(value interface{}) (string, error) {
|
||||
return NewWithTag(value, "yaml").ToYamlString()
|
||||
}
|
||||
|
||||
func MustToYaml(value interface{}) []byte {
|
||||
return NewWithTag(value, "yaml").MustToYaml()
|
||||
}
|
||||
|
||||
func MustToYamlString(value interface{}) string {
|
||||
return NewWithTag(value, "yaml").MustToYamlString()
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// TOML
|
||||
// ========================================================================
|
||||
|
||||
func VarToToml(value interface{}) ([]byte, error) {
|
||||
return NewWithTag(value, "toml").ToToml()
|
||||
}
|
||||
|
||||
func VarToTomlString(value interface{}) (string, error) {
|
||||
return NewWithTag(value, "toml").ToTomlString()
|
||||
}
|
||||
|
||||
func MustToToml(value interface{}) []byte {
|
||||
return NewWithTag(value, "toml").MustToToml()
|
||||
}
|
||||
|
||||
func MustToTomlString(value interface{}) string {
|
||||
return NewWithTag(value, "toml").MustToTomlString()
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// INI
|
||||
// ========================================================================
|
||||
|
||||
func VarToIni(value interface{}) ([]byte, error) {
|
||||
return NewWithTag(value, "ini").ToIni()
|
||||
}
|
||||
|
||||
func VarToIniString(value interface{}) (string, error) {
|
||||
return NewWithTag(value, "ini").ToIniString()
|
||||
}
|
||||
|
||||
func MustToIni(value interface{}) []byte {
|
||||
return NewWithTag(value, "ini").MustToIni()
|
||||
}
|
||||
|
||||
func MustToIniString(value interface{}) string {
|
||||
return NewWithTag(value, "ini").MustToIniString()
|
||||
}
|
||||
@ -1,65 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://gitee.com/johng/gp.
|
||||
|
||||
package gparser
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/encoding/gjson"
|
||||
)
|
||||
|
||||
// New creates a Parser object with any variable type of <data>, but <data> should be a map, struct or
|
||||
// slice for data access reason, or it will make no sense.
|
||||
//
|
||||
// The parameter <safe> specifies whether using this Json object in concurrent-safe context, which
|
||||
// is false in default.
|
||||
func New(data interface{}, safe ...bool) *Parser {
|
||||
return gjson.New(data, safe...)
|
||||
}
|
||||
|
||||
// NewWithTag creates a Parser object with any variable type of <data>, but <data> should be a map
|
||||
// or slice for data access reason, or it will make no sense.
|
||||
//
|
||||
// The parameter <tags> specifies priority tags for struct conversion to map, multiple tags joined
|
||||
// with char ','.
|
||||
//
|
||||
// The parameter <safe> specifies whether using this Json object in concurrent-safe context, which
|
||||
// is false in default.
|
||||
func NewWithTag(data interface{}, tags string, safe ...bool) *Parser {
|
||||
return gjson.NewWithTag(data, tags, safe...)
|
||||
}
|
||||
|
||||
// Load loads content from specified file <path>,
|
||||
// and creates a Parser object from its content.
|
||||
func Load(path string, safe ...bool) (*Parser, error) {
|
||||
return gjson.Load(path, safe...)
|
||||
}
|
||||
|
||||
// LoadContent creates a Parser object from given content,
|
||||
// it checks the data type of <content> automatically,
|
||||
// supporting JSON, XML, INI, YAML and TOML types of data.
|
||||
func LoadContent(data interface{}, safe ...bool) (*Parser, error) {
|
||||
return gjson.LoadContent(data, safe...)
|
||||
}
|
||||
|
||||
func LoadJson(data interface{}, safe ...bool) (*Parser, error) {
|
||||
return gjson.LoadJson(data, safe...)
|
||||
}
|
||||
|
||||
func LoadXml(data interface{}, safe ...bool) (*Parser, error) {
|
||||
return gjson.LoadXml(data, safe...)
|
||||
}
|
||||
|
||||
func LoadYaml(data interface{}, safe ...bool) (*Parser, error) {
|
||||
return gjson.LoadYaml(data, safe...)
|
||||
}
|
||||
|
||||
func LoadToml(data interface{}, safe ...bool) (*Parser, error) {
|
||||
return gjson.LoadToml(data, safe...)
|
||||
}
|
||||
|
||||
func LoadIni(data interface{}, safe ...bool) (*Parser, error) {
|
||||
return gjson.LoadIni(data, safe...)
|
||||
}
|
||||
@ -1,306 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gparser_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/frame/g"
|
||||
"github.com/gogf/gf/test/gtest"
|
||||
)
|
||||
|
||||
func Test_New(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
v := j.Value().(g.Map)
|
||||
t.Assert(v["n"], 123456789)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_NewUnsafe(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Encode(t *testing.T) {
|
||||
value := g.Slice{1, 2, 3}
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
b, err := gparser.VarToJson(value)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(b, []byte(`[1,2,3]`))
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Decode(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_SplitChar(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
j.SetSplitChar(byte('#'))
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m#k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a#1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ViolenceCheck(t *testing.T) {
|
||||
data := []byte(`{"m":{"a":[1,2,3], "v1.v2":"4"}}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.Get("m.a.2"), 3)
|
||||
t.Assert(j.Get("m.v1.v2"), nil)
|
||||
j.SetViolenceCheck(true)
|
||||
t.Assert(j.Get("m.v1.v2"), 4)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetVar(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.GetVar("n").String(), "123456789")
|
||||
t.Assert(j.GetVar("m").Map(), g.Map{"k": "v"})
|
||||
t.Assert(j.GetVar("a").Interfaces(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.GetVar("a").Slice(), g.Slice{1, 2, 3})
|
||||
t.Assert(j.GetMap("a"), g.Map{"1": "2", "3": nil})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetMap(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.GetMap("n"), nil)
|
||||
t.Assert(j.GetMap("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.GetMap("a"), g.Map{"1": "2", "3": nil})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetArray(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.GetArray("n"), g.Array{123456789})
|
||||
t.Assert(j.GetArray("m"), g.Array{g.Map{"k": "v"}})
|
||||
t.Assert(j.GetArray("a"), g.Array{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetString(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.AssertEQ(j.GetString("n"), "123456789")
|
||||
t.AssertEQ(j.GetString("m"), `{"k":"v"}`)
|
||||
t.AssertEQ(j.GetString("a"), `[1,2,3]`)
|
||||
t.AssertEQ(j.GetString("i"), "")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetStrings(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.AssertEQ(j.GetStrings("n"), g.SliceStr{"123456789"})
|
||||
t.AssertEQ(j.GetStrings("m"), g.SliceStr{`{"k":"v"}`})
|
||||
t.AssertEQ(j.GetStrings("a"), g.SliceStr{"1", "2", "3"})
|
||||
t.AssertEQ(j.GetStrings("i"), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetInterfaces(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.AssertEQ(j.GetInterfaces("n"), g.Array{123456789})
|
||||
t.AssertEQ(j.GetInterfaces("m"), g.Array{g.Map{"k": "v"}})
|
||||
t.AssertEQ(j.GetInterfaces("a"), g.Array{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Len(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a", 1)
|
||||
p.Append("a", 2)
|
||||
t.Assert(p.Len("a"), 2)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a.b", 1)
|
||||
p.Append("a.c", 2)
|
||||
t.Assert(p.Len("a"), 2)
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(nil)
|
||||
p.Set("a", 1)
|
||||
t.Assert(p.Len("a"), -1)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Append(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a", 1)
|
||||
p.Append("a", 2)
|
||||
t.Assert(p.Get("a"), g.Slice{1, 2})
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a.b", 1)
|
||||
p.Append("a.c", 2)
|
||||
t.Assert(p.Get("a"), g.Map{
|
||||
"b": g.Slice{1},
|
||||
"c": g.Slice{2},
|
||||
})
|
||||
})
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(nil)
|
||||
p.Set("a", 1)
|
||||
err := p.Append("a", 2)
|
||||
t.AssertNE(err, nil)
|
||||
t.Assert(p.Get("a"), 1)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Convert(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(`{"name":"gf","bool":true,"int":1,"float":1,"ints":[1,2],"floats":[1,2],"time":"2019-06-12","person": {"name": "gf"}}`)
|
||||
t.Assert(p.GetVar("name").String(), "gf")
|
||||
t.Assert(p.GetString("name"), "gf")
|
||||
t.Assert(p.GetBool("bool"), true)
|
||||
t.Assert(p.GetInt("int"), 1)
|
||||
t.Assert(p.GetInt8("int"), 1)
|
||||
t.Assert(p.GetInt16("int"), 1)
|
||||
t.Assert(p.GetInt32("int"), 1)
|
||||
t.Assert(p.GetInt64("int"), 1)
|
||||
t.Assert(p.GetUint("int"), 1)
|
||||
t.Assert(p.GetUint8("int"), 1)
|
||||
t.Assert(p.GetUint16("int"), 1)
|
||||
t.Assert(p.GetUint32("int"), 1)
|
||||
t.Assert(p.GetUint64("int"), 1)
|
||||
t.Assert(p.GetInts("ints")[0], 1)
|
||||
t.Assert(p.GetFloat32("float"), 1)
|
||||
t.Assert(p.GetFloat64("float"), 1)
|
||||
t.Assert(p.GetFloats("floats")[0], 1)
|
||||
t.Assert(p.GetTime("time").Format("2006-01-02"), "2019-06-12")
|
||||
t.Assert(p.GetGTime("time").Format("Y-m-d"), "2019-06-12")
|
||||
t.Assert(p.GetDuration("time").String(), "0s")
|
||||
name := struct {
|
||||
Name string
|
||||
}{}
|
||||
err := p.GetStruct("person", &name)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(name.Name, "gf")
|
||||
t.Assert(p.Map()["name"], "gf")
|
||||
err = p.Struct(&name)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(name.Name, "gf")
|
||||
//p.Dump()
|
||||
|
||||
p = gparser.New(`[0,1,2]`)
|
||||
t.Assert(p.Array()[0], 0)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Convert2(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
xmlArr := []byte{60, 114, 111, 111, 116, 47, 62}
|
||||
p := gparser.New(`<root></root>`)
|
||||
arr, err := p.ToXml("root")
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, xmlArr)
|
||||
arr, err = gparser.VarToXml(`<root></root>`, "root")
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, xmlArr)
|
||||
|
||||
arr, err = p.ToXmlIndent("root")
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, xmlArr)
|
||||
arr, err = gparser.VarToXmlIndent(`<root></root>`, "root")
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, xmlArr)
|
||||
|
||||
p = gparser.New(`{"name":"gf"}`)
|
||||
str, err := p.ToJsonString()
|
||||
t.Assert(err, nil)
|
||||
t.Assert(str, `{"name":"gf"}`)
|
||||
str, err = gparser.VarToJsonString(`{"name":"gf"}`)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(str, `{"name":"gf"}`)
|
||||
|
||||
jsonIndentArr := []byte{123, 10, 9, 34, 110, 97, 109, 101, 34, 58, 32, 34, 103, 102, 34, 10, 125}
|
||||
arr, err = p.ToJsonIndent()
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, jsonIndentArr)
|
||||
arr, err = gparser.VarToJsonIndent(`{"name":"gf"}`)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, jsonIndentArr)
|
||||
|
||||
str, err = p.ToJsonIndentString()
|
||||
t.Assert(err, nil)
|
||||
t.Assert(str, "{\n\t\"name\": \"gf\"\n}")
|
||||
str, err = gparser.VarToJsonIndentString(`{"name":"gf"}`)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(str, "{\n\t\"name\": \"gf\"\n}")
|
||||
|
||||
p = gparser.New(g.Map{"name": "gf"})
|
||||
arr, err = p.ToYaml()
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, "name: gf\n")
|
||||
arr, err = gparser.VarToYaml(g.Map{"name": "gf"})
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, "name: gf\n")
|
||||
|
||||
tomlArr := []byte{110, 97, 109, 101, 32, 61, 32, 34, 103, 102, 34, 10}
|
||||
p = gparser.New(`
|
||||
name= "gf"
|
||||
`)
|
||||
arr, err = p.ToToml()
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, tomlArr)
|
||||
arr, err = gparser.VarToToml(`
|
||||
name= "gf"
|
||||
`)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(arr, tomlArr)
|
||||
})
|
||||
}
|
||||
@ -1,190 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gparser_test
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/frame/g"
|
||||
"github.com/gogf/gf/os/gfile"
|
||||
"github.com/gogf/gf/test/gtest"
|
||||
)
|
||||
|
||||
func Test_Load_JSON(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
// JSON
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gparser.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// JSON
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := "test.json"
|
||||
gfile.PutBytes(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_XML(t *testing.T) {
|
||||
data := []byte(`<doc><a>1</a><a>2</a><a>3</a><m><k>v</k></m><n>123456789</n></doc>`)
|
||||
// XML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gparser.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("doc.n"), "123456789")
|
||||
t.Assert(j.Get("doc.m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("doc.m.k"), "v")
|
||||
t.Assert(j.Get("doc.a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("doc.a.1"), 2)
|
||||
})
|
||||
// XML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := "test.xml"
|
||||
gfile.PutBytes(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("doc.n"), "123456789")
|
||||
t.Assert(j.Get("doc.m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("doc.m.k"), "v")
|
||||
t.Assert(j.Get("doc.a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("doc.a.1"), 2)
|
||||
})
|
||||
|
||||
// XML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
xml := `<?xml version="1.0"?>
|
||||
|
||||
<Output type="o">
|
||||
<itotalSize>0</itotalSize>
|
||||
<ipageSize>1</ipageSize>
|
||||
<ipageIndex>2</ipageIndex>
|
||||
<itotalRecords>GF框架</itotalRecords>
|
||||
<nworkOrderDtos/>
|
||||
<nworkOrderFrontXML/>
|
||||
</Output>`
|
||||
j, err := gparser.LoadContent(xml)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("Output.ipageIndex"), "2")
|
||||
t.Assert(j.Get("Output.itotalRecords"), "GF框架")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_YAML1(t *testing.T) {
|
||||
data := []byte(`
|
||||
a:
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
m:
|
||||
k: v
|
||||
"n": 123456789
|
||||
`)
|
||||
// YAML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gparser.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// YAML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := "test.yaml"
|
||||
gfile.PutBytes(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_YAML2(t *testing.T) {
|
||||
data := []byte("i : 123456789")
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gparser.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("i"), "123456789")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_TOML1(t *testing.T) {
|
||||
data := []byte(`
|
||||
a = ["1", "2", "3"]
|
||||
n = "123456789"
|
||||
|
||||
[m]
|
||||
k = "v"
|
||||
`)
|
||||
// TOML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gparser.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// TOML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
path := "test.toml"
|
||||
gfile.PutBytes(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("n"), "123456789")
|
||||
t.Assert(j.Get("m"), g.Map{"k": "v"})
|
||||
t.Assert(j.Get("m.k"), "v")
|
||||
t.Assert(j.Get("a"), g.Slice{"1", "2", "3"})
|
||||
t.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_TOML2(t *testing.T) {
|
||||
data := []byte("i=123456789")
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j, err := gparser.LoadContent(data)
|
||||
t.Assert(err, nil)
|
||||
t.Assert(j.Get("i"), "123456789")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_Nil(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
p := gparser.New(nil)
|
||||
t.Assert(p.Value(), nil)
|
||||
file := "test22222.json"
|
||||
filePath := gfile.Pwd() + gfile.Separator + file
|
||||
ioutil.WriteFile(filePath, []byte("{"), 0644)
|
||||
defer gfile.Remove(filePath)
|
||||
_, err := gparser.Load(file)
|
||||
t.AssertNE(err, nil)
|
||||
_, err = gparser.LoadContent("{")
|
||||
t.AssertNE(err, nil)
|
||||
})
|
||||
}
|
||||
@ -1,49 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gparser_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/test/gtest"
|
||||
)
|
||||
|
||||
func Test_Load_NewWithTag(t *testing.T) {
|
||||
type User struct {
|
||||
Age int `xml:"age-xml" json:"age-json"`
|
||||
Name string `xml:"name-xml" json:"name-json"`
|
||||
Addr string `xml:"addr-xml" json:"addr-json"`
|
||||
}
|
||||
data := User{
|
||||
Age: 18,
|
||||
Name: "john",
|
||||
Addr: "chengdu",
|
||||
}
|
||||
// JSON
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.New(data)
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.Get("age-xml"), nil)
|
||||
t.Assert(j.Get("age-json"), data.Age)
|
||||
t.Assert(j.Get("name-xml"), nil)
|
||||
t.Assert(j.Get("name-json"), data.Name)
|
||||
t.Assert(j.Get("addr-xml"), nil)
|
||||
t.Assert(j.Get("addr-json"), data.Addr)
|
||||
})
|
||||
// XML
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
j := gparser.NewWithTag(data, "xml")
|
||||
t.AssertNE(j, nil)
|
||||
t.Assert(j.Get("age-xml"), data.Age)
|
||||
t.Assert(j.Get("age-json"), nil)
|
||||
t.Assert(j.Get("name-xml"), data.Name)
|
||||
t.Assert(j.Get("name-json"), nil)
|
||||
t.Assert(j.Get("addr-xml"), data.Addr)
|
||||
t.Assert(j.Get("addr-json"), nil)
|
||||
})
|
||||
}
|
||||
@ -1,215 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gparser_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
)
|
||||
|
||||
func Test_Set1(t *testing.T) {
|
||||
e := []byte(`{"k1":{"k11":[1,2,3]},"k2":"v2"}`)
|
||||
p := gparser.New(map[string]string{
|
||||
"k1": "v1",
|
||||
"k2": "v2",
|
||||
})
|
||||
p.Set("k1.k11", []int{1, 2, 3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, []byte(`{"k1":{"k11":[1,2,3]},"k2":"v2"}`)) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set2(t *testing.T) {
|
||||
e := []byte(`[[null,1]]`)
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("0.1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set3(t *testing.T) {
|
||||
e := []byte(`{"kv":{"k1":"v1"}}`)
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("kv", map[string]string{
|
||||
"k1": "v1",
|
||||
})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set4(t *testing.T) {
|
||||
e := []byte(`["a",[{"k1":"v1"}]]`)
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("1.0", map[string]string{
|
||||
"k1": "v1",
|
||||
})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set5(t *testing.T) {
|
||||
e := []byte(`[[[[[[[[[[[[[[[[[[[[[1,2,3]]]]]]]]]]]]]]]]]]]]]`)
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", []int{1, 2, 3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set6(t *testing.T) {
|
||||
e := []byte(`["a",[1,2,3]]`)
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("1", []int{1, 2, 3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set7(t *testing.T) {
|
||||
e := []byte(`{"0":[null,[1,2,3]],"k1":"v1","k2":"v2"}`)
|
||||
p := gparser.New(map[string]string{
|
||||
"k1": "v1",
|
||||
"k2": "v2",
|
||||
})
|
||||
p.Set("0.1", []int{1, 2, 3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set8(t *testing.T) {
|
||||
e := []byte(`{"0":[[[[[[null,[1,2,3]]]]]]],"k1":"v1","k2":"v2"}`)
|
||||
p := gparser.New(map[string]string{
|
||||
"k1": "v1",
|
||||
"k2": "v2",
|
||||
})
|
||||
p.Set("0.0.0.0.0.0.1", []int{1, 2, 3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set9(t *testing.T) {
|
||||
e := []byte(`{"k1":[null,[1,2,3]],"k2":"v2"}`)
|
||||
p := gparser.New(map[string]string{
|
||||
"k1": "v1",
|
||||
"k2": "v2",
|
||||
})
|
||||
p.Set("k1.1", []int{1, 2, 3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set10(t *testing.T) {
|
||||
e := []byte(`{"a":{"b":{"c":1}}}`)
|
||||
p := gparser.New(nil)
|
||||
p.Set("a.b.c", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set11(t *testing.T) {
|
||||
e := []byte(`{"a":{"b":{}}}`)
|
||||
p, _ := gparser.LoadContent([]byte(`{"a":{"b":{"c":1}}}`))
|
||||
p.Remove("a.b.c")
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set12(t *testing.T) {
|
||||
e := []byte(`[0,1]`)
|
||||
p := gparser.New(nil)
|
||||
p.Set("0", 0)
|
||||
p.Set("1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set13(t *testing.T) {
|
||||
e := []byte(`{"array":[0,1]}`)
|
||||
p := gparser.New(nil)
|
||||
p.Set("array.0", 0)
|
||||
p.Set("array.1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set14(t *testing.T) {
|
||||
e := []byte(`{"f":{"a":1}}`)
|
||||
p := gparser.New(nil)
|
||||
p.Set("f", "m")
|
||||
p.Set("f.a", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package g
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/os/glog"
|
||||
)
|
||||
|
||||
// SetLogLevel sets the logging level globally.
|
||||
// Deprecated, use functions of package glog or g.Log() instead.
|
||||
func SetLogLevel(level int) {
|
||||
glog.SetLevel(level)
|
||||
}
|
||||
|
||||
// GetLogLevel returns the global logging level.
|
||||
// Deprecated, use functions of package glog or g.Log() instead.
|
||||
func GetLogLevel() int {
|
||||
return glog.GetLevel()
|
||||
}
|
||||
@ -86,15 +86,6 @@ func DB(name ...string) gdb.DB {
|
||||
return gins.Database(name...)
|
||||
}
|
||||
|
||||
// Table is alias of Model.
|
||||
// The database component is designed not only for
|
||||
// relational databases but also for NoSQL databases in the future. The name
|
||||
// "Table" is not proper for that purpose anymore.
|
||||
// Deprecated, use Model instead.
|
||||
func Table(tableNameOrStruct ...interface{}) *gdb.Model {
|
||||
return DB().Model(tableNameOrStruct...)
|
||||
}
|
||||
|
||||
// Model creates and returns a model based on configuration of default database group.
|
||||
func Model(tableNameOrStruct ...interface{}) *gdb.Model {
|
||||
return DB().Model(tableNameOrStruct...)
|
||||
|
||||
@ -8,7 +8,6 @@ package g
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/internal/intlog"
|
||||
"github.com/gogf/gf/net/ghttp"
|
||||
)
|
||||
|
||||
// SetDebug enables/disables the GoFrame internal logging manually.
|
||||
@ -17,10 +16,3 @@ import (
|
||||
func SetDebug(enabled bool) {
|
||||
intlog.SetEnabled(enabled)
|
||||
}
|
||||
|
||||
// SetServerGraceful enables/disables graceful reload feature of http Web Server.
|
||||
// This feature is disabled in default.
|
||||
// Deprecated, use configuration of ghttp.Server for controlling this feature.
|
||||
func SetServerGraceful(enabled bool) {
|
||||
ghttp.SetGraceful(enabled)
|
||||
}
|
||||
|
||||
@ -1,44 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gmvc provides basic object classes for MVC.
|
||||
// Deprecated, no longer suggested.
|
||||
package gmvc
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/net/ghttp"
|
||||
)
|
||||
|
||||
// Controller is used for controller register of ghttp.Server.
|
||||
// Deprecated, no longer suggested.
|
||||
type Controller struct {
|
||||
Request *ghttp.Request
|
||||
Response *ghttp.Response
|
||||
Server *ghttp.Server
|
||||
Cookie *ghttp.Cookie
|
||||
Session *ghttp.Session
|
||||
View *View
|
||||
}
|
||||
|
||||
// Init is the callback function for each request initialization.
|
||||
func (c *Controller) Init(r *ghttp.Request) {
|
||||
c.Request = r
|
||||
c.Response = r.Response
|
||||
c.Server = r.Server
|
||||
c.View = NewView(r.Response)
|
||||
c.Cookie = r.Cookie
|
||||
c.Session = r.Session
|
||||
}
|
||||
|
||||
// Shut is the callback function for each request close.
|
||||
func (c *Controller) Shut() {
|
||||
|
||||
}
|
||||
|
||||
// Exit equals to function Request.Exit().
|
||||
func (c *Controller) Exit() {
|
||||
c.Request.Exit()
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gmvc
|
||||
|
||||
import "github.com/gogf/gf/database/gdb"
|
||||
|
||||
type (
|
||||
// M is alias for Model, just for short write purpose.
|
||||
// Deprecated, no longer suggested.
|
||||
M = *gdb.Model
|
||||
|
||||
// Model is alias for *gdb.Model.
|
||||
// Deprecated, no longer suggested.
|
||||
Model = *gdb.Model
|
||||
)
|
||||
@ -1,130 +0,0 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gmvc
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/frame/gins"
|
||||
"sync"
|
||||
|
||||
"github.com/gogf/gf/util/gmode"
|
||||
|
||||
"github.com/gogf/gf/net/ghttp"
|
||||
"github.com/gogf/gf/os/gview"
|
||||
)
|
||||
|
||||
// View is the view object for controller.
|
||||
// It's initialized when controller request initializes and destroyed
|
||||
// when the controller request closes.
|
||||
// Deprecated, no longer suggested.
|
||||
type View struct {
|
||||
mu sync.RWMutex
|
||||
view *gview.View
|
||||
data gview.Params
|
||||
response *ghttp.Response
|
||||
}
|
||||
|
||||
// NewView creates and returns a controller view object.
|
||||
// Deprecated, no longer suggested.
|
||||
func NewView(w *ghttp.Response) *View {
|
||||
return &View{
|
||||
view: gins.View(),
|
||||
data: make(gview.Params),
|
||||
response: w,
|
||||
}
|
||||
}
|
||||
|
||||
// Assigns assigns template variables to this view object.
|
||||
func (view *View) Assigns(data gview.Params) {
|
||||
view.mu.Lock()
|
||||
for k, v := range data {
|
||||
view.data[k] = v
|
||||
}
|
||||
view.mu.Unlock()
|
||||
}
|
||||
|
||||
// Assign assigns one template variable to this view object.
|
||||
func (view *View) Assign(key string, value interface{}) {
|
||||
view.mu.Lock()
|
||||
view.data[key] = value
|
||||
view.mu.Unlock()
|
||||
}
|
||||
|
||||
// Parse parses given template file `tpl` with assigned template variables
|
||||
// and returns the parsed template content.
|
||||
func (view *View) Parse(file string) (string, error) {
|
||||
view.mu.RLock()
|
||||
defer view.mu.RUnlock()
|
||||
buffer, err := view.response.ParseTpl(file, view.data)
|
||||
return buffer, err
|
||||
}
|
||||
|
||||
// ParseContent parses given template file `file` with assigned template variables
|
||||
// and returns the parsed template content.
|
||||
func (view *View) ParseContent(content string) (string, error) {
|
||||
view.mu.RLock()
|
||||
defer view.mu.RUnlock()
|
||||
buffer, err := view.response.ParseTplContent(content, view.data)
|
||||
return buffer, err
|
||||
}
|
||||
|
||||
// LockFunc locks writing for template variables by callback function `f`.
|
||||
func (view *View) LockFunc(f func(data gview.Params)) {
|
||||
view.mu.Lock()
|
||||
defer view.mu.Unlock()
|
||||
f(view.data)
|
||||
}
|
||||
|
||||
// RLockFunc locks reading for template variables by callback function `f`.
|
||||
func (view *View) RLockFunc(f func(data gview.Params)) {
|
||||
view.mu.RLock()
|
||||
defer view.mu.RUnlock()
|
||||
f(view.data)
|
||||
}
|
||||
|
||||
// BindFunc registers customized template function named `name`
|
||||
// with given function `function` to current view object.
|
||||
// The `name` is the function name which can be called in template content.
|
||||
func (view *View) BindFunc(name string, function interface{}) {
|
||||
view.view.BindFunc(name, function)
|
||||
}
|
||||
|
||||
// BindFuncMap registers customized template functions by map to current view object.
|
||||
// The key of map is the template function name
|
||||
// and the value of map is the address of customized function.
|
||||
func (view *View) BindFuncMap(funcMap gview.FuncMap) {
|
||||
view.view.BindFuncMap(funcMap)
|
||||
}
|
||||
|
||||
// Display parses and writes the parsed template file content to http response.
|
||||
func (view *View) Display(file ...string) error {
|
||||
name := view.view.GetDefaultFile()
|
||||
if len(file) > 0 {
|
||||
name = file[0]
|
||||
}
|
||||
if content, err := view.Parse(name); err != nil {
|
||||
if !gmode.IsProduct() {
|
||||
view.response.Write("Tpl Parsing Error: " + err.Error())
|
||||
}
|
||||
return err
|
||||
} else {
|
||||
view.response.Write(content)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DisplayContent parses and writes the parsed content to http response.
|
||||
func (view *View) DisplayContent(content string) error {
|
||||
if content, err := view.ParseContent(content); err != nil {
|
||||
if !gmode.IsProduct() {
|
||||
view.response.Write("Tpl Parsing Error: " + err.Error())
|
||||
}
|
||||
return err
|
||||
} else {
|
||||
view.response.Write(content)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -220,7 +220,7 @@ func (m *Manager) init(ctx context.Context) {
|
||||
m.data[lang] = make(map[string]string)
|
||||
}
|
||||
if j, err := gjson.LoadContent(file.Content()); err == nil {
|
||||
for k, v := range j.Map() {
|
||||
for k, v := range j.Var().Map() {
|
||||
m.data[lang][k] = gconv.String(v)
|
||||
}
|
||||
} else {
|
||||
@ -251,7 +251,7 @@ func (m *Manager) init(ctx context.Context) {
|
||||
m.data[lang] = make(map[string]string)
|
||||
}
|
||||
if j, err := gjson.LoadContent(gfile.GetBytes(file)); err == nil {
|
||||
for k, v := range j.Map() {
|
||||
for k, v := range j.Var().Map() {
|
||||
m.data[lang][k] = gconv.String(v)
|
||||
}
|
||||
} else {
|
||||
|
||||
@ -7,7 +7,6 @@
|
||||
package ghttp
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/container/gvar"
|
||||
"github.com/gogf/gf/net/ghttp/internal/client"
|
||||
)
|
||||
|
||||
@ -21,289 +20,3 @@ type (
|
||||
func NewClient() *Client {
|
||||
return client.New()
|
||||
}
|
||||
|
||||
// Get is a convenience method for sending GET request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Get or NewClient().Get instead.
|
||||
func Get(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("GET", url, data...)
|
||||
}
|
||||
|
||||
// Put is a convenience method for sending PUT request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Put or NewClient().Put instead.
|
||||
func Put(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("PUT", url, data...)
|
||||
}
|
||||
|
||||
// Post is a convenience method for sending POST request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Post or NewClient().Post instead.
|
||||
func Post(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("POST", url, data...)
|
||||
}
|
||||
|
||||
// Delete is a convenience method for sending DELETE request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Delete or NewClient().Delete instead.
|
||||
func Delete(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("DELETE", url, data...)
|
||||
}
|
||||
|
||||
// Head is a convenience method for sending HEAD request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Head or NewClient().Head instead.
|
||||
func Head(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("HEAD", url, data...)
|
||||
}
|
||||
|
||||
// Patch is a convenience method for sending PATCH request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Patch or NewClient().Patch instead.
|
||||
func Patch(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("PATCH", url, data...)
|
||||
}
|
||||
|
||||
// Connect is a convenience method for sending CONNECT request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Connect or NewClient().Connect instead.
|
||||
func Connect(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("CONNECT", url, data...)
|
||||
}
|
||||
|
||||
// Options is a convenience method for sending OPTIONS request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Options or NewClient().Options instead.
|
||||
func Options(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("OPTIONS", url, data...)
|
||||
}
|
||||
|
||||
// Trace is a convenience method for sending TRACE request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().Trace or NewClient().Trace instead.
|
||||
func Trace(url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return DoRequest("TRACE", url, data...)
|
||||
}
|
||||
|
||||
// DoRequest is a convenience method for sending custom http method request.
|
||||
// NOTE that remembers CLOSING the response object when it'll never be used.
|
||||
// Deprecated, please use g.Client().DoRequest or NewClient().DoRequest instead.
|
||||
func DoRequest(method, url string, data ...interface{}) (*ClientResponse, error) {
|
||||
return client.New().DoRequest(method, url, data...)
|
||||
}
|
||||
|
||||
// GetContent is a convenience method for sending GET request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().GetContent or NewClient().GetContent instead.
|
||||
func GetContent(url string, data ...interface{}) string {
|
||||
return RequestContent("GET", url, data...)
|
||||
}
|
||||
|
||||
// PutContent is a convenience method for sending PUT request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().PutContent or NewClient().PutContent instead.
|
||||
func PutContent(url string, data ...interface{}) string {
|
||||
return RequestContent("PUT", url, data...)
|
||||
}
|
||||
|
||||
// PostContent is a convenience method for sending POST request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().PostContent or NewClient().PostContent instead.
|
||||
func PostContent(url string, data ...interface{}) string {
|
||||
return RequestContent("POST", url, data...)
|
||||
}
|
||||
|
||||
// DeleteContent is a convenience method for sending DELETE request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().DeleteContent or NewClient().DeleteContent instead.
|
||||
func DeleteContent(url string, data ...interface{}) string {
|
||||
return RequestContent("DELETE", url, data...)
|
||||
}
|
||||
|
||||
// HeadContent is a convenience method for sending HEAD request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().HeadContent or NewClient().HeadContent instead.
|
||||
func HeadContent(url string, data ...interface{}) string {
|
||||
return RequestContent("HEAD", url, data...)
|
||||
}
|
||||
|
||||
// PatchContent is a convenience method for sending PATCH request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().PatchContent or NewClient().PatchContent instead.
|
||||
func PatchContent(url string, data ...interface{}) string {
|
||||
return RequestContent("PATCH", url, data...)
|
||||
}
|
||||
|
||||
// ConnectContent is a convenience method for sending CONNECT request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().ConnectContent or NewClient().ConnectContent instead.
|
||||
func ConnectContent(url string, data ...interface{}) string {
|
||||
return RequestContent("CONNECT", url, data...)
|
||||
}
|
||||
|
||||
// OptionsContent is a convenience method for sending OPTIONS request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().OptionsContent or NewClient().OptionsContent instead.
|
||||
func OptionsContent(url string, data ...interface{}) string {
|
||||
return RequestContent("OPTIONS", url, data...)
|
||||
}
|
||||
|
||||
// TraceContent is a convenience method for sending TRACE request, which retrieves and returns
|
||||
// the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().TraceContent or NewClient().TraceContent instead.
|
||||
func TraceContent(url string, data ...interface{}) string {
|
||||
return RequestContent("TRACE", url, data...)
|
||||
}
|
||||
|
||||
// RequestContent is a convenience method for sending custom http method request, which
|
||||
// retrieves and returns the result content and automatically closes response object.
|
||||
// Deprecated, please use g.Client().RequestContent or NewClient().RequestContent instead.
|
||||
func RequestContent(method string, url string, data ...interface{}) string {
|
||||
return client.New().RequestContent(method, url, data...)
|
||||
}
|
||||
|
||||
// GetBytes is a convenience method for sending GET request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().GetBytes or NewClient().GetBytes instead.
|
||||
func GetBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("GET", url, data...)
|
||||
}
|
||||
|
||||
// PutBytes is a convenience method for sending PUT request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().PutBytes or NewClient().PutBytes instead.
|
||||
func PutBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("PUT", url, data...)
|
||||
}
|
||||
|
||||
// PostBytes is a convenience method for sending POST request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().PostBytes or NewClient().PostBytes instead.
|
||||
func PostBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("POST", url, data...)
|
||||
}
|
||||
|
||||
// DeleteBytes is a convenience method for sending DELETE request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().DeleteBytes or NewClient().DeleteBytes instead.
|
||||
func DeleteBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("DELETE", url, data...)
|
||||
}
|
||||
|
||||
// HeadBytes is a convenience method for sending HEAD request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().HeadBytes or NewClient().HeadBytes instead.
|
||||
func HeadBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("HEAD", url, data...)
|
||||
}
|
||||
|
||||
// PatchBytes is a convenience method for sending PATCH request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().PatchBytes or NewClient().PatchBytes instead.
|
||||
func PatchBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("PATCH", url, data...)
|
||||
}
|
||||
|
||||
// ConnectBytes is a convenience method for sending CONNECT request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().ConnectBytes or NewClient().ConnectBytes instead.
|
||||
func ConnectBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("CONNECT", url, data...)
|
||||
}
|
||||
|
||||
// OptionsBytes is a convenience method for sending OPTIONS request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().OptionsBytes or NewClient().OptionsBytes instead.
|
||||
func OptionsBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("OPTIONS", url, data...)
|
||||
}
|
||||
|
||||
// TraceBytes is a convenience method for sending TRACE request, which retrieves and returns
|
||||
// the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().TraceBytes or NewClient().TraceBytes instead.
|
||||
func TraceBytes(url string, data ...interface{}) []byte {
|
||||
return RequestBytes("TRACE", url, data...)
|
||||
}
|
||||
|
||||
// RequestBytes is a convenience method for sending custom http method request, which
|
||||
// retrieves and returns the result content as bytes and automatically closes response object.
|
||||
// Deprecated, please use g.Client().RequestBytes or NewClient().RequestBytes instead.
|
||||
func RequestBytes(method string, url string, data ...interface{}) []byte {
|
||||
return client.New().RequestBytes(method, url, data...)
|
||||
}
|
||||
|
||||
// GetVar sends a GET request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().GetVar or NewClient().GetVar instead.
|
||||
func GetVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("GET", url, data...)
|
||||
}
|
||||
|
||||
// PutVar sends a PUT request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().PutVar or NewClient().PutVar instead.
|
||||
func PutVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("PUT", url, data...)
|
||||
}
|
||||
|
||||
// PostVar sends a POST request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().PostVar or NewClient().PostVar instead.
|
||||
func PostVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("POST", url, data...)
|
||||
}
|
||||
|
||||
// DeleteVar sends a DELETE request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().DeleteVar or NewClient().DeleteVar instead.
|
||||
func DeleteVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("DELETE", url, data...)
|
||||
}
|
||||
|
||||
// HeadVar sends a HEAD request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().HeadVar or NewClient().HeadVar instead.
|
||||
func HeadVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("HEAD", url, data...)
|
||||
}
|
||||
|
||||
// PatchVar sends a PATCH request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().PatchVar or NewClient().PatchVar instead.
|
||||
func PatchVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("PATCH", url, data...)
|
||||
}
|
||||
|
||||
// ConnectVar sends a CONNECT request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().ConnectVar or NewClient().ConnectVar instead.
|
||||
func ConnectVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("CONNECT", url, data...)
|
||||
}
|
||||
|
||||
// OptionsVar sends a OPTIONS request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().OptionsVar or NewClient().OptionsVar instead.
|
||||
func OptionsVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("OPTIONS", url, data...)
|
||||
}
|
||||
|
||||
// TraceVar sends a TRACE request, retrieves and converts the result content to specified pointer.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().TraceVar or NewClient().TraceVar instead.
|
||||
func TraceVar(url string, data ...interface{}) *gvar.Var {
|
||||
return RequestVar("TRACE", url, data...)
|
||||
}
|
||||
|
||||
// RequestVar sends request using given HTTP method and data, retrieves converts the result
|
||||
// to specified pointer. It reads and closes the response object internally automatically.
|
||||
// The parameter <pointer> can be type of: struct/*struct/**struct/[]struct/[]*struct/*[]struct, et
|
||||
// Deprecated, please use g.Client().RequestVar or NewClient().RequestVar instead.
|
||||
func RequestVar(method string, url string, data ...interface{}) *gvar.Var {
|
||||
response, err := DoRequest(method, url, data...)
|
||||
if err != nil {
|
||||
return gvar.New(nil)
|
||||
}
|
||||
defer response.Close()
|
||||
return gvar.New(response.ReadAll())
|
||||
}
|
||||
|
||||
@ -118,14 +118,14 @@ func (r *Request) doParse(pointer interface{}, requestType int) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := j.GetStructs(".", pointer); err != nil {
|
||||
if err := j.Var().Scan(pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < reflectVal2.Len(); i++ {
|
||||
if err := gvalid.CheckStructWithData(
|
||||
r.Context(),
|
||||
reflectVal2.Index(i),
|
||||
j.GetMap(gconv.String(i)),
|
||||
j.Get(gconv.String(i)).Map(),
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
@ -142,20 +142,6 @@ func (r *Request) Get(key string, def ...interface{}) *gvar.Var {
|
||||
return r.GetRequest(key, def...)
|
||||
}
|
||||
|
||||
// GetRaw is alias of GetBody.
|
||||
// See GetBody.
|
||||
// Deprecated, use GetBody instead.
|
||||
func (r *Request) GetRaw() []byte {
|
||||
return r.GetBody()
|
||||
}
|
||||
|
||||
// GetRawString is alias of GetBodyString.
|
||||
// See GetBodyString.
|
||||
// Deprecated, use GetBodyString instead.
|
||||
func (r *Request) GetRawString() string {
|
||||
return r.GetBodyString()
|
||||
}
|
||||
|
||||
// GetBody retrieves and returns request body content as bytes.
|
||||
// It can be called multiple times retrieving the same body content.
|
||||
func (r *Request) GetBody() []byte {
|
||||
|
||||
@ -9,11 +9,10 @@ package ghttp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/encoding/gjson"
|
||||
"github.com/gogf/gf/internal/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/util/gconv"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Write writes <content> to the response buffer.
|
||||
@ -183,7 +182,7 @@ func (r *Response) WriteXml(content interface{}, rootTag ...string) error {
|
||||
return nil
|
||||
}
|
||||
// Else use gparser.VarToXml function to encode the parameter.
|
||||
if b, err := gparser.VarToXml(content, rootTag...); err != nil {
|
||||
if b, err := gjson.New(content).ToXml(rootTag...); err != nil {
|
||||
return err
|
||||
} else {
|
||||
r.Header().Set("Content-Type", "application/xml")
|
||||
|
||||
@ -41,15 +41,6 @@ func init() {
|
||||
}
|
||||
}
|
||||
|
||||
// SetGraceful enables/disables the graceful reload feature for server,
|
||||
// which is false in default.
|
||||
//
|
||||
// Note that this feature switch is not for single server instance but for whole process.
|
||||
// Deprecated, use configuration of ghttp.Server for controlling this feature.
|
||||
func SetGraceful(enabled bool) {
|
||||
gracefulEnabled = enabled
|
||||
}
|
||||
|
||||
// serverProcessInit initializes some process configurations, which can only be done once.
|
||||
func serverProcessInit() {
|
||||
var (
|
||||
@ -506,16 +497,3 @@ func (s *Server) getListenerFdMap() map[string]string {
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// IsExitError checks if given error is an exit error of server.
|
||||
// This is used in old version of server for custom error handler.
|
||||
// Deprecated.
|
||||
func IsExitError(err interface{}) bool {
|
||||
errStr := gconv.String(err)
|
||||
if strings.EqualFold(errStr, exceptionExit) ||
|
||||
strings.EqualFold(errStr, exceptionExitAll) ||
|
||||
strings.EqualFold(errStr, exceptionExitHook) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@ -196,9 +196,9 @@ func bufferToServerFdMap(buffer []byte) map[string]listenerFdMap {
|
||||
sfm := make(map[string]listenerFdMap)
|
||||
if len(buffer) > 0 {
|
||||
j, _ := gjson.LoadContent(buffer)
|
||||
for k, _ := range j.Map() {
|
||||
for k, _ := range j.Var().Map() {
|
||||
m := make(map[string]string)
|
||||
for k, v := range j.GetMap(k) {
|
||||
for k, v := range j.Get(k).Map() {
|
||||
m[k] = gconv.String(v)
|
||||
}
|
||||
sfm[k] = m
|
||||
|
||||
@ -27,16 +27,12 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHttpAddr = ":80" // Default listening port for HTTP.
|
||||
defaultHttpsAddr = ":443" // Default listening port for HTTPS.
|
||||
URI_TYPE_DEFAULT = 0 // Deprecated, please use UriTypeDefault instead.
|
||||
URI_TYPE_FULLNAME = 1 // Deprecated, please use UriTypeFullName instead.
|
||||
URI_TYPE_ALLLOWER = 2 // Deprecated, please use UriTypeAllLower instead.
|
||||
URI_TYPE_CAMEL = 3 // Deprecated, please use UriTypeCamel instead.
|
||||
UriTypeDefault = 0 // Method name to URI converting type, which converts name to its lower case and joins the words using char '-'.
|
||||
UriTypeFullName = 1 // Method name to URI converting type, which does no converting to the method name.
|
||||
UriTypeAllLower = 2 // Method name to URI converting type, which converts name to its lower case.
|
||||
UriTypeCamel = 3 // Method name to URI converting type, which converts name to its camel case.
|
||||
defaultHttpAddr = ":80" // Default listening port for HTTP.
|
||||
defaultHttpsAddr = ":443" // Default listening port for HTTPS.
|
||||
UriTypeDefault = 0 // Method names to URI converting type, which converts name to its lower case and joins the words using char '-'.
|
||||
UriTypeFullName = 1 // Method names to URI converting type, which does no converting to the method name.
|
||||
UriTypeAllLower = 2 // Method names to URI converting type, which converts name to its lower case.
|
||||
UriTypeCamel = 3 // Method names to URI converting type, which converts name to its camel case.
|
||||
)
|
||||
|
||||
// ServerConfig is the HTTP Server configuration manager.
|
||||
@ -227,12 +223,6 @@ type ServerConfig struct {
|
||||
GracefulTimeout uint8 `json:"gracefulTimeout"`
|
||||
}
|
||||
|
||||
// Config creates and returns a ServerConfig object with default configurations.
|
||||
// Deprecated. Use NewConfig instead.
|
||||
func Config() ServerConfig {
|
||||
return NewConfig()
|
||||
}
|
||||
|
||||
// NewConfig creates and returns a ServerConfig object with default configurations.
|
||||
// Note that, do not define this default configuration to local package variable, as there are
|
||||
// some pointer attributes that may be shared in different servers.
|
||||
@ -339,8 +329,7 @@ func (s *Server) SetConfig(c ServerConfig) error {
|
||||
if err := s.config.Logger.SetLevelStr(s.config.LogLevel); err != nil {
|
||||
intlog.Error(context.TODO(), err)
|
||||
}
|
||||
|
||||
SetGraceful(c.Graceful)
|
||||
gracefulEnabled = c.Graceful
|
||||
intlog.Printf(context.TODO(), "SetConfig: %+v", s.config)
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -42,10 +42,10 @@ func Test_Client_Basic(t *testing.T) {
|
||||
client := g.Client()
|
||||
client.SetPrefix(url)
|
||||
|
||||
t.Assert(ghttp.GetContent(""), ``)
|
||||
t.Assert(g.Client().GetContent(""), ``)
|
||||
t.Assert(client.GetContent("/hello"), `hello`)
|
||||
|
||||
_, err := ghttp.Post("")
|
||||
_, err := g.Client().Post("")
|
||||
t.AssertNE(err, nil)
|
||||
})
|
||||
}
|
||||
|
||||
@ -206,7 +206,7 @@ func Test_Params_Basic(t *testing.T) {
|
||||
}
|
||||
})
|
||||
s.BindHandler("/raw", func(r *ghttp.Request) {
|
||||
r.Response.Write(r.GetRaw())
|
||||
r.Response.Write(r.GetBody())
|
||||
})
|
||||
s.BindHandler("/json", func(r *ghttp.Request) {
|
||||
j, err := r.GetJson()
|
||||
|
||||
@ -25,7 +25,7 @@ func (o *NamesObject) ShowName(r *ghttp.Request) {
|
||||
func Test_NameToUri_FullName(t *testing.T) {
|
||||
p, _ := ports.PopRand()
|
||||
s := g.Server(p)
|
||||
s.SetNameToUriType(ghttp.URI_TYPE_FULLNAME)
|
||||
s.SetNameToUriType(ghttp.UriTypeFullName)
|
||||
s.BindObject("/{.struct}/{.method}", new(NamesObject))
|
||||
s.SetPort(p)
|
||||
s.SetDumpRouterMap(false)
|
||||
@ -46,7 +46,7 @@ func Test_NameToUri_FullName(t *testing.T) {
|
||||
func Test_NameToUri_AllLower(t *testing.T) {
|
||||
p, _ := ports.PopRand()
|
||||
s := g.Server(p)
|
||||
s.SetNameToUriType(ghttp.URI_TYPE_ALLLOWER)
|
||||
s.SetNameToUriType(ghttp.UriTypeAllLower)
|
||||
s.BindObject("/{.struct}/{.method}", new(NamesObject))
|
||||
s.SetPort(p)
|
||||
s.SetDumpRouterMap(false)
|
||||
@ -67,7 +67,7 @@ func Test_NameToUri_AllLower(t *testing.T) {
|
||||
func Test_NameToUri_Camel(t *testing.T) {
|
||||
p, _ := ports.PopRand()
|
||||
s := g.Server(p)
|
||||
s.SetNameToUriType(ghttp.URI_TYPE_CAMEL)
|
||||
s.SetNameToUriType(ghttp.UriTypeCamel)
|
||||
s.BindObject("/{.struct}/{.method}", new(NamesObject))
|
||||
s.SetPort(p)
|
||||
s.SetDumpRouterMap(false)
|
||||
|
||||
@ -9,6 +9,7 @@ package client
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"github.com/gogf/gf/encoding/gjson"
|
||||
"github.com/gogf/gf/errors/gcode"
|
||||
"github.com/gogf/gf/errors/gerror"
|
||||
"github.com/gogf/gf/internal/intlog"
|
||||
@ -23,7 +24,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/encoding/gparser"
|
||||
"github.com/gogf/gf/text/gregex"
|
||||
"github.com/gogf/gf/text/gstr"
|
||||
"github.com/gogf/gf/util/gconv"
|
||||
@ -138,12 +138,13 @@ func (c *Client) prepareRequest(method, url string, data ...interface{}) (req *h
|
||||
params = string(b)
|
||||
}
|
||||
}
|
||||
|
||||
case "application/xml":
|
||||
switch data[0].(type) {
|
||||
case string, []byte:
|
||||
params = gconv.String(data[0])
|
||||
default:
|
||||
if b, err := gparser.VarToXml(data[0]); err != nil {
|
||||
if b, err := gjson.New(data[0]).ToXml(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
params = string(b)
|
||||
|
||||
@ -146,7 +146,7 @@ func (c *AdapterFile) Data(ctx context.Context) (data map[string]interface{}, er
|
||||
return nil, err
|
||||
}
|
||||
if j != nil {
|
||||
return j.GetVar(".").Map(), nil
|
||||
return j.Var().Map(), nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@ -66,12 +66,6 @@ func GetArgAll() []string {
|
||||
return command.GetArgAll()
|
||||
}
|
||||
|
||||
// GetWithEnv is alias of GetOptWithEnv.
|
||||
// Deprecated, use GetOptWithEnv instead.
|
||||
func GetWithEnv(key string, def ...interface{}) *gvar.Var {
|
||||
return GetOptWithEnv(key, def...)
|
||||
}
|
||||
|
||||
// GetOptWithEnv returns the command line argument of the specified <key>.
|
||||
// If the argument does not exist, then it returns the environment variable with specified <key>.
|
||||
// It returns the default value <def> if none of them exists.
|
||||
|
||||
@ -36,30 +36,6 @@ func GetLogger() *glog.Logger {
|
||||
return defaultCron.GetLogger()
|
||||
}
|
||||
|
||||
// SetLogPath sets the logging folder path for default cron object.
|
||||
// Deprecated, use SetLogger instead.
|
||||
func SetLogPath(path string) {
|
||||
defaultCron.SetLogPath(path)
|
||||
}
|
||||
|
||||
// GetLogPath returns the logging folder path of default cron object.
|
||||
// Deprecated, use GetLogger instead.
|
||||
func GetLogPath() string {
|
||||
return defaultCron.GetLogPath()
|
||||
}
|
||||
|
||||
// SetLogLevel sets the logging level for default cron object.
|
||||
// Deprecated, use SetLogger instead.
|
||||
func SetLogLevel(level int) {
|
||||
defaultCron.SetLogLevel(level)
|
||||
}
|
||||
|
||||
// GetLogLevel returns the logging level for default cron object.
|
||||
// Deprecated, use GetLogger instead.
|
||||
func GetLogLevel() int {
|
||||
return defaultCron.GetLogLevel()
|
||||
}
|
||||
|
||||
// Add adds a timed task to default cron object.
|
||||
// A unique `name` can be bound with the timed task.
|
||||
// It returns and error if the `name` is already used.
|
||||
|
||||
@ -21,24 +21,14 @@ type Cron struct {
|
||||
status *gtype.Int // Timed task status(0: Not Start; 1: Running; 2: Stopped; -1: Closed)
|
||||
entries *gmap.StrAnyMap // All timed task entries.
|
||||
logger *glog.Logger // Logger, it is nil in default.
|
||||
|
||||
// Logging path(folder).
|
||||
// Deprecated, use logger instead.
|
||||
logPath *gtype.String
|
||||
|
||||
// Logging level.
|
||||
// Deprecated, use logger instead.
|
||||
logLevel *gtype.Int
|
||||
}
|
||||
|
||||
// New returns a new Cron object with default settings.
|
||||
func New() *Cron {
|
||||
return &Cron{
|
||||
idGen: gtype.NewInt64(),
|
||||
status: gtype.NewInt(StatusRunning),
|
||||
entries: gmap.NewStrAnyMap(true),
|
||||
logPath: gtype.NewString(),
|
||||
logLevel: gtype.NewInt(glog.LEVEL_PROD),
|
||||
idGen: gtype.NewInt64(),
|
||||
status: gtype.NewInt(StatusRunning),
|
||||
entries: gmap.NewStrAnyMap(true),
|
||||
}
|
||||
}
|
||||
|
||||
@ -52,30 +42,6 @@ func (c *Cron) GetLogger() *glog.Logger {
|
||||
return c.logger
|
||||
}
|
||||
|
||||
// SetLogPath sets the logging folder path.
|
||||
// Deprecated, use SetLogger instead.
|
||||
func (c *Cron) SetLogPath(path string) {
|
||||
c.logPath.Set(path)
|
||||
}
|
||||
|
||||
// GetLogPath return the logging folder path.
|
||||
// Deprecated, use GetLogger instead.
|
||||
func (c *Cron) GetLogPath() string {
|
||||
return c.logPath.Val()
|
||||
}
|
||||
|
||||
// SetLogLevel sets the logging level.
|
||||
// Deprecated, use SetLogger instead.
|
||||
func (c *Cron) SetLogLevel(level int) {
|
||||
c.logLevel.Set(level)
|
||||
}
|
||||
|
||||
// GetLogLevel returns the logging level.
|
||||
// Deprecated, use GetLogger instead.
|
||||
func (c *Cron) GetLogLevel() int {
|
||||
return c.logLevel.Val()
|
||||
}
|
||||
|
||||
// AddEntry creates and returns a new Entry object.
|
||||
func (c *Cron) AddEntry(pattern string, job func(), times int, singleton bool, name ...string) (*Entry, error) {
|
||||
var (
|
||||
|
||||
@ -183,17 +183,6 @@ func ReadLines(file string, callback func(text string) error) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadByteLines reads file content line by line, which is passed to the callback function <callback> as []byte.
|
||||
// It matches each line of text, separated by chars '\r' or '\n', stripped any trailing end-of-line marker.
|
||||
//
|
||||
// Note that the parameter passed to callback function might be an empty value, and the last non-empty line
|
||||
// will be passed to callback function <callback> even if it has no newline marker.
|
||||
//
|
||||
// Deprecated, use ReadLinesBytes instead.
|
||||
func ReadByteLines(file string, callback func(bytes []byte) error) error {
|
||||
return ReadLinesBytes(file, callback)
|
||||
}
|
||||
|
||||
// ReadLinesBytes reads file content line by line, which is passed to the callback function <callback> as []byte.
|
||||
// It matches each line of text, separated by chars '\r' or '\n', stripped any trailing end-of-line marker.
|
||||
//
|
||||
|
||||
@ -158,30 +158,6 @@ func TimestampNanoStr() string {
|
||||
return Now().TimestampNanoStr()
|
||||
}
|
||||
|
||||
// Second returns the timestamp in seconds.
|
||||
// Deprecated, use Timestamp instead.
|
||||
func Second() int64 {
|
||||
return Timestamp()
|
||||
}
|
||||
|
||||
// Millisecond returns the timestamp in milliseconds.
|
||||
// Deprecated, use TimestampMilli instead.
|
||||
func Millisecond() int64 {
|
||||
return TimestampMilli()
|
||||
}
|
||||
|
||||
// Microsecond returns the timestamp in microseconds.
|
||||
// Deprecated, use TimestampMicro instead.
|
||||
func Microsecond() int64 {
|
||||
return TimestampMicro()
|
||||
}
|
||||
|
||||
// Nanosecond returns the timestamp in nanoseconds.
|
||||
// Deprecated, use TimestampNano instead.
|
||||
func Nanosecond() int64 {
|
||||
return TimestampNano()
|
||||
}
|
||||
|
||||
// Date returns current date in string like "2006-01-02".
|
||||
func Date() string {
|
||||
return time.Now().Format("2006-01-02")
|
||||
|
||||
@ -37,20 +37,6 @@ func C(t *testing.T, f func(t *T)) {
|
||||
f(&T{t})
|
||||
}
|
||||
|
||||
// Case creates a unit testing case.
|
||||
// The parameter `t` is the pointer to testing.T of stdlib (*testing.T).
|
||||
// The parameter `f` is the closure function for unit testing case.
|
||||
// Deprecated.
|
||||
func Case(t *testing.T, f func()) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n%s", err, gdebug.StackWithFilter(pathFilterKey))
|
||||
t.Fail()
|
||||
}
|
||||
}()
|
||||
f()
|
||||
}
|
||||
|
||||
// Assert checks `value` and `expect` EQUAL.
|
||||
func Assert(value, expect interface{}) {
|
||||
rvExpect := reflect.ValueOf(expect)
|
||||
|
||||
@ -297,12 +297,6 @@ func WordWrap(str string, width int, br string) string {
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// RuneLen returns string length of unicode.
|
||||
// Deprecated, use LenRune instead.
|
||||
func RuneLen(str string) int {
|
||||
return LenRune(str)
|
||||
}
|
||||
|
||||
// LenRune returns string length of unicode.
|
||||
func LenRune(str string) int {
|
||||
return utf8.RuneCountInString(str)
|
||||
@ -343,20 +337,6 @@ func SplitAndTrim(str, delimiter string, characterMask ...string) []string {
|
||||
return array
|
||||
}
|
||||
|
||||
// SplitAndTrimSpace splits string `str` by a string `delimiter` to an array,
|
||||
// and calls TrimSpace to every element of this array.
|
||||
// Deprecated, use SplitAndTrim instead.
|
||||
func SplitAndTrimSpace(str, delimiter string) []string {
|
||||
array := make([]string, 0)
|
||||
for _, v := range strings.Split(str, delimiter) {
|
||||
v = strings.TrimSpace(v)
|
||||
if v != "" {
|
||||
array = append(array, v)
|
||||
}
|
||||
}
|
||||
return array
|
||||
}
|
||||
|
||||
// Join concatenates the elements of `array` to create a single string. The separator string
|
||||
// `sep` is placed between elements in the resulting string.
|
||||
func Join(array []string, sep string) string {
|
||||
|
||||
@ -29,23 +29,11 @@ var (
|
||||
firstCamelCaseEnd = regexp.MustCompile(`([\w\W]*?)([_]?[A-Z]+)$`)
|
||||
)
|
||||
|
||||
// CamelCase converts a string to CamelCase.
|
||||
// Deprecated, use CaseCamel instead.
|
||||
func CamelCase(s string) string {
|
||||
return CaseCamel(s)
|
||||
}
|
||||
|
||||
// CaseCamel converts a string to CamelCase.
|
||||
func CaseCamel(s string) string {
|
||||
return toCamelInitCase(s, true)
|
||||
}
|
||||
|
||||
// CamelLowerCase converts a string to lowerCamelCase.
|
||||
// Deprecated, use CaseCamelLower instead.
|
||||
func CamelLowerCase(s string) string {
|
||||
return CaseCamelLower(s)
|
||||
}
|
||||
|
||||
// CaseCamelLower converts a string to lowerCamelCase.
|
||||
func CaseCamelLower(s string) string {
|
||||
if s == "" {
|
||||
@ -57,21 +45,9 @@ func CaseCamelLower(s string) string {
|
||||
return toCamelInitCase(s, false)
|
||||
}
|
||||
|
||||
// SnakeCase converts a string to snake_case.
|
||||
// Deprecated, use CaseSnake instead.
|
||||
func SnakeCase(s string) string {
|
||||
return CaseSnake(s)
|
||||
}
|
||||
|
||||
// CaseSnake converts a string to snake_case.
|
||||
func CaseSnake(s string) string {
|
||||
return DelimitedCase(s, '_')
|
||||
}
|
||||
|
||||
// SnakeScreamingCase converts a string to SNAKE_CASE_SCREAMING.
|
||||
// Deprecated, use CaseSnakeScreaming instead.
|
||||
func SnakeScreamingCase(s string) string {
|
||||
return CaseSnakeScreaming(s)
|
||||
return CaseDelimited(s, '_')
|
||||
}
|
||||
|
||||
// CaseSnakeScreaming converts a string to SNAKE_CASE_SCREAMING.
|
||||
@ -79,13 +55,6 @@ func CaseSnakeScreaming(s string) string {
|
||||
return CaseDelimitedScreaming(s, '_', true)
|
||||
}
|
||||
|
||||
// SnakeFirstUpperCase converts a string from RGBCodeMd5 to rgb_code_md5.
|
||||
// The length of word should not be too long
|
||||
// Deprecated, use CaseSnakeFirstUpper instead.
|
||||
func SnakeFirstUpperCase(word string, underscore ...string) string {
|
||||
return CaseSnakeFirstUpper(word, underscore...)
|
||||
}
|
||||
|
||||
// CaseSnakeFirstUpper converts a string like "RGBCodeMd5" to "rgb_code_md5".
|
||||
// TODO for efficiency should change regexp to traversing string in future.
|
||||
func CaseSnakeFirstUpper(word string, underscore ...string) string {
|
||||
@ -114,45 +83,21 @@ func CaseSnakeFirstUpper(word string, underscore ...string) string {
|
||||
return TrimLeft(word, replace)
|
||||
}
|
||||
|
||||
// KebabCase converts a string to kebab-case.
|
||||
// Deprecated, use CaseKebab instead.
|
||||
func KebabCase(s string) string {
|
||||
return CaseKebab(s)
|
||||
}
|
||||
|
||||
// CaseKebab converts a string to kebab-case
|
||||
func CaseKebab(s string) string {
|
||||
return CaseDelimited(s, '-')
|
||||
}
|
||||
|
||||
// KebabScreamingCase converts a string to KEBAB-CASE-SCREAMING.
|
||||
// Deprecated, use CaseKebabScreaming instead.
|
||||
func KebabScreamingCase(s string) string {
|
||||
return CaseKebabScreaming(s)
|
||||
}
|
||||
|
||||
// CaseKebabScreaming converts a string to KEBAB-CASE-SCREAMING.
|
||||
func CaseKebabScreaming(s string) string {
|
||||
return CaseDelimitedScreaming(s, '-', true)
|
||||
}
|
||||
|
||||
// DelimitedCase converts a string to snake.case.delimited.
|
||||
// Deprecated, use CaseDelimited instead.
|
||||
func DelimitedCase(s string, del uint8) string {
|
||||
return CaseDelimited(s, del)
|
||||
}
|
||||
|
||||
// CaseDelimited converts a string to snake.case.delimited.
|
||||
func CaseDelimited(s string, del uint8) string {
|
||||
return CaseDelimitedScreaming(s, del, false)
|
||||
}
|
||||
|
||||
// DelimitedScreamingCase converts a string to DELIMITED.SCREAMING.CASE or delimited.screaming.case.
|
||||
// Deprecated, use CaseDelimitedScreaming instead.
|
||||
func DelimitedScreamingCase(s string, del uint8, screaming bool) string {
|
||||
return CaseDelimitedScreaming(s, del, screaming)
|
||||
}
|
||||
|
||||
// CaseDelimitedScreaming converts a string to DELIMITED.SCREAMING.CASE or delimited.screaming.case.
|
||||
func CaseDelimitedScreaming(s string, del uint8, screaming bool) string {
|
||||
s = addWordBoundariesToNumbers(s)
|
||||
|
||||
@ -19,13 +19,6 @@ func MapToMaps(params interface{}, pointer interface{}, mapping ...map[string]st
|
||||
return doMapToMaps(params, pointer, mapping...)
|
||||
}
|
||||
|
||||
// MapToMapsDeep converts any slice type variable `params` to another map slice type variable
|
||||
// `pointer` recursively.
|
||||
// Deprecated, use MapToMaps instead.
|
||||
func MapToMapsDeep(params interface{}, pointer interface{}, mapping ...map[string]string) error {
|
||||
return doMapToMaps(params, pointer, mapping...)
|
||||
}
|
||||
|
||||
// doMapToMaps converts any map type variable `params` to another map slice variable `pointer`.
|
||||
//
|
||||
// The parameter `params` can be type of []map, []*map, []struct, []*struct.
|
||||
|
||||
@ -67,23 +67,3 @@ func Scan(params interface{}, pointer interface{}, mapping ...map[string]string)
|
||||
return doStruct(params, pointer, keyToAttributeNameMapping, "")
|
||||
}
|
||||
}
|
||||
|
||||
// ScanDeep automatically calls StructDeep or StructsDeep function according to the type of
|
||||
// parameter `pointer` to implement the converting.
|
||||
//
|
||||
// It calls function StructDeep if `pointer` is type of *struct/**struct to do the converting.
|
||||
// It calls function StructsDeep if `pointer` is type of *[]struct/*[]*struct to do the converting.
|
||||
// Deprecated, use Scan instead.
|
||||
func ScanDeep(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) {
|
||||
t := reflect.TypeOf(pointer)
|
||||
k := t.Kind()
|
||||
if k != reflect.Ptr {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "params should be type of pointer, but got: %v", k)
|
||||
}
|
||||
switch t.Elem().Kind() {
|
||||
case reflect.Array, reflect.Slice:
|
||||
return StructsDeep(params, pointer, mapping...)
|
||||
default:
|
||||
return StructDeep(params, pointer, mapping...)
|
||||
}
|
||||
}
|
||||
|
||||
@ -112,23 +112,6 @@ func Interfaces(any interface{}) []interface{} {
|
||||
for i := 0; i < reflectValue.Len(); i++ {
|
||||
array[i] = reflectValue.Index(i).Interface()
|
||||
}
|
||||
// Deprecated.
|
||||
//// Eg: {"K1": "v1", "K2": "v2"} => ["K1", "v1", "K2", "v2"]
|
||||
//case reflect.Map:
|
||||
// array = make([]interface{}, 0)
|
||||
// for _, key := range reflectValue.MapKeys() {
|
||||
// array = append(array, key.Interface())
|
||||
// array = append(array, reflectValue.MapIndex(key).Interface())
|
||||
// }
|
||||
//// Eg: {"K1": "v1", "K2": "v2"} => ["K1", "v1", "K2", "v2"]
|
||||
//case reflect.Struct:
|
||||
// array = make([]interface{}, 0)
|
||||
// // Note that, it uses the gconv tag name instead of the attribute name if
|
||||
// // the gconv tag is fined in the struct attributes.
|
||||
// for k, v := range Map(reflectValue) {
|
||||
// array = append(array, k)
|
||||
// array = append(array, v)
|
||||
// }
|
||||
default:
|
||||
return []interface{}{any}
|
||||
}
|
||||
|
||||
@ -42,16 +42,6 @@ func StructTag(params interface{}, pointer interface{}, priorityTag string) (err
|
||||
return doStruct(params, pointer, nil, priorityTag)
|
||||
}
|
||||
|
||||
// StructDeep do Struct function recursively.
|
||||
// Deprecated, use Struct instead.
|
||||
func StructDeep(params interface{}, pointer interface{}, mapping ...map[string]string) error {
|
||||
var keyToAttributeNameMapping map[string]string
|
||||
if len(mapping) > 0 {
|
||||
keyToAttributeNameMapping = mapping[0]
|
||||
}
|
||||
return doStruct(params, pointer, keyToAttributeNameMapping, "")
|
||||
}
|
||||
|
||||
// doStructWithJsonCheck checks if given `params` is JSON, it then uses json.Unmarshal doing the converting.
|
||||
func doStructWithJsonCheck(params interface{}, pointer interface{}) (err error, ok bool) {
|
||||
switch r := params.(type) {
|
||||
|
||||
@ -26,16 +26,6 @@ func StructsTag(params interface{}, pointer interface{}, priorityTag string) (er
|
||||
return doStructs(params, pointer, nil, priorityTag)
|
||||
}
|
||||
|
||||
// StructsDeep converts any slice to given struct slice recursively.
|
||||
// Deprecated, use Structs instead.
|
||||
func StructsDeep(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) {
|
||||
var keyToAttributeNameMapping map[string]string
|
||||
if len(mapping) > 0 {
|
||||
keyToAttributeNameMapping = mapping[0]
|
||||
}
|
||||
return doStructs(params, pointer, keyToAttributeNameMapping, "")
|
||||
}
|
||||
|
||||
// doStructs converts any slice to given struct slice.
|
||||
//
|
||||
// It automatically checks and converts json string to []map if `params` is string/[]byte.
|
||||
|
||||
Reference in New Issue
Block a user