From ff8633231f9e919b8671b15330e18bd95bcc39e8 Mon Sep 17 00:00:00 2001 From: houseme Date: Tue, 16 Nov 2021 00:26:10 +0800 Subject: [PATCH 01/11] improve code 'if block ends with a return statement, so drop this else and outdent its block (golint)' --- container/garray/garray_normal_str.go | 3 +-- encoding/gurl/url.go | 8 ++++---- errors/gerror/gerror.go | 4 ++-- net/ghttp/ghttp_response_view.go | 18 +++++++++--------- net/ghttp/ghttp_response_writer.go | 2 +- os/gres/gres_instance.go | 2 +- os/gsession/gsession_storage_redis.go | 5 ++--- 7 files changed, 20 insertions(+), 22 deletions(-) diff --git a/container/garray/garray_normal_str.go b/container/garray/garray_normal_str.go index 71a6f2e36..0e178e156 100644 --- a/container/garray/garray_normal_str.go +++ b/container/garray/garray_normal_str.go @@ -407,9 +407,8 @@ func (a *StrArray) SubSlice(offset int, length ...int) []string { s := make([]string, size) copy(s, a.array[offset:]) return s - } else { - return a.array[offset:end] } + return a.array[offset:end] } // Append is alias of PushRight,please See PushRight. diff --git a/encoding/gurl/url.go b/encoding/gurl/url.go index 2e3d2d508..ca3631d9a 100644 --- a/encoding/gurl/url.go +++ b/encoding/gurl/url.go @@ -27,25 +27,25 @@ func Decode(str string) (string, error) { return url.QueryUnescape(str) } -// URL-encode according to RFC 3986. +// RawEncode .URL-encode according to RFC 3986. // See http://php.net/manual/en/function.rawurlencode.php. func RawEncode(str string) string { return strings.Replace(url.QueryEscape(str), "+", "%20", -1) } -// Decode URL-encoded strings. +// RawDecode Decode URL-encoded strings. // See http://php.net/manual/en/function.rawurldecode.php. func RawDecode(str string) (string, error) { return url.QueryUnescape(strings.Replace(str, "%20", "+", -1)) } -// Generate URL-encoded query string. +// BuildQuery Generate URL-encoded query string. // See http://php.net/manual/en/function.http-build-query.php. func BuildQuery(queryData url.Values) string { return queryData.Encode() } -// Parse a URL and return its components. +// ParseURL Parse a URL and return its components. // -1: all; 1: scheme; 2: host; 4: port; 8: user; 16: pass; 32: path; 64: query; 128: fragment. // See http://php.net/manual/en/function.parse-url.php. func ParseURL(str string, component int) (map[string]string, error) { diff --git a/errors/gerror/gerror.go b/errors/gerror/gerror.go index 23be7df27..85b80b465 100644 --- a/errors/gerror/gerror.go +++ b/errors/gerror/gerror.go @@ -6,8 +6,8 @@ // Package gerror provides simple functions to manipulate errors. // -// Very note that, this package is quite a basic package, which SHOULD NOT import extra -// packages except standard packages and internal packages, to avoid cycle imports. +// Very note that, this package is quite a basic package, which SHOULD NOT import extra packages +// except standard packages and internal packages, to avoid cycle imports. package gerror import ( diff --git a/net/ghttp/ghttp_response_view.go b/net/ghttp/ghttp_response_view.go index 4d0aa4ac2..bfc8c6287 100644 --- a/net/ghttp/ghttp_response_view.go +++ b/net/ghttp/ghttp_response_view.go @@ -18,42 +18,42 @@ import ( // WriteTpl parses and responses given template file. // The parameter `params` specifies the template variables for parsing. func (r *Response) WriteTpl(tpl string, params ...gview.Params) error { - if b, err := r.ParseTpl(tpl, params...); err != nil { + b, err := r.ParseTpl(tpl, params...) + if err != nil { if !gmode.IsProduct() { r.Write("Template Parsing Error: " + err.Error()) } return err - } else { - r.Write(b) } + r.Write(b) return nil } // WriteTplDefault parses and responses the default template file. // The parameter `params` specifies the template variables for parsing. func (r *Response) WriteTplDefault(params ...gview.Params) error { - if b, err := r.ParseTplDefault(params...); err != nil { + b, err := r.ParseTplDefault(params...) + if err != nil { if !gmode.IsProduct() { r.Write("Template Parsing Error: " + err.Error()) } return err - } else { - r.Write(b) } + r.Write(b) return nil } // WriteTplContent parses and responses the template content. // The parameter `params` specifies the template variables for parsing. func (r *Response) WriteTplContent(content string, params ...gview.Params) error { - if b, err := r.ParseTplContent(content, params...); err != nil { + b, err := r.ParseTplContent(content, params...) + if err != nil { if !gmode.IsProduct() { r.Write("Template Parsing Error: " + err.Error()) } return err - } else { - r.Write(b) } + r.Write(b) return nil } diff --git a/net/ghttp/ghttp_response_writer.go b/net/ghttp/ghttp_response_writer.go index 08ea3daee..5a8781a02 100644 --- a/net/ghttp/ghttp_response_writer.go +++ b/net/ghttp/ghttp_response_writer.go @@ -50,7 +50,7 @@ func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.writer.(http.Hijacker).Hijack() } -// Flush OutputBuffer outputs the buffer to client and clears the buffer. +// Flush outputs the buffer to client and clears the buffer. func (w *ResponseWriter) Flush() { if w.hijacked { return diff --git a/os/gres/gres_instance.go b/os/gres/gres_instance.go index f9e3fff3f..e04dc4311 100644 --- a/os/gres/gres_instance.go +++ b/os/gres/gres_instance.go @@ -9,7 +9,7 @@ package gres import "github.com/gogf/gf/v2/container/gmap" const ( - // DefaultName Default group name for instance usage. + // DefaultName default group name for instance usage. DefaultName = "default" ) diff --git a/os/gsession/gsession_storage_redis.go b/os/gsession/gsession_storage_redis.go index 642b0d525..7f80f9f3d 100644 --- a/os/gsession/gsession_storage_redis.go +++ b/os/gsession/gsession_storage_redis.go @@ -77,7 +77,7 @@ func (s *StorageRedis) Get(ctx context.Context, id string, key string) (value in return nil, ErrorDisabled } -// GetMap retrieves all key-value pairs as map from storage. +// Data retrieves all key-value pairs as map from storage. func (s *StorageRedis) Data(ctx context.Context, id string) (data map[string]interface{}, err error) { return nil, ErrorDisabled } @@ -135,9 +135,8 @@ func (s *StorageRedis) GetSession(ctx context.Context, id string, ttl time.Durat } if data == nil { return gmap.NewStrAnyMapFrom(m, true), nil - } else { - data.Replace(m) } + data.Replace(m) return data, nil } From 0135d23b1632804d6afef450f6fd78cd41165328 Mon Sep 17 00:00:00 2001 From: houseme Date: Tue, 16 Nov 2021 00:56:14 +0800 Subject: [PATCH 02/11] URL-encode according to RFC 3986 --- encoding/gurl/url.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/encoding/gurl/url.go b/encoding/gurl/url.go index ca3631d9a..a402cd1b4 100644 --- a/encoding/gurl/url.go +++ b/encoding/gurl/url.go @@ -27,13 +27,15 @@ func Decode(str string) (string, error) { return url.QueryUnescape(str) } -// RawEncode .URL-encode according to RFC 3986. +// RawEncode Encodes the given string according +// URL-encode according to RFC 3986. // See http://php.net/manual/en/function.rawurlencode.php. func RawEncode(str string) string { return strings.Replace(url.QueryEscape(str), "+", "%20", -1) } -// RawDecode Decode URL-encoded strings. +// RawDecode does decode +// Decode URL-encoded strings. // See http://php.net/manual/en/function.rawurldecode.php. func RawDecode(str string) (string, error) { return url.QueryUnescape(strings.Replace(str, "%20", "+", -1)) From 857ca4d978ff6fc5a94e77fafada8e18bde43cca Mon Sep 17 00:00:00 2001 From: houseme Date: Tue, 16 Nov 2021 00:59:15 +0800 Subject: [PATCH 03/11] URL encode and decode --- encoding/gurl/url.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/encoding/gurl/url.go b/encoding/gurl/url.go index a402cd1b4..031c4e194 100644 --- a/encoding/gurl/url.go +++ b/encoding/gurl/url.go @@ -27,14 +27,14 @@ func Decode(str string) (string, error) { return url.QueryUnescape(str) } -// RawEncode Encodes the given string according +// RawEncode does encode the given string according // URL-encode according to RFC 3986. // See http://php.net/manual/en/function.rawurlencode.php. func RawEncode(str string) string { return strings.Replace(url.QueryEscape(str), "+", "%20", -1) } -// RawDecode does decode +// RawDecode does decode the given string // Decode URL-encoded strings. // See http://php.net/manual/en/function.rawurldecode.php. func RawDecode(str string) (string, error) { From c6efb5ee3bf4bb80dc3cf98116b733dd70139566 Mon Sep 17 00:00:00 2001 From: houseme Date: Tue, 16 Nov 2021 17:21:13 +0800 Subject: [PATCH 04/11] [feature] improve code range map --- .golangci.yml | 950 ++++++++++++++++++ database/gdb/gdb.go | 4 +- database/gdb/gdb_core.go | 10 +- database/gdb/gdb_core_structure.go | 4 +- database/gdb/gdb_core_tracing.go | 5 +- database/gdb/gdb_core_transaction.go | 12 +- database/gdb/gdb_core_underlying.go | 4 +- database/gdb/gdb_driver_mysql.go | 1 + database/gdb/gdb_driver_oracle.go | 2 +- database/gdb/gdb_func.go | 22 +- database/gdb/gdb_model_cache.go | 2 +- database/gdb/gdb_model_condition.go | 6 +- database/gdb/gdb_model_fields.go | 2 +- database/gdb/gdb_model_insert.go | 32 +- database/gdb/gdb_model_join.go | 12 +- database/gdb/gdb_model_option.go | 2 +- database/gdb/gdb_model_order_group.go | 2 +- database/gdb/gdb_model_select.go | 10 +- database/gdb/gdb_model_time.go | 2 +- database/gdb/gdb_model_update.go | 4 +- database/gdb/gdb_model_utility.go | 8 +- database/gdb/gdb_model_with.go | 2 +- database/gdb/gdb_schema.go | 2 +- database/gdb/gdb_type_result.go | 2 +- database/gdb/gdb_type_result_scanlist.go | 10 +- database/gdb/gdb_z_mysql_basic_test.go | 1 + database/gdb/gdb_z_mysql_method_test.go | 12 +- database/gdb/gdb_z_mysql_model_basic_test.go | 5 +- database/gdb/gdb_z_mysql_model_struct_test.go | 5 +- database/gdb/gdb_z_mysql_model_where_test.go | 1 - .../gdb/gdb_z_mysql_time_maintain_test.go | 6 +- database/gdb/gdb_z_mysql_transaction_test.go | 2 - os/gcache/gcache_adapter_memory.go | 2 +- 33 files changed, 1024 insertions(+), 122 deletions(-) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..5e63d73e6 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,950 @@ +# This file contains all available configuration options +# with their default values. + +# options for analysis running +run: + # default concurrency is a available CPU number + concurrency: 4 + + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout: 5m + + # exit code when at least one issue was found, default is 1 + issues-exit-code: 1 + + # include test files or not, default is true + tests: true + + # list of build tags, all linters use it. Default is empty list. + build-tags: + - mytag + + # which dirs to skip: issues from them won't be reported; + # can use regexp here: generated.*, regexp is applied on full path; + # default value is empty list, but default dirs are skipped independently + # from this option's value (see skip-dirs-use-default). + # "/" will be replaced by current OS file path separator to properly work + # on Windows. + skip-dirs: + - packed + - documentation + - docker + + # default is true. Enables skipping of directories: + # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ + skip-dirs-use-default: true + + # which files to skip: they will be analyzed, but issues from them + # won't be reported. Default value is empty list, but there is + # no need to include all autogenerated files, we confidently recognize + # autogenerated files. If it's not please let us know. + # "/" will be replaced by current OS file path separator to properly work + # on Windows. + skip-files: + - ".*\\.my\\.go$" + - lib/bad.go + + # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": + # If invoked with -mod=readonly, the go command is disallowed from the implicit + # automatic updating of go.mod described above. Instead, it fails when any changes + # to go.mod are needed. This setting is most useful to check that go.mod does + # not need updates, such as in a continuous integration and testing system. + # If invoked with -mod=vendor, the go command assumes that the vendor + # directory holds the correct copies of dependencies and ignores + # the dependency descriptions in go.mod. + #modules-download-mode: release|readonly|vendor + + # Allow multiple parallel golangci-lint instances running. + # If false (default) - golangci-lint acquires file lock on start. + allow-parallel-runners: true + + +# output configuration options +output: + # colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions + # default is "colored-line-number" + format: colored-line-number + + # print lines of code with issue, default is true + print-issued-lines: true + + # print linter name in the end of issue text, default is true + print-linter-name: true + + # make issues output unique by line, default is true + uniq-by-line: true + + # add a prefix to the output file references; default is no prefix + path-prefix: "" + + # sorts results by: filepath, line and column + sort-results: true + + +# all available settings of specific linters +linters-settings: + bidichk: + # The following configurations check for all mentioned invisible unicode + # runes. It can be omitted because all runes are enabled by default. + left-to-right-embedding: true + right-to-left-embedding: true + pop-directional-formatting: true + left-to-right-override: true + right-to-left-override: true + left-to-right-isolate: true + right-to-left-isolate: true + first-strong-isolate: true + pop-directional-isolate: true + + cyclop: + # the maximal code complexity to report + max-complexity: 50 + # the maximal average package complexity. If it's higher than 0.0 (float) the check is enabled (default 0.0) + package-average: 0.0 + # should ignore tests (default false) + skip-tests: false + + dogsled: + # checks assignments with too many blank identifiers; default is 2 + max-blank-identifiers: 2 + + dupl: + # tokens count to trigger issue, 150 by default + threshold: 100 + + errcheck: + # report about not checking of errors in type assertions: `a := b.(MyStruct)`; + # default is false: such cases aren't reported by default. + check-type-assertions: false + + # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; + # default is false: such cases aren't reported by default. + check-blank: false + + # [deprecated] comma-separated list of pairs of the form pkg:regex + # the regex is used to ignore names within pkg. (default "fmt:.*"). + # see https://github.com/kisielk/errcheck#the-deprecated-method for details + #ignore: fmt:.*,io/ioutil:^Read.* + + # [deprecated] use exclude-functions instead. + # path to a file containing a list of functions to exclude from checking + # see https://github.com/kisielk/errcheck#excluding-functions for details + # exclude: /path/to/file.txt + + # list of functions to exclude from checking, where each entry is a single function to exclude. + # see https://github.com/kisielk/errcheck#excluding-functions for details + exclude-functions: + - io/ioutil.ReadFile + - io.Copy(*bytes.Buffer) + - io.Copy(os.Stdout) + + errorlint: + # Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats + errorf: true + # Check for plain type assertions and type switches + asserts: true + # Check for plain error comparisons + comparison: true + + exhaustive: + # check switch statements in generated files also + check-generated: false + # presence of "default" case in switch statements satisfies exhaustiveness, + # even if all enum members are not listed + default-signifies-exhaustive: false + # enum members matching the supplied regex do not have to be listed in + # switch statements to satisfy exhaustiveness + ignore-enum-members: "" + # consider enums only in package scopes, not in inner scopes + package-scope-only: false + + exhaustivestruct: + # Struct Patterns is list of expressions to match struct packages and names + # The struct packages have the form example.com/package.ExampleStruct + # The matching patterns can use matching syntax from https://pkg.go.dev/path#Match + # If this list is empty, all structs are tested. + struct-patterns: + - '*.Test' + - 'example.com/package.ExampleStruct' + - '*.Test2' + - '*.Embedded' + - '*.External' + + forbidigo: + # Forbid the following identifiers (identifiers are written using regexp): + forbid: + - ^print.*$ + - 'fmt\.Print.*' + - fmt.Println.* # too much log noise + - ginkgo\\.F.* # these are used just for local development + # Exclude godoc examples from forbidigo checks. Default is true. + exclude_godoc_examples: false + + funlen: + lines: 150 + statements: 50 + + gci: + # put imports beginning with prefix after 3rd-party packages; + # only support one prefix + # if not set, use goimports.local-prefixes + local-prefixes: github.com/gogf/gf + + gocognit: + # minimal code complexity to report, 30 by default (but we recommend 10-20) + min-complexity: 50 + + goconst: + # minimal length of string constant, 3 by default + min-len: 3 + # minimum occurrences of constant string count to trigger issue, 3 by default + min-occurrences: 3 + # ignore test files, false by default + ignore-tests: false + # look for existing constants matching the values, true by default + match-constant: true + # search also for duplicated numbers, false by default + numbers: false + # minimum value, only works with goconst.numbers, 3 by default + min: 3 + # maximum value, only works with goconst.numbers, 3 by default + max: 3 + # ignore when constant is not used as function argument, true by default + ignore-calls: true + + gocritic: + # Which checks should be enabled; can't be combined with 'disabled-checks'; + # See https://go-critic.github.io/overview#checks-overview + # To check which checks are enabled run `GL_DEBUG=gocritic golangci-lint run` + # By default list of stable checks is used. + enabled-checks: + - nestingReduce + - unnamedresult + - ruleguard + - truncateCmp + + # Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty + disabled-checks: + - regexpMust + - ifElseChain + - exitAfterDefer + + # Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks. + # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags". + enabled-tags: + - performance + disabled-tags: + - experimental + + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be find in https://go-critic.github.io/overview. + settings: + captLocal: # must be valid enabled check name + # whether to restrict checker to params only (default true) + paramsOnly: true + elseif: + # whether to skip balanced if-else pairs (default true) + skipBalanced: true + hugeParam: + # size in bytes that makes the warning trigger (default 80) + sizeThreshold: 80 + nestingReduce: + # min number of statements inside a branch to trigger a warning (default 5) + bodyWidth: 5 + rangeExprCopy: + # size in bytes that makes the warning trigger (default 512) + sizeThreshold: 512 + # whether to check test functions (default true) + skipTestFuncs: true + rangeValCopy: + # size in bytes that makes the warning trigger (default 128) + sizeThreshold: 32 + # whether to check test functions (default true) + skipTestFuncs: true + ruleguard: + # Enable debug to identify which 'Where' condition was rejected. + # The value of the parameter is the name of a function in a ruleguard file. + # + # When a rule is evaluated: + # If: + # The Match() clause is accepted; and + # One of the conditions in the Where() clause is rejected, + # Then: + # ruleguard prints the specific Where() condition that was rejected. + # + # The flag is passed to the ruleguard 'debug-group' argument. + debug: 'emptyDecl' + # Deprecated, use 'failOn' param. + # If set to true, identical to failOn='all', otherwise failOn='' + failOnError: false + # Determines the behavior when an error occurs while parsing ruleguard files. + # If flag is not set, log error and skip rule files that contain an error. + # If flag is set, the value must be a comma-separated list of error conditions. + # - 'all': fail on all errors. + # - 'import': ruleguard rule imports a package that cannot be found. + # - 'dsl': gorule file does not comply with the ruleguard DSL. + failOn: dsl + # Comma-separated list of file paths containing ruleguard rules. + # If a path is relative, it is relative to the directory where the golangci-lint command is executed. + # The special '${configDir}' variable is substituted with the absolute directory containing the golangci config file. + # Glob patterns such as 'rules-*.go' may be specified. + rules: '' #${configDir}/ruleguard/rules-*.go,${configDir}/myrule1.go' + #tooManyResultsChecker: + # maximum number of results (default 5) + #maxResults: 10 + truncateCmp: + # whether to skip int/uint/uintptr types (default true) + skipArchDependent: true + underef: + # whether to skip (*x).method() calls where x is a pointer receiver (default true) + skipRecvDeref: true + unnamedResult: + # whether to check exported functions + checkExported: true + + gocyclo: + # minimal code complexity to report, 30 by default (but we recommend 10-20) + min-complexity: 30 + + godot: + # comments to be checked: `declarations`, `toplevel`, or `all` + scope: declarations + # list of regexps for excluding particular comment lines from check + exclude: + # example: exclude comments which contain numbers + # - '[0-9]+' + # check that each sentence starts with a capital letter + capital: false + + godox: + # report any comments starting with keywords, this is useful for TODO or FIXME comments that + # might be left in the code accidentally and should be resolved before merging + keywords: # default keywords are TODO, BUG, and FIXME, these can be overwritten by this setting + #- NOTE + - BUG + - FIXME + - OPTIMIZE # marks code that should be optimized before merging + - HACK # marks hack-arounds that should be removed before merging + + gofmt: + # simplify code: gofmt with `-s` option, true by default + simplify: true + + gofumpt: + # Select the Go version to target. The default is `1.15`. + lang-version: "1.16" + + # Choose whether or not to use the extra rules that are disabled + # by default + extra-rules: false + + goheader: + values: + const: + # define here const type values in format k:v, for example: + # COMPANY: MY COMPANY + regexp: + # define here regexp type values, for example + # AUTHOR: .*@mycompany\.com + template: # |- + # put here copyright header template for source code files, for example: + # Note: {{ YEAR }} is a builtin value that returns the year relative to the current machine time. + # + # {{ AUTHOR }} {{ COMPANY }} {{ YEAR }} + # SPDX-License-Identifier: Apache-2.0 + + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at: + + # http://www.apache.org/licenses/LICENSE-2.0 + + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + template-path: + # also as alternative of directive 'template' you may put the path to file with the template source + + goimports: + # put imports beginning with prefix after 3rd-party packages; + # it's a comma-separated list of prefixes + local-prefixes: github.com/gogf/gf + + golint: + # minimal confidence for issues, default is 0.8 + min-confidence: 0.9 + + gomnd: + settings: + mnd: + # the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description. + checks: argument,case,condition,operation,return,assign + # ignored-numbers: 1000 + # ignored-files: magic_.*.go + # ignored-functions: math.* + + gomoddirectives: + # Allow local `replace` directives. Default is false. + replace-local: false + # List of allowed `replace` directives. Default is empty. + replace-allow-list: + - launchpad.net/gocheck + - github.com/coreos/etcd + - google.golang.org/grpc + - gitlab.jntmedia.cn/lanren/core + # Allow to not explain why the version has been retracted in the `retract` directives. Default is false. + retract-allow-no-explanation: false + # Forbid the use of the `exclude` directives. Default is false. + exclude-forbidden: false + + gomodguard: + allowed: + modules: # List of allowed modules + # - gopkg.in/yaml.v2 + - gorm.io/gorm + - gorm.io/driver/mysql + - k8s.io/klog + domains: # List of allowed module domains + # - golang.org + - google.golang.org + - gopkg.in + - golang.org + - github.com + - go.uber.org + blocked: + modules: # List of blocked modules + # - github.com/uudashr/go-module: # Blocked module + # recommendations: # Recommended modules that should be used instead (Optional) + # - golang.org/x/mod + # reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional) + versions: # List of blocked module version constraints + # - github.com/mitchellh/go-homedir: # Blocked module with version constraint + # version: "< 1.1.0" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons + # reason: "testing if blocked version constraint works." # Reason why the version constraint exists. (Optional) + local_replace_directives: false # Set to true to raise lint issues for packages that are loaded from a local path via replace directive + + gosec: + # To select a subset of rules to run. + # Available rules: https://github.com/securego/gosec#available-rules + includes: + - G401 + - G306 + - G101 + # To specify a set of rules to explicitly exclude. + # Available rules: https://github.com/securego/gosec#available-rules + excludes: + - G204 + # Exclude generated files + exclude-generated: true + # Filter out the issues with a lower severity than the given value. Valid options are: low, medium, high. + severity: "low" + # Filter out the issues with a lower confidence than the given value. Valid options are: low, medium, high. + confidence: "low" + # To specify the configuration of rules. + # The configuration of rules is not fully documented by gosec: + # https://github.com/securego/gosec#configuration + # https://github.com/securego/gosec/blob/569328eade2ccbad4ce2d0f21ee158ab5356a5cf/rules/rulelist.go#L60-L102 + config: + G306: "0600" + G101: + pattern: "(?i)example" + ignore_entropy: false + entropy_threshold: "80.0" + per_char_threshold: "3.0" + truncate: "32" + + gosimple: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + # https://staticcheck.io/docs/options#checks + checks: [ "all" ] + + govet: + # report about shadowed variables + check-shadowing: true + + # settings per analyzer + settings: + printf: # analyzer name, run `go tool vet help` to see all analyzers + funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + + # enable or disable analyzers by name + # run `go tool vet help` to see all analyzers + enable: + - atomicalign + enable-all: false + disable: + - shadow + disable-all: false + + depguard: + list-type: blacklist + include-go-root: false + packages: + - github.com/sirupsen/logrus + packages-with-error-message: + # specify an error message to output when a blacklisted package is used + - github.com/sirupsen/logrus: "logging is allowed only by logutils.Log" + + ifshort: + # Maximum length of variable declaration measured in number of lines, after which linter won't suggest using short syntax. + # Has higher priority than max-decl-chars. + max-decl-lines: 1 + # Maximum length of variable declaration measured in number of characters, after which linter won't suggest using short syntax. + max-decl-chars: 30 + + importas: + # if set to `true`, force to use alias. + no-unaliased: true + # List of aliases + alias: + # using `servingv1` alias for `knative.dev/serving/pkg/apis/serving/v1` package + - pkg: knative.dev/serving/pkg/apis/serving/v1 + alias: servingv1 + # using `autoscalingv1alpha1` alias for `knative.dev/serving/pkg/apis/autoscaling/v1alpha1` package + - pkg: knative.dev/serving/pkg/apis/autoscaling/v1alpha1 + alias: autoscalingv1alpha1 + # You can specify the package path by regular expression, + # and alias by regular expression expansion syntax like below. + # see https://github.com/julz/importas#use-regular-expression for details + - pkg: knative.dev/serving/pkg/apis/(\w+)/(v[\w\d]+) + alias: $1$2 + + ireturn: + # ireturn allows using `allow` and `reject` settings at the same time. + # Both settings are lists of the keywords and regular expressions matched to interface or package names. + # keywords: + # - `empty` for `interface{}` + # - `error` for errors + # - `stdlib` for standard library + # - `anon` for anonymous interfaces + + # By default, it allows using errors, empty interfaces, anonymous interfaces, + # and interfaces provided by the standard library. + allow: + - anon + - error + - empty + - stdlib + # You can specify idiomatic endings for interface + - (or|er)$ + + # Reject patterns +# reject: +# - github.com\/user\/package\/v4\.Type + + lll: + # max line length, lines longer will be reported. Default is 120. + # '\t' is counted as 1 character by default, and can be changed with the tab-width option + line-length: 240 + # tab width in spaces. Default to 1. + tab-width: 4 + + makezero: + # Allow only slices initialized with a length of zero. Default is false. + always: false + + maligned: + # print struct with more effective memory layout or not, false by default + suggest-new: true + + misspell: + # Correct spellings using locale preferences for US or UK. + # Default is to use a neutral variety of English. + # Setting locale to US will correct the British spelling of 'colour' to 'color'. + locale: US + ignore-words: + - someword + + nakedret: + # make an issue if func has more lines of code than this setting and it has naked returns; default is 30 + max-func-lines: 30 + + nestif: + # minimal complexity of if statements to report, 5 by default + min-complexity: 4 + + nilnil: + # By default, nilnil checks all returned types below. + checked-types: + - ptr + - func + - iface + - map + - chan + + nlreturn: + # size of the block (including return statement that is still "OK") + # so no return split required. + block-size: 1 + + nolintlint: + # Disable to ensure that all nolint directives actually have an effect. Default is true. + allow-unused: true + # Disable to ensure that nolint directives don't have a leading space. Default is true. + allow-leading-space: true + # Exclude following linters from requiring an explanation. Default is []. + allow-no-explanation: [ ] + # Enable to require an explanation of nonzero length after each nolint directive. Default is false. + require-explanation: false + # Enable to require nolint directives to mention the specific linter being suppressed. Default is false. + require-specific: true + + prealloc: + # XXX: we don't recommend using this linter before doing performance profiling. + # For most programs usage of prealloc will be a premature optimization. + + # Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. + # True by default. + simple: true + range-loops: true # Report preallocation suggestions on range loops, true by default + for-loops: false # Report preallocation suggestions on for loops, false by default + + promlinter: + # Promlinter cannot infer all metrics name in static analysis. + # Enable strict mode will also include the errors caused by failing to parse the args. + strict: false + # Please refer to https://github.com/yeya24/promlinter#usage for detailed usage. + disabled-linters: + # - "Help" + # - "MetricUnits" + # - "Counter" + # - "HistogramSummaryReserved" + # - "MetricTypeInName" + # - "ReservedChars" + # - "CamelCase" + # - "lintUnitAbbreviations" + + predeclared: + # comma-separated list of predeclared identifiers to not report on + ignore: "" + # include method names and field names (i.e., qualified names) in checks + q: false + + rowserrcheck: + packages: + - github.com/jmoiron/sqlx + + revive: + # see https://github.com/mgechev/revive#available-rules for details. + ignore-generated-header: true + severity: warning + rules: + - name: indent-error-flow + severity: warning + - name: add-constant + severity: warning + arguments: + - maxLitCount: "3" + allowStrs: '""' + allowInts: "0,1,2" + allowFloats: "0.0,0.,1.0,1.,2.0,2." + + staticcheck: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + # https://staticcheck.io/docs/options#checks + checks: [ "all" ] + + stylecheck: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + # https://staticcheck.io/docs/options#checks + checks: [ "all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022" ] + # https://staticcheck.io/docs/options#dot_import_whitelist + dot-import-whitelist: + - fmt + # https://staticcheck.io/docs/options#initialisms + initialisms: [ "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS" ] + # https://staticcheck.io/docs/options#http_status_code_whitelist + http-status-code-whitelist: [ "200", "400", "404", "500" ] + + tagliatelle: + # check the struck tag name case + case: + # use the struct field name to check the name of the struct tag + use-field-name: true + rules: + # any struct tag type can be used. + # support string case: `camel`, `pascal`, `kebab`, `snake`, `goCamel`, `goPascal`, `goKebab`, `goSnake`, `upper`, `lower` + json: camel + yaml: camel + xml: camel + bson: camel + avro: snake + mapstructure: kebab + + testpackage: + # regexp pattern to skip files + skip-regexp: (export|internal)_test\.go + + thelper: + # The following configurations enable all checks. It can be omitted because all checks are enabled by default. + # You can enable only required checks deleting unnecessary checks. + test: + first: true + name: true + begin: true + benchmark: + first: true + name: true + begin: true + tb: + first: true + name: true + begin: true + + tenv: + # The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures. + # By default, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked. + all: false + + unparam: + # Inspect exported functions, default is false. Set to true if no external program/library imports your code. + # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: + # if it's called for subdir of a project it can't find external interfaces. All text editor integrations + # with golangci-lint call it on a directory with the changed file. + check-exported: false + + unused: + # Select the Go version to target. The default is '1.13'. + go: "1.16" + + varnamelen: + # The longest distance, in source lines, that is being considered a "small scope." (defaults to 5) + # Variables used in at most this many lines will be ignored. + max-distance: 5 + # The minimum length of a variable's name that is considered "long." (defaults to 3) + # Variable names that are at least this long will be ignored. + min-name-length: 3 + # Check method receiver names. (defaults to false) + check-receiver: false + # Check named return values. (defaults to false) + check-return: false + # Ignore "ok" variables that hold the bool return value of a type assertion. (defaults to false) + ignore-type-assert-ok: false + # Ignore "ok" variables that hold the bool return value of a map index. (defaults to false) + ignore-map-index-ok: false + # Ignore "ok" variables that hold the bool return value of a channel receive. (defaults to false) + ignore-chan-recv-ok: false + # Optional list of variable names that should be ignored completely. (defaults to empty list) + ignore-names: + - err + # Optional list of variable declarations that should be ignored completely. (defaults to empty list) + # Entries must be in the form of " " or " *". + ignore-decls: + - c echo.Context + - t testing.T + - f *foo.Bar + - e error + - i int + + whitespace: + multi-if: false # Enforces newlines (or comments) after every multi-line if statement + multi-func: false # Enforces newlines (or comments) after every multi-line function signature + + wrapcheck: + # An array of strings that specify substrings of signatures to ignore. + # If this set, it will override the default set of ignored signatures. + # See https://github.com/tomarrell/wrapcheck#configuration for more information. + ignoreSigs: + - .Errorf( + - errors.New( + - errors.Unwrap( + - .Wrap( + - .Wrapf( + - .WithMessage( + - .WithMessagef( + - .WithStack( + ignorePackageGlobs: + - encoding/* + - github.com/pkg/* + + wsl: + # See https://github.com/bombsimon/wsl/blob/master/doc/configuration.md for + # documentation of available settings. These are the defaults for + # `golangci-lint`. + allow-assign-and-anything: false + allow-assign-and-call: true + allow-cuddle-declarations: false + allow-multiline-assign: true + allow-separated-leading-comment: false + allow-trailing-comment: false + force-case-trailing-whitespace: 0 + force-err-cuddling: false + force-short-decl-cuddling: false + strict-append: true + + # The custom section can be used to define linter plugins to be loaded at runtime. + # See README doc for more info. + # custom: + # Each custom linter should have a unique name. + # example: + # The path to the plugin *.so. Can be absolute or local. Required for each custom linter + # path: /path/to/example.so + # The description of the linter. Optional, just for documentation purposes. + # description: This is an example usage of a plugin linter. + # Intended to point to the repo location of the linter. Optional, just for documentation purposes. + # original-url: github.com/golangci/example-linter + +linters: + #disable-all: true + #enable: + # - megacheck + # - govet + enable-all: true + disable: + - maligned + - prealloc + #- tagliatelle + #- wrapcheck + #- forcetypeassert + - goerr113 + - gomnd + - wsl + - testpackage + - gochecknoglobals + - interfacer + - maligned + - scopelint + - gocritic + - typecheck +# presets: +# - bugs +# - unused + fast: false + + +issues: + # List of regexps of issue texts to exclude, empty list by default. + # But independently from this option we use default exclude patterns, + # it can be disabled by `exclude-use-default: false`. To list all + # excluded by default patterns execute `golangci-lint run --help` + exclude: + - abcdef + - tools/.* + - test/.* + - third_party/.* + + # Excluding configuration per-path, per-linter, per-text and per-source + exclude-rules: + # Exclude some linters from running on tests files. + - linters: + - revive + path: (log/.*)\.go + - linters: + - wrapcheck + path: (cmd/.*|pkg/.*)\.go + - linters: + - typecheck + path: (pkg/storage/.*)\.go + + - path: (cmd/.*|test/.*|tools/.*)\.go + linters: + - forbidigo + - path: (cmd/[a-z]*/.*|store/.*)\.go + linters: + - dupl + - linters: + - gocritic + text: (hugeParam:|rangeValCopy:) + + - path: (cmd/[a-z]*/.*)\.go + linters: + - lll + + - path: (validator/.*|code/.*|validator/.*) + linters: + - gochecknoinits + - path: (pkg/app/.*)\.go + linters: + - gocyclo + - errcheck + - dupl + - gosec + + # Exclude known linters from partially hard-vendored code, + # which is impossible to exclude via "nolint" comments. + - path: internal/hmac/ + text: "weak cryptographic primitive" + linters: + - gosec + + # Exclude some staticcheck messages + - linters: + - staticcheck + text: "SA9003:" + + # Exclude lll issues for long lines with go:generate + - linters: + - lll + source: "^//go:generate " + + # Independently from option `exclude` we use default exclude patterns, + # it can be disabled by this option. To list all + # excluded by default patterns execute `golangci-lint run --help`. + # Default value for this option is true. + exclude-use-default: false + + # The default value is false. If set to true exclude and exclude-rules + # regular expressions become case sensitive. + exclude-case-sensitive: false + + # The list of ids of default excludes to include or disable. By default it's empty. + include: + - EXC0002 # disable excluding of issues about comments from golint + + # Maximum issues count per one linter. Set to 0 to disable. Default is 50. + max-issues-per-linter: 0 + + # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. + max-same-issues: 0 + + # Show only new issues: if there are unstaged changes or untracked files, + # only those changes are analyzed, else only changes in HEAD~ are analyzed. + # It's a super-useful option for integration of golangci-lint into existing + # large codebase. It's not practical to fix all existing issues at the moment + # of integration: much better don't allow issues in new code. + # Default is false. + new: false + + # Show only new issues created after git revision `REV` + new-from-rev: REV + + # Show only new issues created in git patch with set file path. + # new-from-patch: path/to/patch/file + + # Fix found issues (if it's supported by the linter) + fix: true + +severity: + # Default value is empty string. + # Set the default severity for issues. If severity rules are defined and the issues + # do not match or no severity is provided to the rule this will be the default + # severity applied. Severities should match the supported severity names of the + # selected out format. + # - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity + # - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#severity + # - GitHub: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message + default-severity: error + + # The default value is false. + # If set to true severity-rules regular expressions become case sensitive. + case-sensitive: false + + # Default value is empty list. + # When a list of severity rules are provided, severity information will be added to lint + # issues. Severity rules have the same filtering capability as exclude rules except you + # are allowed to specify one matcher per severity rule. + # Only affects out formats that support setting severity information. + rules: + - linters: + - dupl + severity: info diff --git a/database/gdb/gdb.go b/database/gdb/gdb.go index c67129f8a..be855644b 100644 --- a/database/gdb/gdb.go +++ b/database/gdb/gdb.go @@ -301,7 +301,7 @@ var ( // in the field name as it conflicts with "db.table.field" pattern in SOME situations. regularFieldNameWithoutDotRegPattern = `^[\w\-]+$` - // tableFieldsMap caches the table information retrived from database. + // tableFieldsMap caches the table information retrieved from database. tableFieldsMap = gmap.New(true) // allDryRun sets dry-run feature for all database connections. @@ -429,7 +429,7 @@ func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) { // Calculation algorithm brief: // 1. If we have 2 nodes, and their weights are both 1, then the weight range is [0, 199]; // 2. Node1 weight range is [0, 99], and node2 weight range is [100, 199], ratio is 1:1; -// 3. If the random number is 99, it then chooses and returns node1; +// 3. If the random number is 99, it then chooses and returns node1;. func getConfigNodeByWeight(cg ConfigGroup) *ConfigNode { if len(cg) < 2 { return &cg[0] diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index 09c84ef75..c4c495f00 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -393,7 +393,7 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, onDuplicateStr string // onDuplicateStr is used in "ON DUPLICATE KEY UPDATE" statement. ) // Handle the field names and placeholders. - for k, _ := range list[0] { + for k := range list[0] { keys = append(keys, k) } // Prepare the batch result pointer. @@ -448,9 +448,7 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, } func (c *Core) formatOnDuplicate(columns []string, option DoInsertOption) string { - var ( - onDuplicateStr string - ) + var onDuplicateStr string if option.OnDuplicateStr != "" { onDuplicateStr = option.OnDuplicateStr } else if len(option.OnDuplicateMap) > 0 { @@ -505,7 +503,7 @@ func (c *Core) formatOnDuplicate(columns []string, option DoInsertOption) string // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (c *Core) Update(ctx context.Context, table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) { return c.Model(table).Ctx(ctx).Data(data).Where(condition, args...).Update() } @@ -596,7 +594,7 @@ func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data inter // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (c *Core) Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (result sql.Result, err error) { return c.Model(table).Ctx(ctx).Where(condition, args...).Delete() } diff --git a/database/gdb/gdb_core_structure.go b/database/gdb/gdb_core_structure.go index 5cee01ce0..ebed7daa8 100644 --- a/database/gdb/gdb_core_structure.go +++ b/database/gdb/gdb_core_structure.go @@ -149,7 +149,7 @@ func (c *Core) convertFieldValueToLocalValue(fieldValue interface{}, fieldType s func (c *Core) mappingAndFilterData(schema, table string, data map[string]interface{}, filter bool) (map[string]interface{}, error) { if fieldsMap, err := c.db.TableFields(c.GetCtx(), c.guessPrimaryTableName(table), schema); err == nil { fieldsKeyMap := make(map[string]interface{}, len(fieldsMap)) - for k, _ := range fieldsMap { + for k := range fieldsMap { fieldsKeyMap[k] = nil } // Automatic data key to table field name mapping. @@ -166,7 +166,7 @@ func (c *Core) mappingAndFilterData(schema, table string, data map[string]interf // Data filtering. // It deletes all key-value pairs that has incorrect field name. if filter { - for dataKey, _ := range data { + for dataKey := range data { if _, ok := fieldsMap[dataKey]; !ok { delete(data, dataKey) } diff --git a/database/gdb/gdb_core_tracing.go b/database/gdb/gdb_core_tracing.go index 004c37b5d..74f818161 100644 --- a/database/gdb/gdb_core_tracing.go +++ b/database/gdb/gdb_core_tracing.go @@ -11,12 +11,13 @@ import ( "context" "fmt" - "github.com/gogf/gf/v2" - "github.com/gogf/gf/v2/net/gtrace" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2" + "github.com/gogf/gf/v2/net/gtrace" ) const ( diff --git a/database/gdb/gdb_core_transaction.go b/database/gdb/gdb_core_transaction.go index 3f3d3199c..755803585 100644 --- a/database/gdb/gdb_core_transaction.go +++ b/database/gdb/gdb_core_transaction.go @@ -38,9 +38,7 @@ const ( transactionIdForLoggerCtx = "TransactionId" ) -var ( - transactionIdGenerator = gtype.NewUint64() -) +var transactionIdGenerator = gtype.NewUint64() // Begin starts and returns the transaction object. // You should call Commit or Rollback functions of the transaction object @@ -99,9 +97,7 @@ func (c *Core) doBeginCtx(ctx context.Context) (*TX, error) { // Note that, you should not Commit or Rollback the transaction in function `f` // as it is automatically handled by this function. func (c *Core) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error) { - var ( - tx *TX - ) + var tx *TX if ctx == nil { ctx = c.GetCtx() } @@ -537,7 +533,7 @@ func (tx *TX) Save(table string, data interface{}, batch ...int) (sql.Result, er // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (tx *TX) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) { return tx.Model(table).Ctx(tx.ctx).Data(data).Where(condition, args...).Update() } @@ -552,7 +548,7 @@ func (tx *TX) Update(table string, data interface{}, condition interface{}, args // "money>? AND name like ?", 99999, "vip_%" // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 -// User{ Id : 1, UserName : "john"} +// User{ Id : 1, UserName : "john"}. func (tx *TX) Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error) { return tx.Model(table).Ctx(tx.ctx).Where(condition, args...).Delete() } diff --git a/database/gdb/gdb_core_underlying.go b/database/gdb/gdb_core_underlying.go index a6edac505..15035b4cc 100644 --- a/database/gdb/gdb_core_underlying.go +++ b/database/gdb/gdb_core_underlying.go @@ -128,9 +128,7 @@ func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...interf result = new(SqlResult) } mTime2 := gtime.TimestampMilli() - var ( - rowsAffected int64 - ) + var rowsAffected int64 if err == nil { rowsAffected, err = result.RowsAffected() } diff --git a/database/gdb/gdb_driver_mysql.go b/database/gdb/gdb_driver_mysql.go index 4d3d8cf35..b93c6c2f0 100644 --- a/database/gdb/gdb_driver_mysql.go +++ b/database/gdb/gdb_driver_mysql.go @@ -13,6 +13,7 @@ import ( "net/url" _ "github.com/go-sql-driver/mysql" + "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/intlog" diff --git a/database/gdb/gdb_driver_oracle.go b/database/gdb/gdb_driver_oracle.go index 44f8225b6..aced866f1 100644 --- a/database/gdb/gdb_driver_oracle.go +++ b/database/gdb/gdb_driver_oracle.go @@ -267,7 +267,7 @@ func (d *DriverOracle) DoInsert(ctx context.Context, link Link, table string, li listLength = len(list) valueHolder = make([]string, 0) ) - for k, _ := range list[0] { + for k := range list[0] { keys = append(keys, k) valueHolder = append(valueHolder, "?") } diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index d70ac3379..50edd7e36 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -282,7 +282,7 @@ func doQuoteWord(s, charLeft, charRight string) string { // "user u, user_detail ut" => "`user` u,`user_detail` ut" // "user.user u, user.user_detail ut" => "`user`.`user` u,`user`.`user_detail` ut" // "u.id, u.name, u.age" => "`u`.`id`,`u`.`name`,`u`.`age`" -// "u.id asc" => "`u`.`id` asc" +// "u.id asc" => "`u`.`id` asc". func doQuoteString(s, charLeft, charRight string) string { array1 := gstr.SplitAndTrim(s, ",") for k1, v1 := range array1 { @@ -484,9 +484,9 @@ func formatWhere(db DB, in formatWhereInput) (newWhere string, newArgs []interfa default: // Usually a string. - var ( - whereStr = gconv.String(in.Where) - ) + + whereStr := gconv.String(in.Where) + // Is `whereStr` a field name which composed as a key-value condition? // Eg: // Where("id", 1) @@ -514,18 +514,16 @@ func formatWhere(db DB, in formatWhereInput) (newWhere string, newArgs []interfa // Regular string and parameter place holder handling. // Eg: // Where("id in(?) and name=?", g.Slice{1,2,3}, "john") - var ( - i = 0 - ) + + i := 0 + for { if i >= len(in.Args) { break } // Sub query, which is always used along with a string condition. if model, ok := in.Args[i].(*Model); ok { - var ( - index = -1 - ) + index := -1 whereStr, _ = gregex.ReplaceStringFunc(`(\?)`, whereStr, func(s string) string { index++ if i+len(newArgs) == index { @@ -836,9 +834,7 @@ func FormatSqlWithArgs(sql string, args []interface{}) string { if v, ok := args[index].(Raw); ok { return gconv.String(v) } - var ( - reflectInfo = utils.OriginValueAndKind(args[index]) - ) + reflectInfo := utils.OriginValueAndKind(args[index]) if reflectInfo.OriginKind == reflect.Ptr && (reflectInfo.OriginValue.IsNil() || !reflectInfo.OriginValue.IsValid()) { return "null" diff --git a/database/gdb/gdb_model_cache.go b/database/gdb/gdb_model_cache.go index d18db684f..5704cd6ea 100644 --- a/database/gdb/gdb_model_cache.go +++ b/database/gdb/gdb_model_cache.go @@ -46,7 +46,7 @@ func (m *Model) Cache(option CacheOption) *Model { // cache feature is enabled. func (m *Model) checkAndRemoveCache() { if m.cacheEnabled && m.cacheOption.Duration < 0 && len(m.cacheOption.Name) > 0 { - var ctx = m.GetCtx() + ctx := m.GetCtx() _, err := m.db.GetCache().Remove(ctx, m.cacheOption.Name) if err != nil { intlog.Error(ctx, err) diff --git a/database/gdb/gdb_model_condition.go b/database/gdb/gdb_model_condition.go index 3aeb96d94..724a412f7 100644 --- a/database/gdb/gdb_model_condition.go +++ b/database/gdb/gdb_model_condition.go @@ -23,7 +23,7 @@ import ( // Where("uid", 1).Where("name", "john") // Where("status IN (?)", g.Slice{1,2,3}) // Where("age IN(?,?)", 18, 50) -// Where(User{ Id : 1, UserName : "john"}) +// Where(User{ Id : 1, UserName : "john"}). func (m *Model) Where(where interface{}, args ...interface{}) *Model { model := m.getModel() if model.whereHolder == nil { @@ -315,9 +315,7 @@ func (m *Model) Page(page, limit int) *Model { // // The parameter `limit1` specifies whether limits querying only one record if m.limit is not set. func (m *Model) formatCondition(limit1 bool, isCountStatement bool) (conditionWhere string, conditionExtra string, conditionArgs []interface{}) { - var ( - autoPrefix = "" - ) + autoPrefix := "" if gstr.Contains(m.tables, " JOIN ") { autoPrefix = m.db.GetCore().QuoteWord(m.tablesInit) } diff --git a/database/gdb/gdb_model_fields.go b/database/gdb/gdb_model_fields.go index 49dbe1e24..ff03f8b3e 100644 --- a/database/gdb/gdb_model_fields.go +++ b/database/gdb/gdb_model_fields.go @@ -21,7 +21,7 @@ import ( // Fields("id", "name", "age") // Fields([]string{"id", "name", "age"}) // Fields(map[string]interface{}{"id":1, "name":"john", "age":18}) -// Fields(User{ Id: 1, Name: "john", Age: 18}) +// Fields(User{ Id: 1, Name: "john", Age: 18}). func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model { length := len(fieldNamesOrMapStruct) if length == 0 { diff --git a/database/gdb/gdb_model_insert.go b/database/gdb/gdb_model_insert.go index 35e58e9d6..6ec74ba70 100644 --- a/database/gdb/gdb_model_insert.go +++ b/database/gdb/gdb_model_insert.go @@ -36,7 +36,7 @@ func (m *Model) Batch(batch int) *Model { // Data("uid", 10000) // Data("uid=? AND name=?", 10000, "john") // Data(g.Map{"uid": 10000, "name":"john"}) -// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}) +// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}). func (m *Model) Data(data ...interface{}) *Model { model := m.getModel() if len(data) > 1 { @@ -69,9 +69,7 @@ func (m *Model) Data(data ...interface{}) *Model { model.data = gutil.MapCopy(value) default: - var ( - reflectInfo = utils.OriginValueAndKind(value) - ) + reflectInfo := utils.OriginValueAndKind(value) switch reflectInfo.OriginKind { case reflect.Slice, reflect.Array: if reflectInfo.OriginValue.Len() > 0 { @@ -131,7 +129,7 @@ func (m *Model) Data(data ...interface{}) *Model { // }) // OnDuplicate(g.Map{ // "nickname": "passport", -// }) +// }). func (m *Model) OnDuplicate(onDuplicate ...interface{}) *Model { model := m.getModel() if len(onDuplicate) > 1 { @@ -151,7 +149,7 @@ func (m *Model) OnDuplicate(onDuplicate ...interface{}) *Model { // OnDuplicateEx(g.Map{ // "passport": "", // "password": "", -// }) +// }). func (m *Model) OnDuplicateEx(onDuplicateEx ...interface{}) *Model { model := m.getModel() if len(onDuplicateEx) > 1 { @@ -256,9 +254,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err list = List{ConvertDataForTableRecord(value)} default: - var ( - reflectInfo = utils.OriginValueAndKind(newData) - ) + reflectInfo := utils.OriginValueAndKind(newData) switch reflectInfo.OriginKind { // If it's slice type, it then converts it to List type. case reflect.Slice, reflect.Array: @@ -272,9 +268,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err case reflect.Struct: if v, ok := value.(iInterfaces); ok { - var ( - array = v.Interfaces() - ) + array := v.Interfaces() list = make(List, len(array)) for i := 0; i < len(array); i++ { list[i] = ConvertDataForTableRecord(array[i]) @@ -310,7 +304,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err } // Format DoInsertOption, especially for "ON DUPLICATE KEY UPDATE" statement. columnNames := make([]string, 0, len(list[0])) - for k, _ := range list[0] { + for k := range list[0] { columnNames = append(columnNames, k) } doInsertOption, err := m.formatDoInsertOption(insertOption, columnNames) @@ -331,18 +325,14 @@ func (m *Model) formatDoInsertOption(insertOption int, columnNames []string) (op if err != nil { return option, err } - var ( - onDuplicateExKeySet = gset.NewStrSetFrom(onDuplicateExKeys) - ) + onDuplicateExKeySet := gset.NewStrSetFrom(onDuplicateExKeys) if m.onDuplicate != nil { switch m.onDuplicate.(type) { case Raw, *Raw: option.OnDuplicateStr = gconv.String(m.onDuplicate) default: - var ( - reflectInfo = utils.OriginValueAndKind(m.onDuplicate) - ) + reflectInfo := utils.OriginValueAndKind(m.onDuplicate) switch reflectInfo.OriginKind { case reflect.String: option.OnDuplicateMap = make(map[string]interface{}) @@ -397,9 +387,7 @@ func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, er return nil, nil } - var ( - reflectInfo = utils.OriginValueAndKind(onDuplicateEx) - ) + reflectInfo := utils.OriginValueAndKind(onDuplicateEx) switch reflectInfo.OriginKind { case reflect.String: return gstr.SplitAndTrim(reflectInfo.OriginValue.String(), ","), nil diff --git a/database/gdb/gdb_model_join.go b/database/gdb/gdb_model_join.go index 2b3410e78..237397b5f 100644 --- a/database/gdb/gdb_model_join.go +++ b/database/gdb/gdb_model_join.go @@ -30,7 +30,7 @@ func isSubQuery(s string) bool { // Eg: // Model("user").LeftJoin("user_detail", "user_detail.uid=user.uid") // Model("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid") -// Model("user", "u").LeftJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid") +// Model("user", "u").LeftJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid"). func (m *Model) LeftJoin(table ...string) *Model { return m.doJoin("LEFT", table...) } @@ -42,7 +42,7 @@ func (m *Model) LeftJoin(table ...string) *Model { // Eg: // Model("user").RightJoin("user_detail", "user_detail.uid=user.uid") // Model("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid") -// Model("user", "u").RightJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid") +// Model("user", "u").RightJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid"). func (m *Model) RightJoin(table ...string) *Model { return m.doJoin("RIGHT", table...) } @@ -54,7 +54,7 @@ func (m *Model) RightJoin(table ...string) *Model { // Eg: // Model("user").InnerJoin("user_detail", "user_detail.uid=user.uid") // Model("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid") -// Model("user", "u").InnerJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid") +// Model("user", "u").InnerJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid"). func (m *Model) InnerJoin(table ...string) *Model { return m.doJoin("INNER", table...) } @@ -63,7 +63,7 @@ func (m *Model) InnerJoin(table ...string) *Model { // // Eg: // Model("order").LeftJoinOnField("user", "user_id") -// Model("order").LeftJoinOnField("product", "product_id") +// Model("order").LeftJoinOnField("product", "product_id"). func (m *Model) LeftJoinOnField(table, field string) *Model { return m.doJoin("LEFT", table, fmt.Sprintf( `%s.%s=%s.%s`, @@ -78,7 +78,7 @@ func (m *Model) LeftJoinOnField(table, field string) *Model { // // Eg: // Model("order").InnerJoinOnField("user", "user_id") -// Model("order").InnerJoinOnField("product", "product_id") +// Model("order").InnerJoinOnField("product", "product_id"). func (m *Model) RightJoinOnField(table, field string) *Model { return m.doJoin("RIGHT", table, fmt.Sprintf( `%s.%s=%s.%s`, @@ -93,7 +93,7 @@ func (m *Model) RightJoinOnField(table, field string) *Model { // // Eg: // Model("order").InnerJoinOnField("user", "user_id") -// Model("order").InnerJoinOnField("product", "product_id") +// Model("order").InnerJoinOnField("product", "product_id"). func (m *Model) InnerJoinOnField(table, field string) *Model { return m.doJoin("INNER", table, fmt.Sprintf( `%s.%s=%s.%s`, diff --git a/database/gdb/gdb_model_option.go b/database/gdb/gdb_model_option.go index e3947c627..f7520b3e9 100644 --- a/database/gdb/gdb_model_option.go +++ b/database/gdb/gdb_model_option.go @@ -32,7 +32,7 @@ func (m *Model) OmitEmpty() *Model { // Where("id", []int{}).All() -> SELECT xxx FROM xxx WHERE 0=1 // Where("name", "").All() -> SELECT xxx FROM xxx WHERE `name`='' // OmitEmpty().Where("id", []int{}).All() -> SELECT xxx FROM xxx -// OmitEmpty().("name", "").All() -> SELECT xxx FROM xxx +// OmitEmpty().("name", "").All() -> SELECT xxx FROM xxx. func (m *Model) OmitEmptyWhere() *Model { model := m.getModel() model.option = model.option | optionOmitEmptyWhere diff --git a/database/gdb/gdb_model_order_group.go b/database/gdb/gdb_model_order_group.go index e212bc070..bf8fbbc01 100644 --- a/database/gdb/gdb_model_order_group.go +++ b/database/gdb/gdb_model_order_group.go @@ -13,7 +13,7 @@ import "strings" // Eg: // Order("id desc") // Order("id", "desc") -// Order("id desc,name asc") +// Order("id desc,name asc"). func (m *Model) Order(orderBy ...string) *Model { if len(orderBy) == 0 { return m diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index b342852a0..dd1061b28 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -206,7 +206,7 @@ func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error) { // err := db.Model("user").Where("id", 1).Scan(user) // // user := (*User)(nil) -// err := db.Model("user").Where("id", 1).Scan(&user) +// err := db.Model("user").Where("id", 1).Scan(&user). func (m *Model) doStruct(pointer interface{}, where ...interface{}) error { model := m // Auto selecting fields by struct attributes. @@ -242,7 +242,7 @@ func (m *Model) doStruct(pointer interface{}, where ...interface{}) error { // err := db.Model("user").Scan(&users) // // users := ([]*User)(nil) -// err := db.Model("user").Scan(&users) +// err := db.Model("user").Scan(&users). func (m *Model) doStructs(pointer interface{}, where ...interface{}) error { model := m // Auto selecting fields by struct attributes. @@ -291,11 +291,9 @@ func (m *Model) doStructs(pointer interface{}, where ...interface{}) error { // err := db.Model("user").Scan(&users) // // users := ([]*User)(nil) -// err := db.Model("user").Scan(&users) +// err := db.Model("user").Scan(&users). func (m *Model) Scan(pointer interface{}, where ...interface{}) error { - var ( - reflectInfo = utils.OriginTypeAndKind(pointer) - ) + reflectInfo := utils.OriginTypeAndKind(pointer) if reflectInfo.InputKind != reflect.Ptr { return gerror.NewCode( gcode.CodeInvalidParameter, diff --git a/database/gdb/gdb_model_time.go b/database/gdb/gdb_model_time.go index f54445737..e1120fe42 100644 --- a/database/gdb/gdb_model_time.go +++ b/database/gdb/gdb_model_time.go @@ -113,7 +113,7 @@ func (m *Model) getSoftFieldName(table string, keys []string) (field string) { // "user u, user_detail ud" // "user u LEFT JOIN user_detail ud ON(ud.uid=u.uid)" // "user LEFT JOIN user_detail ON(user_detail.uid=user.uid)" -// "user u LEFT JOIN user_detail ud ON(ud.uid=u.uid) LEFT JOIN user_stats us ON(us.uid=u.uid)" +// "user u LEFT JOIN user_detail ud ON(ud.uid=u.uid) LEFT JOIN user_stats us ON(us.uid=u.uid)". func (m *Model) getConditionForSoftDeleting() string { if m.unscoped { return "" diff --git a/database/gdb/gdb_model_update.go b/database/gdb/gdb_model_update.go index 86d4a5a07..da04b436b 100644 --- a/database/gdb/gdb_model_update.go +++ b/database/gdb/gdb_model_update.go @@ -49,9 +49,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro ) // Automatically update the record updating time. if !m.unscoped && fieldNameUpdate != "" { - var ( - reflectInfo = utils.OriginTypeAndKind(m.data) - ) + reflectInfo := utils.OriginTypeAndKind(m.data) switch reflectInfo.OriginKind { case reflect.Map, reflect.Struct: dataMap := ConvertDataForTableRecord(m.data) diff --git a/database/gdb/gdb_model_utility.go b/database/gdb/gdb_model_utility.go index d20241d5a..2df3df2c5 100644 --- a/database/gdb/gdb_model_utility.go +++ b/database/gdb/gdb_model_utility.go @@ -46,7 +46,7 @@ func (m *Model) getModel() *Model { // mappingAndFilterToTableFields mappings and changes given field name to really table field name. // Eg: // ID -> id -// NICK_Name -> nickname +// NICK_Name -> nickname. func (m *Model) mappingAndFilterToTableFields(fields []string, filter bool) []string { fieldsMap, err := m.TableFields(m.tablesInit) if err != nil || len(fieldsMap) == 0 { @@ -57,7 +57,7 @@ func (m *Model) mappingAndFilterToTableFields(fields []string, filter bool) []st outputFieldsArray = make([]string, 0, len(inputFieldsArray)) ) fieldsKeyMap := make(map[string]interface{}, len(fieldsMap)) - for k, _ := range fieldsMap { + for k := range fieldsMap { fieldsKeyMap[k] = nil } for _, field := range inputFieldsArray { @@ -87,9 +87,7 @@ func (m *Model) filterDataForInsertOrUpdate(data interface{}) (interface{}, erro var err error switch value := data.(type) { case List: - var ( - omitEmpty bool - ) + var omitEmpty bool if m.option&optionOmitNilDataList > 0 { omitEmpty = true } diff --git a/database/gdb/gdb_model_with.go b/database/gdb/gdb_model_with.go index 0e103077e..8be613401 100644 --- a/database/gdb/gdb_model_with.go +++ b/database/gdb/gdb_model_with.go @@ -229,7 +229,7 @@ func (m *Model) doWithScanStructs(pointer interface{}) error { relatedTargetValue interface{} ) // Find the value slice of related attribute from `pointer`. - for attributeName, _ := range currentStructFieldMap { + for attributeName := range currentStructFieldMap { if utils.EqualFoldWithoutChars(attributeName, relatedTargetName) { relatedTargetValue = ListItemValuesUnique(pointer, attributeName) break diff --git a/database/gdb/gdb_schema.go b/database/gdb/gdb_schema.go index d1c3242d3..4cf7c496c 100644 --- a/database/gdb/gdb_schema.go +++ b/database/gdb/gdb_schema.go @@ -32,7 +32,7 @@ func (tx *TX) Schema(schema string) *Schema { // Model creates and returns a new ORM model. // The parameter `tables` can be more than one table names, like : -// "user", "user u", "user, user_detail", "user u, user_detail ud" +// "user", "user u", "user, user_detail", "user u, user_detail ud". func (s *Schema) Model(table string) *Model { var m *Model if s.tx != nil { diff --git a/database/gdb/gdb_type_result.go b/database/gdb/gdb_type_result.go index 4b6306200..062381a48 100644 --- a/database/gdb/gdb_type_result.go +++ b/database/gdb/gdb_type_result.go @@ -83,7 +83,7 @@ func (r Result) Array(field ...string) []Value { if len(field) > 0 && field[0] != "" { key = field[0] } else { - for k, _ := range r[0] { + for k := range r[0] { key = k break } diff --git a/database/gdb/gdb_type_result_scanlist.go b/database/gdb/gdb_type_result_scanlist.go index 8195137a3..95d0712ca 100644 --- a/database/gdb/gdb_type_result_scanlist.go +++ b/database/gdb/gdb_type_result_scanlist.go @@ -290,12 +290,10 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin if relationFields != "" && !relationBindToFieldNameChecked { relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) if !relationFromAttrField.IsValid() { - var ( - filedMap, _ = structs.FieldMap(structs.FieldMapInput{ - Pointer: relationFromAttrValue, - RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, - }) - ) + filedMap, _ := structs.FieldMap(structs.FieldMapInput{ + Pointer: relationFromAttrValue, + RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, + }) if key, _ := gutil.MapPossibleItemByKey(gconv.Map(filedMap), relationBindToFieldName); key == "" { return gerror.NewCodef( gcode.CodeInvalidParameter, diff --git a/database/gdb/gdb_z_mysql_basic_test.go b/database/gdb/gdb_z_mysql_basic_test.go index 61d116752..29fc7679f 100644 --- a/database/gdb/gdb_z_mysql_basic_test.go +++ b/database/gdb/gdb_z_mysql_basic_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/go-sql-driver/mysql" + "github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/test/gtest" ) diff --git a/database/gdb/gdb_z_mysql_method_test.go b/database/gdb/gdb_z_mysql_method_test.go index 49795cb8b..b16a91f55 100644 --- a/database/gdb/gdb_z_mysql_method_test.go +++ b/database/gdb/gdb_z_mysql_method_test.go @@ -45,7 +45,6 @@ func Test_DB_Query(t *testing.T) { _, err = db.Query(ctx, "ERROR") t.AssertNE(err, nil) }) - } func Test_DB_Exec(t *testing.T) { @@ -56,7 +55,6 @@ func Test_DB_Exec(t *testing.T) { _, err = db.Exec(ctx, "ERROR") t.AssertNE(err, nil) }) - } func Test_DB_Prepare(t *testing.T) { @@ -391,7 +389,6 @@ func Test_DB_BatchInsert(t *testing.T) { n, _ := result.RowsAffected() t.Assert(n, 1) }) - } func Test_DB_BatchInsert_Struct(t *testing.T) { @@ -924,12 +921,10 @@ func Test_DB_ToXml(t *testing.T) { } else { gtest.Fatal("FAIL") } - }) } func Test_DB_ToStringMap(t *testing.T) { - table := createInitTable() defer dropTable(table) _, err := db.Update(ctx, table, "create_time='2010-10-10 00:00:01'", "id=?", 1) @@ -965,7 +960,6 @@ func Test_DB_ToStringMap(t *testing.T) { } func Test_DB_ToIntMap(t *testing.T) { - table := createInitTable() defer dropTable(table) _, err := db.Update(ctx, table, "create_time='2010-10-10 00:00:01'", "id=?", 1) @@ -1034,7 +1028,6 @@ func Test_DB_ToUintMap(t *testing.T) { t.Assert(t_users[0].Password, resultUintMap[uint(id)]["password"]) t.Assert(t_users[0].NickName, resultUintMap[uint(id)]["nickname"]) t.Assert(t_users[0].CreateTime, resultUintMap[uint(id)]["create_time"]) - }) } @@ -1072,7 +1065,6 @@ func Test_DB_ToStringRecord(t *testing.T) { t.Assert(t_users[0].Password, resultStringRecord[ids]["password"].String()) t.Assert(t_users[0].NickName, resultStringRecord[ids]["nickname"].String()) t.Assert(t_users[0].CreateTime, resultStringRecord[ids]["create_time"].String()) - }) } @@ -1109,7 +1101,6 @@ func Test_DB_ToIntRecord(t *testing.T) { t.Assert(t_users[0].Password, resultIntRecord[id]["password"].String()) t.Assert(t_users[0].NickName, resultIntRecord[id]["nickname"].String()) t.Assert(t_users[0].CreateTime, resultIntRecord[id]["create_time"].String()) - }) } @@ -1301,7 +1292,6 @@ func Test_DB_Prefix(t *testing.T) { t.Assert(e, nil) t.Assert(n, TableSize) }) - } func Test_Model_InnerJoin(t *testing.T) { @@ -1420,7 +1410,7 @@ func Test_Empty_Slice_Argument(t *testing.T) { }) } -// update counter test +// update counter test. func Test_DB_UpdateCounter(t *testing.T) { tableName := "gf_update_counter_test_" + gtime.TimestampNanoStr() _, err := db.Exec(ctx, fmt.Sprintf(` diff --git a/database/gdb/gdb_z_mysql_model_basic_test.go b/database/gdb/gdb_z_mysql_model_basic_test.go index 86b81d756..0e242397f 100644 --- a/database/gdb/gdb_z_mysql_model_basic_test.go +++ b/database/gdb/gdb_z_mysql_model_basic_test.go @@ -970,7 +970,6 @@ func Test_Model_StructsWithOrmTag(t *testing.T) { t.Assert(one["passport"], "user_2") t.Assert(one["password"], "pass_2") }) - } func Test_Model_Scan(t *testing.T) { @@ -1984,7 +1983,6 @@ func Test_Model_Option_List(t *testing.T) { t.Assert(list[1]["nickname"].String(), "") t.Assert(list[1]["passport"].String(), "") t.Assert(list[1]["password"].String(), "2") - }) } @@ -2827,6 +2825,7 @@ func Test_Model_Fields_Struct(t *testing.T) { t.Assert(one["nickname"], "name_2") }) } + func Test_Model_NullField(t *testing.T) { table := createTable() defer dropTable(table) @@ -3058,7 +3057,7 @@ func Test_Model_Fields_Map_Struct(t *testing.T) { PASSPORT string XXX_TYPE int } - var a = A{} + a := A{} err := db.Model(table).Fields(a).Where("id", 1).Scan(&a) t.AssertNil(err) t.Assert(a.ID, 1) diff --git a/database/gdb/gdb_z_mysql_model_struct_test.go b/database/gdb/gdb_z_mysql_model_struct_test.go index aa54bcf3e..78dda93d5 100644 --- a/database/gdb/gdb_z_mysql_model_struct_test.go +++ b/database/gdb/gdb_z_mysql_model_struct_test.go @@ -99,7 +99,6 @@ func Test_Model_Embedded_MapToStruct(t *testing.T) { t.Assert(user.Password, data["password"]) t.Assert(user.Nickname, data["nickname"]) t.Assert(user.CreateTime, data["create_time"]) - }) } @@ -550,9 +549,7 @@ func Test_Scan_JsonAttributes(t *testing.T) { Passport string } - var ( - table = "jfy_gift" - ) + table := "jfy_gift" array := gstr.SplitAndTrim(gtest.TestDataContent(`issue1380.sql`), ";") for _, v := range array { if _, err := db.Exec(ctx, v); err != nil { diff --git a/database/gdb/gdb_z_mysql_model_where_test.go b/database/gdb/gdb_z_mysql_model_where_test.go index 044083ad7..55cc3bd7f 100644 --- a/database/gdb/gdb_z_mysql_model_where_test.go +++ b/database/gdb/gdb_z_mysql_model_where_test.go @@ -66,6 +66,5 @@ func Test_Model_WhereOrPrefix(t *testing.T) { t.Assert(r[1]["id"], "2") t.Assert(r[2]["id"], "8") t.Assert(r[3]["id"], "9") - }) } diff --git a/database/gdb/gdb_z_mysql_time_maintain_test.go b/database/gdb/gdb_z_mysql_time_maintain_test.go index 8621dc4e9..77ff68a21 100644 --- a/database/gdb/gdb_z_mysql_time_maintain_test.go +++ b/database/gdb/gdb_z_mysql_time_maintain_test.go @@ -16,7 +16,7 @@ import ( "github.com/gogf/gf/v2/test/gtest" ) -// CreateAt/UpdateAt/DeleteAt +// CreateAt/UpdateAt/DeleteAt. func Test_SoftCreateUpdateDeleteTime(t *testing.T) { table := "time_test_table_" + gtime.TimestampNanoStr() if _, err := db.Exec(ctx, fmt.Sprintf(` @@ -150,7 +150,7 @@ CREATE TABLE %s ( }) } -// CreatedAt/UpdatedAt/DeletedAt +// CreatedAt/UpdatedAt/DeletedAt. func Test_SoftCreatedUpdatedDeletedTime_Map(t *testing.T) { table := "time_test_table_" + gtime.TimestampNanoStr() if _, err := db.Exec(ctx, fmt.Sprintf(` @@ -284,7 +284,7 @@ CREATE TABLE %s ( }) } -// CreatedAt/UpdatedAt/DeletedAt +// CreatedAt/UpdatedAt/DeletedAt. func Test_SoftCreatedUpdatedDeletedTime_Struct(t *testing.T) { table := "time_test_table_" + gtime.TimestampNanoStr() if _, err := db.Exec(ctx, fmt.Sprintf(` diff --git a/database/gdb/gdb_z_mysql_transaction_test.go b/database/gdb/gdb_z_mysql_transaction_test.go index d0da6fd6b..41a7d5fc1 100644 --- a/database/gdb/gdb_z_mysql_transaction_test.go +++ b/database/gdb/gdb_z_mysql_transaction_test.go @@ -144,7 +144,6 @@ func Test_TX_Insert(t *testing.T) { if err := tx.Commit(); err != nil { gtest.Error(err) } - }) } @@ -415,7 +414,6 @@ func Test_TX_GetValue(t *testing.T) { gtest.Error(err) } }) - } func Test_TX_GetCount(t *testing.T) { diff --git a/os/gcache/gcache_adapter_memory.go b/os/gcache/gcache_adapter_memory.go index 5d1a40d29..4d189fc87 100644 --- a/os/gcache/gcache_adapter_memory.go +++ b/os/gcache/gcache_adapter_memory.go @@ -99,7 +99,7 @@ func (c *AdapterMemory) SetMap(ctx context.Context, data map[interface{}]interfa if err != nil { return err } - for k, _ := range data { + for k := range data { c.eventList.PushBack(&adapterMemoryEvent{ k: k, e: expireTime, From e86ee052cb73fe408f04b7f3c001edc440da6582 Mon Sep 17 00:00:00 2001 From: houseme Date: Tue, 16 Nov 2021 19:29:02 +0800 Subject: [PATCH 05/11] improve code import --- .example/os/gfsnotify/fsnotify.go | 9 ++++--- .golangci.yml | 2 +- database/gredis/gredis_adapter_goredis.go | 1 + .../gredis/gredis_adapter_goredis_conn.go | 1 + encoding/gbinary/gbinary_bit.go | 25 ++++++------------- encoding/gcharset/gcharset.go | 7 +++--- encoding/gyaml/gyaml.go | 3 ++- net/gtrace/gtrace.go | 9 ++++--- net/gtrace/gtrace_baggage.go | 3 ++- net/gtrace/gtrace_unit_carrier_test.go | 5 ++-- os/gfsnotify/gfsnotify.go | 1 + os/glog/glog_logger.go | 3 ++- 12 files changed, 35 insertions(+), 34 deletions(-) diff --git a/.example/os/gfsnotify/fsnotify.go b/.example/os/gfsnotify/fsnotify.go index 833732398..729fcd1b9 100644 --- a/.example/os/gfsnotify/fsnotify.go +++ b/.example/os/gfsnotify/fsnotify.go @@ -5,6 +5,7 @@ import ( "log" "github.com/fsnotify/fsnotify" + "github.com/gogf/gf/v2/os/glog" ) @@ -15,13 +16,13 @@ func main() { log.Fatal(err) } defer watch.Close() - //添加要监控的对象,文件或文件夹 - //err = watch.Add("D:\\Workspace\\Go\\GOPATH\\src\\gitee.com\\johng\\gf\\geg\\other\\test.go") + // 添加要监控的对象,文件或文件夹 + // err = watch.Add("D:\\Workspace\\Go\\GOPATH\\src\\gitee.com\\johng\\gf\\geg\\other\\test.go") err = watch.Add("/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/other/test.go") if err != nil { log.Fatal(err) } - //我们另启一个goroutine来处理监控对象的事件 + // 我们另启一个goroutine来处理监控对象的事件 go func() { for { select { @@ -36,6 +37,6 @@ func main() { } }() - //循环 + // 循环 select {} } diff --git a/.golangci.yml b/.golangci.yml index 5e63d73e6..511d6b8c3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -723,7 +723,7 @@ linters-settings: max-distance: 5 # The minimum length of a variable's name that is considered "long." (defaults to 3) # Variable names that are at least this long will be ignored. - min-name-length: 3 + min-name-length: 1 # Check method receiver names. (defaults to false) check-receiver: false # Check named return values. (defaults to false) diff --git a/database/gredis/gredis_adapter_goredis.go b/database/gredis/gredis_adapter_goredis.go index 4081b7037..ed5c3feae 100644 --- a/database/gredis/gredis_adapter_goredis.go +++ b/database/gredis/gredis_adapter_goredis.go @@ -11,6 +11,7 @@ import ( "time" "github.com/go-redis/redis/v8" + "github.com/gogf/gf/v2/text/gstr" ) diff --git a/database/gredis/gredis_adapter_goredis_conn.go b/database/gredis/gredis_adapter_goredis_conn.go index 36e32223f..a4a1bd243 100644 --- a/database/gredis/gredis_adapter_goredis_conn.go +++ b/database/gredis/gredis_adapter_goredis_conn.go @@ -10,6 +10,7 @@ import ( "context" "github.com/go-redis/redis/v8" + "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" diff --git a/encoding/gbinary/gbinary_bit.go b/encoding/gbinary/gbinary_bit.go index e382fecea..3e93dcab6 100644 --- a/encoding/gbinary/gbinary_bit.go +++ b/encoding/gbinary/gbinary_bit.go @@ -8,19 +8,16 @@ package gbinary // NOTE: THIS IS AN EXPERIMENTAL FEATURE! -// Bit Binary bit (0 | 1) 二进制位(0|1) +// Bit Binary bit (0 | 1) type Bit int8 -// EncodeBits . -// Default coding -// 默认编码 +// EncodeBits does encode bits return bits Default coding func EncodeBits(bits []Bit, i int, l int) []Bit { return EncodeBitsWithUint(bits, uint(i), l) } -// EncodeBitsWithUint . -// Merge ui bitwise into the bits array and occupy the length length bits (Note: binary 0 | 1 digits are stored in the uis array) -// 将ui按位合并到bits数组中,并占length长度位(注意:uis数组中存放的是二进制的0|1数字) +// EncodeBitsWithUint . Merge ui bitwise into the bits array and occupy the length bits +// (Note: binary 0 | 1 digits are stored in the uis array) func EncodeBitsWithUint(bits []Bit, ui uint, l int) []Bit { a := make([]Bit, l) for i := l - 1; i >= 0; i-- { @@ -33,9 +30,8 @@ func EncodeBitsWithUint(bits []Bit, ui uint, l int) []Bit { return a } -// EncodeBitsToBytes . +// EncodeBitsToBytes . does encode bits to bytes // Convert bits to [] byte, encode from left to right, and add less than 1 byte from 0 to the end. -// 将bits转换为[]byte,从左至右进行编码,不足1 byte按0往末尾补充 func EncodeBitsToBytes(bits []Bit) []byte { if len(bits)%8 != 0 { for i := 0; i < len(bits)%8; i++ { @@ -49,9 +45,8 @@ func EncodeBitsToBytes(bits []Bit) []byte { return b } -// DecodeBits . +// DecodeBits .does decode bits to int // Resolve to int -// 解析为int func DecodeBits(bits []Bit) int { v := 0 for _, i := range bits { @@ -60,9 +55,7 @@ func DecodeBits(bits []Bit) int { return v } -// DecodeBitsToUint . -// Resolve to uint -// 解析为uint +// DecodeBitsToUint .Resolve to uint func DecodeBitsToUint(bits []Bit) uint { v := uint(0) for _, i := range bits { @@ -71,9 +64,7 @@ func DecodeBitsToUint(bits []Bit) uint { return v } -// DecodeBytesToBits . -// Parsing [] byte into character array [] uint8 -// 解析[]byte为字位数组[]uint8 +// DecodeBytesToBits .Parsing [] byte into character array [] uint8 func DecodeBytesToBits(bs []byte) []Bit { bits := make([]Bit, 0) for _, b := range bs { diff --git a/encoding/gcharset/gcharset.go b/encoding/gcharset/gcharset.go index 534f84aa3..bd283bc56 100644 --- a/encoding/gcharset/gcharset.go +++ b/encoding/gcharset/gcharset.go @@ -24,12 +24,13 @@ import ( "context" "io/ioutil" - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/internal/intlog" "golang.org/x/text/encoding" "golang.org/x/text/encoding/ianaindex" "golang.org/x/text/transform" + + "github.com/gogf/gf/v2/errors/gcode" + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/internal/intlog" ) var ( diff --git a/encoding/gyaml/gyaml.go b/encoding/gyaml/gyaml.go index 4a9cbe234..143834dc0 100644 --- a/encoding/gyaml/gyaml.go +++ b/encoding/gyaml/gyaml.go @@ -8,10 +8,11 @@ package gyaml import ( + "gopkg.in/yaml.v3" + "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/internal/json" "github.com/gogf/gf/v2/util/gconv" - "gopkg.in/yaml.v3" ) func Encode(value interface{}) (out []byte, err error) { diff --git a/net/gtrace/gtrace.go b/net/gtrace/gtrace.go index f64bc621b..846cefb47 100644 --- a/net/gtrace/gtrace.go +++ b/net/gtrace/gtrace.go @@ -12,14 +12,15 @@ import ( "os" "strings" - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/container/gvar" - "github.com/gogf/gf/v2/net/gipv4" - "github.com/gogf/gf/v2/os/gcmd" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/net/gipv4" + "github.com/gogf/gf/v2/os/gcmd" ) const ( diff --git a/net/gtrace/gtrace_baggage.go b/net/gtrace/gtrace_baggage.go index dd7a0dfb4..26a9eb86a 100644 --- a/net/gtrace/gtrace_baggage.go +++ b/net/gtrace/gtrace_baggage.go @@ -9,10 +9,11 @@ package gtrace import ( "context" + "go.opentelemetry.io/otel/baggage" + "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/util/gconv" - "go.opentelemetry.io/otel/baggage" ) // Baggage holds the data through all tracing spans. diff --git a/net/gtrace/gtrace_unit_carrier_test.go b/net/gtrace/gtrace_unit_carrier_test.go index 24262222f..d3fecf225 100644 --- a/net/gtrace/gtrace_unit_carrier_test.go +++ b/net/gtrace/gtrace_unit_carrier_test.go @@ -10,10 +10,11 @@ import ( "context" "testing" - "github.com/gogf/gf/v2/net/gtrace" - "github.com/gogf/gf/v2/test/gtest" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2/net/gtrace" + "github.com/gogf/gf/v2/test/gtest" ) const ( diff --git a/os/gfsnotify/gfsnotify.go b/os/gfsnotify/gfsnotify.go index 12235ae61..b6de60e0e 100644 --- a/os/gfsnotify/gfsnotify.go +++ b/os/gfsnotify/gfsnotify.go @@ -13,6 +13,7 @@ import ( "time" "github.com/fsnotify/fsnotify" + "github.com/gogf/gf/v2/container/glist" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/container/gqueue" diff --git a/os/glog/glog_logger.go b/os/glog/glog_logger.go index 178c5828b..0190e3f09 100644 --- a/os/glog/glog_logger.go +++ b/os/glog/glog_logger.go @@ -16,6 +16,8 @@ import ( "time" "github.com/fatih/color" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/internal/intlog" @@ -27,7 +29,6 @@ import ( "github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/util/gconv" - "go.opentelemetry.io/otel/trace" ) // Logger is the struct for logging management. From bb4f72d1ecef20fbf126f2be3103805206666336 Mon Sep 17 00:00:00 2001 From: houseme Date: Tue, 16 Nov 2021 19:43:02 +0800 Subject: [PATCH 06/11] improve code Introduce according to grouping --- database/gredis/gredis_redis_tracing.go | 7 ++++--- encoding/gtoml/gtoml.go | 1 + encoding/gxml/gxml.go | 4 ++-- internal/intlog/intlog.go | 3 ++- net/ghttp/ghttp_middleware_tracing.go | 11 ++++++----- net/ghttp/ghttp_server.go | 3 ++- net/ghttp/internal/client/client.go | 6 +++--- net/ghttp/internal/client/client_tracing.go | 11 ++++++----- 8 files changed, 26 insertions(+), 20 deletions(-) diff --git a/database/gredis/gredis_redis_tracing.go b/database/gredis/gredis_redis_tracing.go index b2d41c75b..2fd5fb2b3 100644 --- a/database/gredis/gredis_redis_tracing.go +++ b/database/gredis/gredis_redis_tracing.go @@ -10,13 +10,14 @@ import ( "context" "fmt" - "github.com/gogf/gf/v2" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/net/gtrace" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/v2" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/net/gtrace" ) // tracingItem holds the information for redis tracing. diff --git a/encoding/gtoml/gtoml.go b/encoding/gtoml/gtoml.go index 23fc52af0..fe636f610 100644 --- a/encoding/gtoml/gtoml.go +++ b/encoding/gtoml/gtoml.go @@ -11,6 +11,7 @@ import ( "bytes" "github.com/BurntSushi/toml" + "github.com/gogf/gf/v2/internal/json" ) diff --git a/encoding/gxml/gxml.go b/encoding/gxml/gxml.go index 9dc9a5780..f1c61d441 100644 --- a/encoding/gxml/gxml.go +++ b/encoding/gxml/gxml.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/clbanning/mxj/v2" + "github.com/gogf/gf/v2/encoding/gcharset" "github.com/gogf/gf/v2/text/gregex" ) @@ -63,9 +64,8 @@ func ToJson(content []byte) ([]byte, error) { mv, err := mxj.NewMapXml(res) if err == nil { return mv.Json() - } else { - return nil, err } + return nil, err } // convert does convert the encoding of given XML content from XML root tag into UTF-8 encoding content. diff --git a/internal/intlog/intlog.go b/internal/intlog/intlog.go index 5247f75bc..602e16000 100644 --- a/internal/intlog/intlog.go +++ b/internal/intlog/intlog.go @@ -14,9 +14,10 @@ import ( "path/filepath" "time" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/v2/debug/gdebug" "github.com/gogf/gf/v2/internal/utils" - "go.opentelemetry.io/otel/trace" ) const ( diff --git a/net/ghttp/ghttp_middleware_tracing.go b/net/ghttp/ghttp_middleware_tracing.go index f7c71a512..8f885bf1b 100644 --- a/net/ghttp/ghttp_middleware_tracing.go +++ b/net/ghttp/ghttp_middleware_tracing.go @@ -11,6 +11,12 @@ import ( "io/ioutil" "net/http" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/v2" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/net/ghttp/internal/client" @@ -18,11 +24,6 @@ import ( "github.com/gogf/gf/v2/net/gtrace" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/trace" ) const ( diff --git a/net/ghttp/ghttp_server.go b/net/ghttp/ghttp_server.go index 9d2266d1f..7738d9a85 100644 --- a/net/ghttp/ghttp_server.go +++ b/net/ghttp/ghttp_server.go @@ -16,6 +16,8 @@ import ( "strings" "time" + "github.com/olekukonko/tablewriter" + "github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/gtype" "github.com/gogf/gf/v2/debug/gdebug" @@ -34,7 +36,6 @@ import ( "github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "github.com/olekukonko/tablewriter" ) func init() { diff --git a/net/ghttp/internal/client/client.go b/net/ghttp/internal/client/client.go index c685b0f6a..1738495db 100644 --- a/net/ghttp/internal/client/client.go +++ b/net/ghttp/internal/client/client.go @@ -18,14 +18,14 @@ import ( "strings" "time" + "golang.org/x/net/proxy" + "github.com/gogf/gf/v2" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/text/gstr" - "golang.org/x/net/proxy" - "github.com/gogf/gf/v2/text/gregex" + "github.com/gogf/gf/v2/text/gstr" ) // Client is the HTTP client for HTTP request management. diff --git a/net/ghttp/internal/client/client_tracing.go b/net/ghttp/internal/client/client_tracing.go index 630617e6f..078ad4cb1 100644 --- a/net/ghttp/internal/client/client_tracing.go +++ b/net/ghttp/internal/client/client_tracing.go @@ -12,17 +12,18 @@ import ( "net/http" "net/http/httptrace" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/v2" "github.com/gogf/gf/v2/internal/utils" "github.com/gogf/gf/v2/net/ghttp/internal/httputil" "github.com/gogf/gf/v2/net/gtrace" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/trace" ) const ( From 0b9931a3a4cf8e8b016e005393b9767991ad9f29 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 16 Nov 2021 20:41:31 +0800 Subject: [PATCH 07/11] improve Dump feature for package gutil --- util/gutil/gutil_dump.go | 33 +++++++++++++++++----------- util/gutil/gutil_z_unit_dump_test.go | 16 ++++++++++++++ 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/util/gutil/gutil_dump.go b/util/gutil/gutil_dump.go index fe97476b4..7f264e36a 100644 --- a/util/gutil/gutil_dump.go +++ b/util/gutil/gutil_dump.go @@ -9,6 +9,7 @@ package gutil import ( "bytes" "fmt" + "io" "reflect" "strings" @@ -57,12 +58,21 @@ func DumpWithType(values ...interface{}) { // Export returns variables `values` as a string with more manually readable. func Export(value interface{}, option ExportOption) string { buffer := bytes.NewBuffer(nil) - doExport(value, "", buffer, doExportOption{ + ExportTo(buffer, value, ExportOption{ WithoutType: option.WithoutType, }) return buffer.String() } +// ExportTo writes variables `values` as a string in to `writer` with more manually readable +func ExportTo(writer io.Writer, value interface{}, option ExportOption) { + buffer := bytes.NewBuffer(nil) + doExport(value, "", buffer, doExportOption{ + WithoutType: option.WithoutType, + }) + _, _ = writer.Write(buffer.Bytes()) +} + type doExportOption struct { WithoutType bool } @@ -88,15 +98,15 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE } switch reflectKind { case reflect.Slice, reflect.Array: - if _, ok := value.([]byte); ok { + if b, ok := value.([]byte); ok { if option.WithoutType { - buffer.WriteString(fmt.Sprintf(`"%s"`, value)) + buffer.WriteString(fmt.Sprintf(`"%s"`, gstr.AddSlashes(string(b)))) } else { buffer.WriteString(fmt.Sprintf( `%s(%d) "%s"`, reflectTypeName, len(reflectValue.String()), - value, + string(b), )) } return @@ -197,12 +207,8 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE if structContentStr == "" { structContentStr = "{}" } else { - if strings.HasPrefix(structContentStr, `"`) && strings.HasSuffix(structContentStr, `"`) { - attributeCountStr = fmt.Sprintf(`%d`, len(structContentStr)) - } else { - structContentStr = fmt.Sprintf(`"%s"`, gstr.AddSlashes(structContentStr)) - attributeCountStr = fmt.Sprintf(`%d`, len(structContentStr)-2) - } + structContentStr = fmt.Sprintf(`"%s"`, gstr.AddSlashes(structContentStr)) + attributeCountStr = fmt.Sprintf(`%d`, len(structContentStr)-2) } if option.WithoutType { buffer.WriteString(structContentStr) @@ -246,14 +252,15 @@ func doExport(value interface{}, indent string, buffer *bytes.Buffer, option doE buffer.WriteString(fmt.Sprintf("%s}", indent)) case reflect.String: + s, _ := value.(string) if option.WithoutType { - buffer.WriteString(fmt.Sprintf("\"%v\"", value)) + buffer.WriteString(fmt.Sprintf(`"%v"`, gstr.AddSlashes(s))) } else { buffer.WriteString(fmt.Sprintf( - "%s(%d) \"%v\"", + `%s(%d) "%v"`, reflectTypeName, len(reflectValue.String()), - value, + gstr.AddSlashes(s), )) } diff --git a/util/gutil/gutil_z_unit_dump_test.go b/util/gutil/gutil_z_unit_dump_test.go index 2e0d9a2d1..d90052643 100755 --- a/util/gutil/gutil_z_unit_dump_test.go +++ b/util/gutil/gutil_z_unit_dump_test.go @@ -126,3 +126,19 @@ func TestDumpWithType(t *testing.T) { gutil.DumpWithType([][]byte{[]byte("hello")}) }) } + +func Test_Dump_Slashes(t *testing.T) { + type Req struct { + Content string + } + req := &Req{ + Content: `{"name":"john", "age":18}`, + } + gtest.C(t, func(t *gtest.T) { + gutil.Dump(req) + gutil.Dump(req.Content) + + gutil.DumpWithType(req) + gutil.DumpWithType(req.Content) + }) +} From 459aaea6e1730c7192da1f11d94e33c036aa6090 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 16 Nov 2021 21:25:14 +0800 Subject: [PATCH 08/11] .golangci.yml updates --- .golangci.yml | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 511d6b8c3..c5481fc95 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,11 +13,11 @@ run: issues-exit-code: 1 # include test files or not, default is true - tests: true + tests: false # list of build tags, all linters use it. Default is empty list. build-tags: - - mytag +# - mytag # which dirs to skip: issues from them won't be reported; # can use regexp here: generated.*, regexp is applied on full path; @@ -26,9 +26,8 @@ run: # "/" will be replaced by current OS file path separator to properly work # on Windows. skip-dirs: - - packed - - documentation - - docker + - .example + - .test # default is true. Enables skipping of directories: # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ @@ -41,8 +40,8 @@ run: # "/" will be replaced by current OS file path separator to properly work # on Windows. skip-files: - - ".*\\.my\\.go$" - - lib/bad.go + - ".*_test\\.go$" + - ".*_packed\\.go$" # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": # If invoked with -mod=readonly, the go command is disallowed from the implicit @@ -134,9 +133,9 @@ linters-settings: # list of functions to exclude from checking, where each entry is a single function to exclude. # see https://github.com/kisielk/errcheck#excluding-functions for details exclude-functions: - - io/ioutil.ReadFile - - io.Copy(*bytes.Buffer) - - io.Copy(os.Stdout) +# - io/ioutil.ReadFile +# - io.Copy(*bytes.Buffer) +# - io.Copy(os.Stdout) errorlint: # Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats @@ -164,19 +163,19 @@ linters-settings: # The matching patterns can use matching syntax from https://pkg.go.dev/path#Match # If this list is empty, all structs are tested. struct-patterns: - - '*.Test' - - 'example.com/package.ExampleStruct' - - '*.Test2' - - '*.Embedded' - - '*.External' +# - '*.Test' +# - 'example.com/package.ExampleStruct' +# - '*.Test2' +# - '*.Embedded' +# - '*.External' forbidigo: # Forbid the following identifiers (identifiers are written using regexp): forbid: - - ^print.*$ - - 'fmt\.Print.*' - - fmt.Println.* # too much log noise - - ginkgo\\.F.* # these are used just for local development +# - ^print.*$ +# - 'fmt\.Print.*' +# - fmt.Println.* # too much log noise +# - ginkgo\\.F.* # these are used just for local development # Exclude godoc examples from forbidigo checks. Default is true. exclude_godoc_examples: false @@ -200,7 +199,7 @@ linters-settings: # minimum occurrences of constant string count to trigger issue, 3 by default min-occurrences: 3 # ignore test files, false by default - ignore-tests: false + ignore-tests: true # look for existing constants matching the values, true by default match-constant: true # search also for duplicated numbers, false by default From 67a479a2cdae1c19b07d167debc667b0820d41f9 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 16 Nov 2021 21:37:59 +0800 Subject: [PATCH 09/11] remove .example --- .example/container/garray/basic_array.go | 46 -- .example/container/garray/json_marshal.go | 22 - .example/container/garray/json_unmarshal.go | 19 - .../container/garray/sorted_array_basic.go | 40 -- .../container/garray/sorted_string_array.go | 23 - .example/container/glist/basic.go | 22 - .example/container/glist/json_marshal.go | 23 - .example/container/glist/json_unmarshal.go | 19 - .example/container/gmap/basic.go | 74 --- .example/container/gmap/gmap_json_marshal.go | 19 - .../container/gmap/gmap_json_unmarshal.go | 14 - .../container/gmap/gmap_map_clone_safe.go | 26 - .example/container/gmap/gmap_maps.go | 31 - .example/container/gmap/gmap_treemap.go | 63 -- .example/container/gpool/gpool.go | 26 - .example/container/gpool/gpool_expirefunc.go | 33 - .example/container/gqueue/gqueue.go | 34 -- .example/container/gqueue/gqueue2.go | 28 - .example/container/gqueue/gqueue3.go | 30 - .example/container/gring/gring.go | 28 - .example/container/gring/gring_josephus.go | 58 -- .example/container/gset/gset1.go | 53 -- .example/container/gset/gset2.go | 23 - .example/container/gset/json_marshal.go | 22 - .example/container/gset/json_unmarshal.go | 19 - .example/container/gtree/gtree_avltree.go | 29 - .example/container/gtree/gtree_btree.go | 22 - .example/container/gtree/gtree_redblackmap.go | 63 -- .../container/gtree/gtree_redblacktree.go | 17 - .example/container/gtype/gtype_int.go | 21 - .example/container/gtype/json_marshal.go | 22 - .example/container/gtype/json_unmarshal.go | 19 - .example/container/gvar/json_marshal.go | 22 - .example/container/gvar/json_unmarshal.go | 19 - .example/container/gvar/var.go | 33 - .example/database/gdb/driver/driver/driver.go | 71 --- .example/database/gdb/driver/main.go | 1 - .example/database/gdb/mssql/config.toml | 3 - .example/database/gdb/mssql/gdb_all.go | 23 - .example/database/gdb/mssql/gdb_sqlserver.go | 565 ------------------ .example/database/gdb/mysql/config.toml | 26 - .example/database/gdb/mysql/config/gdb.go | 41 -- .example/database/gdb/mysql/config2.toml | 4 - .example/database/gdb/mysql/config3.toml | 7 - .example/database/gdb/mysql/gdb_all.go | 24 - .example/database/gdb/mysql/gdb_args_slice.go | 29 - .../database/gdb/mysql/gdb_batch_insert.go | 28 - .example/database/gdb/mysql/gdb_binary.go | 55 -- .example/database/gdb/mysql/gdb_bit.go | 24 - .example/database/gdb/mysql/gdb_cache.go | 44 -- .../database/gdb/mysql/gdb_complecated.go | 24 - .example/database/gdb/mysql/gdb_config.go | 16 - .example/database/gdb/mysql/gdb_config2.go | 17 - .example/database/gdb/mysql/gdb_config3.go | 24 - .example/database/gdb/mysql/gdb_ctx.go | 14 - .example/database/gdb/mysql/gdb_ctx_model.go | 14 - .example/database/gdb/mysql/gdb_datetime.go | 27 - .example/database/gdb/mysql/gdb_debug1.go | 41 -- .example/database/gdb/mysql/gdb_debug2.go | 22 - .example/database/gdb/mysql/gdb_distinct.go | 9 - .example/database/gdb/mysql/gdb_insert.go | 30 - .example/database/gdb/mysql/gdb_issue_278.go | 50 -- .example/database/gdb/mysql/gdb_json_xml.go | 41 -- .example/database/gdb/mysql/gdb_pool.go | 26 - .example/database/gdb/mysql/gdb_reconnect.go | 22 - .example/database/gdb/mysql/gdb_struct.go | 23 - .example/database/gdb/mysql/gdb_tables.go | 22 - .../database/gdb/mysql/gdb_tables_fields.go | 29 - .../database/gdb/mysql/gdb_transaction.go | 27 - .../gdb/mysql/gdb_transaction_closure.go | 37 -- .../gdb/mysql/gdb_transaction_savepoint.go | 40 -- .../database/gdb/mysql/gdb_update_field.go | 34 -- .../database/gdb/mysql/gdb_update_union.go | 17 - .example/database/gdb/mysql/gdb_value.go | 15 - .../database/gdb/mysql/gdb_with_insert.go | 69 --- .example/database/gdb/mysql/gdb_with_slect.go | 37 -- .example/database/gdb/mysql/issue364.go | 34 -- .example/database/gdb/oracle/gdb.go | 565 ------------------ .example/database/gdb/sqlite/sqlite.go | 47 -- .example/database/gredis/config.toml | 4 - .example/database/gredis/gredis.go | 21 - .example/database/gredis/gredis2.go | 15 - .example/database/gredis/gredis_conn_do.go | 16 - .../database/gredis/gredis_conn_do_var.go | 17 - .example/database/gredis/gredis_conn_send.go | 21 - .../database/gredis/gredis_conn_send_var.go | 20 - .../database/gredis/gredis_conn_subscribe.go | 24 - .../gredis/gredis_conn_subscribe_var.go | 23 - .example/debug/gdebug/gdebug.go | 12 - .example/debug/gdebug/gdebug_info.go | 10 - .example/encoding/gbase64/gbase64.go | 16 - .example/encoding/gbinary/binary.go | 55 -- .example/encoding/gbinary/bits1.go | 33 - .example/encoding/gbinary/bits2.go | 33 - .example/encoding/gcfg/config.toml | 28 - .example/encoding/gcfg/gcfg1.go | 20 - .example/encoding/gcharset/gcharset.go | 20 - .example/encoding/gcompress/unzip.go | 15 - .example/encoding/gcompress/unzip_content.go | 16 - .example/encoding/gcompress/zip.go | 68 --- .example/encoding/ghash/ghash_repeat_check.go | 20 - .example/encoding/gini/gini.go | 16 - .example/encoding/gjson/gjson.go | 155 ----- .example/encoding/gjson/issue#IZXU2.go | 156 ----- .example/encoding/gjson/issue283.go | 69 --- .example/encoding/gjson/issue360.go | 19 - .example/encoding/gyaml/gyaml.go | 30 - .example/errors/gerror/gerror1.go | 25 - .example/errors/gerror/gerror2.go | 26 - .example/errors/gerror/gerror3.go | 23 - .example/errors/gerror/gerror4.go | 23 - .example/errors/gerror/gerror5.go | 22 - .example/i18n/gi18n/gi18n-dir.go | 19 - .example/i18n/gi18n/gi18n-file.go | 19 - .example/i18n/gi18n/gi18n.go | 23 - .example/i18n/gi18n/http_view_i18n.go | 22 - .example/i18n/gi18n/i18n-dir/en/hello.toml | 2 - .example/i18n/gi18n/i18n-dir/en/world.toml | 2 - .example/i18n/gi18n/i18n-dir/ja/hello.yaml | 2 - .example/i18n/gi18n/i18n-dir/ja/world.yaml | 1 - .example/i18n/gi18n/i18n-dir/ru/hello.ini | 1 - .example/i18n/gi18n/i18n-dir/ru/world.ini | 1 - .example/i18n/gi18n/i18n-dir/zh-CN/hello.json | 3 - .example/i18n/gi18n/i18n-dir/zh-CN/world.json | 3 - .example/i18n/gi18n/i18n-dir/zh-TW/hello.xml | 4 - .example/i18n/gi18n/i18n-dir/zh-TW/world.xml | 4 - .example/i18n/gi18n/i18n-file/en.toml | 3 - .example/i18n/gi18n/i18n-file/ja.yaml | 3 - .example/i18n/gi18n/i18n-file/ru.ini | 2 - .example/i18n/gi18n/i18n-file/zh-CN.json | 4 - .example/i18n/gi18n/i18n-file/zh-TW.xml | 5 - .example/i18n/gi18n/i18n/en.toml | 1 - .example/i18n/gi18n/i18n/ja.toml | 3 - .example/i18n/gi18n/i18n/ru.toml | 3 - .example/i18n/gi18n/i18n/zh-CN.toml | 3 - .example/i18n/gi18n/i18n/zh-TW.toml | 2 - .../i18n/gi18n/resource/gi18n-resource.go | 20 - .example/i18n/gi18n/template/index.html | 1 - .example/net/ghttp/client/cookie/client.go | 18 - .example/net/ghttp/client/cookie/server.go | 15 - .example/net/ghttp/client/get.go | 12 - .../net/ghttp/client/middleware/client.go | 64 -- .../net/ghttp/client/middleware/server.go | 17 - .../net/ghttp/client/upload-batch/client.go | 22 - .../net/ghttp/client/upload-batch/client2.go | 22 - .../net/ghttp/client/upload-batch/server.go | 62 -- .example/net/ghttp/client/upload/client.go | 41 -- .example/net/ghttp/client/upload/server.go | 62 -- .example/net/ghttp/server/admin/admin.go | 17 - .example/net/ghttp/server/body.go | 22 - .../server/controller/template/footer.html | 1 - .../server/controller/template/header.html | 1 - .../server/controller/template/layout.html | 3 - .../controller/template/main/main1.html | 2 - .../controller/template/main/main2.html | 2 - .example/net/ghttp/server/controller/user.go | 27 - .example/net/ghttp/server/controller/view.go | 23 - .example/net/ghttp/server/cookie.go | 18 - .example/net/ghttp/server/cors/cors1.go | 27 - .example/net/ghttp/server/cors/cors2.go | 27 - .example/net/ghttp/server/cors/cors3.go | 33 - .../net/ghttp/server/denyroutes/config.toml | 1 - .../net/ghttp/server/denyroutes/denyroutes.go | 12 - .example/net/ghttp/server/domain.go | 19 - .../net/ghttp/server/download/download.go | 20 - .example/net/ghttp/server/download/text.txt | 1 - .../net/ghttp/server/duplicate/duplicate1.go | 19 - .../net/ghttp/server/duplicate/duplicate2.go | 33 - .../net/ghttp/server/duplicate/duplicate3.go | 25 - .example/net/ghttp/server/exit.go | 27 - .example/net/ghttp/server/form/form-client.go | 9 - .example/net/ghttp/server/form/form.go | 16 - .example/net/ghttp/server/form/form.html | 30 - .example/net/ghttp/server/hello.go | 15 - .example/net/ghttp/server/hooks/cors1.go | 19 - .example/net/ghttp/server/hooks/cors2.go | 22 - .example/net/ghttp/server/hooks/hooks1.go | 24 - .example/net/ghttp/server/hooks/hooks4.go | 36 -- .example/net/ghttp/server/hooks/hooks5.go | 19 - .../net/ghttp/server/hooks/hooks_param.go | 20 - .../server/hooks/same_route_multi_hook.go | 31 - .example/net/ghttp/server/https/https.go | 17 - .example/net/ghttp/server/https/https_http.go | 18 - .example/net/ghttp/server/https/server.crt | 23 - .example/net/ghttp/server/https/server.key | 27 - .../net/ghttp/server/https/server.key.public | 27 - .example/net/ghttp/server/log/config.toml | 7 - .example/net/ghttp/server/log/log.go | 21 - .example/net/ghttp/server/log/log_error.go | 15 - .example/net/ghttp/server/middleware/auth.go | 34 -- .../ghttp/server/middleware/auth_exception.go | 41 -- .example/net/ghttp/server/middleware/cors.go | 23 - .../ghttp/server/middleware/error_handling.go | 42 -- .../net/ghttp/server/middleware/issue355.go | 21 - .example/net/ghttp/server/middleware/log.go | 42 -- .../net/ghttp/server/middleware/middleware.go | 40 -- .example/net/ghttp/server/middleware/param.go | 36 -- .example/net/ghttp/server/name.go | 41 -- .example/net/ghttp/server/nethttp_server.go | 19 - .example/net/ghttp/server/object/user.go | 22 - .example/net/ghttp/server/openapi/openapi.go | 33 - .example/net/ghttp/server/ports.go | 14 - .example/net/ghttp/server/pprof.go | 16 - .../ghttp/server/redirect/redirect_back.go | 18 - .../net/ghttp/server/redirect/redirect_to.go | 18 - .example/net/ghttp/server/reload/admin.go | 13 - .example/net/ghttp/server/reload/https.go | 17 - .../net/ghttp/server/reload/https_http.go | 18 - .../server/reload/multi_port_and_server.go | 19 - .example/net/ghttp/server/reload/simple.go | 27 - .example/net/ghttp/server/request/basic.go | 17 - .../net/ghttp/server/request/exit/exit.go | 18 - .../ghttp/server/request/json-xml/test1.go | 15 - .../ghttp/server/request/json-xml/test2.go | 47 -- .../net/ghttp/server/request/params/array.go | 15 - .../net/ghttp/server/request/params/map.go | 15 - .../net/ghttp/server/request/params/repeat.go | 15 - .example/net/ghttp/server/request/priority.go | 18 - .../ghttp/server/request/request_struct.go | 29 - .../server/request/request_validation.go | 41 -- .../net/ghttp/server/request/struct/parse1.go | 25 - .../net/ghttp/server/request/struct/parse2.go | 37 -- .../validation/validation1/validation1.go | 37 -- .../validation/validation2/validation2.go | 46 -- .../net/ghttp/server/resource/resource.go | 29 - .../net/ghttp/server/reuseport/reuseport.go | 27 - .../server/router/duplicated/duplicated.go | 20 - .../net/ghttp/server/router/group/basic.go | 22 - .../net/ghttp/server/router/group/batch.go | 38 -- .../net/ghttp/server/router/group/level.go | 67 --- .example/net/ghttp/server/router/router1.go | 27 - .example/net/ghttp/server/router/router2.go | 33 - .example/net/ghttp/server/router/router3.go | 29 - .example/net/ghttp/server/router/router4.go | 24 - .example/net/ghttp/server/router/router5.go | 26 - .example/net/ghttp/server/router/router6.go | 16 - .../net/ghttp/server/servefile/servefile.go | 15 - .../server/servefile/servefiledownload.go | 15 - .example/net/ghttp/server/servefile/test.txt | 1 - .example/net/ghttp/server/server2.go | 21 - .example/net/ghttp/server/session.go | 18 - .../net/ghttp/server/session/basic/session.go | 25 - .../ghttp/server/session/redis/config.toml | 2 - .../net/ghttp/server/session/redis/redis.go | 29 - .../server/session/redis/redis_bigint.go | 36 -- .example/net/ghttp/server/static/static.go | 15 - .../net/ghttp/server/static/static_path.go | 14 - .../net/ghttp/server/static/static_path2.go | 15 - .example/net/ghttp/server/status.go | 18 - .example/net/ghttp/server/status_map.go | 17 - .example/net/ghttp/server/status_redirect.go | 18 - .../template/build-in/objects/objects.go | 16 - .../server/template/build-in/vars/config.toml | 4 - .../server/template/build-in/vars/vars.go | 23 - .../ghttp/server/template/config/config.go | 17 - .../ghttp/server/template/config/config.toml | 2 - .../server/template/conflicts-name/client.go | 16 - .../template/client/layout.html | 1 - .../net/ghttp/server/template/layout/main.go | 23 - .../template/layout/template/footer.html | 1 - .../template/layout/template/header.html | 1 - .../template/layout/template/layout.html | 3 - .../template/layout/template/main/main1.html | 1 - .../template/layout/template/main/main2.html | 1 - .../net/ghttp/server/template/tpl1/index.tpl | 10 - .../net/ghttp/server/template/tpl1/tpl1.go | 19 - .../net/ghttp/server/template/tpl2/main.go | 23 - .../server/template/tpl2/public/test.html | 1 - .../server/template/tpl2/template/test.html | 1 - .../server/websocket/echo-wss/index.html | 93 --- .../ghttp/server/websocket/echo-wss/main.go | 32 - .../ghttp/server/websocket/echo/index.html | 93 --- .../ghttp/server/websocket/echo/main-group.go | 36 -- .../net/ghttp/server/websocket/echo/main.go | 31 - .example/net/gsmtp/gsmtp_sendMail.go | 24 - .example/net/gtcp/gtcp_conn.go | 56 -- .example/net/gtcp/gtcp_echo_server.go | 24 - .example/net/gtcp/gtcp_func.go | 17 - .example/net/gtcp/gtcp_pool1.go | 45 -- .example/net/gtcp/gtcp_pool2.go | 46 -- .example/net/gtcp/gtcp_server_client1.go | 50 -- .example/net/gtcp/gtcp_server_client2.go | 45 -- .example/net/gtcp/gtcp_timeout_client.go | 23 - .example/net/gtcp/gtcp_timeout_server.go | 25 - .../gtcp/pkg_operations/common/funcs/funcs.go | 39 -- .../common/gtcp_common_client.go | 64 -- .../common/gtcp_common_server.go | 48 -- .../gtcp/pkg_operations/common/types/types.go | 6 - .../net/gtcp/pkg_operations/gtcp_basic.go | 40 -- .../gtcp/pkg_operations/gtcp_empty_data.go | 39 -- .../gtcp/pkg_operations/gtcp_pkg_option.go | 40 -- .../monitor/gtcp_monitor_client.go | 43 -- .../monitor/gtcp_monitor_server.go | 32 - .../pkg_operations/monitor/types/types.go | 12 - .../net/gtcp/server_client/gtcp_client.go | 24 - .../net/gtcp/server_client/gtcp_server.go | 25 - .example/net/gtcp/tcp_server_client.go | 76 --- .example/net/gtcp/tls/gtcp_server_client.go | 59 -- .example/net/gtcp/tls/server.crt | 23 - .example/net/gtcp/tls/server.key | 27 - .example/net/gtcp/tls/server.key.public | 27 - .example/net/gudp/gudp_server.go | 17 - .example/net/gudp/gudp_server_client.go | 45 -- .example/net/gudp/udp_client.go | 23 - .example/net/gudp/udp_server.go | 29 - .example/os/gbuild/config.toml | 9 - .example/os/gbuild/gbuild.go | 11 - .example/os/gcache/getorset_func_lock.go | 28 - .example/os/gcache/note_interface_key.go | 19 - .example/os/gcache/note_interface_value.go | 29 - .example/os/gcache/usage_basic.go | 30 - .example/os/gcache/usage_lru.go | 28 - .example/os/gcache/usage_senior.go | 31 - .example/os/gcfg/basic/config.json | 33 - .example/os/gcfg/basic/config.toml | 33 - .example/os/gcfg/basic/gcfg1.go | 16 - .example/os/gcfg/basic/gcfg2.go | 13 - .example/os/gcfg/basic/gcfg3.go | 12 - .example/os/gcfg/basic/gcfg4.go | 12 - .example/os/gcfg/basic/gcfg_auto_update.go | 21 - .example/os/gcfg/basic/gcfg_error.go | 11 - .example/os/gcfg/basic/memcache.yml | 7 - .example/os/gcfg/basic/redis.toml | 20 - .example/os/gcfg/resource/resource.go | 21 - .example/os/gcmd/main.go | 22 - .example/os/gcron/gcron-log.go | 16 - .example/os/gcron/gcron1.go | 29 - .example/os/gcron/gcron2.go | 20 - .example/os/gfile/gfile.go | 46 -- .example/os/gfile/gfile_contents.go | 21 - .example/os/gfile/gfile_scan.go | 11 - .example/os/gfpool/gfpool.go | 21 - .example/os/gfsnotify/fsnotify.go | 42 -- .example/os/gfsnotify/gfsnotify.go | 19 - .example/os/gfsnotify/gfsnotify_callback.go | 37 -- .../os/gfsnotify/gfsnotify_callback_folder.go | 32 - .example/os/gfsnotify/gfsnotify_limit.go | 19 - .example/os/glog/glog_CtxKeys.go | 14 - .example/os/glog/glog_SetConfigWithMap.go | 16 - .example/os/glog/glog_async_chaining.go | 13 - .example/os/glog/glog_async_configure.go | 14 - .example/os/glog/glog_category.go | 15 - .example/os/glog/glog_color.go | 15 - .example/os/glog/glog_debug.go | 19 - .example/os/glog/glog_error.go | 11 - .example/os/glog/glog_file.go | 34 -- .example/os/glog/glog_flags.go | 15 - .example/os/glog/glog_gerror.go | 27 - .example/os/glog/glog_json.go | 15 - .example/os/glog/glog_level.go | 13 - .example/os/glog/glog_level_prefix.go | 11 - .example/os/glog/glog_line.go | 10 - .example/os/glog/glog_line2.go | 14 - .example/os/glog/glog_path.go | 16 - .example/os/glog/glog_pool.go | 18 - .example/os/glog/glog_prefix.go | 11 - .example/os/glog/glog_stack.go | 12 - .example/os/glog/glog_stdout.go | 23 - .example/os/glog/glog_writer_greylog.go | 30 - .example/os/glog/glog_writer_hook.go | 31 - .../os/glog/handler/glog_handler_greylog.go | 31 - .example/os/glog/handler/glog_handler_json.go | 42 -- .example/os/gmlock/1.lock&unlock.go | 28 - .example/os/gmlock/2.trylock.go | 29 - .example/os/gmlock/3.lock_conflicts.go | 39 -- .example/os/gmlock/4.test_deadlock.go | 97 --- .example/os/gmutex/gmutex_basic.go | 29 - .example/os/gmutex/gmutex_func.go | 22 - .example/os/gproc/gproc.go | 28 - .example/os/gproc/gproc3.go | 36 -- .example/os/gproc/gproc4.go | 18 - .example/os/gproc/gproc_comm.go | 32 - .example/os/gproc/gproc_comm_group.go | 58 -- .example/os/gproc/gproc_comm_send.go | 13 - .example/os/gproc/gproc_kill.go | 16 - .example/os/gproc/gproc_shellexec.go | 14 - .example/os/gproc/gproc_sleep.go | 12 - .example/os/gproc/signal/signal_handler.go | 54 -- .../os/gproc/signal/signal_handler_gproc.go | 27 - .example/os/gres/gres_example.go | 20 - .example/os/gres/gres_pack.go | 25 - .example/os/gres/gres_unpack.go | 23 - .example/os/grpool/goroutine.go | 23 - .example/os/grpool/grpool.go | 25 - .example/os/grpool/grpool1.go | 30 - .example/os/grpool/grpool2.go | 21 - .example/os/grpool/grpool3.go | 22 - .example/os/grpool/grpool4.go | 18 - .example/os/grpool/grpool5.go | 20 - .example/os/gsession/storage-file/file.go | 30 - .example/os/gsession/storage-memory/memory.go | 32 - .../storage-redis-hashtable/config.toml | 4 - .../redis-hashtable.go | 32 - .../os/gsession/storage-redis/config.toml | 4 - .example/os/gsession/storage-redis/redis.go | 32 - .example/os/gspath/gspath.go | 26 - .example/os/gtime/gtime_format.go | 20 - .example/os/gtime/gtime_func.go | 16 - .example/os/gtime/gtime_json.go | 15 - .example/os/gtime/gtime_layout.go | 20 - .example/os/gtime/gtime_linkop.go | 23 - .example/os/gtime/gtime_parsertime.go | 28 - .example/os/gtime/gtime_regex1.go | 39 -- .example/os/gtime/gtime_regex2.go | 33 - .example/os/gtime/gtime_strtotime.go | 46 -- .example/os/gtime/gtime_strtotime2.go | 15 - .example/os/gtime/gtime_zone.go | 22 - .example/os/gtimer/gtimer-batch.go | 18 - .example/os/gtimer/gtimer1.go | 19 - .example/os/gtimer/gtimer2.go | 28 - .example/os/gtimer/gtimer3.go | 18 - .example/os/gtimer/gtimer4.go | 20 - .example/os/gtimer/sleep1.go | 33 - .example/os/gtimer/sleep2.go | 18 - .example/os/gtimer/ticker1.go | 21 - .example/os/gtimer/ticker2.go | 21 - .example/os/gview/assign/assign.go | 18 - .example/os/gview/basic/gview.go | 18 - .example/os/gview/basic/gview.tpl | 1 - .example/os/gview/bind_func/gview_func1.go | 24 - .example/os/gview/bind_func/gview_func2.go | 31 - .example/os/gview/bind_func/index.html | 1 - .../gview/build_in_funcs/build_in_funcs1.go | 36 -- .../gview/build_in_funcs/build_in_funcs2.go | 46 -- .../os/gview/build_in_funcs/issue359-1.go | 16 - .../os/gview/build_in_funcs/issue359-2.go | 19 - .example/os/gview/define/main.go | 21 - .example/os/gview/define/template/index.html | 8 - .../os/gview/define/template/subs/sub.html | 4 - .../os/gview/delimiters/gview_delimiters.go | 17 - .../os/gview/delimiters/gview_delimiters.tpl | 1 - .example/os/gview/func_html/func_html.go | 24 - .example/os/gview/func_text/func_text.go | 10 - .../gview/hot_update/controller_hot_update.go | 27 - .../os/gview/hot_update/gview_hot_update.go | 20 - .../os/gview/hot_update/web_hot_update.go | 16 - .example/os/gview/i18n/i18n.go | 21 - .example/os/gview/include/main.go | 21 - .example/os/gview/include/template/index.html | 2 - .../os/gview/include/template/subs/sub.html | 1 - .example/os/gview/layout/layout1/main.go | 19 - .../layout/layout1/template/container.html | 3 - .../gview/layout/layout1/template/footer.html | 3 - .../gview/layout/layout1/template/header.html | 3 - .../gview/layout/layout1/template/layout.html | 15 - .example/os/gview/layout/layout2/main.go | 24 - .../gview/layout/layout2/template/footer.html | 1 - .../gview/layout/layout2/template/header.html | 1 - .../gview/layout/layout2/template/layout.html | 3 - .../layout/layout2/template/main/main1.html | 1 - .../layout/layout2/template/main/main2.html | 1 - .example/os/gview/object/object.go | 28 - .example/os/gview/resource/main1.go | 19 - .example/os/gview/resource/main2.go | 21 - .example/os/gview/resource/main3.go | 18 - .example/text/gregex/gregex.go | 12 - .example/text/gstr/gstr_hidestr.go | 12 - .example/text/gstr/gstr_substr.go | 12 - .example/util/gconv/gconv.go | 31 - .example/util/gconv/gconv_map1.go | 29 - .example/util/gconv/gconv_map2.go | 24 - .example/util/gconv/gconv_map_deep.go | 32 - .example/util/gconv/gconv_map_tag.go | 18 - .example/util/gconv/gconv_slice.go | 25 - .example/util/gconv/gconv_struct1.go | 47 -- .example/util/gconv/gconv_struct2.go | 30 - .example/util/gconv/gconv_struct4.go | 41 -- .example/util/gconv/gconv_struct5.go | 33 - .example/util/gconv/gconv_struct6.go | 39 -- .example/util/gconv/gconv_struct_create.go | 23 - .example/util/gconv/gconv_struct_deep.go | 34 -- .example/util/gconv/strings.go | 11 - .example/util/gconv/time1.go | 16 - .example/util/gconv/time2.go | 16 - .example/util/gpage/gpage.go | 38 -- .example/util/gpage/gpage_ajax.go | 47 -- .example/util/gpage/gpage_custom1.go | 47 -- .example/util/gpage/gpage_custom2.go | 47 -- .example/util/gpage/gpage_static1.go | 38 -- .example/util/gpage/gpage_static2.go | 38 -- .example/util/gpage/gpage_template.go | 39 -- .example/util/grand/grand.go | 16 - .example/util/grand/rand.go | 83 --- .example/util/guid/guid.go | 13 - .example/util/guid/guid_length.go | 20 - .example/util/guid/guid_unique.go | 23 - .example/util/gutil/dump.go | 11 - .example/util/gutil/stack.go | 14 - .example/util/gutil/try_catch.go | 17 - .example/util/gvalid/config.toml | 14 - .example/util/gvalid/gvalid.go | 71 --- .../util/gvalid/gvalid_checkstructwithdata.go | 28 - .example/util/gvalid/gvalid_custom_message.go | 14 - .example/util/gvalid/gvalid_error.go | 29 - .example/util/gvalid/gvalid_i18n.go | 38 -- .example/util/gvalid/gvalid_i18n_http.go | 35 -- .example/util/gvalid/gvalid_result.go | 25 - .example/util/gvalid/gvalid_sequence.go | 29 - .example/util/gvalid/gvalid_struct1.go | 36 -- .example/util/gvalid/gvalid_struct2.go | 18 - .example/util/gvalid/gvalid_struct3.go | 20 - .example/util/gvalid/gvalid_struct_meta.go | 40 -- .example/util/gvalid/i18n/en.toml | 7 - .example/util/gvalid/i18n/zh-CN.toml | 16 - .gitignore | 2 +- text/gstr/gstr_trim.go | 3 +- 506 files changed, 3 insertions(+), 13347 deletions(-) delete mode 100644 .example/container/garray/basic_array.go delete mode 100644 .example/container/garray/json_marshal.go delete mode 100644 .example/container/garray/json_unmarshal.go delete mode 100644 .example/container/garray/sorted_array_basic.go delete mode 100644 .example/container/garray/sorted_string_array.go delete mode 100644 .example/container/glist/basic.go delete mode 100644 .example/container/glist/json_marshal.go delete mode 100644 .example/container/glist/json_unmarshal.go delete mode 100644 .example/container/gmap/basic.go delete mode 100644 .example/container/gmap/gmap_json_marshal.go delete mode 100644 .example/container/gmap/gmap_json_unmarshal.go delete mode 100644 .example/container/gmap/gmap_map_clone_safe.go delete mode 100644 .example/container/gmap/gmap_maps.go delete mode 100644 .example/container/gmap/gmap_treemap.go delete mode 100644 .example/container/gpool/gpool.go delete mode 100644 .example/container/gpool/gpool_expirefunc.go delete mode 100644 .example/container/gqueue/gqueue.go delete mode 100644 .example/container/gqueue/gqueue2.go delete mode 100644 .example/container/gqueue/gqueue3.go delete mode 100644 .example/container/gring/gring.go delete mode 100644 .example/container/gring/gring_josephus.go delete mode 100644 .example/container/gset/gset1.go delete mode 100644 .example/container/gset/gset2.go delete mode 100644 .example/container/gset/json_marshal.go delete mode 100644 .example/container/gset/json_unmarshal.go delete mode 100644 .example/container/gtree/gtree_avltree.go delete mode 100644 .example/container/gtree/gtree_btree.go delete mode 100644 .example/container/gtree/gtree_redblackmap.go delete mode 100644 .example/container/gtree/gtree_redblacktree.go delete mode 100644 .example/container/gtype/gtype_int.go delete mode 100644 .example/container/gtype/json_marshal.go delete mode 100644 .example/container/gtype/json_unmarshal.go delete mode 100644 .example/container/gvar/json_marshal.go delete mode 100644 .example/container/gvar/json_unmarshal.go delete mode 100644 .example/container/gvar/var.go delete mode 100644 .example/database/gdb/driver/driver/driver.go delete mode 100644 .example/database/gdb/driver/main.go delete mode 100644 .example/database/gdb/mssql/config.toml delete mode 100644 .example/database/gdb/mssql/gdb_all.go delete mode 100644 .example/database/gdb/mssql/gdb_sqlserver.go delete mode 100644 .example/database/gdb/mysql/config.toml delete mode 100644 .example/database/gdb/mysql/config/gdb.go delete mode 100644 .example/database/gdb/mysql/config2.toml delete mode 100644 .example/database/gdb/mysql/config3.toml delete mode 100644 .example/database/gdb/mysql/gdb_all.go delete mode 100644 .example/database/gdb/mysql/gdb_args_slice.go delete mode 100644 .example/database/gdb/mysql/gdb_batch_insert.go delete mode 100644 .example/database/gdb/mysql/gdb_binary.go delete mode 100644 .example/database/gdb/mysql/gdb_bit.go delete mode 100644 .example/database/gdb/mysql/gdb_cache.go delete mode 100644 .example/database/gdb/mysql/gdb_complecated.go delete mode 100644 .example/database/gdb/mysql/gdb_config.go delete mode 100644 .example/database/gdb/mysql/gdb_config2.go delete mode 100644 .example/database/gdb/mysql/gdb_config3.go delete mode 100644 .example/database/gdb/mysql/gdb_ctx.go delete mode 100644 .example/database/gdb/mysql/gdb_ctx_model.go delete mode 100644 .example/database/gdb/mysql/gdb_datetime.go delete mode 100644 .example/database/gdb/mysql/gdb_debug1.go delete mode 100644 .example/database/gdb/mysql/gdb_debug2.go delete mode 100644 .example/database/gdb/mysql/gdb_distinct.go delete mode 100644 .example/database/gdb/mysql/gdb_insert.go delete mode 100644 .example/database/gdb/mysql/gdb_issue_278.go delete mode 100644 .example/database/gdb/mysql/gdb_json_xml.go delete mode 100644 .example/database/gdb/mysql/gdb_pool.go delete mode 100644 .example/database/gdb/mysql/gdb_reconnect.go delete mode 100644 .example/database/gdb/mysql/gdb_struct.go delete mode 100644 .example/database/gdb/mysql/gdb_tables.go delete mode 100644 .example/database/gdb/mysql/gdb_tables_fields.go delete mode 100644 .example/database/gdb/mysql/gdb_transaction.go delete mode 100644 .example/database/gdb/mysql/gdb_transaction_closure.go delete mode 100644 .example/database/gdb/mysql/gdb_transaction_savepoint.go delete mode 100644 .example/database/gdb/mysql/gdb_update_field.go delete mode 100644 .example/database/gdb/mysql/gdb_update_union.go delete mode 100644 .example/database/gdb/mysql/gdb_value.go delete mode 100644 .example/database/gdb/mysql/gdb_with_insert.go delete mode 100644 .example/database/gdb/mysql/gdb_with_slect.go delete mode 100644 .example/database/gdb/mysql/issue364.go delete mode 100644 .example/database/gdb/oracle/gdb.go delete mode 100644 .example/database/gdb/sqlite/sqlite.go delete mode 100644 .example/database/gredis/config.toml delete mode 100644 .example/database/gredis/gredis.go delete mode 100644 .example/database/gredis/gredis2.go delete mode 100644 .example/database/gredis/gredis_conn_do.go delete mode 100644 .example/database/gredis/gredis_conn_do_var.go delete mode 100644 .example/database/gredis/gredis_conn_send.go delete mode 100644 .example/database/gredis/gredis_conn_send_var.go delete mode 100644 .example/database/gredis/gredis_conn_subscribe.go delete mode 100644 .example/database/gredis/gredis_conn_subscribe_var.go delete mode 100644 .example/debug/gdebug/gdebug.go delete mode 100644 .example/debug/gdebug/gdebug_info.go delete mode 100644 .example/encoding/gbase64/gbase64.go delete mode 100644 .example/encoding/gbinary/binary.go delete mode 100644 .example/encoding/gbinary/bits1.go delete mode 100644 .example/encoding/gbinary/bits2.go delete mode 100644 .example/encoding/gcfg/config.toml delete mode 100644 .example/encoding/gcfg/gcfg1.go delete mode 100644 .example/encoding/gcharset/gcharset.go delete mode 100644 .example/encoding/gcompress/unzip.go delete mode 100644 .example/encoding/gcompress/unzip_content.go delete mode 100644 .example/encoding/gcompress/zip.go delete mode 100644 .example/encoding/ghash/ghash_repeat_check.go delete mode 100644 .example/encoding/gini/gini.go delete mode 100644 .example/encoding/gjson/gjson.go delete mode 100644 .example/encoding/gjson/issue#IZXU2.go delete mode 100644 .example/encoding/gjson/issue283.go delete mode 100644 .example/encoding/gjson/issue360.go delete mode 100644 .example/encoding/gyaml/gyaml.go delete mode 100644 .example/errors/gerror/gerror1.go delete mode 100644 .example/errors/gerror/gerror2.go delete mode 100644 .example/errors/gerror/gerror3.go delete mode 100644 .example/errors/gerror/gerror4.go delete mode 100644 .example/errors/gerror/gerror5.go delete mode 100644 .example/i18n/gi18n/gi18n-dir.go delete mode 100644 .example/i18n/gi18n/gi18n-file.go delete mode 100644 .example/i18n/gi18n/gi18n.go delete mode 100644 .example/i18n/gi18n/http_view_i18n.go delete mode 100644 .example/i18n/gi18n/i18n-dir/en/hello.toml delete mode 100644 .example/i18n/gi18n/i18n-dir/en/world.toml delete mode 100644 .example/i18n/gi18n/i18n-dir/ja/hello.yaml delete mode 100644 .example/i18n/gi18n/i18n-dir/ja/world.yaml delete mode 100644 .example/i18n/gi18n/i18n-dir/ru/hello.ini delete mode 100644 .example/i18n/gi18n/i18n-dir/ru/world.ini delete mode 100644 .example/i18n/gi18n/i18n-dir/zh-CN/hello.json delete mode 100644 .example/i18n/gi18n/i18n-dir/zh-CN/world.json delete mode 100644 .example/i18n/gi18n/i18n-dir/zh-TW/hello.xml delete mode 100644 .example/i18n/gi18n/i18n-dir/zh-TW/world.xml delete mode 100644 .example/i18n/gi18n/i18n-file/en.toml delete mode 100644 .example/i18n/gi18n/i18n-file/ja.yaml delete mode 100644 .example/i18n/gi18n/i18n-file/ru.ini delete mode 100644 .example/i18n/gi18n/i18n-file/zh-CN.json delete mode 100644 .example/i18n/gi18n/i18n-file/zh-TW.xml delete mode 100644 .example/i18n/gi18n/i18n/en.toml delete mode 100644 .example/i18n/gi18n/i18n/ja.toml delete mode 100644 .example/i18n/gi18n/i18n/ru.toml delete mode 100644 .example/i18n/gi18n/i18n/zh-CN.toml delete mode 100644 .example/i18n/gi18n/i18n/zh-TW.toml delete mode 100644 .example/i18n/gi18n/resource/gi18n-resource.go delete mode 100644 .example/i18n/gi18n/template/index.html delete mode 100644 .example/net/ghttp/client/cookie/client.go delete mode 100644 .example/net/ghttp/client/cookie/server.go delete mode 100644 .example/net/ghttp/client/get.go delete mode 100644 .example/net/ghttp/client/middleware/client.go delete mode 100644 .example/net/ghttp/client/middleware/server.go delete mode 100644 .example/net/ghttp/client/upload-batch/client.go delete mode 100644 .example/net/ghttp/client/upload-batch/client2.go delete mode 100644 .example/net/ghttp/client/upload-batch/server.go delete mode 100644 .example/net/ghttp/client/upload/client.go delete mode 100644 .example/net/ghttp/client/upload/server.go delete mode 100644 .example/net/ghttp/server/admin/admin.go delete mode 100644 .example/net/ghttp/server/body.go delete mode 100644 .example/net/ghttp/server/controller/template/footer.html delete mode 100644 .example/net/ghttp/server/controller/template/header.html delete mode 100644 .example/net/ghttp/server/controller/template/layout.html delete mode 100644 .example/net/ghttp/server/controller/template/main/main1.html delete mode 100644 .example/net/ghttp/server/controller/template/main/main2.html delete mode 100644 .example/net/ghttp/server/controller/user.go delete mode 100644 .example/net/ghttp/server/controller/view.go delete mode 100644 .example/net/ghttp/server/cookie.go delete mode 100644 .example/net/ghttp/server/cors/cors1.go delete mode 100644 .example/net/ghttp/server/cors/cors2.go delete mode 100644 .example/net/ghttp/server/cors/cors3.go delete mode 100644 .example/net/ghttp/server/denyroutes/config.toml delete mode 100644 .example/net/ghttp/server/denyroutes/denyroutes.go delete mode 100644 .example/net/ghttp/server/domain.go delete mode 100644 .example/net/ghttp/server/download/download.go delete mode 100644 .example/net/ghttp/server/download/text.txt delete mode 100644 .example/net/ghttp/server/duplicate/duplicate1.go delete mode 100644 .example/net/ghttp/server/duplicate/duplicate2.go delete mode 100644 .example/net/ghttp/server/duplicate/duplicate3.go delete mode 100644 .example/net/ghttp/server/exit.go delete mode 100644 .example/net/ghttp/server/form/form-client.go delete mode 100644 .example/net/ghttp/server/form/form.go delete mode 100644 .example/net/ghttp/server/form/form.html delete mode 100644 .example/net/ghttp/server/hello.go delete mode 100644 .example/net/ghttp/server/hooks/cors1.go delete mode 100644 .example/net/ghttp/server/hooks/cors2.go delete mode 100644 .example/net/ghttp/server/hooks/hooks1.go delete mode 100644 .example/net/ghttp/server/hooks/hooks4.go delete mode 100644 .example/net/ghttp/server/hooks/hooks5.go delete mode 100644 .example/net/ghttp/server/hooks/hooks_param.go delete mode 100644 .example/net/ghttp/server/hooks/same_route_multi_hook.go delete mode 100644 .example/net/ghttp/server/https/https.go delete mode 100644 .example/net/ghttp/server/https/https_http.go delete mode 100644 .example/net/ghttp/server/https/server.crt delete mode 100644 .example/net/ghttp/server/https/server.key delete mode 100644 .example/net/ghttp/server/https/server.key.public delete mode 100644 .example/net/ghttp/server/log/config.toml delete mode 100644 .example/net/ghttp/server/log/log.go delete mode 100644 .example/net/ghttp/server/log/log_error.go delete mode 100644 .example/net/ghttp/server/middleware/auth.go delete mode 100644 .example/net/ghttp/server/middleware/auth_exception.go delete mode 100644 .example/net/ghttp/server/middleware/cors.go delete mode 100644 .example/net/ghttp/server/middleware/error_handling.go delete mode 100644 .example/net/ghttp/server/middleware/issue355.go delete mode 100644 .example/net/ghttp/server/middleware/log.go delete mode 100644 .example/net/ghttp/server/middleware/middleware.go delete mode 100644 .example/net/ghttp/server/middleware/param.go delete mode 100644 .example/net/ghttp/server/name.go delete mode 100644 .example/net/ghttp/server/nethttp_server.go delete mode 100644 .example/net/ghttp/server/object/user.go delete mode 100644 .example/net/ghttp/server/openapi/openapi.go delete mode 100644 .example/net/ghttp/server/ports.go delete mode 100644 .example/net/ghttp/server/pprof.go delete mode 100644 .example/net/ghttp/server/redirect/redirect_back.go delete mode 100644 .example/net/ghttp/server/redirect/redirect_to.go delete mode 100644 .example/net/ghttp/server/reload/admin.go delete mode 100644 .example/net/ghttp/server/reload/https.go delete mode 100644 .example/net/ghttp/server/reload/https_http.go delete mode 100644 .example/net/ghttp/server/reload/multi_port_and_server.go delete mode 100644 .example/net/ghttp/server/reload/simple.go delete mode 100644 .example/net/ghttp/server/request/basic.go delete mode 100644 .example/net/ghttp/server/request/exit/exit.go delete mode 100644 .example/net/ghttp/server/request/json-xml/test1.go delete mode 100644 .example/net/ghttp/server/request/json-xml/test2.go delete mode 100644 .example/net/ghttp/server/request/params/array.go delete mode 100644 .example/net/ghttp/server/request/params/map.go delete mode 100644 .example/net/ghttp/server/request/params/repeat.go delete mode 100644 .example/net/ghttp/server/request/priority.go delete mode 100644 .example/net/ghttp/server/request/request_struct.go delete mode 100644 .example/net/ghttp/server/request/request_validation.go delete mode 100644 .example/net/ghttp/server/request/struct/parse1.go delete mode 100644 .example/net/ghttp/server/request/struct/parse2.go delete mode 100644 .example/net/ghttp/server/request/validation/validation1/validation1.go delete mode 100644 .example/net/ghttp/server/request/validation/validation2/validation2.go delete mode 100644 .example/net/ghttp/server/resource/resource.go delete mode 100644 .example/net/ghttp/server/reuseport/reuseport.go delete mode 100644 .example/net/ghttp/server/router/duplicated/duplicated.go delete mode 100644 .example/net/ghttp/server/router/group/basic.go delete mode 100644 .example/net/ghttp/server/router/group/batch.go delete mode 100644 .example/net/ghttp/server/router/group/level.go delete mode 100644 .example/net/ghttp/server/router/router1.go delete mode 100644 .example/net/ghttp/server/router/router2.go delete mode 100644 .example/net/ghttp/server/router/router3.go delete mode 100644 .example/net/ghttp/server/router/router4.go delete mode 100644 .example/net/ghttp/server/router/router5.go delete mode 100644 .example/net/ghttp/server/router/router6.go delete mode 100644 .example/net/ghttp/server/servefile/servefile.go delete mode 100644 .example/net/ghttp/server/servefile/servefiledownload.go delete mode 100644 .example/net/ghttp/server/servefile/test.txt delete mode 100644 .example/net/ghttp/server/server2.go delete mode 100644 .example/net/ghttp/server/session.go delete mode 100644 .example/net/ghttp/server/session/basic/session.go delete mode 100644 .example/net/ghttp/server/session/redis/config.toml delete mode 100644 .example/net/ghttp/server/session/redis/redis.go delete mode 100644 .example/net/ghttp/server/session/redis/redis_bigint.go delete mode 100644 .example/net/ghttp/server/static/static.go delete mode 100644 .example/net/ghttp/server/static/static_path.go delete mode 100644 .example/net/ghttp/server/static/static_path2.go delete mode 100644 .example/net/ghttp/server/status.go delete mode 100644 .example/net/ghttp/server/status_map.go delete mode 100644 .example/net/ghttp/server/status_redirect.go delete mode 100644 .example/net/ghttp/server/template/build-in/objects/objects.go delete mode 100644 .example/net/ghttp/server/template/build-in/vars/config.toml delete mode 100644 .example/net/ghttp/server/template/build-in/vars/vars.go delete mode 100644 .example/net/ghttp/server/template/config/config.go delete mode 100644 .example/net/ghttp/server/template/config/config.toml delete mode 100644 .example/net/ghttp/server/template/conflicts-name/client.go delete mode 100644 .example/net/ghttp/server/template/conflicts-name/template/client/layout.html delete mode 100644 .example/net/ghttp/server/template/layout/main.go delete mode 100644 .example/net/ghttp/server/template/layout/template/footer.html delete mode 100644 .example/net/ghttp/server/template/layout/template/header.html delete mode 100644 .example/net/ghttp/server/template/layout/template/layout.html delete mode 100644 .example/net/ghttp/server/template/layout/template/main/main1.html delete mode 100644 .example/net/ghttp/server/template/layout/template/main/main2.html delete mode 100644 .example/net/ghttp/server/template/tpl1/index.tpl delete mode 100644 .example/net/ghttp/server/template/tpl1/tpl1.go delete mode 100644 .example/net/ghttp/server/template/tpl2/main.go delete mode 100644 .example/net/ghttp/server/template/tpl2/public/test.html delete mode 100644 .example/net/ghttp/server/template/tpl2/template/test.html delete mode 100644 .example/net/ghttp/server/websocket/echo-wss/index.html delete mode 100644 .example/net/ghttp/server/websocket/echo-wss/main.go delete mode 100644 .example/net/ghttp/server/websocket/echo/index.html delete mode 100644 .example/net/ghttp/server/websocket/echo/main-group.go delete mode 100644 .example/net/ghttp/server/websocket/echo/main.go delete mode 100644 .example/net/gsmtp/gsmtp_sendMail.go delete mode 100644 .example/net/gtcp/gtcp_conn.go delete mode 100644 .example/net/gtcp/gtcp_echo_server.go delete mode 100644 .example/net/gtcp/gtcp_func.go delete mode 100644 .example/net/gtcp/gtcp_pool1.go delete mode 100644 .example/net/gtcp/gtcp_pool2.go delete mode 100644 .example/net/gtcp/gtcp_server_client1.go delete mode 100644 .example/net/gtcp/gtcp_server_client2.go delete mode 100644 .example/net/gtcp/gtcp_timeout_client.go delete mode 100644 .example/net/gtcp/gtcp_timeout_server.go delete mode 100644 .example/net/gtcp/pkg_operations/common/funcs/funcs.go delete mode 100644 .example/net/gtcp/pkg_operations/common/gtcp_common_client.go delete mode 100644 .example/net/gtcp/pkg_operations/common/gtcp_common_server.go delete mode 100644 .example/net/gtcp/pkg_operations/common/types/types.go delete mode 100644 .example/net/gtcp/pkg_operations/gtcp_basic.go delete mode 100644 .example/net/gtcp/pkg_operations/gtcp_empty_data.go delete mode 100644 .example/net/gtcp/pkg_operations/gtcp_pkg_option.go delete mode 100644 .example/net/gtcp/pkg_operations/monitor/gtcp_monitor_client.go delete mode 100644 .example/net/gtcp/pkg_operations/monitor/gtcp_monitor_server.go delete mode 100644 .example/net/gtcp/pkg_operations/monitor/types/types.go delete mode 100644 .example/net/gtcp/server_client/gtcp_client.go delete mode 100644 .example/net/gtcp/server_client/gtcp_server.go delete mode 100644 .example/net/gtcp/tcp_server_client.go delete mode 100644 .example/net/gtcp/tls/gtcp_server_client.go delete mode 100644 .example/net/gtcp/tls/server.crt delete mode 100644 .example/net/gtcp/tls/server.key delete mode 100644 .example/net/gtcp/tls/server.key.public delete mode 100644 .example/net/gudp/gudp_server.go delete mode 100644 .example/net/gudp/gudp_server_client.go delete mode 100644 .example/net/gudp/udp_client.go delete mode 100644 .example/net/gudp/udp_server.go delete mode 100644 .example/os/gbuild/config.toml delete mode 100644 .example/os/gbuild/gbuild.go delete mode 100644 .example/os/gcache/getorset_func_lock.go delete mode 100644 .example/os/gcache/note_interface_key.go delete mode 100644 .example/os/gcache/note_interface_value.go delete mode 100644 .example/os/gcache/usage_basic.go delete mode 100644 .example/os/gcache/usage_lru.go delete mode 100644 .example/os/gcache/usage_senior.go delete mode 100644 .example/os/gcfg/basic/config.json delete mode 100644 .example/os/gcfg/basic/config.toml delete mode 100644 .example/os/gcfg/basic/gcfg1.go delete mode 100644 .example/os/gcfg/basic/gcfg2.go delete mode 100644 .example/os/gcfg/basic/gcfg3.go delete mode 100644 .example/os/gcfg/basic/gcfg4.go delete mode 100644 .example/os/gcfg/basic/gcfg_auto_update.go delete mode 100644 .example/os/gcfg/basic/gcfg_error.go delete mode 100644 .example/os/gcfg/basic/memcache.yml delete mode 100644 .example/os/gcfg/basic/redis.toml delete mode 100644 .example/os/gcfg/resource/resource.go delete mode 100644 .example/os/gcmd/main.go delete mode 100644 .example/os/gcron/gcron-log.go delete mode 100644 .example/os/gcron/gcron1.go delete mode 100644 .example/os/gcron/gcron2.go delete mode 100644 .example/os/gfile/gfile.go delete mode 100644 .example/os/gfile/gfile_contents.go delete mode 100644 .example/os/gfile/gfile_scan.go delete mode 100644 .example/os/gfpool/gfpool.go delete mode 100644 .example/os/gfsnotify/fsnotify.go delete mode 100644 .example/os/gfsnotify/gfsnotify.go delete mode 100644 .example/os/gfsnotify/gfsnotify_callback.go delete mode 100644 .example/os/gfsnotify/gfsnotify_callback_folder.go delete mode 100644 .example/os/gfsnotify/gfsnotify_limit.go delete mode 100644 .example/os/glog/glog_CtxKeys.go delete mode 100644 .example/os/glog/glog_SetConfigWithMap.go delete mode 100644 .example/os/glog/glog_async_chaining.go delete mode 100644 .example/os/glog/glog_async_configure.go delete mode 100644 .example/os/glog/glog_category.go delete mode 100644 .example/os/glog/glog_color.go delete mode 100644 .example/os/glog/glog_debug.go delete mode 100644 .example/os/glog/glog_error.go delete mode 100644 .example/os/glog/glog_file.go delete mode 100644 .example/os/glog/glog_flags.go delete mode 100644 .example/os/glog/glog_gerror.go delete mode 100644 .example/os/glog/glog_json.go delete mode 100644 .example/os/glog/glog_level.go delete mode 100644 .example/os/glog/glog_level_prefix.go delete mode 100644 .example/os/glog/glog_line.go delete mode 100644 .example/os/glog/glog_line2.go delete mode 100644 .example/os/glog/glog_path.go delete mode 100644 .example/os/glog/glog_pool.go delete mode 100644 .example/os/glog/glog_prefix.go delete mode 100644 .example/os/glog/glog_stack.go delete mode 100644 .example/os/glog/glog_stdout.go delete mode 100644 .example/os/glog/glog_writer_greylog.go delete mode 100644 .example/os/glog/glog_writer_hook.go delete mode 100644 .example/os/glog/handler/glog_handler_greylog.go delete mode 100644 .example/os/glog/handler/glog_handler_json.go delete mode 100644 .example/os/gmlock/1.lock&unlock.go delete mode 100644 .example/os/gmlock/2.trylock.go delete mode 100644 .example/os/gmlock/3.lock_conflicts.go delete mode 100644 .example/os/gmlock/4.test_deadlock.go delete mode 100644 .example/os/gmutex/gmutex_basic.go delete mode 100644 .example/os/gmutex/gmutex_func.go delete mode 100644 .example/os/gproc/gproc.go delete mode 100644 .example/os/gproc/gproc3.go delete mode 100644 .example/os/gproc/gproc4.go delete mode 100644 .example/os/gproc/gproc_comm.go delete mode 100644 .example/os/gproc/gproc_comm_group.go delete mode 100644 .example/os/gproc/gproc_comm_send.go delete mode 100644 .example/os/gproc/gproc_kill.go delete mode 100644 .example/os/gproc/gproc_shellexec.go delete mode 100644 .example/os/gproc/gproc_sleep.go delete mode 100644 .example/os/gproc/signal/signal_handler.go delete mode 100644 .example/os/gproc/signal/signal_handler_gproc.go delete mode 100644 .example/os/gres/gres_example.go delete mode 100644 .example/os/gres/gres_pack.go delete mode 100644 .example/os/gres/gres_unpack.go delete mode 100644 .example/os/grpool/goroutine.go delete mode 100644 .example/os/grpool/grpool.go delete mode 100644 .example/os/grpool/grpool1.go delete mode 100644 .example/os/grpool/grpool2.go delete mode 100644 .example/os/grpool/grpool3.go delete mode 100644 .example/os/grpool/grpool4.go delete mode 100644 .example/os/grpool/grpool5.go delete mode 100644 .example/os/gsession/storage-file/file.go delete mode 100644 .example/os/gsession/storage-memory/memory.go delete mode 100644 .example/os/gsession/storage-redis-hashtable/config.toml delete mode 100644 .example/os/gsession/storage-redis-hashtable/redis-hashtable.go delete mode 100644 .example/os/gsession/storage-redis/config.toml delete mode 100644 .example/os/gsession/storage-redis/redis.go delete mode 100644 .example/os/gspath/gspath.go delete mode 100644 .example/os/gtime/gtime_format.go delete mode 100644 .example/os/gtime/gtime_func.go delete mode 100644 .example/os/gtime/gtime_json.go delete mode 100644 .example/os/gtime/gtime_layout.go delete mode 100644 .example/os/gtime/gtime_linkop.go delete mode 100644 .example/os/gtime/gtime_parsertime.go delete mode 100644 .example/os/gtime/gtime_regex1.go delete mode 100644 .example/os/gtime/gtime_regex2.go delete mode 100644 .example/os/gtime/gtime_strtotime.go delete mode 100644 .example/os/gtime/gtime_strtotime2.go delete mode 100644 .example/os/gtime/gtime_zone.go delete mode 100644 .example/os/gtimer/gtimer-batch.go delete mode 100644 .example/os/gtimer/gtimer1.go delete mode 100644 .example/os/gtimer/gtimer2.go delete mode 100644 .example/os/gtimer/gtimer3.go delete mode 100644 .example/os/gtimer/gtimer4.go delete mode 100644 .example/os/gtimer/sleep1.go delete mode 100644 .example/os/gtimer/sleep2.go delete mode 100644 .example/os/gtimer/ticker1.go delete mode 100644 .example/os/gtimer/ticker2.go delete mode 100644 .example/os/gview/assign/assign.go delete mode 100644 .example/os/gview/basic/gview.go delete mode 100644 .example/os/gview/basic/gview.tpl delete mode 100644 .example/os/gview/bind_func/gview_func1.go delete mode 100644 .example/os/gview/bind_func/gview_func2.go delete mode 100644 .example/os/gview/bind_func/index.html delete mode 100644 .example/os/gview/build_in_funcs/build_in_funcs1.go delete mode 100644 .example/os/gview/build_in_funcs/build_in_funcs2.go delete mode 100644 .example/os/gview/build_in_funcs/issue359-1.go delete mode 100644 .example/os/gview/build_in_funcs/issue359-2.go delete mode 100644 .example/os/gview/define/main.go delete mode 100644 .example/os/gview/define/template/index.html delete mode 100644 .example/os/gview/define/template/subs/sub.html delete mode 100644 .example/os/gview/delimiters/gview_delimiters.go delete mode 100644 .example/os/gview/delimiters/gview_delimiters.tpl delete mode 100644 .example/os/gview/func_html/func_html.go delete mode 100644 .example/os/gview/func_text/func_text.go delete mode 100644 .example/os/gview/hot_update/controller_hot_update.go delete mode 100644 .example/os/gview/hot_update/gview_hot_update.go delete mode 100644 .example/os/gview/hot_update/web_hot_update.go delete mode 100644 .example/os/gview/i18n/i18n.go delete mode 100644 .example/os/gview/include/main.go delete mode 100644 .example/os/gview/include/template/index.html delete mode 100644 .example/os/gview/include/template/subs/sub.html delete mode 100644 .example/os/gview/layout/layout1/main.go delete mode 100644 .example/os/gview/layout/layout1/template/container.html delete mode 100644 .example/os/gview/layout/layout1/template/footer.html delete mode 100644 .example/os/gview/layout/layout1/template/header.html delete mode 100644 .example/os/gview/layout/layout1/template/layout.html delete mode 100644 .example/os/gview/layout/layout2/main.go delete mode 100644 .example/os/gview/layout/layout2/template/footer.html delete mode 100644 .example/os/gview/layout/layout2/template/header.html delete mode 100644 .example/os/gview/layout/layout2/template/layout.html delete mode 100644 .example/os/gview/layout/layout2/template/main/main1.html delete mode 100644 .example/os/gview/layout/layout2/template/main/main2.html delete mode 100644 .example/os/gview/object/object.go delete mode 100644 .example/os/gview/resource/main1.go delete mode 100644 .example/os/gview/resource/main2.go delete mode 100644 .example/os/gview/resource/main3.go delete mode 100644 .example/text/gregex/gregex.go delete mode 100644 .example/text/gstr/gstr_hidestr.go delete mode 100644 .example/text/gstr/gstr_substr.go delete mode 100644 .example/util/gconv/gconv.go delete mode 100644 .example/util/gconv/gconv_map1.go delete mode 100644 .example/util/gconv/gconv_map2.go delete mode 100644 .example/util/gconv/gconv_map_deep.go delete mode 100644 .example/util/gconv/gconv_map_tag.go delete mode 100644 .example/util/gconv/gconv_slice.go delete mode 100644 .example/util/gconv/gconv_struct1.go delete mode 100644 .example/util/gconv/gconv_struct2.go delete mode 100644 .example/util/gconv/gconv_struct4.go delete mode 100644 .example/util/gconv/gconv_struct5.go delete mode 100644 .example/util/gconv/gconv_struct6.go delete mode 100644 .example/util/gconv/gconv_struct_create.go delete mode 100644 .example/util/gconv/gconv_struct_deep.go delete mode 100644 .example/util/gconv/strings.go delete mode 100644 .example/util/gconv/time1.go delete mode 100644 .example/util/gconv/time2.go delete mode 100644 .example/util/gpage/gpage.go delete mode 100644 .example/util/gpage/gpage_ajax.go delete mode 100644 .example/util/gpage/gpage_custom1.go delete mode 100644 .example/util/gpage/gpage_custom2.go delete mode 100644 .example/util/gpage/gpage_static1.go delete mode 100644 .example/util/gpage/gpage_static2.go delete mode 100644 .example/util/gpage/gpage_template.go delete mode 100644 .example/util/grand/grand.go delete mode 100644 .example/util/grand/rand.go delete mode 100644 .example/util/guid/guid.go delete mode 100644 .example/util/guid/guid_length.go delete mode 100644 .example/util/guid/guid_unique.go delete mode 100644 .example/util/gutil/dump.go delete mode 100644 .example/util/gutil/stack.go delete mode 100644 .example/util/gutil/try_catch.go delete mode 100644 .example/util/gvalid/config.toml delete mode 100644 .example/util/gvalid/gvalid.go delete mode 100644 .example/util/gvalid/gvalid_checkstructwithdata.go delete mode 100644 .example/util/gvalid/gvalid_custom_message.go delete mode 100644 .example/util/gvalid/gvalid_error.go delete mode 100644 .example/util/gvalid/gvalid_i18n.go delete mode 100644 .example/util/gvalid/gvalid_i18n_http.go delete mode 100644 .example/util/gvalid/gvalid_result.go delete mode 100644 .example/util/gvalid/gvalid_sequence.go delete mode 100644 .example/util/gvalid/gvalid_struct1.go delete mode 100644 .example/util/gvalid/gvalid_struct2.go delete mode 100644 .example/util/gvalid/gvalid_struct3.go delete mode 100644 .example/util/gvalid/gvalid_struct_meta.go delete mode 100644 .example/util/gvalid/i18n/en.toml delete mode 100644 .example/util/gvalid/i18n/zh-CN.toml diff --git a/.example/container/garray/basic_array.go b/.example/container/garray/basic_array.go deleted file mode 100644 index 3db377d4d..000000000 --- a/.example/container/garray/basic_array.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - // Create a int array, which is concurrent-unsafe in default. - a := garray.NewIntArray() - - // Appending items. - for i := 0; i < 10; i++ { - a.Append(i) - } - - // Get the length of the array. - fmt.Println(a.Len()) - - // Get the slice of the array. - fmt.Println(a.Slice()) - - // Get the item of specified index. - fmt.Println(a.Get(6)) - - // Insert after/before specified index. - a.InsertAfter(9, 11) - a.InsertBefore(10, 10) - fmt.Println(a.Slice()) - - a.Set(0, 100) - fmt.Println(a.Slice()) - - // Searching the item and returning the index. - fmt.Println(a.Search(5)) - - // Remove item of specified index. - a.Remove(0) - fmt.Println(a.Slice()) - - // Clearing the array. - fmt.Println(a.Slice()) - a.Clear() - fmt.Println(a.Slice()) -} diff --git a/.example/container/garray/json_marshal.go b/.example/container/garray/json_marshal.go deleted file mode 100644 index 4f5859413..000000000 --- a/.example/container/garray/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - type Student struct { - Id int - Name string - Scores *garray.IntArray - } - s := Student{ - Id: 1, - Name: "john", - Scores: garray.NewIntArrayFrom([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/garray/json_unmarshal.go b/.example/container/garray/json_unmarshal.go deleted file mode 100644 index 144287a99..000000000 --- a/.example/container/garray/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id int - Name string - Scores *garray.IntArray - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/garray/sorted_array_basic.go b/.example/container/garray/sorted_array_basic.go deleted file mode 100644 index 81e0531f8..000000000 --- a/.example/container/garray/sorted_array_basic.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - // 自定义排序数组,降序排序(SortedIntArray管理的数据是升序) - a := garray.NewSortedArray(func(v1, v2 interface{}) int { - if v1.(int) < v2.(int) { - return 1 - } - if v1.(int) > v2.(int) { - return -1 - } - return 0 - }) - - // 添加数据 - a.Add(2) - a.Add(3) - a.Add(1) - fmt.Println(a.Slice()) - - // 添加重复数据 - a.Add(3) - fmt.Println(a.Slice()) - - // 检索数据,返回最后对比的索引位置,检索结果 - // 检索结果:0: 匹配; <0:参数小于对比值; >0:参数大于对比值 - fmt.Println(a.Search(1)) - - // 设置不可重复 - a.SetUnique(true) - fmt.Println(a.Slice()) - a.Add(1) - fmt.Println(a.Slice()) -} diff --git a/.example/container/garray/sorted_string_array.go b/.example/container/garray/sorted_string_array.go deleted file mode 100644 index a89de1f46..000000000 --- a/.example/container/garray/sorted_string_array.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/garray" -) - -func main() { - array := garray.NewSortedStrArray() - array.Add("9") - array.Add("8") - array.Add("7") - array.Add("6") - array.Add("5") - array.Add("4") - array.Add("3") - array.Add("2") - array.Add("1") - fmt.Println(array.Slice()) - // output: - // [1 2 3 4 5 6 7 8 9] -} diff --git a/.example/container/glist/basic.go b/.example/container/glist/basic.go deleted file mode 100644 index a904ea345..000000000 --- a/.example/container/glist/basic.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/container/glist" -) - -func main() { - l := glist.New() - // Push - l.PushBack(1) - l.PushBack(2) - e := l.PushFront(0) - // Insert - l.InsertBefore(e, -1) - l.InsertAfter(e, "a") - fmt.Println(l) - // Pop - fmt.Println(l.PopFront()) - fmt.Println(l.PopBack()) - fmt.Println(l) -} diff --git a/.example/container/glist/json_marshal.go b/.example/container/glist/json_marshal.go deleted file mode 100644 index 00cc3409b..000000000 --- a/.example/container/glist/json_marshal.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/glist" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - type Student struct { - Id int - Name string - Scores *glist.List - } - s := Student{ - Id: 1, - Name: "john", - Scores: glist.NewFrom(g.Slice{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/glist/json_unmarshal.go b/.example/container/glist/json_unmarshal.go deleted file mode 100644 index 7b03f7cff..000000000 --- a/.example/container/glist/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/glist" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id int - Name string - Scores *glist.List - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gmap/basic.go b/.example/container/gmap/basic.go deleted file mode 100644 index 4d9b5a453..000000000 --- a/.example/container/gmap/basic.go +++ /dev/null @@ -1,74 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gmap" -) - -func main() { - // 创建一个默认的gmap对象, - // 默认情况下该gmap对象不支持并发安全特性, - // 初始化时可以给定true参数开启并发安全特性,用以并发安全场景。 - m := gmap.New() - - // 设置键值对 - for i := 0; i < 10; i++ { - m.Set(i, i) - } - // 查询大小 - fmt.Println(m.Size()) - // 批量设置键值对(不同的数据类型对象参数不同) - m.Sets(map[interface{}]interface{}{ - 10: 10, - 11: 11, - }) - fmt.Println(m.Size()) - - // 查询是否存在 - fmt.Println(m.Contains(1)) - - // 查询键值 - fmt.Println(m.Get(1)) - - // 删除数据项 - m.Remove(9) - fmt.Println(m.Size()) - - // 批量删除 - m.Removes([]interface{}{10, 11}) - fmt.Println(m.Size()) - - // 当前键名列表(随机排序) - fmt.Println(m.Keys()) - // 当前键值列表(随机排序) - fmt.Println(m.Values()) - - // 查询键名,当键值不存在时,写入给定的默认值 - fmt.Println(m.GetOrSet(100, 100)) - - // 删除键值对,并返回对应的键值 - fmt.Println(m.Remove(100)) - - // 遍历map - m.Iterator(func(k interface{}, v interface{}) bool { - fmt.Printf("%v:%v ", k, v) - return true - }) - - // 自定义写锁操作 - m.LockFunc(func(m map[interface{}]interface{}) { - m[99] = 99 - }) - - // 自定义读锁操作 - m.RLockFunc(func(m map[interface{}]interface{}) { - fmt.Println(m[99]) - }) - - // 清空map - m.Clear() - - // 判断map是否为空 - fmt.Println(m.IsEmpty()) -} diff --git a/.example/container/gmap/gmap_json_marshal.go b/.example/container/gmap/gmap_json_marshal.go deleted file mode 100644 index 76ac64630..000000000 --- a/.example/container/gmap/gmap_json_marshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/container/gmap" -) - -func main() { - m := gmap.New() - m.Sets(g.MapAnyAny{ - "name": "john", - "score": 100, - }) - b, _ := json.Marshal(m) - fmt.Println(string(b)) -} diff --git a/.example/container/gmap/gmap_json_unmarshal.go b/.example/container/gmap/gmap_json_unmarshal.go deleted file mode 100644 index 7f5a9d24a..000000000 --- a/.example/container/gmap/gmap_json_unmarshal.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gmap" -) - -func main() { - m := gmap.Map{} - s := []byte(`{"name":"john","score":100}`) - json.Unmarshal(s, &m) - fmt.Println(m.Map()) -} diff --git a/.example/container/gmap/gmap_map_clone_safe.go b/.example/container/gmap/gmap_map_clone_safe.go deleted file mode 100644 index 912ea9eff..000000000 --- a/.example/container/gmap/gmap_map_clone_safe.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - m1 := gmap.New(true) - m1.Set("1", "1") - - m2 := m1.Map() - m2["2"] = "2" - - g.Dump(m1.Clone()) - g.Dump(m2) - //output: - //{ - // "1": "1" - //} - // - //{ - // "1": "1", - // "2": "2" - //} -} diff --git a/.example/container/gmap/gmap_maps.go b/.example/container/gmap/gmap_maps.go deleted file mode 100644 index 7b7267b1b..000000000 --- a/.example/container/gmap/gmap_maps.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - array := g.Slice{2, 3, 1, 5, 4, 6, 8, 7, 9} - hashMap := gmap.New() - linkMap := gmap.NewListMap() - treeMap := gmap.NewTreeMap(gutil.ComparatorInt) - for _, v := range array { - hashMap.Set(v, v) - } - for _, v := range array { - linkMap.Set(v, v) - } - for _, v := range array { - treeMap.Set(v, v) - } - fmt.Println("HashMap Keys:", hashMap.Keys()) - fmt.Println("HashMap Values:", hashMap.Values()) - fmt.Println("LinkMap Keys:", linkMap.Keys()) - fmt.Println("LinkMap Values:", linkMap.Values()) - fmt.Println("TreeMap Keys:", treeMap.Keys()) - fmt.Println("TreeMap Values:", treeMap.Values()) -} diff --git a/.example/container/gmap/gmap_treemap.go b/.example/container/gmap/gmap_treemap.go deleted file mode 100644 index d495ac336..000000000 --- a/.example/container/gmap/gmap_treemap.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gmap" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - m := gmap.NewTreeMap(gutil.ComparatorInt) - - // 设置键值对 - for i := 0; i < 10; i++ { - m.Set(i, i) - } - // 查询大小 - fmt.Println(m.Size()) - // 批量设置键值对(不同的数据类型对象参数不同) - m.Sets(map[interface{}]interface{}{ - 10: 10, - 11: 11, - }) - fmt.Println(m.Size()) - - // 查询是否存在 - fmt.Println(m.Contains(1)) - - // 查询键值 - fmt.Println(m.Get(1)) - - // 删除数据项 - m.Remove(9) - fmt.Println(m.Size()) - - // 批量删除 - m.Removes([]interface{}{10, 11}) - fmt.Println(m.Size()) - - // 当前键名列表(随机排序) - fmt.Println(m.Keys()) - // 当前键值列表(随机排序) - fmt.Println(m.Values()) - - // 查询键名,当键值不存在时,写入给定的默认值 - fmt.Println(m.GetOrSet(100, 100)) - - // 删除键值对,并返回对应的键值 - fmt.Println(m.Remove(100)) - - // 遍历map - m.IteratorAsc(func(k interface{}, v interface{}) bool { - fmt.Printf("%v:%v ", k, v) - return true - }) - fmt.Println() - - // 清空map - m.Clear() - - // 判断map是否为空 - fmt.Println(m.IsEmpty()) -} diff --git a/.example/container/gpool/gpool.go b/.example/container/gpool/gpool.go deleted file mode 100644 index a027dcba5..000000000 --- a/.example/container/gpool/gpool.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gpool" -) - -func main() { - // 创建一个对象池,过期时间为1000毫秒 - p := gpool.New(1000*time.Millisecond, nil) - - // 从池中取一个对象,返回nil及错误信息 - fmt.Println(p.Get()) - - // 丢一个对象到池中 - p.Put(1) - - // 重新从池中取一个对象,返回1 - fmt.Println(p.Get()) - - // 等待1秒后重试,发现对象已过期,返回nil及错误信息 - time.Sleep(time.Second) - fmt.Println(p.Get()) -} diff --git a/.example/container/gpool/gpool_expirefunc.go b/.example/container/gpool/gpool_expirefunc.go deleted file mode 100644 index 36ded0980..000000000 --- a/.example/container/gpool/gpool_expirefunc.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gpool" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 创建对象复用池,对象过期时间为3000毫秒,并给定创建及销毁方法 - p := gpool.New(3000*time.Millisecond, func() (interface{}, error) { - return gtcp.NewConn("www.baidu.com:80") - }, func(i interface{}) { - glog.Print("expired") - i.(*gtcp.Conn).Close() - }) - conn, err := p.Get() - if err != nil { - panic(err) - } - result, err := conn.(*gtcp.Conn).SendRecv([]byte("HEAD / HTTP/1.1\n\n"), -1) - if err != nil { - panic(err) - } - fmt.Println(string(result)) - // 丢回池中以便重复使用 - p.Put(conn) - // 等待一定时间观察过期方法调用 - time.Sleep(4 * time.Second) -} diff --git a/.example/container/gqueue/gqueue.go b/.example/container/gqueue/gqueue.go deleted file mode 100644 index 5a1474330..000000000 --- a/.example/container/gqueue/gqueue.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gqueue" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - q := gqueue.New() - // 数据生产者,每隔1秒往队列写数据 - gtimer.SetInterval(time.Second, func() { - v := gtime.Now().String() - q.Push(v) - fmt.Println("Push:", v) - }) - - // 3秒后关闭队列 - gtimer.SetTimeout(3*time.Second, func() { - q.Close() - }) - - // 消费者,不停读取队列数据并输出到终端 - for { - if v := q.Pop(); v != nil { - fmt.Println(" Pop:", v) - } else { - break - } - } -} diff --git a/.example/container/gqueue/gqueue2.go b/.example/container/gqueue/gqueue2.go deleted file mode 100644 index 6b5459c47..000000000 --- a/.example/container/gqueue/gqueue2.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gqueue" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - q := gqueue.New() - // 数据生产者,每隔1秒往队列写数据 - gtimer.SetInterval(time.Second, func() { - for i := 0; i < 10; i++ { - q.Push(i) - } - }) - - // 消费者,不停读取队列数据并输出到终端 - for { - if v := q.Pop(); v != nil { - fmt.Println(" Pop:", v) - } else { - break - } - } -} diff --git a/.example/container/gqueue/gqueue3.go b/.example/container/gqueue/gqueue3.go deleted file mode 100644 index 55c279a4c..000000000 --- a/.example/container/gqueue/gqueue3.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gqueue" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - queue := gqueue.New() - // 数据生产者,每隔1秒往队列写数据 - gtimer.SetInterval(time.Second, func() { - queue.Push(gtime.Now().String()) - }) - - // 消费者,不停读取队列数据并输出到终端 - for { - select { - case v := <-queue.C: - if v != nil { - fmt.Println(v) - } else { - return - } - } - } -} diff --git a/.example/container/gring/gring.go b/.example/container/gring/gring.go deleted file mode 100644 index 871c4b9c2..000000000 --- a/.example/container/gring/gring.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gring" -) - -func main() { - r1 := gring.New(10) - for i := 0; i < 5; i++ { - r1.Set(i).Next() - } - fmt.Println("Len:", r1.Len()) - fmt.Println("Cap:", r1.Cap()) - fmt.Println(r1.SlicePrev()) - fmt.Println(r1.SliceNext()) - - r2 := gring.New(10) - for i := 0; i < 10; i++ { - r2.Set(i).Next() - } - fmt.Println("Len:", r2.Len()) - fmt.Println("Cap:", r2.Cap()) - fmt.Println(r2.SlicePrev()) - fmt.Println(r2.SliceNext()) - -} diff --git a/.example/container/gring/gring_josephus.go b/.example/container/gring/gring_josephus.go deleted file mode 100644 index 078c31b5e..000000000 --- a/.example/container/gring/gring_josephus.go +++ /dev/null @@ -1,58 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gring" -) - -type Player struct { - position int // 位置 - alive bool // 是否存活 -} - -const ( - playerCount = 41 // 玩家人数 - startPos = 1 // 开始报数位置 -) - -var ( - deadline = 3 -) - -func main() { - // 关闭并发安全,当前场景没有必要 - r := gring.New(playerCount, false) - - // 设置所有玩家初始值 - for i := 1; i <= playerCount; i++ { - r.Put(&Player{i, true}) - } - - // 如果开始报数的位置不为1,则设置开始位置 - if startPos > 1 { - r.Move(startPos - 1) - } - - counter := 1 // 报数从1开始,因为下面的循环从第二个开始计算 - deadCount := 0 // 死亡人数,初始值为0 - - // 直到所有人都死亡,否则循环一直执行 - for deadCount < playerCount { - // 跳到下一个人 - r.Next() - - // 如果是活着的人,则报数 - if r.Val().(*Player).alive { - counter++ - } - - // 如果报数为deadline,则此人淘汰出局 - if counter == deadline { - r.Val().(*Player).alive = false - fmt.Printf("Player %d died!\n", r.Val().(*Player).position) - deadCount++ - counter = 0 - } - } -} diff --git a/.example/container/gset/gset1.go b/.example/container/gset/gset1.go deleted file mode 100644 index 2033edf3c..000000000 --- a/.example/container/gset/gset1.go +++ /dev/null @@ -1,53 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gset" -) - -func main() { - // 创建一个非并发安全的集合对象 - s := gset.New(true) - - // 添加数据项 - s.Add(1) - - // 批量添加数据项 - s.Add([]interface{}{1, 2, 3}...) - - // 集合数据项大小 - fmt.Println(s.Size()) - - // 集合中是否存在指定数据项 - fmt.Println(s.Contains(2)) - - // 返回数据项slice - fmt.Println(s.Slice()) - - // 删除数据项 - s.Remove(3) - - // 遍历数据项 - s.Iterator(func(v interface{}) bool { - fmt.Println("Iterator:", v) - return true - }) - - // 将集合转换为字符串 - fmt.Println(s.String()) - - // 并发安全写锁操作 - s.LockFunc(func(m map[interface{}]struct{}) { - m[4] = struct{}{} - }) - - // 并发安全读锁操作 - s.RLockFunc(func(m map[interface{}]struct{}) { - fmt.Println(m) - }) - - // 清空集合 - s.Clear() - fmt.Println(s.Size()) -} diff --git a/.example/container/gset/gset2.go b/.example/container/gset/gset2.go deleted file mode 100644 index 25fc11762..000000000 --- a/.example/container/gset/gset2.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gset" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s1 := gset.NewFrom(g.Slice{1, 2, 3}) - s2 := gset.NewFrom(g.Slice{4, 5, 6}) - s3 := gset.NewFrom(g.Slice{1, 2, 3, 4, 5, 6, 7}) - - // 交集 - fmt.Println(s3.Intersect(s1).Slice()) - // 差集 - fmt.Println(s3.Diff(s1).Slice()) - // 并集 - fmt.Println(s1.Union(s2).Slice()) - // 补集 - fmt.Println(s1.Complement(s3).Slice()) -} diff --git a/.example/container/gset/json_marshal.go b/.example/container/gset/json_marshal.go deleted file mode 100644 index a554f1e3b..000000000 --- a/.example/container/gset/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gset" -) - -func main() { - type Student struct { - Id int - Name string - Scores *gset.IntSet - } - s := Student{ - Id: 1, - Name: "john", - Scores: gset.NewIntSetFrom([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/gset/json_unmarshal.go b/.example/container/gset/json_unmarshal.go deleted file mode 100644 index a71208a31..000000000 --- a/.example/container/gset/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gset" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id int - Name string - Scores *gset.IntSet - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gtree/gtree_avltree.go b/.example/container/gtree/gtree_avltree.go deleted file mode 100644 index 5814212ec..000000000 --- a/.example/container/gtree/gtree_avltree.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtree" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - tree := gtree.NewAVLTree(gutil.ComparatorInt) - for i := 0; i < 10; i++ { - tree.Set(i, i*10) - } - // 打印树形 - tree.Print() - // 前序遍历 - fmt.Println("ASC:") - tree.IteratorAsc(func(key, value interface{}) bool { - fmt.Println(key, value) - return true - }) - // 后续遍历 - fmt.Println("DESC:") - tree.IteratorDesc(func(key, value interface{}) bool { - fmt.Println(key, value) - return true - }) -} diff --git a/.example/container/gtree/gtree_btree.go b/.example/container/gtree/gtree_btree.go deleted file mode 100644 index f1b04d66b..000000000 --- a/.example/container/gtree/gtree_btree.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtree" -) - -func main() { - tree := gtree.NewBTree(10, func(v1, v2 interface{}) int { - return v1.(int) - v2.(int) - }) - for i := 0; i < 20; i++ { - tree.Set(i, i*10) - } - fmt.Println(tree.String()) - - tree.IteratorDesc(func(key, value interface{}) bool { - fmt.Println(key, value) - return true - }) -} diff --git a/.example/container/gtree/gtree_redblackmap.go b/.example/container/gtree/gtree_redblackmap.go deleted file mode 100644 index 5689110a2..000000000 --- a/.example/container/gtree/gtree_redblackmap.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtree" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - m := gtree.NewRedBlackTree(gutil.ComparatorInt) - - // 设置键值对 - for i := 0; i < 10; i++ { - m.Set(i, i*10) - } - // 查询大小 - fmt.Println(m.Size()) - // 批量设置键值对(不同的数据类型对象参数不同) - m.Sets(map[interface{}]interface{}{ - 10: 10, - 11: 11, - }) - fmt.Println(m.Size()) - - // 查询是否存在 - fmt.Println(m.Contains(1)) - - // 查询键值 - fmt.Println(m.Get(1)) - - // 删除数据项 - m.Remove(9) - fmt.Println(m.Size()) - - // 批量删除 - m.Removes([]interface{}{10, 11}) - fmt.Println(m.Size()) - - // 当前键名列表(随机排序) - fmt.Println(m.Keys()) - // 当前键值列表(随机排序) - fmt.Println(m.Values()) - - // 查询键名,当键值不存在时,写入给定的默认值 - fmt.Println(m.GetOrSet(100, 100)) - - // 删除键值对,并返回对应的键值 - fmt.Println(m.Remove(100)) - - // 遍历map - m.IteratorAsc(func(k interface{}, v interface{}) bool { - fmt.Printf("%v:%v ", k, v) - return true - }) - fmt.Println() - - // 清空map - m.Clear() - - // 判断map是否为空 - fmt.Println(m.IsEmpty()) -} diff --git a/.example/container/gtree/gtree_redblacktree.go b/.example/container/gtree/gtree_redblacktree.go deleted file mode 100644 index 01bbafb69..000000000 --- a/.example/container/gtree/gtree_redblacktree.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/container/gtree" -) - -func main() { - tree := gtree.NewRedBlackTree(func(v1, v2 interface{}) int { - return v1.(int) - v2.(int) - }) - for i := 0; i < 10; i++ { - tree.Set(i, i) - } - tree.Print() - tree.Flip() - tree.Print() -} diff --git a/.example/container/gtype/gtype_int.go b/.example/container/gtype/gtype_int.go deleted file mode 100644 index ba8307290..000000000 --- a/.example/container/gtype/gtype_int.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/container/gtype" -) - -func main() { - // 创建一个Int型的并发安全基本类型对象 - i := gtype.NewInt() - - // 设置值 - i.Set(10) - - // 获取值 - fmt.Println(i.Val()) - - // (整型/浮点型有效)数值 增加/删除 delta - fmt.Println(i.Add(-1)) -} diff --git a/.example/container/gtype/json_marshal.go b/.example/container/gtype/json_marshal.go deleted file mode 100644 index e91e4d7d9..000000000 --- a/.example/container/gtype/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gtype" -) - -func main() { - type Student struct { - Id *gtype.Int - Name *gtype.String - Scores *gtype.Interface - } - s := Student{ - Id: gtype.NewInt(1), - Name: gtype.NewString("john"), - Scores: gtype.NewInterface([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/gtype/json_unmarshal.go b/.example/container/gtype/json_unmarshal.go deleted file mode 100644 index d460cfc67..000000000 --- a/.example/container/gtype/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/container/gtype" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id *gtype.Int - Name *gtype.String - Scores *gtype.Interface - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gvar/json_marshal.go b/.example/container/gvar/json_marshal.go deleted file mode 100644 index fbbb01679..000000000 --- a/.example/container/gvar/json_marshal.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - type Student struct { - Id *g.Var - Name *g.Var - Scores *g.Var - } - s := Student{ - Id: g.NewVar(1), - Name: g.NewVar("john"), - Scores: g.NewVar([]int{100, 99, 98}), - } - b, _ := json.Marshal(s) - fmt.Println(string(b)) -} diff --git a/.example/container/gvar/json_unmarshal.go b/.example/container/gvar/json_unmarshal.go deleted file mode 100644 index 2e79601e7..000000000 --- a/.example/container/gvar/json_unmarshal.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`) - type Student struct { - Id *g.Var - Name *g.Var - Scores *g.Var - } - s := Student{} - json.Unmarshal(b, &s) - fmt.Println(s) -} diff --git a/.example/container/gvar/var.go b/.example/container/gvar/var.go deleted file mode 100644 index 7752eed11..000000000 --- a/.example/container/gvar/var.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var v g.Var - - v.Set("123") - - fmt.Println(v.Val()) - - // 基本类型转换 - fmt.Println(v.Int()) - fmt.Println(v.Uint()) - fmt.Println(v.Float64()) - - // slice转换 - fmt.Println(v.Ints()) - fmt.Println(v.Floats()) - fmt.Println(v.Strings()) - - // struct转换 - type Score struct { - Value int - } - s := new(Score) - v.Struct(s) - fmt.Println(s) -} diff --git a/.example/database/gdb/driver/driver/driver.go b/.example/database/gdb/driver/driver/driver.go deleted file mode 100644 index 9350832c1..000000000 --- a/.example/database/gdb/driver/driver/driver.go +++ /dev/null @@ -1,71 +0,0 @@ -package driver - -import ( - "context" - "database/sql" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/os/gtime" -) - -// MyDriver is a custom database driver, which is used for testing only. -// For simplifying the unit testing case purpose, MyDriver struct inherits the mysql driver -// gdb.DriverMysql and overwrites its functions DoQuery and DoExec. -// So if there's any sql execution, it goes through MyDriver.DoQuery/MyDriver.DoExec firstly -// and then gdb.DriverMysql.DoQuery/gdb.DriverMysql.DoExec. -// You can call it sql "HOOK" or "HiJack" as your will. -type MyDriver struct { - *gdb.DriverMysql -} - -var ( - // customDriverName is my driver name, which is used for registering. - customDriverName = "MyDriver" -) - -func init() { - // It here registers my custom driver in package initialization function "init". - // You can later use this type in the database configuration. - if err := gdb.Register(customDriverName, &MyDriver{}); err != nil { - panic(err) - } -} - -// New creates and returns a database object for mysql. -// It implements the interface of gdb.Driver for extra database driver installation. -func (d *MyDriver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) { - return &MyDriver{ - &gdb.DriverMysql{ - Core: core, - }, - }, nil -} - -// DoQuery commits the sql string and its arguments to underlying driver -// through given link object and returns the execution result. -func (d *MyDriver) DoQuery(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (rows *sql.Rows, err error) { - tsMilli := gtime.TimestampMilli() - rows, err = d.DriverMysql.DoQuery(ctx, link, sql, args...) - link.Exec( - "INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)", - gdb.FormatSqlWithArgs(sql, args), - gtime.TimestampMilli()-tsMilli, - gtime.Now(), - err, - ) - return -} - -// DoExec commits the query string and its arguments to underlying driver -// through given link object and returns the execution result. -func (d *MyDriver) DoExec(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (result sql.Result, err error) { - tsMilli := gtime.TimestampMilli() - result, err = d.DriverMysql.DoExec(ctx, link, sql, args...) - link.Exec( - "INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)", - gdb.FormatSqlWithArgs(sql, args), - gtime.TimestampMilli()-tsMilli, - gtime.Now(), - err, - ) - return -} diff --git a/.example/database/gdb/driver/main.go b/.example/database/gdb/driver/main.go deleted file mode 100644 index 06ab7d0f9..000000000 --- a/.example/database/gdb/driver/main.go +++ /dev/null @@ -1 +0,0 @@ -package main diff --git a/.example/database/gdb/mssql/config.toml b/.example/database/gdb/mssql/config.toml deleted file mode 100644 index a57e9aa78..000000000 --- a/.example/database/gdb/mssql/config.toml +++ /dev/null @@ -1,3 +0,0 @@ - -[database] - linkinfo = "mssql:user id=test;password=test1;server=122.152.202.91;port=1433;database=test;encrypt=disable" \ No newline at end of file diff --git a/.example/database/gdb/mssql/gdb_all.go b/.example/database/gdb/mssql/gdb_all.go deleted file mode 100644 index 396099c6a..000000000 --- a/.example/database/gdb/mssql/gdb_all.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gtime" - - //_ "github.com/denisenkom/go-mssqldb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - type Table2 struct { - Id string `orm:"id;pr" json:"id"` //ID - CreateTime gtime.Time `orm:"createtime" json:"createtime"` //创建时间 - UpdateTime gtime.Time `orm:"updatetime" json:"updatetime"` //更新时间 - } - var table2 Table2 - err := g.DB().Model("table2").Where("id", 1).Scan(&table2) - if err != nil { - panic(err) - } - fmt.Println(table2.CreateTime) -} diff --git a/.example/database/gdb/mssql/gdb_sqlserver.go b/.example/database/gdb/mssql/gdb_sqlserver.go deleted file mode 100644 index 1281f0e08..000000000 --- a/.example/database/gdb/mssql/gdb_sqlserver.go +++ /dev/null @@ -1,565 +0,0 @@ -package main - -import ( - "fmt" - "time" - - //_ "github.com/denisenkom/go-mssqldb" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -// 本文件用于gf框架的mssql数据库操作示例,不作为单元测试使用 - -var db gdb.DB - -// 初始化配置及创建数据库 -func init() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "1433", - User: "sa", - Pass: "123456", - Name: "test", - Type: "mssql", - Role: "master", - Charset: "utf8", - }) - db, _ = gdb.New() - - //gins.Config().SetPath("/home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/frame") - //db = g.Database() - - //gdb.SetConfig(gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : 3306, - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - //}) - //db, _ = gdb.Instance() - - //gdb.SetConfig(gdb.Config { - // "default" : gdb.ConfigGroup { - // gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.2", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.3", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.4", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // }, - //}) - //db, _ = gdb.Instance() -} - -// 创建测试数据库 -func create() error { - fmt.Println("drop table aa_user:") - _, err := db.Exec("drop table aa_user") - if err != nil { - fmt.Println("drop table aa_user error.", err) - } - - s := ` - CREATE TABLE aa_user ( - id int not null, - name VARCHAR(60), - age int, - addr varchar(60), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table aa_user:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table error.", err) - return err - } - - /*_, err = db.Exec("drop sequence id_seq") - if err != nil { - fmt.Println("drop sequence id_seq", err) - } - - fmt.Println("create sequence id_seq") - _, err = db.Exec("create sequence id_seq increment by 1 start with 1 maxvalue 9999999999 cycle cache 10") - if err != nil { - fmt.Println("create sequence id_seq error.", err) - return err - } - - s = ` - CREATE TRIGGER id_trigger before insert on aa_user for each row - begin - select id_seq.nextval into :new.id from dual; - end; - ` - _, err = db.Exec(s) - if err != nil { - fmt.Println("create trigger error.", err) - return err - }*/ - - _, err = db.Exec("drop table user_detail") - if err != nil { - fmt.Println("drop table user_detail", err) - } - - s = ` - CREATE TABLE user_detail ( - id int not null, - site VARCHAR(255), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table user_detail:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table user_detail error.", err) - return err - } - fmt.Println("create table success.") - return nil -} - -// 数据写入 -func insert(id int) { - fmt.Println("insert:") - r, err := db.Insert("aa_user", gdb.Map{ - "id": id, - "name": "john", - "age": id, - }) - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - if err == nil { - r, err = db.Insert("user_detail", gdb.Map{ - "id": id, - "site": "http://johng.cn", - }) - if err == nil { - fmt.Printf("id: %d\n", id) - } else { - fmt.Println(err) - } - - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 基本sql查询 -func query() { - fmt.Println("query:") - list, err := db.GetAll("select * from aa_user where 1=1") - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - - list, err = db.Table("aa_user").OrderBy("id").Limit(0, 5).Select() - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// replace into -func replace() { - fmt.Println("replace:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据保存 -func save() { - fmt.Println("save:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 批量写入 -func batchInsert() { - fmt.Println("batchInsert:") - _, err := db.BatchInsert("aa_user", gdb.List{ - {"id": 11, "name": "batchInsert_john_1", "age": 11}, - {"id": 12, "name": "batchInsert_john_2", "age": 12}, - {"id": 13, "name": "batchInsert_john_3", "age": 13}, - {"id": 14, "name": "batchInsert_john_4", "age": 14}, - }, 10) - if err != nil { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update1() { - fmt.Println("update1:") - r, err := db.Update("aa_user", gdb.Map{"name": "john1", "age": 1}, "id=?", 1) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update2() { - fmt.Println("update2:") - r, err := db.Update("aa_user", gdb.Map{"name": "john6", "age": 6}, "id=?", 2) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update3() { - fmt.Println("update3:") - r, err := db.Update("aa_user", "name=?", "id=?", "john2", 3) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作1 -func linkopSelect1() { - fmt.Println("linkopSelect1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*, ud.site").Where("u.id > ?", 1).Limit(3, 5).Select() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作2 -func linkopSelect2() { - fmt.Println("linkopSelect2:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*,ud.site").Where("u.id=?", 1).One() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作3 -func linkopSelect3() { - fmt.Println("linkopSelect3:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("ud.site").Where("u.id=?", 1).Value() - if err == nil { - fmt.Println(r.String()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询数量1 -func linkopCount1() { - fmt.Println("linkopCount1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Where("name like ?", "john").Count() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 错误操作 -func linkopUpdate1() { - fmt.Println("linkopUpdate1:") - r, err := db.Table("henghe_setting").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println("error", err) - } - fmt.Println() -} - -// 通过Map指针方式传参方式 -func linkopUpdate2() { - fmt.Println("linkopUpdate2:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john2"}).Where("name=?", "john").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 通过字符串方式传参 -func linkopUpdate3() { - fmt.Println("linkopUpdate3:") - r, err := db.Table("aa_user").Data("name='john3'").Where("name=?", "john2").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// Where条件使用Map -func linkopUpdate4() { - fmt.Println("linkopUpdate4:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john11111"}).Where(g.Map{"id": 1}).Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入 -func linkopBatchInsert1() { - fmt.Println("linkopBatchInsert1:") - r, err := db.Table("aa_user").Filter().Data(gdb.List{ - {"id": 21, "name": "linkopBatchInsert1_john_1", "amt": 21.21, "tt": "haha"}, - {"id": 22, "name": "linkopBatchInsert1_john_2", "amt": 22.22, "cc": "hahacc"}, - {"id": 23, "name": "linkopBatchInsert1_john_3", "amt": 23.23, "bb": "hahabb"}, - {"id": 24, "name": "linkopBatchInsert1_john_4", "amt": 24.24, "aa": "hahaaa"}, - }).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入,指定每批次写入的条数 -func linkopBatchInsert2() { - fmt.Println("linkopBatchInsert2:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 25, "name": "linkopBatchInsert2john_1"}, - {"id": 26, "name": "linkopBatchInsert2john_2"}, - {"id": 27, "name": "linkopBatchInsert2john_3"}, - {"id": 28, "name": "linkopBatchInsert2john_4"}, - }).Batch(2).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量保存 -func linkopBatchSave() { - fmt.Println("linkopBatchSave:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 1, "name": "john_1"}, - {"id": 2, "name": "john_2"}, - {"id": 3, "name": "john_3"}, - {"id": 4, "name": "john_4"}, - }).Save() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 事务操作示例1 -func transaction1() { - fmt.Println("transaction1:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Insert("aa_user", gdb.Map{ - "id": 30, - "name": "transaction1", - }) - tx.Rollback() - fmt.Println(r, err) - } - fmt.Println() -} - -// 事务操作示例2 -func transaction2() { - fmt.Println("transaction2:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Table("user_detail").Data(gdb.Map{"id": 6, "site": "www.baidu.com哈哈哈*?''\"~!@#$%^&*()"}).Insert() - tx.Commit() - fmt.Println(r, err) - } - fmt.Println() -} - -// 主从io复用测试,在mysql中使用 show full processlist 查看链接信息 -func keepPing() { - fmt.Println("keepPing:") - for i := 0; i < 30; i++ { - fmt.Println("ping...", i) - err := db.PingMaster() - if err != nil { - fmt.Println(err) - return - } - err = db.PingSlave() - if err != nil { - fmt.Println(err) - return - } - time.Sleep(1 * time.Second) - } -} - -// like语句查询 -func likeQuery() { - fmt.Println("likeQuery:") - if r, err := db.Table("aa_user").Where("name like ?", "%john%").Select(); err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } -} - -// mapToStruct -func mapToStruct() { - type User struct { - Id int - Name string - Age int - Addr string - } - fmt.Println("mapToStruct:") - if r, err := db.Table("aa_user").Where("id=?", 1).One(); err == nil { - u := User{} - if err := r.ToStruct(&u); err == nil { - fmt.Println(r) - fmt.Println(u) - } else { - fmt.Println(err) - } - } else { - fmt.Println(err) - } -} - -func main() { - - db.PingMaster() - db.SetDebug(true) - /*err := create() - if err != nil { - return - }*/ - - //test1 - /*for i := 1; i < 5; i++ { - insert(i) - }*/ - //insert(2) - //query() - - //batchInsert() - //query() - - //replace() - //save() - - /*update1() - update2() - update3() - */ - - /*linkopSelect1() - linkopSelect2() - linkopSelect3() - linkopCount1() - */ - - /*linkopUpdate1() - linkopUpdate2() - linkopUpdate3() - linkopUpdate4() - */ - - linkopBatchInsert1() - query() - //linkopBatchInsert2() - - //transaction1() - //transaction2() - // - //keepPing() - //likeQuery() - //mapToStruct() - //getQueriedSqls() -} diff --git a/.example/database/gdb/mysql/config.toml b/.example/database/gdb/mysql/config.toml deleted file mode 100644 index 0ea384859..000000000 --- a/.example/database/gdb/mysql/config.toml +++ /dev/null @@ -1,26 +0,0 @@ - -# MySQL. -[database] - [database.logger] - Level = "all" - Stdout = true - CtxKeys = ["RequestId"] - [database.default] - link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test" - debug = true - -# Redis. -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" - -#[database] -# [[database.default]] -# type = "mysql" -# link = "root:12345678@tcp(127.0.0.1:3306)/test?parseTime=true&loc=Local" -# - - - - - diff --git a/.example/database/gdb/mysql/config/gdb.go b/.example/database/gdb/mysql/config/gdb.go deleted file mode 100644 index 3dcb15ddd..000000000 --- a/.example/database/gdb/mysql/config/gdb.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/os/gctx" - "sync" - "time" -) - -var db gdb.DB - -func init() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - MaxOpenConnCount: 100, - }) - db, _ = gdb.New() -} - -func main() { - var ( - wg = sync.WaitGroup{} - ctx = gctx.New() - ) - for i := 0; i < 100000; i++ { - wg.Add(1) - go func() { - defer wg.Done() - time.Sleep(10 * time.Second) - db.Ctx(ctx).Model("user").Where("id=1").All() - }() - } - wg.Wait() -} diff --git a/.example/database/gdb/mysql/config2.toml b/.example/database/gdb/mysql/config2.toml deleted file mode 100644 index 8722ede8c..000000000 --- a/.example/database/gdb/mysql/config2.toml +++ /dev/null @@ -1,4 +0,0 @@ - -# MySQL数据库配置 -[database] - link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test" diff --git a/.example/database/gdb/mysql/config3.toml b/.example/database/gdb/mysql/config3.toml deleted file mode 100644 index ce3512864..000000000 --- a/.example/database/gdb/mysql/config3.toml +++ /dev/null @@ -1,7 +0,0 @@ - -# MySQL数据库配置 -[database] - [database.default] - link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test" - [database.user] - link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test" \ No newline at end of file diff --git a/.example/database/gdb/mysql/gdb_all.go b/.example/database/gdb/mysql/gdb_all.go deleted file mode 100644 index 38c5e3409..000000000 --- a/.example/database/gdb/mysql/gdb_all.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - r, e := db.Ctx(ctx).GetAll("SELECT * from `user` where id in(?)", g.Slice{}) - if e != nil { - fmt.Println(e) - } - if r != nil { - fmt.Println(r) - } -} diff --git a/.example/database/gdb/mysql/gdb_args_slice.go b/.example/database/gdb/mysql/gdb_args_slice.go deleted file mode 100644 index 88496f345..000000000 --- a/.example/database/gdb/mysql/gdb_args_slice.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - - db.Ctx(ctx).Model("user"). - Where("nickname like ? and passport like ?", g.Slice{"T3", "t3"}). - OrderAsc("id").All() - - conditions := g.Map{ - "nickname like ?": "%T%", - "id between ? and ?": g.Slice{1, 3}, - "id >= ?": 1, - "create_time > ?": 0, - "id in(?)": g.Slice{1, 2, 3}, - } - db.Ctx(ctx).Model("user").Where(conditions).OrderAsc("id").All() - - var params []interface{} - db.Ctx(ctx).Model("user").Where("1=1", params).OrderAsc("id").All() -} diff --git a/.example/database/gdb/mysql/gdb_batch_insert.go b/.example/database/gdb/mysql/gdb_batch_insert.go deleted file mode 100644 index cdc2e7b36..000000000 --- a/.example/database/gdb/mysql/gdb_batch_insert.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - list := make(g.List, 0) - for i := 0; i < 100; i++ { - list = append(list, g.Map{ - "name": fmt.Sprintf(`name_%d`, i), - }) - } - r, e := db.Ctx(ctx).Model("user").Data(list).Batch(2).Insert() - if e != nil { - panic(e) - } - if r != nil { - fmt.Println(r.LastInsertId()) - } -} diff --git a/.example/database/gdb/mysql/gdb_binary.go b/.example/database/gdb/mysql/gdb_binary.go deleted file mode 100644 index e0f0b4f6b..000000000 --- a/.example/database/gdb/mysql/gdb_binary.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/crypto/gaes" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "123456", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - var ( - ctx = gctx.New() - ) - db, err := gdb.New() - if err != nil { - panic(err) - } - - key := "0123456789123456" - - name := "john" - encryptedName, err := gaes.Encrypt([]byte(name), []byte(key)) - if err != nil { - fmt.Println(err) - } - - // 写入 - r, err := db.Ctx(ctx).Model("user").Data(g.Map{ - "uid": 1, - "name": encryptedName, - }).Save() - if err != nil { - fmt.Println(err) - } - fmt.Println(r.RowsAffected()) - - // 查询 - one, err := db.Ctx(ctx).Model("user").Where("name=?", encryptedName).One() - if err != nil { - fmt.Println(err) - } - fmt.Println(one.Map()) -} diff --git a/.example/database/gdb/mysql/gdb_bit.go b/.example/database/gdb/mysql/gdb_bit.go deleted file mode 100644 index f08133af1..000000000 --- a/.example/database/gdb/mysql/gdb_bit.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - r, e := db.Ctx(ctx).Model("test").All() - if e != nil { - panic(e) - } - if r != nil { - fmt.Println(r.List()) - } -} diff --git a/.example/database/gdb/mysql/gdb_cache.go b/.example/database/gdb/mysql/gdb_cache.go deleted file mode 100644 index 35583865b..000000000 --- a/.example/database/gdb/mysql/gdb_cache.go +++ /dev/null @@ -1,44 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/util/gutil" - "time" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - var ( - ctx = gctx.New() - ) - db, err := gdb.New() - if err != nil { - panic(err) - } - //db.GetCache().SetAdapter(adapter.NewRedis(g.Redis())) - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - // 执行2次查询并将查询结果缓存3秒,并可执行缓存名称(可选) - for i := 0; i < 3; i++ { - r, _ := db.Ctx(ctx).Model("user").Cache(3000*time.Second).Where("id=?", 1).One() - gutil.Dump(r.Map()) - } - - // 执行更新操作,并清理指定名称的查询缓存 - //db.Table("user").Cache(-1, "vip-user").Data(gdb.Map{"name": "smith"}).Where("id=?", 1).Update() - - // 再次执行查询,启用查询缓存特性 - //r, _ := db.Table("user").Cache(300000*time.Second, "vip-user").Where("id=?", 1).One() - //gutil.Dump(r.Map()) -} diff --git a/.example/database/gdb/mysql/gdb_complecated.go b/.example/database/gdb/mysql/gdb_complecated.go deleted file mode 100644 index b8af08994..000000000 --- a/.example/database/gdb/mysql/gdb_complecated.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - // error! - r, err := g.DB().Model("user").Where(g.Map{ - "or": g.Map{ - "nickname": "jim", - "create_time > ": "2019-10-01", - }, - "and": g.Map{ - "nickname": "tom", - "create_time > ": "2019-10-01", - }, - }).All() - if err != nil { - panic(err) - } - g.Dump(r) - -} diff --git a/.example/database/gdb/mysql/gdb_config.go b/.example/database/gdb/mysql/gdb_config.go deleted file mode 100644 index 9e0efa73d..000000000 --- a/.example/database/gdb/mysql/gdb_config.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil { - fmt.Println(r["uid"].Int()) - fmt.Println(r["name"].String()) - } else { - fmt.Println(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_config2.go b/.example/database/gdb/mysql/gdb_config2.go deleted file mode 100644 index 15120d2d0..000000000 --- a/.example/database/gdb/mysql/gdb_config2.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Config().SetFileName("config2.toml") - if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil { - fmt.Println(r["uid"].Int()) - fmt.Println(r["name"].String()) - } else { - fmt.Println(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_config3.go b/.example/database/gdb/mysql/gdb_config3.go deleted file mode 100644 index 960c34a24..000000000 --- a/.example/database/gdb/mysql/gdb_config3.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Config().SetFileName("config3.toml") - if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil { - fmt.Println(r["uid"].Int()) - fmt.Println(r["name"].String()) - } else { - fmt.Println(err) - } - - if r, err := g.DB("user").Model("user").Where("uid=?", 1).One(); err == nil { - fmt.Println(r["uid"].Int()) - fmt.Println(r["name"].String()) - } else { - fmt.Println(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_ctx.go b/.example/database/gdb/mysql/gdb_ctx.go deleted file mode 100644 index a27edc2f9..000000000 --- a/.example/database/gdb/mysql/gdb_ctx.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - ctx := context.WithValue(context.Background(), "RequestId", "123456789") - _, err := g.DB().Ctx(ctx).Query("SELECT 1") - if err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_ctx_model.go b/.example/database/gdb/mysql/gdb_ctx_model.go deleted file mode 100644 index 3d8796f9a..000000000 --- a/.example/database/gdb/mysql/gdb_ctx_model.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - ctx := context.WithValue(context.Background(), "RequestId", "123456789") - _, err := g.DB().Model("user").Ctx(ctx).All() - if err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_datetime.go b/.example/database/gdb/mysql/gdb_datetime.go deleted file mode 100644 index 317316ec3..000000000 --- a/.example/database/gdb/mysql/gdb_datetime.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - r, err := db.Ctx(ctx).Model("user").Data(g.Map{ - "name": "john", - "create_time": gtime.Now().String(), - }).Insert() - if err == nil { - fmt.Println(r.LastInsertId()) - } else { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_debug1.go b/.example/database/gdb/mysql/gdb_debug1.go deleted file mode 100644 index 8eaa2e49d..000000000 --- a/.example/database/gdb/mysql/gdb_debug1.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - var ( - ctx = gctx.New() - ) - db, err := gdb.New() - if err != nil { - panic(err) - } - //db.SetDebug(false) - - glog.SetPath("/tmp") - - // 执行3条SQL查询 - for i := 1; i <= 3; i++ { - db.Ctx(ctx).Model("user").Where("uid=?", i).One() - } - // 构造一条错误查询 - db.Model("user").Where("no_such_field=?", "just_test").One() - - db.Ctx(ctx).Model("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save() - -} diff --git a/.example/database/gdb/mysql/gdb_debug2.go b/.example/database/gdb/mysql/gdb_debug2.go deleted file mode 100644 index 0ab81ac21..000000000 --- a/.example/database/gdb/mysql/gdb_debug2.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - - // 执行3条SQL查询 - for i := 1; i <= 3; i++ { - db.Ctx(ctx).Model("user").Where("id=?", i).One() - } - // 构造一条错误查询 - db.Ctx(ctx).Model("user").Where("no_such_field=?", "just_test").One() - - db.Ctx(ctx).Model("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save() -} diff --git a/.example/database/gdb/mysql/gdb_distinct.go b/.example/database/gdb/mysql/gdb_distinct.go deleted file mode 100644 index c043102e9..000000000 --- a/.example/database/gdb/mysql/gdb_distinct.go +++ /dev/null @@ -1,9 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.DB().Model("user").Distinct().CountColumn("uid,name") -} diff --git a/.example/database/gdb/mysql/gdb_insert.go b/.example/database/gdb/mysql/gdb_insert.go deleted file mode 100644 index a8a3f1bbd..000000000 --- a/.example/database/gdb/mysql/gdb_insert.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - //db := g.DB() - - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Link: "root:12345678@tcp(127.0.0.1:3306)/test?parseTime=true&loc=Local", - Type: "mysql", - Charset: "utf8", - }) - db, _ := gdb.New() - - db.SetDebug(true) - - r, e := db.Model("user").Data(g.Map{ - "create_at": "now()", - }).Unscoped().Insert() - if e != nil { - panic(e) - } - if r != nil { - fmt.Println(r.LastInsertId()) - } -} diff --git a/.example/database/gdb/mysql/gdb_issue_278.go b/.example/database/gdb/mysql/gdb_issue_278.go deleted file mode 100644 index 4bcb82ffa..000000000 --- a/.example/database/gdb/mysql/gdb_issue_278.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -var ( - tableName = "orders" - dao = g.DB().Model(tableName).Safe() -) - -type OrderServiceEntity struct { - GoodsPrice float64 `json:"goods_price" gvalid:"required"` - PayTo int8 `json:"payTo" gvalid:"required"` - PayStatus int8 `json:"payStatus" ` - CreateTime string `json:"createTime" ` - AppId string `json:"appId" gvalid:"required"` - PayUser string `json:"pay_user" gvalid:"required"` - QrUrl string `json:"qr_url" ` -} - -type Create struct { - Id int64 `json:"id" gconv:"id"` - GoodsPrice float64 `json:"goodsPrice" gconv:"goods_price"` - PayTo int8 `json:"payTo" gconv:"pay_to"` - PayStatus int8 `json:"payStatus" gconv:"pay_status"` - CreateTime string `json:"createTime" gconv:"create_time"` - UserId int `json:"user_id" ` - PayUser string `json:"pay_user" ` - QrUrl string `json:"qr_url" ` -} - -func main() { - g.DB().SetDebug(true) - userInfo := Create{ - Id: 3, - } - orderService := OrderServiceEntity{ - GoodsPrice: 0.1, - PayTo: 1, - } - size, err := dao.Where("user_id", userInfo.Id). - And("goods_price", float64(100.10)). - And("pay_status", 0). - And("pay_to", orderService.PayTo).Count() - fmt.Println(err) - fmt.Println(size) -} diff --git a/.example/database/gdb/mysql/gdb_json_xml.go b/.example/database/gdb/mysql/gdb_json_xml.go deleted file mode 100644 index ec986e321..000000000 --- a/.example/database/gdb/mysql/gdb_json_xml.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/os/gctx" - - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "127.0.0.1", - Port: "3306", - User: "root", - Pass: "12345678", - Name: "test", - Type: "mysql", - Role: "master", - Charset: "utf8", - }) - var ( - db = g.DB() - ctx = gctx.New() - ) - one, err := db.Ctx(ctx).Model("user").Where("id=?", 1).One() - if err != nil { - panic(err) - } - - // 使用内置方法转换为json/xml - fmt.Println(one.Json()) - fmt.Println(one.Xml()) - - // 自定义方法方法转换为json/xml - jsonContent, _ := gjson.New(one.Map()).ToJson() - fmt.Println(string(jsonContent)) - xmlContent, _ := gjson.New(one.Map()).ToJson() - fmt.Println(string(xmlContent)) -} diff --git a/.example/database/gdb/mysql/gdb_pool.go b/.example/database/gdb/mysql/gdb_pool.go deleted file mode 100644 index 1ef261186..000000000 --- a/.example/database/gdb/mysql/gdb_pool.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gctx" - "time" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - for { - for i := 0; i < 10; i++ { - go db.Ctx(ctx).Model("user").All() - } - time.Sleep(time.Millisecond * 100) - } - -} diff --git a/.example/database/gdb/mysql/gdb_reconnect.go b/.example/database/gdb/mysql/gdb_reconnect.go deleted file mode 100644 index 4ae644c99..000000000 --- a/.example/database/gdb/mysql/gdb_reconnect.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" - "time" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - for { - r, err := db.Ctx(ctx).Model("user").All() - fmt.Println(err) - fmt.Println(r) - time.Sleep(time.Second * 10) - } -} diff --git a/.example/database/gdb/mysql/gdb_struct.go b/.example/database/gdb/mysql/gdb_struct.go deleted file mode 100644 index 5c1f421c8..000000000 --- a/.example/database/gdb/mysql/gdb_struct.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - db := g.DB() - // 开启调试模式,以便于记录所有执行的SQL - db.SetDebug(true) - - type User struct { - Uid int - Name string - } - user := (*User)(nil) - fmt.Println(user) - err := db.Model("test").Where("id=1").Scan(&user) - fmt.Println(err) - fmt.Println(user) -} diff --git a/.example/database/gdb/mysql/gdb_tables.go b/.example/database/gdb/mysql/gdb_tables.go deleted file mode 100644 index f179183c5..000000000 --- a/.example/database/gdb/mysql/gdb_tables.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - tables, err := db.Tables(ctx) - if err != nil { - panic(err) - } - if tables != nil { - g.Dump(tables) - } -} diff --git a/.example/database/gdb/mysql/gdb_tables_fields.go b/.example/database/gdb/mysql/gdb_tables_fields.go deleted file mode 100644 index 96dff35ba..000000000 --- a/.example/database/gdb/mysql/gdb_tables_fields.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - db = g.DB() - ctx = gctx.New() - ) - db.SetDebug(true) - - tables, e := db.Tables(ctx) - if e != nil { - panic(e) - } - if tables != nil { - g.Dump(tables) - for _, table := range tables { - fields, err := db.TableFields(ctx, table) - if err != nil { - panic(err) - } - g.Dump(fields) - } - } -} diff --git a/.example/database/gdb/mysql/gdb_transaction.go b/.example/database/gdb/mysql/gdb_transaction.go deleted file mode 100644 index a181829f4..000000000 --- a/.example/database/gdb/mysql/gdb_transaction.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - db = g.DB() - table = "user" - ) - tx, err := db.Begin() - if err != nil { - panic(err) - } - if err = tx.Begin(); err != nil { - panic(err) - } - _, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert() - if err = tx.Rollback(); err != nil { - panic(err) - } - _, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert() - if err = tx.Commit(); err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_transaction_closure.go b/.example/database/gdb/mysql/gdb_transaction_closure.go deleted file mode 100644 index 9c39a7db0..000000000 --- a/.example/database/gdb/mysql/gdb_transaction_closure.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - err error - db = g.DB() - ctx = gctx.New() - table = "user" - ) - if err = db.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error { - // Nested transaction 1. - if err = tx.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error { - _, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert() - return err - }); err != nil { - return err - } - // Nested transaction 2, panic. - if err = tx.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error { - _, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert() - // Create a panic that can make this transaction rollback automatically. - panic("error") - }); err != nil { - return err - } - return nil - }); err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_transaction_savepoint.go b/.example/database/gdb/mysql/gdb_transaction_savepoint.go deleted file mode 100644 index 13eba5d0b..000000000 --- a/.example/database/gdb/mysql/gdb_transaction_savepoint.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - var ( - err error - db = g.DB() - table = "user" - ) - tx, err := db.Begin() - if err != nil { - panic(err) - } - defer func() { - if err := recover(); err != nil { - _ = tx.Rollback() - } - }() - if _, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert(); err != nil { - panic(err) - } - if err = tx.SavePoint("MyPoint"); err != nil { - panic(err) - } - if _, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert(); err != nil { - panic(err) - } - if _, err = tx.Model(table).Data(g.Map{"id": 3, "name": "green"}).Insert(); err != nil { - panic(err) - } - if err = tx.RollbackTo("MyPoint"); err != nil { - panic(err) - } - if err = tx.Commit(); err != nil { - panic(err) - } -} diff --git a/.example/database/gdb/mysql/gdb_update_field.go b/.example/database/gdb/mysql/gdb_update_field.go deleted file mode 100644 index e653469f0..000000000 --- a/.example/database/gdb/mysql/gdb_update_field.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "database/sql" - - "github.com/gogf/gf/v2/os/gfile" - - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - db := g.DB() - table := "medicine_clinics_upload_yinchuan" - list, err := db.Model(table).All() - if err != nil && err != sql.ErrNoRows { - panic(err) - } - content := "" - for _, item := range list { - if j, err := gjson.DecodeToJson(item["upload_data"].String()); err != nil { - panic(err) - } else { - s, _ := j.ToJsonIndentString() - content += item["id"].String() + "\t" + item["medicine_clinic_id"].String() + "\t" - content += s - content += "\n\n" - //if _, err := db.Table(table).Data("data_decode", s).Where("id", item["id"].Int()).Update(); err != nil { - // panic(err) - //} - } - } - gfile.PutContents("/Users/john/Temp/medicine_clinics_upload_yinchuan.txt", content) -} diff --git a/.example/database/gdb/mysql/gdb_update_union.go b/.example/database/gdb/mysql/gdb_update_union.go deleted file mode 100644 index edacbdbe7..000000000 --- a/.example/database/gdb/mysql/gdb_update_union.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - db := g.DB() - db.SetDebug(true) - result, err := db.Model("pw_passageway m,pw_template t").Data("t.status", 99).Where("m.templateId=t.id AND m.status = 0").Update() - if err != nil { - panic(err) - } - fmt.Println(result.RowsAffected()) -} diff --git a/.example/database/gdb/mysql/gdb_value.go b/.example/database/gdb/mysql/gdb_value.go deleted file mode 100644 index aace6c5b2..000000000 --- a/.example/database/gdb/mysql/gdb_value.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - one, err := g.Model("carlist c"). - LeftJoin("cardetail d", "c.postid=d.carid"). - Where("c.postid", "142039140032006"). - Fields("c.*,d.*").One() - fmt.Println(err) - g.Dump(one) -} diff --git a/.example/database/gdb/mysql/gdb_with_insert.go b/.example/database/gdb/mysql/gdb_with_insert.go deleted file mode 100644 index 79e8e3d86..000000000 --- a/.example/database/gdb/mysql/gdb_with_insert.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gctx" - "github.com/gogf/gf/v2/util/gmeta" -) - -func main() { - type UserDetail struct { - gmeta.Meta `orm:"table:user_detail"` - Uid int `json:"uid"` - Address string `json:"address"` - } - - type UserScore struct { - gmeta.Meta `orm:"table:user_score"` - Id int `json:"id"` - Uid int `json:"uid"` - Score int `json:"score"` - } - - type User struct { - gmeta.Meta `orm:"table:user"` - Id int `json:"id"` - Name string `json:"name"` - UserDetail *UserDetail `orm:"with:uid=id"` - UserScores []*UserScore `orm:"with:uid=id"` - } - - db := g.DB() - err := db.Transaction(gctx.New(), func(ctx context.Context, tx *gdb.TX) error { - for i := 1; i <= 5; i++ { - // User. - user := User{ - Name: fmt.Sprintf(`name_%d`, i), - } - lastInsertId, err := db.Ctx(ctx).Model(user).Data(user).OmitEmpty().InsertAndGetId() - if err != nil { - return err - } - // Detail. - userDetail := UserDetail{ - Uid: int(lastInsertId), - Address: fmt.Sprintf(`address_%d`, lastInsertId), - } - _, err = db.Ctx(ctx).Model(userDetail).Data(userDetail).OmitEmpty().Insert() - if err != nil { - return err - } - // Scores. - for j := 1; j <= 5; j++ { - userScore := UserScore{ - Uid: int(lastInsertId), - Score: j, - } - _, err = db.Ctx(ctx).Model(userScore).Data(userScore).OmitEmpty().Insert() - if err != nil { - return err - } - } - } - return nil - }) - fmt.Println(err) -} diff --git a/.example/database/gdb/mysql/gdb_with_slect.go b/.example/database/gdb/mysql/gdb_with_slect.go deleted file mode 100644 index 327062e88..000000000 --- a/.example/database/gdb/mysql/gdb_with_slect.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gmeta" -) - -func main() { - type UserDetail struct { - gmeta.Meta `orm:"table:user_detail"` - Uid int `json:"uid"` - Address string `json:"address"` - } - - type UserScore struct { - gmeta.Meta `orm:"table:user_score"` - Id int `json:"id"` - Uid int `json:"uid"` - Score int `json:"score"` - } - - type User struct { - gmeta.Meta `orm:"table:user"` - Id int `json:"id"` - Name string `json:"name"` - UserDetail *UserDetail `orm:"with:uid=id"` - UserScores []*UserScore `orm:"with:uid=id"` - } - - db := g.DB() - var user *User - err := db.Model(user).WithAll().Where("id", 3).Scan(&user) - if err != nil { - panic(err) - } - g.Dump(user) -} diff --git a/.example/database/gdb/mysql/issue364.go b/.example/database/gdb/mysql/issue364.go deleted file mode 100644 index 2f84b1aaf..000000000 --- a/.example/database/gdb/mysql/issue364.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" -) - -func test1() { - db := g.DB() - db.SetDebug(true) - time.Sleep(1 * time.Minute) - r, e := db.Model("test").Where("id", 10000).Count() - if e != nil { - panic(e) - } - g.Dump(r) -} - -func test2() { - db := g.DB() - db.SetDebug(true) - dao := db.Model("test").Safe() - time.Sleep(1 * time.Minute) - r, e := dao.Where("id", 10000).Count() - if e != nil { - panic(e) - } - g.Dump(r) -} - -func main() { - test1() - test2() -} diff --git a/.example/database/gdb/oracle/gdb.go b/.example/database/gdb/oracle/gdb.go deleted file mode 100644 index c2f35661d..000000000 --- a/.example/database/gdb/oracle/gdb.go +++ /dev/null @@ -1,565 +0,0 @@ -package main - -import ( - "fmt" - "time" - - //_ "github.com/mattn/go-oci8" - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" -) - -// 本文件用于gf框架的mysql数据库操作示例,不作为单元测试使用 - -var db gdb.DB - -// 初始化配置及创建数据库 -func init() { - gdb.AddDefaultConfigNode(gdb.ConfigNode{ - Host: "192.168.146.0", - Port: "1521", - User: "test", - Pass: "test", - Name: "orcl", - Type: "oracle", - Role: "master", - }) - db, _ = gdb.New() - - //gins.Config().SetPath("/home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/frame") - //db = g.Database() - - //gdb.SetConfig(gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : 3306, - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - //}) - //db, _ = gdb.Instance() - - //gdb.SetConfig(gdb.Config { - // "default" : gdb.ConfigGroup { - // gdb.ConfigNode { - // Host : "127.0.0.1", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.2", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.3", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // gdb.ConfigNode { - // Host : "127.0.0.4", - // Port : "3306", - // User : "root", - // Pass : "123456", - // Name : "test", - // Type : "mysql", - // Role : "master", - // Weight : 100, - // }, - // }, - //}) - //db, _ = gdb.Instance() -} - -// 创建测试数据库 -func create() error { - fmt.Println("drop table aa_user:") - _, err := db.Exec("drop table aa_user") - if err != nil { - fmt.Println("drop table aa_user error.", err) - } - - s := ` - CREATE TABLE aa_user ( - id number(10) not null, - name VARCHAR2(45), - age number(8), - addr varchar2(60), - amt number(12,2), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table aa_user:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table error.", err) - return err - } - - _, err = db.Exec("drop sequence id_seq") - if err != nil { - fmt.Println("drop sequence id_seq", err) - } - - /*fmt.Println("create sequence id_seq") - _, err = db.Exec("create sequence id_seq increment by 1 start with 1 maxvalue 9999999999 cycle cache 10") - if err != nil { - fmt.Println("create sequence id_seq error.", err) - return err - } - - s = ` - CREATE TRIGGER id_trigger before insert on aa_user for each row - begin - select id_seq.nextval into :new.id from dual; - end; - ` - _, err = db.Exec(s) - if err != nil { - fmt.Println("create trigger error.", err) - return err - }*/ - - _, err = db.Exec("drop table user_detail") - if err != nil { - fmt.Println("drop table user_detail", err) - } - - s = ` - CREATE TABLE user_detail ( - id number(10) not null, - site VARCHAR2(255), - PRIMARY KEY (id) - ) - ` - fmt.Println("create table user_detail:") - _, err = db.Exec(s) - if err != nil { - fmt.Println("create table user_detail error.", err) - return err - } - fmt.Println("create table success.") - return nil -} - -// 数据写入 -func insert(id int) { - fmt.Println("insert:") - - r, err := db.Insert("aa_user", gdb.Map{ - "id": id, - "name": "john", - "age": id, - }) - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - if err == nil { - r, err = db.Insert("user_detail", gdb.Map{ - "id": id, - "site": "http://johng.cn", - }) - if err == nil { - fmt.Printf("id: %d\n", id) - } else { - fmt.Println(err) - } - - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 基本sql查询 -func query() { - fmt.Println("query:") - list, err := db.GetAll("select * from aa_user") - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - - list, err = db.Table("aa_user").OrderBy("id").Limit(0, 2).Select() - if err == nil { - fmt.Println(list) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// replace into -func replace() { - fmt.Println("replace:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据保存 -func save() { - fmt.Println("save:") - r, err := db.Save("aa_user", gdb.Map{ - "id": 1, - "name": "john", - }) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 批量写入 -func batchInsert() { - fmt.Println("batchInsert:") - _, err := db.BatchInsert("aa_user", gdb.List{ - {"id": 11, "name": "batchInsert_john_1", "age": 11, "amt": 11.11}, - {"id": 12, "name": "batchInsert_john_2", "age": 12, "amt": 12.12}, - {"id": 13, "name": "batchInsert_john_3", "age": 13, "amt": 13.13}, - {"id": 14, "name": "batchInsert_john_4", "age": 14, "amt": 14.14}, - }, 10) - if err != nil { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update1() { - fmt.Println("update1:") - r, err := db.Update("aa_user", gdb.Map{"name": "john1", "age": 1}, "id=?", 1) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update2() { - fmt.Println("update2:") - r, err := db.Update("aa_user", gdb.Map{"name": "john6", "age": 6}, "id=?", 2) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 数据更新 -func update3() { - fmt.Println("update3:") - r, err := db.Update("aa_user", "name=?", "id=?", "john2", 3) - if err == nil { - fmt.Println(r.LastInsertId()) - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作1 -func linkopSelect1() { - fmt.Println("linkopSelect1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*, ud.site").Where("u.id > ?", 1).Limit(0, 2).Select() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作2 -func linkopSelect2() { - fmt.Println("linkopSelect2:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*,ud.site").Where("u.id=?", 1).One() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询操作3 -func linkopSelect3() { - fmt.Println("linkopSelect3:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("ud.site").Where("u.id=?", 1).Value() - if err == nil { - fmt.Println(r.String()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式查询数量1 -func linkopCount1() { - fmt.Println("linkopCount1:") - r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Where("name like ?", "john").Count() - if err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 错误操作 -func linkopUpdate1() { - fmt.Println("linkopUpdate1:") - r, err := db.Table("henghe_setting").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println("error", err) - } - fmt.Println() -} - -// 通过Map指针方式传参方式 -func linkopUpdate2() { - fmt.Println("linkopUpdate2:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john2"}).Where("name=?", "john").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 通过字符串方式传参 -func linkopUpdate3() { - fmt.Println("linkopUpdate3:") - r, err := db.Table("aa_user").Data("name='john3'").Where("name=?", "john2").Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// Where条件使用Map -func linkopUpdate4() { - fmt.Println("linkopUpdate4:") - r, err := db.Table("aa_user").Data(gdb.Map{"name": "john11111"}).Where(g.Map{"id": 1}).Update() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入 -func linkopBatchInsert1() { - fmt.Println("linkopBatchInsert1:") - r, err := db.Table("aa_user").Filter().Data(gdb.List{ - {"id": 21, "name": "linkopBatchInsert1_john_1", "amt": 21.21, "tt": "haha"}, - {"id": 22, "name": "linkopBatchInsert1_john_2", "amt": 22.22, "cc": "hahacc"}, - {"id": 23, "name": "linkopBatchInsert1_john_3", "amt": 23.23, "bb": "hahabb"}, - {"id": 24, "name": "linkopBatchInsert1_john_4", "amt": 24.24, "aa": "hahaaa"}, - }).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量写入,指定每批次写入的条数 -func linkopBatchInsert2() { - fmt.Println("linkopBatchInsert2:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 25, "name": "linkopBatchInsert2john_1"}, - {"id": 26, "name": "linkopBatchInsert2john_2"}, - {"id": 27, "name": "linkopBatchInsert2john_3"}, - {"id": 28, "name": "linkopBatchInsert2john_4"}, - }).Batch(2).Insert() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 链式批量保存 -func linkopBatchSave() { - fmt.Println("linkopBatchSave:") - r, err := db.Table("aa_user").Data(gdb.List{ - {"id": 1, "name": "john_1"}, - {"id": 2, "name": "john_2"}, - {"id": 3, "name": "john_3"}, - {"id": 4, "name": "john_4"}, - }).Save() - if err == nil { - fmt.Println(r.RowsAffected()) - } else { - fmt.Println(err) - } - fmt.Println() -} - -// 事务操作示例1 -func transaction1() { - fmt.Println("transaction1:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Insert("aa_user", gdb.Map{ - "id": 30, - "name": "transaction1", - }) - tx.Rollback() - fmt.Println(r, err) - } - fmt.Println() -} - -// 事务操作示例2 -func transaction2() { - fmt.Println("transaction2:") - if tx, err := db.Begin(); err == nil { - r, err := tx.Table("user_detail").Data(gdb.Map{"id": 5, "site": "www.baidu.com哈哈哈*?~!@#$%^&*()"}).Insert() - tx.Commit() - fmt.Println(r, err) - } - fmt.Println() -} - -// 主从io复用测试,在mysql中使用 show full processlist 查看链接信息 -func keepPing() { - fmt.Println("keepPing:") - for i := 0; i < 30; i++ { - fmt.Println("ping...", i) - err := db.PingMaster() - if err != nil { - fmt.Println(err) - return - } - err = db.PingSlave() - if err != nil { - fmt.Println(err) - return - } - time.Sleep(1 * time.Second) - } -} - -// like语句查询 -func likeQuery() { - fmt.Println("likeQuery:") - if r, err := db.Table("aa_user").Where("name like ?", "%john%").Select(); err == nil { - fmt.Println(r) - } else { - fmt.Println(err) - } -} - -// mapToStruct -func mapToStruct() { - type User struct { - Id int - Name string - Age int - Addr string - } - fmt.Println("mapToStruct:") - if r, err := db.Table("aa_user").Where("id=?", 1).One(); err == nil { - u := User{} - if err := r.ToStruct(&u); err == nil { - fmt.Println(r) - fmt.Println(u) - } else { - fmt.Println(err) - } - } else { - fmt.Println(err) - } -} - -func main() { - - db.PingMaster() - db.SetDebug(true) - /*err := create() - if err != nil { - return - }*/ - - //test1 - /*for i := 1; i < 5; i++ { - insert(i) - } - query() - */ - - //batchInsert() - //query() - - //replace() - //save() - - //update1() - //update2() - //update3() - - /*linkopSelect1() - linkopSelect2() - linkopSelect3() - linkopCount1() - */ - - /*linkopUpdate1() - linkopUpdate2() - linkopUpdate3() - linkopUpdate4() - */ - - linkopBatchInsert1() - query() - //linkopBatchInsert2() - - //transaction1() - //transaction2() - // - //keepPing() - //likeQuery() - //mapToStruct() - //getQueriedSqls() -} diff --git a/.example/database/gdb/sqlite/sqlite.go b/.example/database/gdb/sqlite/sqlite.go deleted file mode 100644 index 4160d5f4d..000000000 --- a/.example/database/gdb/sqlite/sqlite.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/database/gdb" - "github.com/gogf/gf/v2/frame/g" - _ "github.com/mattn/go-sqlite3" -) - -func main() { - gdb.SetConfig(gdb.Config{ - "default": gdb.ConfigGroup{ - gdb.ConfigNode{ - Name: "/tmp/my.db", - Type: "sqlite", - }, - }, - }) - db := g.DB() - if db == nil { - panic("db create failed") - } - - // 创建表 - sql := `CREATE TABLE user ( - uid INT PRIMARY KEY NOT NULL, - name VARCHAR(30) NOT NULL - );` - if _, err := db.Exec(sql); err != nil { - fmt.Println(err) - } - - // 写入数据 - result, err := db.Table("user").Data(g.Map{"uid": 1, "name": "john"}).Save() - if err == nil { - fmt.Println(result.RowsAffected()) - } else { - fmt.Println(err) - } - - // 删除表 - sql = `DROP TABLE user;` - if _, err := db.Exec(sql); err != nil { - fmt.Println(err) - } -} diff --git a/.example/database/gredis/config.toml b/.example/database/gredis/config.toml deleted file mode 100644 index 5632e6444..000000000 --- a/.example/database/gredis/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/database/gredis/gredis.go b/.example/database/gredis/gredis.go deleted file mode 100644 index 32815d06c..000000000 --- a/.example/database/gredis/gredis.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/database/gredis" - "github.com/gogf/gf/v2/util/gconv" -) - -// 使用原生gredis.New操作redis,但是注意需要自己调用Close方法关闭redis链接池 -func main() { - config := &gredis.Config{ - Host: "127.0.0.1", - Port: 6379, - } - redis := gredis.New(config) - defer redis.Close() - redis.Do("SET", "k", "v") - v, _ := redis.Do("GET", "k") - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis2.go b/.example/database/gredis/gredis2.go deleted file mode 100644 index e141cb06e..000000000 --- a/.example/database/gredis/gredis2.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -// 使用框架封装的g.Redis()方法获得redis操作对象单例,不需要开发者显示调用Close方法 -func main() { - g.Redis().Do("SET", "k", "v") - v, _ := g.Redis().Do("GET", "k") - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis_conn_do.go b/.example/database/gredis/gredis_conn_do.go deleted file mode 100644 index 6f3f2c6a2..000000000 --- a/.example/database/gredis/gredis_conn_do.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - conn.Do("SET", "k", "v") - v, _ := conn.Do("GET", "k") - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis_conn_do_var.go b/.example/database/gredis/gredis_conn_do_var.go deleted file mode 100644 index 363d762ed..000000000 --- a/.example/database/gredis/gredis_conn_do_var.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - if _, err := conn.Do("SET", "k", "v"); err != nil { - panic(err) - } - v, _ := conn.DoVar("GET", "k") - fmt.Println(v.String()) -} diff --git a/.example/database/gredis/gredis_conn_send.go b/.example/database/gredis/gredis_conn_send.go deleted file mode 100644 index 727e38ffc..000000000 --- a/.example/database/gredis/gredis_conn_send.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - conn.Send("SET", "foo", "bar") - conn.Send("GET", "foo") - conn.Flush() - // reply from SET - conn.Receive() - // reply from GET - v, _ := conn.Receive() - fmt.Println(gconv.String(v)) -} diff --git a/.example/database/gredis/gredis_conn_send_var.go b/.example/database/gredis/gredis_conn_send_var.go deleted file mode 100644 index 019582ddd..000000000 --- a/.example/database/gredis/gredis_conn_send_var.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - conn.Send("SET", "foo", "bar") - conn.Send("GET", "foo") - conn.Flush() - // reply from SET - conn.Receive() - // reply from GET - v, _ := conn.ReceiveVar() - fmt.Println(v.String()) -} diff --git a/.example/database/gredis/gredis_conn_subscribe.go b/.example/database/gredis/gredis_conn_subscribe.go deleted file mode 100644 index 7baf3a62d..000000000 --- a/.example/database/gredis/gredis_conn_subscribe.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - _, err := conn.Do("SUBSCRIBE", "channel") - if err != nil { - panic(err) - } - for { - reply, err := conn.Receive() - if err != nil { - panic(err) - } - fmt.Println(gconv.Strings(reply)) - } -} diff --git a/.example/database/gredis/gredis_conn_subscribe_var.go b/.example/database/gredis/gredis_conn_subscribe_var.go deleted file mode 100644 index d171d2cac..000000000 --- a/.example/database/gredis/gredis_conn_subscribe_var.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - conn := g.Redis().Conn() - defer conn.Close() - _, err := conn.Do("SUBSCRIBE", "channel") - if err != nil { - panic(err) - } - for { - reply, err := conn.ReceiveVar() - if err != nil { - panic(err) - } - fmt.Println(reply.Strings()) - } -} diff --git a/.example/debug/gdebug/gdebug.go b/.example/debug/gdebug/gdebug.go deleted file mode 100644 index 2c67adf32..000000000 --- a/.example/debug/gdebug/gdebug.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/debug/gdebug" -) - -func main() { - gdebug.PrintStack() - fmt.Println(gdebug.CallerPackage()) - fmt.Println(gdebug.CallerFunction()) -} diff --git a/.example/debug/gdebug/gdebug_info.go b/.example/debug/gdebug/gdebug_info.go deleted file mode 100644 index a829d8a7f..000000000 --- a/.example/debug/gdebug/gdebug_info.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/debug/gdebug" -) - -func main() { - fmt.Println(gdebug.BuildInfo()) -} diff --git a/.example/encoding/gbase64/gbase64.go b/.example/encoding/gbase64/gbase64.go deleted file mode 100644 index e87206a9c..000000000 --- a/.example/encoding/gbase64/gbase64.go +++ /dev/null @@ -1,16 +0,0 @@ -package gbase64 - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbase64" -) - -func main() { - s := "john" - b := gbase64.Encode(s) - c, e := gbase64.Decode(b) - fmt.Println(b) - fmt.Println(c) - fmt.Println(e) -} diff --git a/.example/encoding/gbinary/binary.go b/.example/encoding/gbinary/binary.go deleted file mode 100644 index 53e1e81de..000000000 --- a/.example/encoding/gbinary/binary.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbinary" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 使用gbinary.Encoded对基本数据类型进行二进制打包 - fmt.Println(gbinary.Encode(18, 300, 1.01)) - - // 使用gbinary.Decode对整形二进制解包,注意第二个及其后参数为字长确定的整形变量的指针地址,字长确定的类型, - // 例如:int8/16/32/64、uint8/16/32/64、float32/64 - // 这里的1.01默认为float64类型(64位系统下) - buffer := gbinary.Encode(18, 300, 1.01) - var i1 int8 - var i2 int16 - var f3 float64 - if err := gbinary.Decode(buffer, &i1, &i2, &f3); err != nil { - glog.Error(err) - } else { - fmt.Println(i1, i2, f3) - } - - // 编码/解析 int,自动识别变量长度 - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(1))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(300))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(70000))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(2000000000))) - fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(500000000000))) - - // 编码/解析 uint,自动识别变量长度 - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(1))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(300))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(70000))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(2000000000))) - fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(500000000000))) - - // 编码/解析 int8/16/32/64 - fmt.Println(gbinary.DecodeToInt8(gbinary.EncodeInt8(int8(100)))) - fmt.Println(gbinary.DecodeToInt16(gbinary.EncodeInt16(int16(100)))) - fmt.Println(gbinary.DecodeToInt32(gbinary.EncodeInt32(int32(100)))) - fmt.Println(gbinary.DecodeToInt64(gbinary.EncodeInt64(int64(100)))) - - // 编码/解析 uint8/16/32/64 - fmt.Println(gbinary.DecodeToUint8(gbinary.EncodeUint8(uint8(100)))) - fmt.Println(gbinary.DecodeToUint16(gbinary.EncodeUint16(uint16(100)))) - fmt.Println(gbinary.DecodeToUint32(gbinary.EncodeUint32(uint32(100)))) - fmt.Println(gbinary.DecodeToUint64(gbinary.EncodeUint64(uint64(100)))) - - // 编码/解析 string - fmt.Println(gbinary.DecodeToString(gbinary.EncodeString("I'm string!"))) -} diff --git a/.example/encoding/gbinary/bits1.go b/.example/encoding/gbinary/bits1.go deleted file mode 100644 index 6d2696157..000000000 --- a/.example/encoding/gbinary/bits1.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbinary" -) - -func main() { - // 传感器状态,0:已下线, 1:开启, 2:关闭, 3:待机 - count := 100 - status := 1 - - // 网关编码 - bits := make([]gbinary.Bit, 0) - for i := 0; i < count; i++ { - bits = gbinary.EncodeBits(bits, status, 2) - } - buffer := gbinary.EncodeBitsToBytes(bits) - fmt.Println("buffer length:", len(buffer)) - - /* 上报过程忽略,这里只展示编码/解码示例 */ - - // 平台解码 - alivecount := 0 - sensorbits := gbinary.DecodeBytesToBits(buffer) - for i := 0; i < len(sensorbits); i += 2 { - if gbinary.DecodeBits(sensorbits[i:i+2]) == 1 { - alivecount++ - } - } - fmt.Println("alived sensor:", alivecount) -} diff --git a/.example/encoding/gbinary/bits2.go b/.example/encoding/gbinary/bits2.go deleted file mode 100644 index d85d04cb8..000000000 --- a/.example/encoding/gbinary/bits2.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gbinary" -) - -func main() { - // Meta元数据文件数据结构:[键名哈希64(64bit,8byte) 键名长度(8bit,1byte) 键值长度(24bit,3byte) 数据文件偏移量(40bit,5byte)](变长) - hash := 521369841259754125 - klen := 12 - vlen := 35535 - offset := 80000000 - - // 编码 - bits := make([]gbinary.Bit, 0) - bits = gbinary.EncodeBits(bits, hash, 64) - bits = gbinary.EncodeBits(bits, klen, 8) - bits = gbinary.EncodeBits(bits, vlen, 24) - bits = gbinary.EncodeBits(bits, offset, 40) - buffer := gbinary.EncodeBitsToBytes(bits) - fmt.Println("meta length:", len(buffer)) - - /* 文件存储及数据查询过程忽略,这里只展示元数据编码/解码示例 */ - - // 解码 - metabits := gbinary.DecodeBytesToBits(buffer) - fmt.Println("hash :", gbinary.DecodeBits(metabits[0:64])) - fmt.Println("klen :", gbinary.DecodeBits(metabits[64:72])) - fmt.Println("vlen :", gbinary.DecodeBits(metabits[72:96])) - fmt.Println("offset:", gbinary.DecodeBits(metabits[96:136])) -} diff --git a/.example/encoding/gcfg/config.toml b/.example/encoding/gcfg/config.toml deleted file mode 100644 index d58ffea7c..000000000 --- a/.example/encoding/gcfg/config.toml +++ /dev/null @@ -1,28 +0,0 @@ -# 模板引擎目录 -viewpath = "/home/www/templates/" -# MySQL数据库配置 -[database] - [[database.default]] - host = "127.0.0.1" - port = "3306" - user = "root" - pass = "123456" - name = "test" - type = "mysql" - role = "master" - charset = "utf8" - priority = "1" - [[database.default]] - host = "127.0.0.1" - port = "3306" - user = "root" - pass = "123456" - name = "test" - type = "mysql" - role = "master" - charset = "utf8" - priority = "1" -# Redis数据库配置 -[redis] - disk = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/encoding/gcfg/gcfg1.go b/.example/encoding/gcfg/gcfg1.go deleted file mode 100644 index b59e0af91..000000000 --- a/.example/encoding/gcfg/gcfg1.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - fmt.Println(g.Config().Get("redis")) - - type RedisConfig struct { - Disk string - Cache string - } - - redisCfg := new(RedisConfig) - fmt.Println(g.Config().GetStruct("redis", redisCfg)) - fmt.Println(redisCfg) -} diff --git a/.example/encoding/gcharset/gcharset.go b/.example/encoding/gcharset/gcharset.go deleted file mode 100644 index cf3a8017a..000000000 --- a/.example/encoding/gcharset/gcharset.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gcharset" -) - -func main() { - src := "~{;(F#,6@WCN^O`GW!#" - srcCharset := "GB2312" - dstCharset := "UTF-8" - str, err := gcharset.Convert(dstCharset, srcCharset, src) - if err != nil { - panic(err) - } - fmt.Println(str) - // output: - // 花间一壶酒,独酌无相亲。 -} diff --git a/.example/encoding/gcompress/unzip.go b/.example/encoding/gcompress/unzip.go deleted file mode 100644 index 112b1977f..000000000 --- a/.example/encoding/gcompress/unzip.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gcompress" -) - -func main() { - err := gcompress.UnZipFile( - `D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg\encoding\gcompress\data.zip`, - `D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg`, - ) - fmt.Println(err) -} diff --git a/.example/encoding/gcompress/unzip_content.go b/.example/encoding/gcompress/unzip_content.go deleted file mode 100644 index b5d464998..000000000 --- a/.example/encoding/gcompress/unzip_content.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gcompress" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - err := gcompress.UnZipContent( - gfile.GetBytes(`D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg\encoding\gcompress\data.zip`), - `D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg`, - ) - fmt.Println(err) -} diff --git a/.example/encoding/gcompress/zip.go b/.example/encoding/gcompress/zip.go deleted file mode 100644 index 6e055200d..000000000 --- a/.example/encoding/gcompress/zip.go +++ /dev/null @@ -1,68 +0,0 @@ -package main - -import ( - "archive/zip" - "fmt" - "github.com/gogf/gf/v2/encoding/gcompress" - "io" - "os" - "path/filepath" - "strings" -) - -// srcFile could be a single file or a directory -func Zip(srcFile string, destZip string) error { - zipfile, err := os.Create(destZip) - if err != nil { - return err - } - defer zipfile.Close() - - archive := zip.NewWriter(zipfile) - defer archive.Close() - - filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - header, err := zip.FileInfoHeader(info) - if err != nil { - return err - } - - header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/") - // header.Name = path - if info.IsDir() { - header.Name += "/" - } else { - header.Method = zip.Deflate - } - - writer, err := archive.CreateHeader(header) - if err != nil { - return err - } - - if !info.IsDir() { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - _, err = io.Copy(writer, file) - } - return err - }) - - return err -} - -func main() { - src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test` - dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test.zip` - //src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD` - //dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD.zip` - fmt.Println(gcompress.ZipPath(src, dst)) - //fmt.Println(Zip(src, dst)) -} diff --git a/.example/encoding/ghash/ghash_repeat_check.go b/.example/encoding/ghash/ghash_repeat_check.go deleted file mode 100644 index 8451b1bc6..000000000 --- a/.example/encoding/ghash/ghash_repeat_check.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "strconv" - - "github.com/gogf/gf/v2/encoding/ghash" -) - -func main() { - m := make(map[uint64]bool) - for i := 0; i < 100000000; i++ { - hash := ghash.BKDRHash64([]byte("key_" + strconv.Itoa(i))) - if _, ok := m[hash]; ok { - fmt.Printf("duplicated hash %d\n", hash) - } else { - m[hash] = true - } - } -} diff --git a/.example/encoding/gini/gini.go b/.example/encoding/gini/gini.go deleted file mode 100644 index 9e6c55a58..000000000 --- a/.example/encoding/gini/gini.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/encoding/gini" -) - -func main() { - s := ` -a = b - -` - m, err := gini.Decode([]byte(s)) - fmt.Println(err) - fmt.Println(m) -} diff --git a/.example/encoding/gjson/gjson.go b/.example/encoding/gjson/gjson.go deleted file mode 100644 index 07da40f89..000000000 --- a/.example/encoding/gjson/gjson.go +++ /dev/null @@ -1,155 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func getByPattern() { - data := - `{ - "users" : { - "count" : 100, - "list" : [ - {"name" : "小明", "score" : 60}, - {"name" : "John", "score" : 99.5} - ] - } - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - fmt.Println("John Score:", j.GetFloat32("users.list.1.score")) - } -} - -// 当键名存在"."号时,检索优先级:键名->层级,因此不会引起歧义 -func testMultiDots() { - data := - `{ - "users" : { - "count" : 100 - }, - "users.count" : 101 - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - fmt.Println("Users Count:", j.GetInt("users.count")) - } -} - -// 设置数据 -func testSet() { - data := - `{ - "users" : { - "count" : 100 - } - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - j.Set("users.count", 1) - j.Set("users.list", []string{"John", "小明"}) - c, _ := j.ToJson() - fmt.Println(string(c)) - } -} - -// 将Json数据转换为其他数据格式 -func testConvert() { - data := - `{ - "users" : { - "count" : 100, - "list" : ["John", "小明"] - } - }` - j, err := gjson.DecodeToJson([]byte(data)) - if err != nil { - glog.Error(err) - } else { - c, _ := j.ToJson() - fmt.Println("JSON:") - fmt.Println(string(c)) - fmt.Println("======================") - - fmt.Println("XML:") - c, _ = j.ToXmlIndent() - fmt.Println(string(c)) - fmt.Println("======================") - - fmt.Println("YAML:") - c, _ = j.ToYaml() - fmt.Println(string(c)) - fmt.Println("======================") - - fmt.Println("TOML:") - c, _ = j.ToToml() - fmt.Println(string(c)) - } -} - -func testSplitChar() { - var v interface{} - j := gjson.New(nil) - t1 := gtime.TimestampNano() - j.Set("a.b.c.d.e.f.g.h.i.j.k", 1) - t2 := gtime.TimestampNano() - fmt.Println(t2 - t1) - - t5 := gtime.TimestampNano() - v = j.Get("a.b.c.d.e.f.g.h.i.j.k") - t6 := gtime.TimestampNano() - fmt.Println(v) - fmt.Println(t6 - t5) - - j.SetSplitChar('#') - - t7 := gtime.TimestampNano() - v = j.Get("a#b#c#d#e#f#g#h#i#j#k") - t8 := gtime.TimestampNano() - fmt.Println(v) - fmt.Println(t8 - t7) -} - -func testViolenceCheck() { - j := gjson.New(nil) - t1 := gtime.TimestampNano() - j.Set("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", 1) - t2 := gtime.TimestampNano() - fmt.Println(t2 - t1) - - t3 := gtime.TimestampNano() - j.Set("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", 1) - t4 := gtime.TimestampNano() - fmt.Println(t4 - t3) - - t5 := gtime.TimestampNano() - j.Get("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a") - t6 := gtime.TimestampNano() - fmt.Println(t6 - t5) - - j.SetViolenceCheck(false) - - t7 := gtime.TimestampNano() - j.Set("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", 1) - t8 := gtime.TimestampNano() - fmt.Println(t8 - t7) - - t9 := gtime.TimestampNano() - j.Get("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a") - t10 := gtime.TimestampNano() - fmt.Println(t10 - t9) -} - -func main() { - testViolenceCheck() -} diff --git a/.example/encoding/gjson/issue#IZXU2.go b/.example/encoding/gjson/issue#IZXU2.go deleted file mode 100644 index abbbc7fd9..000000000 --- a/.example/encoding/gjson/issue#IZXU2.go +++ /dev/null @@ -1,156 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - - "github.com/gogf/gf/v2/encoding/gjson" -) - -type XinYanModel struct { - Success bool `json:"success"` - Data Data `json:"data"` - ErrorCode interface{} `json:"errorCode"` - ErrorMsg interface{} `json:"errorMsg"` -} -type ApplyReportDetail struct { - ApplyScore string `json:"apply_score"` - ApplyCredibility string `json:"apply_credibility"` - QueryOrgCount string `json:"apply_query_org_count"` - QueryFinanceCount string `json:"apply_query_finance_count"` - QueryCashCount string `json:"apply_query_cash_count"` - QuerySumCount string `json:"apply_query_sum_count"` - LatestQueryTime string `json:"apply_latest_query_time"` - LatestOneMonth string `json:"apply_latest_one_month"` - LatestThreeMonth string `json:"apply_latest_three_month"` - LatestSixMonth string `json:"apply_latest_six_month"` -} -type BehaviorReportDetail struct { - LoansScore string `json:"behavior_report_detailloans_score"` - LoansCredibility string `json:"behavior_report_detailloans_credibility"` - LoansCount string `json:"behavior_report_detailloans_count"` - LoansSettleCount string `json:"behavior_report_detailloans_settle_count"` - LoansOverdueCount string `json:"behavior_report_detailloans_overdue_count"` - LoansOrgCount string `json:"behavior_report_detailloans_org_count"` - ConsfinOrgCount string `json:"behavior_report_detailconsfin_org_count"` - LoansCashCount string `json:"behavior_report_detailloans_cash_count"` - LatestOneMonth string `json:"behavior_report_detaillatest_one_month"` - LatestThreeMonth string `json:"behavior_report_detaillatest_three_month"` - LatestSixMonth string `json:"behavior_report_detaillatest_six_month"` - HistorySucFee string `json:"behavior_report_detailhistory_suc_fee"` - HistoryFailFee string `json:"behavior_report_detailhistory_fail_fee"` - LatestOneMonthSuc string `json:"behavior_report_detaillatest_one_month_suc"` - LatestOneMonthFail string `json:"behavior_report_detaillatest_one_month_fail"` - LoansLongTime string `json:"behavior_report_detailloans_long_time"` - LoansLatestTime string `json:"behavior_report_detailloans_latest_time"` -} -type CurrentReportDetail struct { - LoansCreditLimit string `json:"current_report_detailloans_credit_limit"` - LoansCredibility string `json:"current_report_detailloans_credibility"` - LoansOrgCount string `json:"current_report_detailloans_org_count"` - LoansProductCount string `json:"current_report_detailloans_product_count"` - LoansMaxLimit string `json:"current_report_detailloans_max_limit"` - LoansAvgLimit string `json:"current_report_detailloans_avg_limit"` - ConsfinCreditLimit string `json:"current_report_detailconsfin_credit_limit"` - ConsfinCredibility string `json:"current_report_detailconsfin_credibility"` - ConsfinOrgCount string `json:"current_report_detailconsfin_org_count"` - ConsfinProductCount string `json:"current_report_detailconsfin_product_count"` - ConsfinMaxLimit string `json:"current_report_detailconsfin_max_limit"` - ConsfinAvgLimit string `json:"current_report_detailconsfin_avg_limit"` -} -type ResultDetail struct { - ApplyReportDetail ApplyReportDetail `json:"apply_report_detail"` - BehaviorReportDetail BehaviorReportDetail `json:"behavior_report_detail"` - CurrentReportDetail CurrentReportDetail `json:"current_report_detail"` -} -type Data struct { - Code string `json:"code"` - Desc string `json:"desc1"` - TransID string `json:"trans_id"` - TradeNo string `json:"trade_no"` - Fee string `json:"fee"` - IDNo string `json:"id_no"` - IDName string `json:"id_name"` - Versions string `json:"versions"` - ResultDetail ResultDetail `json:"result_detail"` -} - -var data = `{ - "success": true, - "data": { - "code": "0", - "desc": "查询成功", - "trans_id": "14910304379231213", - "trade_no": "201704011507240100057329", - "fee": "Y", - "id_no": "0783231bcc39f4957e99907e02ae401c", - "id_name": "dd67a5943781369ddd7c594e231e9e70 ", - "versions": "1.0.0", - "result_detail":{ - "apply_report_detail": { - "apply_score": "189", - "apply_credibility": "84", - "query_org_count": "7", - "query_finance_count": "2", - "query_cash_count": "2", - "query_sum_count": "13", - "latest_query_time": "2017-09-03", - "latest_one_month": "1", - "latest_three_month": "5", - "latest_six_month": "12" - }, - "behavior_report_detail": { - "loans_score": "199", - "loans_credibility": "90", - "loans_count": "300", - "loans_settle_count": "280", - "loans_overdue_count": "20", - "loans_org_count": "5", - "consfin_org_count": "3", - "loans_cash_count": "2", - "latest_one_month": "3", - "latest_three_month": "20", - "latest_six_month": "23", - "history_suc_fee": "30", - "history_fail_fee": "25", - "latest_one_month_suc": "5", - "latest_one_month_fail": "20", - "loans_long_time": "130", - "loans_latest_time": "2017-09-16" - }, - "current_report_detail": { - "loans_credit_limit": "1400", - "loans_credibility": "80", - "loans_org_count": "7", - "loans_product_count": "8", - "loans_max_limit": "2000", - "loans_avg_limit": "1000", - "consfin_credit_limit": "1500", - "consfin_credibility": "90", - "consfin_org_count": "8", - "consfin_product_count": "5", - "consfin_max_limit": "5000", - "consfin_avg_limit": "3000" - } - } - }, - "errorCode": null, - "errorMsg": null -}` - -func main() { - struct1 := new(XinYanModel) - err := json.Unmarshal([]byte(data), struct1) - fmt.Println(err) - fmt.Println(struct1) - - fmt.Println() - - struct2 := new(XinYanModel) - j, err := gjson.DecodeToJson(data) - fmt.Println(err) - fmt.Println(j.Get("data.desc")) - err = j.ToStruct(struct2) - fmt.Println(err) - fmt.Println(struct2) -} diff --git a/.example/encoding/gjson/issue283.go b/.example/encoding/gjson/issue283.go deleted file mode 100644 index 52b20a274..000000000 --- a/.example/encoding/gjson/issue283.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/encoding/gjson" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -type GameUser struct { - Uid int `json:"uid"` - Account string `json:"account"` - Tel string `json:"tel"` - Role string `json:"role"` - Vip int `json:"vip"` - GameLevel int `json:"gamelevel"` - Diamond int `json:"diamond"` - Coin int `json:"coin"` - Value int `json:"value"` - Area string `json:"area"` - ServerName string `json:"servername"` - Time int `json:"time"` - ClientInfo *ClientInfo `json:"client_info"` -} - -type ClientInfo struct { - ClientGuid string `json:"client_guid"` - ClientType int `json:"client_type"` - ClientSDKVersion string `json:"client_sdk_version"` - ClientVersion string `json:"client_version"` - PackageId string `json:"packageid"` - PhoneType string `json:"phone_type"` - DevicesId string `json:"devices_id"` - ClientMac string `json:"client_mac"` -} - -func main() { - s := `{ - "uid":9527, - "account":"zhangsan", - "tel":"15248787", - "role":"test", - "vip":7, - "gamelevel":59, - "diamond ":59, - "coin ":59, - "value ":99, - "area":"s", - "servername":"灵动", - "time":15454878787, - "client_info": { - "client_guid": "aaaa", - "client_type": 1, - "client_sdk_version": "1.0.1", - "client_version": "1.0.1", - "packageid":"", - "phone_type": "vivi", - "devices_id":"", - "client_mac":"" - } -}` - - gameUser := &GameUser{} - err := gjson.DecodeTo(s, gameUser) - if err != nil { - glog.Error(err) - } - g.Dump(gameUser) - -} diff --git a/.example/encoding/gjson/issue360.go b/.example/encoding/gjson/issue360.go deleted file mode 100644 index 7b753f312..000000000 --- a/.example/encoding/gjson/issue360.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/encoding/gjson" -) - -func main() { - s := ` -{"apiVersion":"v1","kind":"Service","metadata":{"labels":{"name":"http-daemon"},"name":"http-daemon","namespace":"default"},"spec":{"ports":[{"name":"http-daemon","port":8080,"protocol":"TCP","targetPort":9212}],"selector":{"app":"http-daemon","version":"v0930-082326"}}} -` - js, err := gjson.DecodeToJson(s) - if err != nil { - panic(err) - } - //g.Dump(js.ToMap()) - y, _ := js.ToYamlString() - fmt.Println(y) -} diff --git a/.example/encoding/gyaml/gyaml.go b/.example/encoding/gyaml/gyaml.go deleted file mode 100644 index fc6380291..000000000 --- a/.example/encoding/gyaml/gyaml.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/encoding/gyaml" -) - -func main() { - var yamlStr string = ` -#即表示url属性值; -url: http://www.wolfcode.cn -#即表示server.host属性的值; -server: - host: http://www.wolfcode.cn -#数组,即表示server为[a,b,c] -server: - - 120.168.117.21 - - 120.168.117.22 - - 120.168.117.23 -#常量 -pi: 3.14 #定义一个数值3.14 -hasChild: true #定义一个boolean值 -name: '你好YAML' #定义一个字符串 -` - - i, err := gyaml.Decode([]byte(yamlStr)) - fmt.Println(err) - fmt.Println(i) -} diff --git a/.example/errors/gerror/gerror1.go b/.example/errors/gerror/gerror1.go deleted file mode 100644 index 32ed092e3..000000000 --- a/.example/errors/gerror/gerror1.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "errors" - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func Error1() error { - return errors.New("test1") -} - -func Error2() error { - return gerror.New("test2") -} - -func main() { - err1 := Error1() - err2 := Error2() - fmt.Printf("%s, %-s, %+s\n", err1, err1, err1) - fmt.Printf("%v, %-v, %+v\n", err1, err1, err1) - fmt.Printf("%s, %-s, %+s\n", err2, err2, err2) - fmt.Printf("%v, %-v, %+v\n", err2, err2, err2) -} diff --git a/.example/errors/gerror/gerror2.go b/.example/errors/gerror/gerror2.go deleted file mode 100644 index 0d78edd99..000000000 --- a/.example/errors/gerror/gerror2.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func OpenFile() error { - return gerror.New("permission denied") -} - -func OpenConfig() error { - return gerror.Wrap(OpenFile(), "configuration file opening failed") -} - -func ReadConfig() error { - return gerror.Wrap(OpenConfig(), "reading configuration failed") -} - -func main() { - //err := ReadConfig() - //glog.Printf("%s\n%+s", err, err) - //glog.Printf("%+v", err) - fmt.Printf("%+v", ReadConfig()) -} diff --git a/.example/errors/gerror/gerror3.go b/.example/errors/gerror/gerror3.go deleted file mode 100644 index 007db4f0a..000000000 --- a/.example/errors/gerror/gerror3.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "errors" - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func Error1() error { - return errors.New("test1") -} - -func Error2() error { - return gerror.New("test2") -} - -func main() { - err1 := Error1() - err2 := Error2() - fmt.Println("err1:\n", gerror.Stack(err1)) - fmt.Println("err2:\n", gerror.Stack(err2)) -} diff --git a/.example/errors/gerror/gerror4.go b/.example/errors/gerror/gerror4.go deleted file mode 100644 index 03a10ac2e..000000000 --- a/.example/errors/gerror/gerror4.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func OpenFile() error { - return gerror.New("permission denied") -} - -func OpenConfig() error { - return gerror.Wrap(OpenFile(), "configuration file opening failed") -} - -func ReadConfig() error { - return gerror.Wrap(OpenConfig(), "reading configuration failed") -} - -func main() { - fmt.Println(gerror.Cause(ReadConfig())) -} diff --git a/.example/errors/gerror/gerror5.go b/.example/errors/gerror/gerror5.go deleted file mode 100644 index 56426ae37..000000000 --- a/.example/errors/gerror/gerror5.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "errors" - - "github.com/gogf/gf/v2/os/glog" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func Error1() error { - return errors.New("test1") -} - -func Error2() error { - return gerror.New("test2") -} - -func main() { - glog.Print(Error1()) - glog.Print(Error2()) -} diff --git a/.example/i18n/gi18n/gi18n-dir.go b/.example/i18n/gi18n/gi18n-dir.go deleted file mode 100644 index f05751e85..000000000 --- a/.example/i18n/gi18n/gi18n-dir.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "context" - "fmt" - - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - t := gi18n.New() - t.SetLanguage("ja") - err := t.SetPath("./i18n-dir") - if err != nil { - panic(err) - } - fmt.Println(t.Translate(context.TODO(), `hello`)) - fmt.Println(t.Translate(context.TODO(), `{#hello}{#world}!`)) -} diff --git a/.example/i18n/gi18n/gi18n-file.go b/.example/i18n/gi18n/gi18n-file.go deleted file mode 100644 index 3c81bf1f5..000000000 --- a/.example/i18n/gi18n/gi18n-file.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "context" - "fmt" - - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - t := gi18n.New() - t.SetLanguage("ja") - err := t.SetPath("./i18n-file") - if err != nil { - panic(err) - } - fmt.Println(t.Translate(context.TODO(), `hello`)) - fmt.Println(t.Translate(context.TODO(), `{#hello}{#world}!`)) -} diff --git a/.example/i18n/gi18n/gi18n.go b/.example/i18n/gi18n/gi18n.go deleted file mode 100644 index e54764bbf..000000000 --- a/.example/i18n/gi18n/gi18n.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - var ( - orderId = 865271654 - orderAmount = 99.8 - ) - fmt.Println(g.I18n().Tf( - gi18n.WithLanguage(context.TODO(), `en`), - `{#OrderPaid}`, orderId, orderAmount, - )) - fmt.Println(g.I18n().Tf( - gi18n.WithLanguage(context.TODO(), `zh-CN`), - `{#OrderPaid}`, orderId, orderAmount, - )) -} diff --git a/.example/i18n/gi18n/http_view_i18n.go b/.example/i18n/gi18n/http_view_i18n.go deleted file mode 100644 index e38340288..000000000 --- a/.example/i18n/gi18n/http_view_i18n.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - r.SetCtx(gi18n.WithLanguage(r.Context(), r.GetString("lang", "zh-CN"))) - r.Middleware.Next() - }) - group.ALL("/", func(r *ghttp.Request) { - r.Response.WriteTplContent(`{#hello}{#world}!`) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/i18n/gi18n/i18n-dir/en/hello.toml b/.example/i18n/gi18n/i18n-dir/en/hello.toml deleted file mode 100644 index 1680a362c..000000000 --- a/.example/i18n/gi18n/i18n-dir/en/hello.toml +++ /dev/null @@ -1,2 +0,0 @@ - -hello = "Hello" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/en/world.toml b/.example/i18n/gi18n/i18n-dir/en/world.toml deleted file mode 100644 index f9afd1e67..000000000 --- a/.example/i18n/gi18n/i18n-dir/en/world.toml +++ /dev/null @@ -1,2 +0,0 @@ - -world = "World" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ja/hello.yaml b/.example/i18n/gi18n/i18n-dir/ja/hello.yaml deleted file mode 100644 index ec827cd49..000000000 --- a/.example/i18n/gi18n/i18n-dir/ja/hello.yaml +++ /dev/null @@ -1,2 +0,0 @@ - -hello: "こんにちは" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ja/world.yaml b/.example/i18n/gi18n/i18n-dir/ja/world.yaml deleted file mode 100644 index 04e828b42..000000000 --- a/.example/i18n/gi18n/i18n-dir/ja/world.yaml +++ /dev/null @@ -1 +0,0 @@ -world: "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ru/hello.ini b/.example/i18n/gi18n/i18n-dir/ru/hello.ini deleted file mode 100644 index c65ec2155..000000000 --- a/.example/i18n/gi18n/i18n-dir/ru/hello.ini +++ /dev/null @@ -1 +0,0 @@ -hello = "Привет" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/ru/world.ini b/.example/i18n/gi18n/i18n-dir/ru/world.ini deleted file mode 100644 index 7e9e60499..000000000 --- a/.example/i18n/gi18n/i18n-dir/ru/world.ini +++ /dev/null @@ -1 +0,0 @@ -world = "мир" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-CN/hello.json b/.example/i18n/gi18n/i18n-dir/zh-CN/hello.json deleted file mode 100644 index b8eb10e94..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-CN/hello.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "hello": "你好" -} \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-CN/world.json b/.example/i18n/gi18n/i18n-dir/zh-CN/world.json deleted file mode 100644 index 9d6392149..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-CN/world.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "world": "世界" -} \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-TW/hello.xml b/.example/i18n/gi18n/i18n-dir/zh-TW/hello.xml deleted file mode 100644 index a4e52ef07..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-TW/hello.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - 你好 - \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-dir/zh-TW/world.xml b/.example/i18n/gi18n/i18n-dir/zh-TW/world.xml deleted file mode 100644 index 877b402c5..000000000 --- a/.example/i18n/gi18n/i18n-dir/zh-TW/world.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - 世界 - \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/en.toml b/.example/i18n/gi18n/i18n-file/en.toml deleted file mode 100644 index 17df41597..000000000 --- a/.example/i18n/gi18n/i18n-file/en.toml +++ /dev/null @@ -1,3 +0,0 @@ - -hello = "Hello" -world = "World" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/ja.yaml b/.example/i18n/gi18n/i18n-file/ja.yaml deleted file mode 100644 index 0166fcefb..000000000 --- a/.example/i18n/gi18n/i18n-file/ja.yaml +++ /dev/null @@ -1,3 +0,0 @@ - -hello: "こんにちは" -world: "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/ru.ini b/.example/i18n/gi18n/i18n-file/ru.ini deleted file mode 100644 index fa2df856c..000000000 --- a/.example/i18n/gi18n/i18n-file/ru.ini +++ /dev/null @@ -1,2 +0,0 @@ -hello = "Привет" -world = "мир" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/zh-CN.json b/.example/i18n/gi18n/i18n-file/zh-CN.json deleted file mode 100644 index 1de75ba1a..000000000 --- a/.example/i18n/gi18n/i18n-file/zh-CN.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "hello": "你好", - "world": "世界" -} \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n-file/zh-TW.xml b/.example/i18n/gi18n/i18n-file/zh-TW.xml deleted file mode 100644 index 9a4356f4c..000000000 --- a/.example/i18n/gi18n/i18n-file/zh-TW.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - 你好 - 世界 - \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/en.toml b/.example/i18n/gi18n/i18n/en.toml deleted file mode 100644 index 67762d579..000000000 --- a/.example/i18n/gi18n/i18n/en.toml +++ /dev/null @@ -1 +0,0 @@ -OrderPaid = "You have successfully complete order #%d payment, paid amount: ¥%0.2f." \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/ja.toml b/.example/i18n/gi18n/i18n/ja.toml deleted file mode 100644 index 8ca47ed7f..000000000 --- a/.example/i18n/gi18n/i18n/ja.toml +++ /dev/null @@ -1,3 +0,0 @@ - -hello = "こんにちは" -world = "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/ru.toml b/.example/i18n/gi18n/i18n/ru.toml deleted file mode 100644 index 938434a5a..000000000 --- a/.example/i18n/gi18n/i18n/ru.toml +++ /dev/null @@ -1,3 +0,0 @@ - -hello = "Привет" -world = "мир" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/zh-CN.toml b/.example/i18n/gi18n/i18n/zh-CN.toml deleted file mode 100644 index 20406d93a..000000000 --- a/.example/i18n/gi18n/i18n/zh-CN.toml +++ /dev/null @@ -1,3 +0,0 @@ -OrderPaid = "您已成功完成订单号 #%d 支付,支付金额¥%.2f。" -hello = "你好" -world = "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/i18n/zh-TW.toml b/.example/i18n/gi18n/i18n/zh-TW.toml deleted file mode 100644 index b3a52c527..000000000 --- a/.example/i18n/gi18n/i18n/zh-TW.toml +++ /dev/null @@ -1,2 +0,0 @@ -hello = "你好" -world = "世界" \ No newline at end of file diff --git a/.example/i18n/gi18n/resource/gi18n-resource.go b/.example/i18n/gi18n/resource/gi18n-resource.go deleted file mode 100644 index 7867b202c..000000000 --- a/.example/i18n/gi18n/resource/gi18n-resource.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - m := g.I18n() - m.SetLanguage("ja") - err := m.SetPath("/i18n-dir") - if err != nil { - panic(err) - } - fmt.Println(m.Translate(`hello`)) - fmt.Println(m.Translate(`{#hello}{#world}!`)) -} diff --git a/.example/i18n/gi18n/template/index.html b/.example/i18n/gi18n/template/index.html deleted file mode 100644 index e2a2a6b43..000000000 --- a/.example/i18n/gi18n/template/index.html +++ /dev/null @@ -1 +0,0 @@ -{{T "hello" "你好"}} {{T "world" "世界"}}! \ No newline at end of file diff --git a/.example/net/ghttp/client/cookie/client.go b/.example/net/ghttp/client/cookie/client.go deleted file mode 100644 index 212a81f6b..000000000 --- a/.example/net/ghttp/client/cookie/client.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - c := ghttp.NewClient() - c.SetHeader("Cookie", "name=john; score=100") - if r, e := c.Get("http://127.0.0.1:8199/"); e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - } -} diff --git a/.example/net/ghttp/client/cookie/server.go b/.example/net/ghttp/client/cookie/server.go deleted file mode 100644 index e262d9097..000000000 --- a/.example/net/ghttp/client/cookie/server.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln(r.Cookie.Map()) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/client/get.go b/.example/net/ghttp/client/get.go deleted file mode 100644 index 623073f3d..000000000 --- a/.example/net/ghttp/client/get.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - r, err := ghttp.Get("http://127.0.0.1:8199/11111/11122") - fmt.Println(err) - fmt.Println(r.Header) -} diff --git a/.example/net/ghttp/client/middleware/client.go b/.example/net/ghttp/client/middleware/client.go deleted file mode 100644 index babba4fa5..000000000 --- a/.example/net/ghttp/client/middleware/client.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "bytes" - "fmt" - "github.com/gogf/gf/v2/container/garray" - "github.com/gogf/gf/v2/crypto/gmd5" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/util/guid" - "github.com/gogf/gf/v2/util/gutil" - "io/ioutil" - "net/http" -) - -const ( - appId = "123" - appSecret = "456" -) - -// 注入统一的接口签名参数 -func injectSignature(jsonContent []byte) []byte { - var m map[string]interface{} - _ = json.Unmarshal(jsonContent, &m) - if len(m) > 0 { - m["appid"] = appId - m["nonce"] = guid.S() - m["timestamp"] = gtime.Timestamp() - var ( - keyArray = garray.NewSortedStrArrayFrom(gutil.Keys(m)) - sigContent string - ) - keyArray.Iterator(func(k int, v string) bool { - sigContent += v - sigContent += gconv.String(m[v]) - return true - }) - m["signature"] = gmd5.MustEncryptString(gmd5.MustEncryptString(sigContent) + appSecret) - jsonContent, _ = json.Marshal(m) - } - return jsonContent -} - -func main() { - c := g.Client() - c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) { - bodyBytes, _ := ioutil.ReadAll(r.Body) - if len(bodyBytes) > 0 { - // 注入签名相关参数,修改Request原有的提交参数 - bodyBytes = injectSignature(bodyBytes) - r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) - r.ContentLength = int64(len(bodyBytes)) - } - return c.Next(r) - }) - content := c.ContentJson().PostContent("http://127.0.0.1:8199/", g.Map{ - "name": "goframe", - "site": "https://goframe.org", - }) - fmt.Println(content) -} diff --git a/.example/net/ghttp/client/middleware/server.go b/.example/net/ghttp/client/middleware/server.go deleted file mode 100644 index 8b431f89b..000000000 --- a/.example/net/ghttp/client/middleware/server.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/", func(r *ghttp.Request) { - r.Response.Write(r.GetMap()) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/client/upload-batch/client.go b/.example/net/ghttp/client/upload-batch/client.go deleted file mode 100644 index d8176b703..000000000 --- a/.example/net/ghttp/client/upload-batch/client.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - path1 := "/Users/john/Pictures/logo1.png" - path2 := "/Users/john/Pictures/logo2.png" - r, e := ghttp.Post( - "http://127.0.0.1:8199/upload", - fmt.Sprintf(`upload-file=@file:%s&upload-file=@file:%s`, path1, path2), - ) - if e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - r.Close() - } -} diff --git a/.example/net/ghttp/client/upload-batch/client2.go b/.example/net/ghttp/client/upload-batch/client2.go deleted file mode 100644 index 7cc2963e5..000000000 --- a/.example/net/ghttp/client/upload-batch/client2.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - path1 := "/Users/john/Pictures/logo1.png" - path2 := "/Users/john/Pictures/logo2.png" - r, e := ghttp.Post( - "http://127.0.0.1:8199/upload", - fmt.Sprintf(`upload-file[]=@file:%s&upload-file[]=@file:%s`, path1, path2), - ) - if e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - r.Close() - } -} diff --git a/.example/net/ghttp/client/upload-batch/server.go b/.example/net/ghttp/client/upload-batch/server.go deleted file mode 100644 index 5443dc298..000000000 --- a/.example/net/ghttp/client/upload-batch/server.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// Upload uploads files to /tmp . -func Upload(r *ghttp.Request) { - saveDirPath := "/tmp/" - files := r.GetUploadFiles("upload-file") - if _, err := files.Save(saveDirPath); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit("upload successfully") -} - -// UploadShow shows uploading simgle file page. -func UploadShow(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload File Demo - - -
- - -
- - - `) -} - -// UploadShowBatch shows uploading multiple files page. -func UploadShowBatch(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload Files Demo - - -
- - - -
- - - `) -} - -func main() { - s := g.Server() - s.Group("/upload", func(group *ghttp.RouterGroup) { - group.POST("/", Upload) - group.ALL("/show", UploadShow) - group.ALL("/batch", UploadShowBatch) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/client/upload/client.go b/.example/net/ghttp/client/upload/client.go deleted file mode 100644 index 606c5252a..000000000 --- a/.example/net/ghttp/client/upload/client.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "path/filepath" - - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func SendXmlFile(gameId int, areaName string, filePath string) error { - path := filepath.FromSlash(filePath) - fmt.Println(path) - data := g.Map{ - "gameName": gameId, - "area": areaName, - "file": "@file:" + path, - "contentType": "json", - } - if r, err := ghttp.Post("http://127.0.0.1:8199/upload", data); err != nil { - panic(err) - } else { - defer r.Close() - fmt.Println("ok") - } - return nil -} - -func main() { - SendXmlFile(1, "xxx", "/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/net/ghttp/server/session.go") - return - path := "/home/john/Workspace/Go/github.com/gogf/gf/version.go" - r, e := ghttp.Post("http://127.0.0.1:8199/upload", "upload-file=@file:"+path) - if e != nil { - glog.Error(e) - } else { - fmt.Println(string(r.ReadAll())) - r.Close() - } -} diff --git a/.example/net/ghttp/client/upload/server.go b/.example/net/ghttp/client/upload/server.go deleted file mode 100644 index 4573fae51..000000000 --- a/.example/net/ghttp/client/upload/server.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// Upload uploads files to /tmp . -func Upload(r *ghttp.Request) { - saveDirPath := "/tmp/" - files := r.GetUploadFiles("file") - if _, err := files.Save(saveDirPath); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit("upload successfully") -} - -// UploadShow shows uploading simgle file page. -func UploadShow(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload File Demo - - -
- - -
- - - `) -} - -// UploadShowBatch shows uploading multiple files page. -func UploadShowBatch(r *ghttp.Request) { - r.Response.Write(` - - - GF Upload Files Demo - - -
- - - -
- - - `) -} - -func main() { - s := g.Server() - s.Group("/upload", func(group *ghttp.RouterGroup) { - group.POST("/", Upload) - group.ALL("/show", UploadShow) - group.ALL("/batch", UploadShowBatch) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/admin/admin.go b/.example/net/ghttp/server/admin/admin.go deleted file mode 100644 index 640954823..000000000 --- a/.example/net/ghttp/server/admin/admin.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.SetNameToUriType(ghttp.URI_TYPE_FULLNAME) - s.EnableAdmin() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write("hello world") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/body.go b/.example/net/ghttp/server/body.go deleted file mode 100644 index ea762fd54..000000000 --- a/.example/net/ghttp/server/body.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "io/ioutil" -) - -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.BindHandler("/", func(r *ghttp.Request) { - body1 := r.GetBody() - body2, _ := ioutil.ReadAll(r.Body) - fmt.Println(body1) - fmt.Println(body2) - r.Response.Write("hello world") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/controller/template/footer.html b/.example/net/ghttp/server/controller/template/footer.html deleted file mode 100644 index 83ae25b65..000000000 --- a/.example/net/ghttp/server/controller/template/footer.html +++ /dev/null @@ -1 +0,0 @@ -

FOOTER

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/header.html b/.example/net/ghttp/server/controller/template/header.html deleted file mode 100644 index b9cb0a77c..000000000 --- a/.example/net/ghttp/server/controller/template/header.html +++ /dev/null @@ -1 +0,0 @@ -

HEADER

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/layout.html b/.example/net/ghttp/server/controller/template/layout.html deleted file mode 100644 index 9f58c21a0..000000000 --- a/.example/net/ghttp/server/controller/template/layout.html +++ /dev/null @@ -1,3 +0,0 @@ -{{include "header.html" .}} -{{include .mainTpl .}} -{{include "footer.html" .}} \ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/main/main1.html b/.example/net/ghttp/server/controller/template/main/main1.html deleted file mode 100644 index ac8fb6186..000000000 --- a/.example/net/ghttp/server/controller/template/main/main1.html +++ /dev/null @@ -1,2 +0,0 @@ -

MAIN1

-

Name: {{.name}}

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/template/main/main2.html b/.example/net/ghttp/server/controller/template/main/main2.html deleted file mode 100644 index 3d2351aea..000000000 --- a/.example/net/ghttp/server/controller/template/main/main2.html +++ /dev/null @@ -1,2 +0,0 @@ -

MAIN2

-

Name: {{.name}}

\ No newline at end of file diff --git a/.example/net/ghttp/server/controller/user.go b/.example/net/ghttp/server/controller/user.go deleted file mode 100644 index 1fe010bbf..000000000 --- a/.example/net/ghttp/server/controller/user.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -type User struct { - gmvc.Controller -} - -func (c *User) Index() { - c.View.Display("index.html") -} - -// 不符合规范,不会被自动注册 -func (c *User) Test(value interface{}) { - c.View.Display("index.html") -} - -func main() { - //g.View().SetPath("C:/www/static") - s := g.Server() - s.BindController("/user", new(User)) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/controller/view.go b/.example/net/ghttp/server/controller/view.go deleted file mode 100644 index 70f3f96c3..000000000 --- a/.example/net/ghttp/server/controller/view.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -type Controller struct { - gmvc.Controller -} - -func (c *Controller) Index() { - c.View.Assign("name", "john") - c.View.Assign("mainTpl", "main/main2.html") - c.View.Display("layout.html") -} - -func main() { - s := g.Server() - s.BindController("/view", new(Controller)) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cookie.go b/.example/net/ghttp/server/cookie.go deleted file mode 100644 index 7702456cb..000000000 --- a/.example/net/ghttp/server/cookie.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - s := g.Server() - s.BindHandler("/cookie", func(r *ghttp.Request) { - datetime := r.Cookie.Get("datetime") - r.Cookie.Set("datetime", gtime.Datetime()) - r.Response.Write("datetime:", datetime) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cors/cors1.go b/.example/net/ghttp/server/cors/cors1.go deleted file mode 100644 index 03c50b6aa..000000000 --- a/.example/net/ghttp/server/cors/cors1.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func Order(r *ghttp.Request) { - glog.Print("order") - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cors/cors2.go b/.example/net/ghttp/server/cors/cors2.go deleted file mode 100644 index 307ab1ddf..000000000 --- a/.example/net/ghttp/server/cors/cors2.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareCORS(r *ghttp.Request) { - corsOptions := r.Response.DefaultCORSOptions() - corsOptions.AllowDomain = []string{"goframe.org", "baidu.com"} - r.Response.CORS(corsOptions) - r.Middleware.Next() -} - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/cors/cors3.go b/.example/net/ghttp/server/cors/cors3.go deleted file mode 100644 index 499e75d28..000000000 --- a/.example/net/ghttp/server/cors/cors3.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareCORS(r *ghttp.Request) { - corsOptions := r.Response.DefaultCORSOptions() - corsOptions.AllowDomain = []string{"goframe.org"} - if !r.Response.CORSAllowedOrigin(corsOptions) { - r.Response.WriteStatus(http.StatusForbidden) - return - } - r.Response.CORS(corsOptions) - r.Middleware.Next() -} - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/denyroutes/config.toml b/.example/net/ghttp/server/denyroutes/config.toml deleted file mode 100644 index 0e7810036..000000000 --- a/.example/net/ghttp/server/denyroutes/config.toml +++ /dev/null @@ -1 +0,0 @@ -You're not supposed to view this \ No newline at end of file diff --git a/.example/net/ghttp/server/denyroutes/denyroutes.go b/.example/net/ghttp/server/denyroutes/denyroutes.go deleted file mode 100644 index 4dc0020f0..000000000 --- a/.example/net/ghttp/server/denyroutes/denyroutes.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -func main() { - s := g.Server() - s.SetDenyRoutes([]string{ - "/config*", - }) - s.SetPort(8299) - s.Run() -} diff --git a/.example/net/ghttp/server/domain.go b/.example/net/ghttp/server/domain.go deleted file mode 100644 index f43bc4611..000000000 --- a/.example/net/ghttp/server/domain.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/net/ghttp" - -func Hello1(r *ghttp.Request) { - r.Response.Write("127.0.0.1: Hello World1!") -} - -func Hello2(r *ghttp.Request) { - r.Response.Write("localhost: Hello World2!") -} - -func main() { - s := ghttp.GetServer() - s.Domain("127.0.0.1").BindHandler("/", Hello1) - s.Domain("localhost, local").BindHandler("/", Hello2) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/download/download.go b/.example/net/ghttp/server/download/download.go deleted file mode 100644 index cc1ebee35..000000000 --- a/.example/net/ghttp/server/download/download.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/download", func(r *ghttp.Request) { - r.Response.Header().Set("Content-Type", "text/html;charset=utf-8") - r.Response.Header().Set("Content-type", "application/force-download") - r.Response.Header().Set("Content-Type", "application/octet-stream") - r.Response.Header().Set("Accept-Ranges", "bytes") - r.Response.Header().Set("Content-Disposition", "attachment;filename=\"下载文件名称.txt\"") - r.Response.ServeFile("text.txt") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/download/text.txt b/.example/net/ghttp/server/download/text.txt deleted file mode 100644 index 7e7566d8c..000000000 --- a/.example/net/ghttp/server/download/text.txt +++ /dev/null @@ -1 +0,0 @@ -下载文件内容。 \ No newline at end of file diff --git a/.example/net/ghttp/server/duplicate/duplicate1.go b/.example/net/ghttp/server/duplicate/duplicate1.go deleted file mode 100644 index 65b506465..000000000 --- a/.example/net/ghttp/server/duplicate/duplicate1.go +++ /dev/null @@ -1,19 +0,0 @@ -// 路由重复注册检查 - handler -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/duplicate/duplicate2.go b/.example/net/ghttp/server/duplicate/duplicate2.go deleted file mode 100644 index 85bcae9a3..000000000 --- a/.example/net/ghttp/server/duplicate/duplicate2.go +++ /dev/null @@ -1,33 +0,0 @@ -// 路由重复注册检查 - controller -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -type User struct { - gmvc.Controller -} - -func (u *User) Index() { - u.Response.Write("User") -} - -func (u *User) Info() { - u.Response.Write("Info - Uid: ", u.Request.Get("uid")) -} - -func (u *User) List() { - u.Response.Write("List - Page: ", u.Request.Get("page")) -} - -func main() { - s := g.Server() - s.BindController("/user", new(User)) - s.BindController("/user/{.method}/{uid}", new(User), "Info") - s.BindController("/user/{.method}/{page}.html", new(User), "List") - s.BindController("/user/{.method}/{page}.html", new(User), "List") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/duplicate/duplicate3.go b/.example/net/ghttp/server/duplicate/duplicate3.go deleted file mode 100644 index e2b870f6c..000000000 --- a/.example/net/ghttp/server/duplicate/duplicate3.go +++ /dev/null @@ -1,25 +0,0 @@ -// 路由重复注册检查 - object -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type Object struct{} - -func (o *Object) Index(r *ghttp.Request) { - r.Response.Write("object index") -} - -func (o *Object) Show(r *ghttp.Request) { - r.Response.Write("object show") -} - -func main() { - s := g.Server() - g.Server().BindObject("/object", new(Object)) - g.Server().BindObject("/object", new(Object)) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/exit.go b/.example/net/ghttp/server/exit.go deleted file mode 100644 index c000f3270..000000000 --- a/.example/net/ghttp/server/exit.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - p := "/" - s := g.Server() - s.BindHandler(p, func(r *ghttp.Request) { - r.Response.Writeln("start") - r.Exit() - r.Response.Writeln("end") - }) - s.BindHookHandlerByMap(p, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - glog.To(r.Response.Writer).Print(r.Context(), "BeforeServe") - }, - ghttp.HookAfterServe: func(r *ghttp.Request) { - glog.To(r.Response.Writer).Print(r.Context(), "AfterServe") - }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/form/form-client.go b/.example/net/ghttp/server/form/form-client.go deleted file mode 100644 index 9a7e29bce..000000000 --- a/.example/net/ghttp/server/form/form-client.go +++ /dev/null @@ -1,9 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - ghttp.PostContent("http://127.0.0.1:8199/", "array[]=1&array[]=2") -} diff --git a/.example/net/ghttp/server/form/form.go b/.example/net/ghttp/server/form/form.go deleted file mode 100644 index 447ea6d78..000000000 --- a/.example/net/ghttp/server/form/form.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - g.Dump(r.GetForm("array")) - r.Response.WriteTpl("form.html") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/form/form.html b/.example/net/ghttp/server/form/form.html deleted file mode 100644 index 2619de805..000000000 --- a/.example/net/ghttp/server/form/form.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - form test - - -

form1

-
-

-

-

-

-

-

-

-

-

- -
- -

form2

-
-

-

-

-

-

- -
- \ No newline at end of file diff --git a/.example/net/ghttp/server/hello.go b/.example/net/ghttp/server/hello.go deleted file mode 100644 index 98bb79771..000000000 --- a/.example/net/ghttp/server/hello.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write("Hello World") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/cors1.go b/.example/net/ghttp/server/hooks/cors1.go deleted file mode 100644 index 352bac573..000000000 --- a/.example/net/ghttp/server/hooks/cors1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - g.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/cors2.go b/.example/net/ghttp/server/hooks/cors2.go deleted file mode 100644 index dfa1d170b..000000000 --- a/.example/net/ghttp/server/hooks/cors2.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func Order(r *ghttp.Request) { - r.Response.Write("GET") -} - -func main() { - s := g.Server() - s.Group("/api.v1", func(group *ghttp.RouterGroup) { - group.Hook("/*any", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.CORSDefault() - }) - g.GET("/order", Order) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks1.go b/.example/net/ghttp/server/hooks/hooks1.go deleted file mode 100644 index 817a11eca..000000000 --- a/.example/net/ghttp/server/hooks/hooks1.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 基本事件回调使用 - p := "/:name/info/{uid}" - s := g.Server() - s.BindHookHandlerByMap(p, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { glog.Print(ghttp.HookBeforeServe) }, - ghttp.HookAfterServe: func(r *ghttp.Request) { glog.Print(ghttp.HookAfterServe) }, - ghttp.HookBeforeOutput: func(r *ghttp.Request) { glog.Print(ghttp.HookBeforeOutput) }, - ghttp.HookAfterOutput: func(r *ghttp.Request) { glog.Print(ghttp.HookAfterOutput) }, - }) - s.BindHandler(p, func(r *ghttp.Request) { - r.Response.Write("用户:", r.Get("name"), ", uid:", r.Get("uid")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks4.go b/.example/net/ghttp/server/hooks/hooks4.go deleted file mode 100644 index b13b8de69..000000000 --- a/.example/net/ghttp/server/hooks/hooks4.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - // 多事件回调示例,事件1 - pattern1 := "/:name/info" - s.BindHookHandlerByMap(pattern1, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.SetParam("uid", 1000) - }, - }) - s.BindHandler(pattern1, func(r *ghttp.Request) { - r.Response.Write("用户:", r.Get("name"), ", uid:", r.Get("uid")) - }) - - // 多事件回调示例,事件2 - pattern2 := "/{object}/list/{page}.java" - s.BindHookHandlerByMap(pattern2, map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeOutput: func(r *ghttp.Request) { - r.Response.SetBuffer([]byte( - fmt.Sprintf("通过事件修改输出内容, object:%s, page:%s", r.Get("object"), r.GetRouterString("page"))), - ) - }, - }) - s.BindHandler(pattern2, func(r *ghttp.Request) { - r.Response.Write(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks5.go b/.example/net/ghttp/server/hooks/hooks5.go deleted file mode 100644 index c61a6b167..000000000 --- a/.example/net/ghttp/server/hooks/hooks5.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHookHandler("/*any", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Writeln("/*any") - }) - s.BindHookHandler("/v1/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Writeln("/v1/*") - r.ExitHook() - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/hooks_param.go b/.example/net/ghttp/server/hooks/hooks_param.go deleted file mode 100644 index 2670e276a..000000000 --- a/.example/net/ghttp/server/hooks/hooks_param.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("name")) - }) - s.BindHookHandlerByMap("/", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.SetParam("name", "john") - }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/hooks/same_route_multi_hook.go b/.example/net/ghttp/server/hooks/same_route_multi_hook.go deleted file mode 100644 index bd448bcb2..000000000 --- a/.example/net/ghttp/server/hooks/same_route_multi_hook.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/priority/show", func(r *ghttp.Request) { - r.Response.Writeln("priority service") - }) - - s.BindHookHandlerByMap("/priority/:name", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.Response.Writeln("/priority/:name") - }, - }) - s.BindHookHandlerByMap("/priority/*any", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.Response.Writeln("/priority/*any") - }, - }) - s.BindHookHandlerByMap("/priority/show", map[string]ghttp.HandlerFunc{ - ghttp.HookBeforeServe: func(r *ghttp.Request) { - r.Response.Writeln("/priority/show") - }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/https/https.go b/.example/net/ghttp/server/https/https.go deleted file mode 100644 index 5ccb9ab49..000000000 --- a/.example/net/ghttp/server/https/https.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("来自于HTTPS的:哈喽世界!") - }) - s.EnableHTTPS("./server.crt", "./server.key") - s.SetAccessLogEnabled(true) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/https/https_http.go b/.example/net/ghttp/server/https/https_http.go deleted file mode 100644 index dc5c3ff0e..000000000 --- a/.example/net/ghttp/server/https/https_http.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("您可以同时通过HTTP和HTTPS方式看到该内容!") - }) - s.EnableHTTPS("./server.crt", "./server.key") - s.SetHTTPSPort(8100, 8200) - s.SetPort(8300, 8400) - s.EnableAdmin() - s.Run() -} diff --git a/.example/net/ghttp/server/https/server.crt b/.example/net/ghttp/server/https/server.crt deleted file mode 100644 index 4d254ea21..000000000 --- a/.example/net/ghttp/server/https/server.crt +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDzzCCAregAwIBAgIJAJYpWLkC2lEXMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV -BAYTAkNIMRAwDgYDVQQIDAdTaUNodWFuMRAwDgYDVQQHDAdDaGVuZ2R1MRAwDgYD -VQQKDAdKb2huLmNuMQwwCgYDVQQLDANEZXYxDTALBgNVBAMMBEpvaG4xHDAaBgkq -hkiG9w0BCQEWDWpvaG5Aam9obmcuY24wHhcNMTgwNDIzMTMyNjA4WhcNMTkwNDIz -MTMyNjA4WjB+MQswCQYDVQQGEwJDSDEQMA4GA1UECAwHU2lDaHVhbjEQMA4GA1UE -BwwHQ2hlbmdkdTEQMA4GA1UECgwHSm9obi5jbjEMMAoGA1UECwwDRGV2MQ0wCwYD -VQQDDARKb2huMRwwGgYJKoZIhvcNAQkBFg1qb2huQGpvaG5nLmNuMIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlS -F/tCPyKINhsePGqHkR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg -+Vps/RimBpiz+RU3FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMz -CRKoZ2dQ+98o5LwES+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJIN -DIp5Ypszg1cPs0gIr5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIO -NcqaHeGaTUVjzX9XwRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABo1Aw -TjAdBgNVHQ4EFgQU1/tUQpOK0xEwLLlYDiNrckqPlDowHwYDVR0jBBgwFoAU1/tU -QpOK0xEwLLlYDiNrckqPlDowDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC -AQEA5MbG2xU3s/GDU1MV4f0wKhWCNhXfrLaYSwNYGT/eb8ZG2iHSTO0dvl0+pjO2 -EK63PDMvMhUtL1Zlyvl+OqssYcDhVfDzdFoYX6TZNbYxFwSzcx78mO6boAADk9ro -GEQWN+VHsl984SzBRZRJbtNbiw5iVuPruofeKHrrk4dLMiCsStyUaz9lUZxjo2Fi -vVJOY+mRNOBqz1HgU2+RilFTl04zWadCWPJMugQSgJcUPgxRXQ96PkC8uYevEnmR -2DUReSRULIOYEjHw0DZ6yGlqUkJcUGge3XAQEx3LlCpJasOC8Xpsh5i6WBnDPbMh -kPBjRRTooSrJOQJC5v3QW+0Kgw== ------END CERTIFICATE----- diff --git a/.example/net/ghttp/server/https/server.key b/.example/net/ghttp/server/https/server.key deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/ghttp/server/https/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/ghttp/server/https/server.key.public b/.example/net/ghttp/server/https/server.key.public deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/ghttp/server/https/server.key.public +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/ghttp/server/log/config.toml b/.example/net/ghttp/server/log/config.toml deleted file mode 100644 index 32a428e4d..000000000 --- a/.example/net/ghttp/server/log/config.toml +++ /dev/null @@ -1,7 +0,0 @@ -[server] - LogPath = "/tmp/gflog/server" - LogStdout = true - ErrorLogEnabled = true - ErrorLogPattern = "error.log" - AccessLogEnabled = true - AccessLogPattern = "access.log" \ No newline at end of file diff --git a/.example/net/ghttp/server/log/log.go b/.example/net/ghttp/server/log/log.go deleted file mode 100644 index 613a2c881..000000000 --- a/.example/net/ghttp/server/log/log.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "net/http" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/", func(r *ghttp.Request) { - r.Response.Write("halo world!") - }) - group.ALL("/log/handler", func(r *ghttp.Request) { - r.Response.WriteStatus(http.StatusNotFound, "File Not Found!") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/log/log_error.go b/.example/net/ghttp/server/log/log_error.go deleted file mode 100644 index 727592f21..000000000 --- a/.example/net/ghttp/server/log/log_error.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.BindHandler("/log/error", func(r *ghttp.Request) { - panic("OMG") - }) - s.SetErrorLogEnabled(true) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/auth.go b/.example/net/ghttp/server/middleware/auth.go deleted file mode 100644 index d4d4efdfd..000000000 --- a/.example/net/ghttp/server/middleware/auth.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS) - group.ALL("/user/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/auth_exception.go b/.example/net/ghttp/server/middleware/auth_exception.go deleted file mode 100644 index 2dbfbcc4f..000000000 --- a/.example/net/ghttp/server/middleware/auth_exception.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func main() { - s := g.Server() - s.Group("/admin", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - if action := r.GetRouterString("action"); action != "" { - switch action { - case "login": - r.Middleware.Next() - return - } - } - MiddlewareAuth(r) - }) - group.ALL("/login", func(r *ghttp.Request) { - r.Response.Write("login") - }) - group.ALL("/dashboard", func(r *ghttp.Request) { - r.Response.Write("dashboard") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/cors.go b/.example/net/ghttp/server/middleware/cors.go deleted file mode 100644 index 761d7f458..000000000 --- a/.example/net/ghttp/server/middleware/cors.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareCORS) - group.ALL("/user/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/error_handling.go b/.example/net/ghttp/server/middleware/error_handling.go deleted file mode 100644 index 9eee48fe3..000000000 --- a/.example/net/ghttp/server/middleware/error_handling.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func MiddlewareError(r *ghttp.Request) { - r.Middleware.Next() - if r.Response.Status >= http.StatusInternalServerError { - r.Response.ClearBuffer() - r.Response.Write("Internal error occurred, please try again later.") - } -} - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS, MiddlewareError) - group.ALL("/user/list", func(r *ghttp.Request) { - panic("db error: sql is xxxxxxx") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/issue355.go b/.example/net/ghttp/server/middleware/issue355.go deleted file mode 100644 index 048530a70..000000000 --- a/.example/net/ghttp/server/middleware/issue355.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindMiddlewareDefault(func(r *ghttp.Request) { - fmt.Println("cors") - r.Response.CORSDefault() - r.Middleware.Next() - }) - s.BindHandler("/api/captcha", func(r *ghttp.Request) { - r.Response.Write("captcha") - }) - s.SetPort(8010) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/log.go b/.example/net/ghttp/server/middleware/log.go deleted file mode 100644 index 09869d7ad..000000000 --- a/.example/net/ghttp/server/middleware/log.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/os/glog" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func MiddlewareLog(r *ghttp.Request) { - r.Middleware.Next() - g.Log().Print(r.Response.Status, r.URL.Path) -} - -func main() { - s := g.Server() - s.Use(MiddlewareLog) - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS) - group.ALL("/user/list", func(r *ghttp.Request) { - panic("custom error") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/middleware.go b/.example/net/ghttp/server/middleware/middleware.go deleted file mode 100644 index 7ebad3f37..000000000 --- a/.example/net/ghttp/server/middleware/middleware.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - r.Response.Write("start") - r.Middleware.Next() - r.Response.Write("end") - }) - group.Group("/order", func(group *ghttp.RouterGroup) { - group.GET("/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - }) - group.Group("/user", func(group *ghttp.RouterGroup) { - group.GET("/info", func(r *ghttp.Request) { - r.Response.Write("info") - }) - group.POST("/edit", func(r *ghttp.Request) { - r.Response.Write("edit") - }) - }) - group.Group("/hook", func(group *ghttp.RouterGroup) { - group.Hook("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook any") - }) - group.Hook("/:name", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook name") - }) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/middleware/param.go b/.example/net/ghttp/server/middleware/param.go deleted file mode 100644 index 385db1d96..000000000 --- a/.example/net/ghttp/server/middleware/param.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// 前置中间件1 -func MiddlewareBefore1(r *ghttp.Request) { - r.SetParam("name", "GoFrame") - r.Response.Writeln("set name") - r.Middleware.Next() -} - -// 前置中间件2 -func MiddlewareBefore2(r *ghttp.Request) { - r.SetParam("site", "https://goframe.org") - r.Response.Writeln("set site") - r.Middleware.Next() -} - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareBefore1, MiddlewareBefore2) - group.ALL("/", func(r *ghttp.Request) { - r.Response.Writefln( - "%s: %s", - r.GetParamVar("name").String(), - r.GetParamVar("site").String(), - ) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/name.go b/.example/net/ghttp/server/name.go deleted file mode 100644 index fc5d5499b..000000000 --- a/.example/net/ghttp/server/name.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type User struct{} - -func (u *User) ShowList(r *ghttp.Request) { - r.Response.Write("list") -} - -func main() { - s1 := g.Server(1) - s2 := g.Server(2) - s3 := g.Server(3) - s4 := g.Server(4) - - s1.SetNameToUriType(ghttp.URI_TYPE_DEFAULT) - s2.SetNameToUriType(ghttp.URI_TYPE_FULLNAME) - s3.SetNameToUriType(ghttp.URI_TYPE_ALLLOWER) - s4.SetNameToUriType(ghttp.URI_TYPE_CAMEL) - - s1.BindObject("/{.struct}/{.method}", new(User)) - s2.BindObject("/{.struct}/{.method}", new(User)) - s3.BindObject("/{.struct}/{.method}", new(User)) - s4.BindObject("/{.struct}/{.method}", new(User)) - - s1.SetPort(8100) - s2.SetPort(8200) - s3.SetPort(8300) - s4.SetPort(8400) - - s1.Start() - s2.Start() - s3.Start() - s4.Start() - - g.Wait() -} diff --git a/.example/net/ghttp/server/nethttp_server.go b/.example/net/ghttp/server/nethttp_server.go deleted file mode 100644 index ec30e5608..000000000 --- a/.example/net/ghttp/server/nethttp_server.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "net/http" - "time" -) - -func main() { - s := &http.Server{ - Addr: ":8199", - ReadTimeout: 2 * time.Second, - WriteTimeout: 2 * time.Second, - } - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("hi")) - time.Sleep(3 * time.Second) - }) - s.ListenAndServe() -} diff --git a/.example/net/ghttp/server/object/user.go b/.example/net/ghttp/server/object/user.go deleted file mode 100644 index 89215b840..000000000 --- a/.example/net/ghttp/server/object/user.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type User struct{} - -func (c *User) Test(r *ghttp.Request) { - r.Response.Write("Test") -} - -func main() { - s := g.Server() - u := new(User) - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/db-{table}/{id}", u, "Test") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/openapi/openapi.go b/.example/net/ghttp/server/openapi/openapi.go deleted file mode 100644 index 1cad75843..000000000 --- a/.example/net/ghttp/server/openapi/openapi.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type HelloReq struct { - g.Meta `path:"/hello" tags:"Test" method:"get" description:"Hello world handler for test"` - Content string `json:"content" in:"query"` -} - -type HelloRes struct { - Content string `json:"content" description:"Hello response content for test"` -} - -// Hello is an example handler. -func Hello(ctx context.Context, req *HelloReq) (res *HelloRes, err error) { - return &HelloRes{Content: req.Content}, nil -} - -func main() { - s := g.Server() - s.Use( - ghttp.MiddlewareHandlerResponse, - ) - s.BindHandler("/hello", Hello) - s.SetOpenApiPath("/api.json") - s.SetSwaggerPath("/swagger") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/ports.go b/.example/net/ghttp/server/ports.go deleted file mode 100644 index dfb187c66..000000000 --- a/.example/net/ghttp/server/ports.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("go frame!") - }) - s.SetPort(8100, 8200, 8300) - s.Run() -} diff --git a/.example/net/ghttp/server/pprof.go b/.example/net/ghttp/server/pprof.go deleted file mode 100644 index 800f098f0..000000000 --- a/.example/net/ghttp/server/pprof.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Domain("localhost").EnablePProf() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/redirect/redirect_back.go b/.example/net/ghttp/server/redirect/redirect_back.go deleted file mode 100644 index 2e2f93e15..000000000 --- a/.example/net/ghttp/server/redirect/redirect_back.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/page", func(r *ghttp.Request) { - r.Response.Writeln(`back`) - }) - s.BindHandler("/back", func(r *ghttp.Request) { - r.Response.RedirectBack() - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/redirect/redirect_to.go b/.example/net/ghttp/server/redirect/redirect_to.go deleted file mode 100644 index b67b5a3c6..000000000 --- a/.example/net/ghttp/server/redirect/redirect_to.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.RedirectTo("/login") - }) - s.BindHandler("/login", func(r *ghttp.Request) { - r.Response.Writeln("Login First") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/reload/admin.go b/.example/net/ghttp/server/reload/admin.go deleted file mode 100644 index eff842a5a..000000000 --- a/.example/net/ghttp/server/reload/admin.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{"Graceful": true}) - s.EnableAdmin() - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/reload/https.go b/.example/net/ghttp/server/reload/https.go deleted file mode 100644 index ace087ee6..000000000 --- a/.example/net/ghttp/server/reload/https.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈罗!") - }) - s.EnableHTTPS("/home/john/temp/server.crt", "/home/john/temp/server.key") - s.EnableAdmin() - s.SetPort(8200) - s.Run() -} diff --git a/.example/net/ghttp/server/reload/https_http.go b/.example/net/ghttp/server/reload/https_http.go deleted file mode 100644 index b0e8de1e8..000000000 --- a/.example/net/ghttp/server/reload/https_http.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.EnableAdmin() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("您可以同时通过HTTP和HTTPS方式看到该内容!") - }) - s.EnableHTTPS("/home/john/temp/server.crt", "/home/john/temp/server.key") - s.SetHTTPSPort(8198, 8199) - s.SetPort(8200, 8300) - s.EnableAdmin() - s.Run() -} diff --git a/.example/net/ghttp/server/reload/multi_port_and_server.go b/.example/net/ghttp/server/reload/multi_port_and_server.go deleted file mode 100644 index e6c4b5233..000000000 --- a/.example/net/ghttp/server/reload/multi_port_and_server.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s1 := g.Server("s1") - s1.EnableAdmin() - s1.SetPort(8100, 8200) - s1.Start() - - s2 := g.Server("s2") - s2.EnableAdmin() - s2.SetPort(8300, 8400) - s2.Start() - - g.Wait() -} diff --git a/.example/net/ghttp/server/reload/simple.go b/.example/net/ghttp/server/reload/simple.go deleted file mode 100644 index a5b06250b..000000000 --- a/.example/net/ghttp/server/reload/simple.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("哈喽!") - }) - s.BindHandler("/pid", func(r *ghttp.Request) { - r.Response.Writeln(gproc.Pid()) - }) - s.BindHandler("/sleep", func(r *ghttp.Request) { - r.Response.Writeln(gproc.Pid()) - time.Sleep(10 * time.Second) - r.Response.Writeln(gproc.Pid()) - }) - s.EnableAdmin() - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/basic.go b/.example/net/ghttp/server/request/basic.go deleted file mode 100644 index 3c4aedf28..000000000 --- a/.example/net/ghttp/server/request/basic.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("amount")) - r.Response.Writeln(r.GetInt("amount")) - r.Response.Writeln(r.GetFloat32("amount")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/exit/exit.go b/.example/net/ghttp/server/request/exit/exit.go deleted file mode 100644 index 57d43e0d2..000000000 --- a/.example/net/ghttp/server/request/exit/exit.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - if r.GetInt("type") == 1 { - r.Response.Writeln("john") - } - r.Response.Writeln("smith") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/json-xml/test1.go b/.example/net/ghttp/server/request/json-xml/test1.go deleted file mode 100644 index aabe06e5a..000000000 --- a/.example/net/ghttp/server/request/json-xml/test1.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writef("name: %v, pass: %v", r.Get("name"), r.Get("pass")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/json-xml/test2.go b/.example/net/ghttp/server/request/json-xml/test2.go deleted file mode 100644 index 21b8de109..000000000 --- a/.example/net/ghttp/server/request/json-xml/test2.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gvalid" -) - -type RegisterReq struct { - Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"` - Pass string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"` - Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|两次密码不一致"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - //fmt.Println(r.GetBody()) - if err := r.Parse(&req); err != nil { - // Validation error. - if v, ok := err.(gvalid.Error); ok { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: v.FirstString(), - }) - } - // Other error. - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/params/array.go b/.example/net/ghttp/server/request/params/array.go deleted file mode 100644 index 36ba6055f..000000000 --- a/.example/net/ghttp/server/request/params/array.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write(r.Get("array")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/params/map.go b/.example/net/ghttp/server/request/params/map.go deleted file mode 100644 index bc913ae33..000000000 --- a/.example/net/ghttp/server/request/params/map.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write(r.Get("map")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/params/repeat.go b/.example/net/ghttp/server/request/params/repeat.go deleted file mode 100644 index ba8f18e63..000000000 --- a/.example/net/ghttp/server/request/params/repeat.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Write(r.Get("name")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/priority.go b/.example/net/ghttp/server/request/priority.go deleted file mode 100644 index 93ced6777..000000000 --- a/.example/net/ghttp/server/request/priority.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/input", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("amount")) - }) - s.BindHandler("/query", func(r *ghttp.Request) { - r.Response.Writeln(r.GetQuery("amount")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/request_struct.go b/.example/net/ghttp/server/request/request_struct.go deleted file mode 100644 index dfc15e349..000000000 --- a/.example/net/ghttp/server/request/request_struct.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - type User struct { - Uid int `json:"uid"` - Name string `json:"name" p:"username"` - Pass1 string `json:"pass1" p:"password1"` - Pass2 string `json:"pass2" p:"password2"` - } - - s := g.Server() - s.BindHandler("/user", func(r *ghttp.Request) { - var user *User - if err := r.Parse(&user); err != nil { - panic(err) - } - r.Response.WriteJson(user) - }) - s.SetPort(8199) - s.Run() - - // http://127.0.0.1:8199/user?uid=1&name=john&password1=123&userpass2=123 - // {"name":"john","pass1":"123","pass2":"123","uid":1} -} diff --git a/.example/net/ghttp/server/request/request_validation.go b/.example/net/ghttp/server/request/request_validation.go deleted file mode 100644 index a6ab6185f..000000000 --- a/.example/net/ghttp/server/request/request_validation.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gvalid" -) - -type User struct { - Uid int `gvalid:"uid@min:1"` - Name string `params:"username" gvalid:"username @required|length:6,30"` - Pass1 string `params:"password1" gvalid:"password1@required|password3"` - Pass2 string `params:"password2" gvalid:"password2@required|password3|same:password1#||两次密码不一致,请重新输入"` -} - -func main() { - s := g.Server() - s.Group("/", func(rgroup *ghttp.RouterGroup) { - rgroup.ALL("/user", func(r *ghttp.Request) { - user := new(User) - if err := r.GetStruct(user); err != nil { - r.Response.WriteJsonExit(g.Map{ - "message": err, - "errcode": 1, - }) - } - if err := gvalid.CheckStruct(r.Context(), user, nil); err != nil { - r.Response.WriteJsonExit(g.Map{ - "message": err.Maps(), - "errcode": 1, - }) - } - r.Response.WriteJsonExit(g.Map{ - "message": "ok", - "errcode": 0, - }) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/struct/parse1.go b/.example/net/ghttp/server/request/struct/parse1.go deleted file mode 100644 index f00d79c81..000000000 --- a/.example/net/ghttp/server/request/struct/parse1.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - type User struct { - Id int `json:"id"` - Name string `json:"name"` - Pass1 string `json:"password1" p:"password1"` - Pass2 string `json:"password2" p:"password2"` - } - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - var user *User - if err := r.Parse(&user); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit(user) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/struct/parse2.go b/.example/net/ghttp/server/request/struct/parse2.go deleted file mode 100644 index 8d5f19786..000000000 --- a/.example/net/ghttp/server/request/struct/parse2.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type RegisterReq struct { - Name string - Pass string `p:"password1"` - Pass2 string `p:"password2"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - if err := r.Parse(&req); err != nil { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/validation/validation1/validation1.go b/.example/net/ghttp/server/request/validation/validation1/validation1.go deleted file mode 100644 index 759115fa1..000000000 --- a/.example/net/ghttp/server/request/validation/validation1/validation1.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type RegisterReq struct { - Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"` - Pass string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"` - Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|两次密码不一致"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - if err := r.Parse(&req); err != nil { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/request/validation/validation2/validation2.go b/.example/net/ghttp/server/request/validation/validation2/validation2.go deleted file mode 100644 index 93f5d021f..000000000 --- a/.example/net/ghttp/server/request/validation/validation2/validation2.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gvalid" -) - -type RegisterReq struct { - Name string `p:"username" v:"required|length:6,30#请输入账号|账号长度为:min到:max位"` - Pass string `p:"password1" v:"required|length:6,30#请输入密码|密码长度不够"` - Pass2 string `p:"password2" v:"required|length:6,30|same:password1#请确认密码|两次密码不一致"` -} - -type RegisterRes struct { - Code int `json:"code"` - Error string `json:"error"` - Data interface{} `json:"data"` -} - -func main() { - s := g.Server() - s.BindHandler("/register", func(r *ghttp.Request) { - var req *RegisterReq - if err := r.Parse(&req); err != nil { - // Validation error. - if v, ok := err.(gvalid.Error); ok { - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: v.FirstString(), - }) - } - // Other error. - r.Response.WriteJsonExit(RegisterRes{ - Code: 1, - Error: err.Error(), - }) - } - // ... - r.Response.WriteJsonExit(RegisterRes{ - Data: req, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/resource/resource.go b/.example/net/ghttp/server/resource/resource.go deleted file mode 100644 index c5b63fec9..000000000 --- a/.example/net/ghttp/server/resource/resource.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata/data" -) - -func main() { - gres.Dump() - - //v := g.View() - //v.SetPath("template/layout1") - - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("root") - s.BindHookHandler("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - fmt.Println(r.URL.Path, r.IsFileRequest()) - }) - s.BindHandler("/template", func(r *ghttp.Request) { - r.Response.WriteTpl("layout1/layout.html") - }) - s.SetPort(8198) - s.Run() -} diff --git a/.example/net/ghttp/server/reuseport/reuseport.go b/.example/net/ghttp/server/reuseport/reuseport.go deleted file mode 100644 index a3d3764fa..000000000 --- a/.example/net/ghttp/server/reuseport/reuseport.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - s1 := ghttp.GetServer("s1") - s1.SetPort(8882) - s1.BindHandler("/", func(r *ghttp.Request) { - glog.Print(r.Context(), "s1") - r.Response.Writeln("s1") - }) - s1.Start() - - s2 := ghttp.GetServer("s2") - s2.SetPort(8882) - s2.BindHandler("/", func(r *ghttp.Request) { - glog.Print(r.Context(), "s2") - r.Response.Writeln("s2") - }) - s2.Start() - - g.Wait() -} diff --git a/.example/net/ghttp/server/router/duplicated/duplicated.go b/.example/net/ghttp/server/router/duplicated/duplicated.go deleted file mode 100644 index fb23d03a2..000000000 --- a/.example/net/ghttp/server/router/duplicated/duplicated.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/test", func(r *ghttp.Request) { - r.Response.Writeln(1) - }) - group.ALL("/test", func(r *ghttp.Request) { - r.Response.Writeln(2) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/group/basic.go b/.example/net/ghttp/server/router/group/basic.go deleted file mode 100644 index bd87d6867..000000000 --- a/.example/net/ghttp/server/router/group/basic.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - group := s.Group("/api") - group.ALL("/all", func(r *ghttp.Request) { - r.Response.Write("all") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.Write("get") - }) - group.POST("/post", func(r *ghttp.Request) { - r.Response.Write("post") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/group/batch.go b/.example/net/ghttp/server/router/group/batch.go deleted file mode 100644 index 185393e7f..000000000 --- a/.example/net/ghttp/server/router/group/batch.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -type Object struct{} - -func (o *Object) Show(r *ghttp.Request) { - r.Response.Writeln("Show") -} - -func (o *Object) Delete(r *ghttp.Request) { - r.Response.Writeln("REST Delete") -} - -func Handler(r *ghttp.Request) { - r.Response.Writeln("Handler") -} - -func HookHandler(r *ghttp.Request) { - r.Response.Writeln("HOOK Handler") -} - -func main() { - s := g.Server() - obj := new(Object) - s.Group("/api").Bind([]ghttp.GroupItem{ - {"ALL", "*", HookHandler, ghttp.HookBeforeServe}, - {"ALL", "/handler", Handler}, - {"ALL", "/obj", obj}, - {"GET", "/obj/show", obj, "Show"}, - {"REST", "/obj/rest", obj}, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/group/level.go b/.example/net/ghttp/server/router/group/level.go deleted file mode 100644 index f0563e671..000000000 --- a/.example/net/ghttp/server/router/group/level.go +++ /dev/null @@ -1,67 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func MiddlewareAuth(r *ghttp.Request) { - token := r.Get("token") - if token == "123456" { - r.Middleware.Next() - } else { - r.Response.WriteStatus(http.StatusForbidden) - } -} - -func MiddlewareCORS(r *ghttp.Request) { - r.Response.CORSDefault() - r.Middleware.Next() -} - -func MiddlewareLog(r *ghttp.Request) { - r.Middleware.Next() - g.Log().Print(r.Response.Status, r.URL.Path) -} - -func main() { - s := g.Server() - s.Use(MiddlewareLog) - s.Group("/api.v2", func(group *ghttp.RouterGroup) { - group.Middleware(MiddlewareAuth, MiddlewareCORS) - group.GET("/test", func(r *ghttp.Request) { - r.Response.Write("test") - }) - group.Group("/order", func(group *ghttp.RouterGroup) { - group.GET("/list", func(r *ghttp.Request) { - r.Response.Write("list") - }) - group.PUT("/update", func(r *ghttp.Request) { - r.Response.Write("update") - }) - }) - group.Group("/user", func(group *ghttp.RouterGroup) { - group.GET("/info", func(r *ghttp.Request) { - r.Response.Write("info") - }) - group.POST("/edit", func(r *ghttp.Request) { - r.Response.Write("edit") - }) - group.DELETE("/drop", func(r *ghttp.Request) { - r.Response.Write("drop") - }) - }) - group.Group("/hook", func(group *ghttp.RouterGroup) { - group.Hook("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook any") - }) - group.Hook("/:name", ghttp.HookBeforeServe, func(r *ghttp.Request) { - r.Response.Write("hook name") - }) - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router1.go b/.example/net/ghttp/server/router/router1.go deleted file mode 100644 index ce2276266..000000000 --- a/.example/net/ghttp/server/router/router1.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/:name", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/:name/update", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/:name/:action", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/:name/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/list/{field}.html", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router2.go b/.example/net/ghttp/server/router/router2.go deleted file mode 100644 index 3732e8026..000000000 --- a/.example/net/ghttp/server/router/router2.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/user/:name", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/edit/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/edit/sex", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/member/:name/edit/info/*any", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/user/community/female/:name", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/admin/stats/today/:hour", func(r *ghttp.Request) { - r.Response.Writeln(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router3.go b/.example/net/ghttp/server/router/router3.go deleted file mode 100644 index dbf6ba73d..000000000 --- a/.example/net/ghttp/server/router/router3.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - // 一个简单的分页路由示例 - s.BindHandler("/user/list/{page}.html", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("page")) - }) - // {xxx} 规则与 :xxx 规则混合使用 - s.BindHandler("/{object}/:attr/{act}.php", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("object")) - r.Response.Writeln(r.Get("attr")) - r.Response.Writeln(r.Get("act")) - }) - // 多种模糊匹配规则混合使用 - s.BindHandler("/{class}-{course}/:name/*act", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("class")) - r.Response.Writeln(r.Get("course")) - r.Response.Writeln(r.Get("name")) - r.Response.Writeln(r.Get("act")) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router4.go b/.example/net/ghttp/server/router/router4.go deleted file mode 100644 index 3218be3ea..000000000 --- a/.example/net/ghttp/server/router/router4.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - // 该路由规则仅会在GET请求下有效 - s.BindHandler("GET:/{table}/list/{page}.html", func(r *ghttp.Request) { - r.Response.WriteJson(r.Router) - }) - // 该路由规则仅会在GET请求及localhost域名下有效 - s.BindHandler("GET:/order/info/{order_id}@localhost", func(r *ghttp.Request) { - r.Response.WriteJson(r.Router) - }) - // 该路由规则仅会在DELETE请求下有效 - s.BindHandler("DELETE:/comment/{id}", func(r *ghttp.Request) { - r.Response.WriteJson(r.Router) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router5.go b/.example/net/ghttp/server/router/router5.go deleted file mode 100644 index 06664e3b5..000000000 --- a/.example/net/ghttp/server/router/router5.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHookHandler("/*any", ghttp.HookBeforeServe, func(r *ghttp.Request) { - fmt.Println(r.Router) - fmt.Println(r.Get("customer_id")) - }) - s.BindHandler("/admin/customer/{customer_id}/edit", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("customer_id")) - r.Response.Writeln(r.Router.Uri) - }) - s.BindHandler("/admin/customer/{customer_id}/disable", func(r *ghttp.Request) { - r.Response.Writeln(r.Get("customer_id")) - r.Response.Writeln(r.Router.Uri) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/router/router6.go b/.example/net/ghttp/server/router/router6.go deleted file mode 100644 index 548acfc5e..000000000 --- a/.example/net/ghttp/server/router/router6.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// 试试模糊匹配规则不带名称会怎么样 -func main() { - s := g.Server() - s.BindHandler("/hello/*", func(r *ghttp.Request) { - r.Response.Writeln("哈喽世界!") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/servefile/servefile.go b/.example/net/ghttp/server/servefile/servefile.go deleted file mode 100644 index 85d52b650..000000000 --- a/.example/net/ghttp/server/servefile/servefile.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.ServeFile("test.txt") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/servefile/servefiledownload.go b/.example/net/ghttp/server/servefile/servefiledownload.go deleted file mode 100644 index 9c9f67ff5..000000000 --- a/.example/net/ghttp/server/servefile/servefiledownload.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.ServeFileDownload("test.txt") - }) - s.SetPort(8999) - s.Run() -} diff --git a/.example/net/ghttp/server/servefile/test.txt b/.example/net/ghttp/server/servefile/test.txt deleted file mode 100644 index 30d74d258..000000000 --- a/.example/net/ghttp/server/servefile/test.txt +++ /dev/null @@ -1 +0,0 @@ -test \ No newline at end of file diff --git a/.example/net/ghttp/server/server2.go b/.example/net/ghttp/server/server2.go deleted file mode 100644 index fe96ae6bb..000000000 --- a/.example/net/ghttp/server/server2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s1 := ghttp.GetServer("s1") - s1.SetAddr(":8080") - s1.SetIndexFolder(true) - s1.SetServerRoot("/home/www/static1") - go s1.Run() - - s2 := ghttp.GetServer("s2") - s2.SetAddr(":8081") - s2.SetIndexFolder(true) - s2.SetServerRoot("/home/www/static2") - go s2.Run() - - select {} -} diff --git a/.example/net/ghttp/server/session.go b/.example/net/ghttp/server/session.go deleted file mode 100644 index 704bc8a6d..000000000 --- a/.example/net/ghttp/server/session.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - s := g.Server() - s.BindHandler("/session", func(r *ghttp.Request) { - id := r.Session.GetInt("id") - r.Session.Set("id", id+1) - r.Response.Write("id:" + gconv.String(id)) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/session/basic/session.go b/.example/net/ghttp/server/session/basic/session.go deleted file mode 100644 index b2d101845..000000000 --- a/.example/net/ghttp/server/session/basic/session.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.WriteJson(r.Session.Map()) - }) - group.GET("/clear", func(r *ghttp.Request) { - r.Session.Clear() - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/session/redis/config.toml b/.example/net/ghttp/server/session/redis/config.toml deleted file mode 100644 index d5195ad6d..000000000 --- a/.example/net/ghttp/server/session/redis/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[redis] - default = "127.0.0.1:6379,10" \ No newline at end of file diff --git a/.example/net/ghttp/server/session/redis/redis.go b/.example/net/ghttp/server/session/redis/redis.go deleted file mode 100644 index f581dcdcd..000000000 --- a/.example/net/ghttp/server/session/redis/redis.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetSessionMaxAge(2 * time.Minute) - s.SetSessionStorage(gsession.NewStorageRedis(g.Redis())) - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.WriteJson(r.Session.Map()) - }) - group.GET("/clear", func(r *ghttp.Request) { - r.Session.Clear() - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/session/redis/redis_bigint.go b/.example/net/ghttp/server/session/redis/redis_bigint.go deleted file mode 100644 index 07580bbfd..000000000 --- a/.example/net/ghttp/server/session/redis/redis_bigint.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" -) - -func main() { - type User struct { - Id int64 - Name string - } - s := g.Server() - s.SetSessionStorage(gsession.NewStorageRedis(g.Redis())) - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/set", func(r *ghttp.Request) { - user := &User{ - Id: 1265476890672672808, - Name: "john", - } - if err := r.Session.Set("user", user); err != nil { - panic(err) - } - r.Response.Write("ok") - }) - group.GET("/get", func(r *ghttp.Request) { - r.Response.WriteJson(r.Session.Get("user")) - }) - group.GET("/clear", func(r *ghttp.Request) { - r.Session.Clear() - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/static/static.go b/.example/net/ghttp/server/static/static.go deleted file mode 100644 index 2a06b196d..000000000 --- a/.example/net/ghttp/server/static/static.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -// 静态文件服务器基本使用 -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("/Users/john/Downloads") - //s.AddSearchPath("/Users/john/Documents") - s.SetErrorLogEnabled(true) - s.SetAccessLogEnabled(true) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/static/static_path.go b/.example/net/ghttp/server/static/static_path.go deleted file mode 100644 index 30579ec53..000000000 --- a/.example/net/ghttp/server/static/static_path.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -// 静态文件服务器,支持自定义静态目录映射 -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("/Users/john/Temp") - s.AddSearchPath("/Users/john/Documents") - s.AddStaticPath("/my-doc", "/Users/john/Documents") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/static/static_path2.go b/.example/net/ghttp/server/static/static_path2.go deleted file mode 100644 index 30c5c3258..000000000 --- a/.example/net/ghttp/server/static/static_path2.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/frame/g" - -// 静态文件服务器,支持自定义静态目录映射 -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.SetServerRoot("/Users/john/Temp") - s.AddSearchPath("/Users/john/Documents") - s.AddStaticPath("/my-doc", "/Users/john/Documents") - s.AddStaticPath("/my-doc/test", "/Users/john/Temp") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/status.go b/.example/net/ghttp/server/status.go deleted file mode 100644 index c06feca06..000000000 --- a/.example/net/ghttp/server/status.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.Writeln("halo 世界!") - }) - s.BindStatusHandler(404, func(r *ghttp.Request) { - r.Response.Writeln("This is customized 404 page") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/status_map.go b/.example/net/ghttp/server/status_map.go deleted file mode 100644 index 517af3fc8..000000000 --- a/.example/net/ghttp/server/status_map.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindStatusHandlerByMap(map[int]ghttp.HandlerFunc{ - 403: func(r *ghttp.Request) { r.Response.Writeln("403") }, - 404: func(r *ghttp.Request) { r.Response.Writeln("404") }, - 500: func(r *ghttp.Request) { r.Response.Writeln("500") }, - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/status_redirect.go b/.example/net/ghttp/server/status_redirect.go deleted file mode 100644 index 5658a3109..000000000 --- a/.example/net/ghttp/server/status_redirect.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/status/:status", func(r *ghttp.Request) { - r.Response.Write("woops, status ", r.Get("status"), " found") - }) - s.BindStatusHandler(404, func(r *ghttp.Request) { - r.Response.RedirectTo("/status/404") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/build-in/objects/objects.go b/.example/net/ghttp/server/template/build-in/objects/objects.go deleted file mode 100644 index 69d1311e5..000000000 --- a/.example/net/ghttp/server/template/build-in/objects/objects.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - content := `{{.Request.Get "name"}}` - r.Response.WriteTplContent(content) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/build-in/vars/config.toml b/.example/net/ghttp/server/template/build-in/vars/config.toml deleted file mode 100644 index cf3c1cdf6..000000000 --- a/.example/net/ghttp/server/template/build-in/vars/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - disk = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/net/ghttp/server/template/build-in/vars/vars.go b/.example/net/ghttp/server/template/build-in/vars/vars.go deleted file mode 100644 index 0d6544202..000000000 --- a/.example/net/ghttp/server/template/build-in/vars/vars.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Cookie.Set("theme", "default") - r.Session.Set("name", "john") - content := ` -Get: {{.Get.name}} -Post: {{.Post.name}} -Config: {{.Config.redis}} -Cookie: {{.Cookie.theme}}, -Session: {{.Session.name}}` - r.Response.WriteTplContent(content) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/config/config.go b/.example/net/ghttp/server/template/config/config.go deleted file mode 100644 index 94eaa48d6..000000000 --- a/.example/net/ghttp/server/template/config/config.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTplContent(`${.name}`, g.Map{ - "name": "john", - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/config/config.toml b/.example/net/ghttp/server/template/config/config.toml deleted file mode 100644 index 1d5fc0dbb..000000000 --- a/.example/net/ghttp/server/template/config/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[viewer] - delimiters = ["${", "}"] \ No newline at end of file diff --git a/.example/net/ghttp/server/template/conflicts-name/client.go b/.example/net/ghttp/server/template/conflicts-name/client.go deleted file mode 100644 index c82e35f1a..000000000 --- a/.example/net/ghttp/server/template/conflicts-name/client.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -// https://github.com/gogf/gf/issues/437 -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTpl("client/layout.html") - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/conflicts-name/template/client/layout.html b/.example/net/ghttp/server/template/conflicts-name/template/client/layout.html deleted file mode 100644 index 56a6051ca..000000000 --- a/.example/net/ghttp/server/template/conflicts-name/template/client/layout.html +++ /dev/null @@ -1 +0,0 @@ -1 \ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/main.go b/.example/net/ghttp/server/template/layout/main.go deleted file mode 100644 index 9040ced33..000000000 --- a/.example/net/ghttp/server/template/layout/main.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/main1", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "mainTpl": "main/main1.html", - }) - }) - s.BindHandler("/main2", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "mainTpl": "main/main2.html", - }) - }) - g.View().SetPath("template") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/layout/template/footer.html b/.example/net/ghttp/server/template/layout/template/footer.html deleted file mode 100644 index 83ae25b65..000000000 --- a/.example/net/ghttp/server/template/layout/template/footer.html +++ /dev/null @@ -1 +0,0 @@ -

FOOTER

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/header.html b/.example/net/ghttp/server/template/layout/template/header.html deleted file mode 100644 index b9cb0a77c..000000000 --- a/.example/net/ghttp/server/template/layout/template/header.html +++ /dev/null @@ -1 +0,0 @@ -

HEADER

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/layout.html b/.example/net/ghttp/server/template/layout/template/layout.html deleted file mode 100644 index 9f58c21a0..000000000 --- a/.example/net/ghttp/server/template/layout/template/layout.html +++ /dev/null @@ -1,3 +0,0 @@ -{{include "header.html" .}} -{{include .mainTpl .}} -{{include "footer.html" .}} \ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/main/main1.html b/.example/net/ghttp/server/template/layout/template/main/main1.html deleted file mode 100644 index fdb0016f3..000000000 --- a/.example/net/ghttp/server/template/layout/template/main/main1.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN1

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/layout/template/main/main2.html b/.example/net/ghttp/server/template/layout/template/main/main2.html deleted file mode 100644 index 608512269..000000000 --- a/.example/net/ghttp/server/template/layout/template/main/main2.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN2

\ No newline at end of file diff --git a/.example/net/ghttp/server/template/tpl1/index.tpl b/.example/net/ghttp/server/template/tpl1/index.tpl deleted file mode 100644 index 0dbd0a075..000000000 --- a/.example/net/ghttp/server/template/tpl1/index.tpl +++ /dev/null @@ -1,10 +0,0 @@ - - - - - {{.title}} - - -

{{.name}}: {{.score}}

- - \ No newline at end of file diff --git a/.example/net/ghttp/server/template/tpl1/tpl1.go b/.example/net/ghttp/server/template/tpl1/tpl1.go deleted file mode 100644 index da6d18b0e..000000000 --- a/.example/net/ghttp/server/template/tpl1/tpl1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := ghttp.GetServer() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTpl("index.tpl", g.Map{ - "title": "Test", - "name": "John", - "score": 100, - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/template/tpl2/main.go b/.example/net/ghttp/server/template/tpl2/main.go deleted file mode 100644 index 8489511eb..000000000 --- a/.example/net/ghttp/server/template/tpl2/main.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gins" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.SetServerRoot("public") - s.SetNameToUriType(ghttp.URI_TYPE_ALLLOWER) - s.SetErrorLogEnabled(true) - s.SetAccessLogEnabled(true) - s.SetPort(2333) - - s.BindHandler("/", func(r *ghttp.Request) { - content, _ := gins.View().Parse("test.html", nil) - r.Response.Write(content) - }) - - s.Run() -} diff --git a/.example/net/ghttp/server/template/tpl2/public/test.html b/.example/net/ghttp/server/template/tpl2/public/test.html deleted file mode 100644 index 29c9de328..000000000 --- a/.example/net/ghttp/server/template/tpl2/public/test.html +++ /dev/null @@ -1 +0,0 @@ -hello gf! \ No newline at end of file diff --git a/.example/net/ghttp/server/template/tpl2/template/test.html b/.example/net/ghttp/server/template/tpl2/template/test.html deleted file mode 100644 index 4632e068d..000000000 --- a/.example/net/ghttp/server/template/tpl2/template/test.html +++ /dev/null @@ -1 +0,0 @@ -123456 \ No newline at end of file diff --git a/.example/net/ghttp/server/websocket/echo-wss/index.html b/.example/net/ghttp/server/websocket/echo-wss/index.html deleted file mode 100644 index 6b1f50583..000000000 --- a/.example/net/ghttp/server/websocket/echo-wss/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - gf websocket echo server - - - - -
-
-
-
-
-
-
- - - - \ No newline at end of file diff --git a/.example/net/ghttp/server/websocket/echo-wss/main.go b/.example/net/ghttp/server/websocket/echo-wss/main.go deleted file mode 100644 index 32689e893..000000000 --- a/.example/net/ghttp/server/websocket/echo-wss/main.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - s := g.Server() - s.BindHandler("/wss", func(r *ghttp.Request) { - ws, err := r.WebSocket() - if err != nil { - glog.Error(err) - r.Exit() - } - for { - msgType, msg, err := ws.ReadMessage() - if err != nil { - return - } - if err = ws.WriteMessage(msgType, msg); err != nil { - return - } - } - }) - s.SetServerRoot(gfile.MainPkgPath()) - s.EnableHTTPS("../../https/server.crt", "../../https/server.key") - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/websocket/echo/index.html b/.example/net/ghttp/server/websocket/echo/index.html deleted file mode 100644 index 1accbfdfb..000000000 --- a/.example/net/ghttp/server/websocket/echo/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - gf websocket echo server - - - - -
-
-
-
-
-
-
- - - - \ No newline at end of file diff --git a/.example/net/ghttp/server/websocket/echo/main-group.go b/.example/net/ghttp/server/websocket/echo/main-group.go deleted file mode 100644 index 5a6cd8285..000000000 --- a/.example/net/ghttp/server/websocket/echo/main-group.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/glog" -) - -func ws(r *ghttp.Request) { - ws, err := r.WebSocket() - if err != nil { - glog.Error(err) - return - } - for { - msgType, msg, err := ws.ReadMessage() - if err != nil { - return - } - if err = ws.WriteMessage(msgType, msg); err != nil { - return - } - } -} - -func main() { - s := g.Server() - s.Group("").Bind([]ghttp.GroupItem{ - {"ALL", "/ws", ws}, - }) - s.SetAccessLogEnabled(true) - s.SetServerRoot(gfile.MainPkgPath()) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/ghttp/server/websocket/echo/main.go b/.example/net/ghttp/server/websocket/echo/main.go deleted file mode 100644 index 61e45cebb..000000000 --- a/.example/net/ghttp/server/websocket/echo/main.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - s := g.Server() - s.BindHandler("/ws", func(r *ghttp.Request) { - ws, err := r.WebSocket() - if err != nil { - glog.Error(err) - return - } - for { - msgType, msg, err := ws.ReadMessage() - if err != nil { - return - } - if err = ws.WriteMessage(msgType, msg); err != nil { - return - } - } - }) - s.SetServerRoot(gfile.MainPkgPath()) - s.SetPort(8199) - s.Run() -} diff --git a/.example/net/gsmtp/gsmtp_sendMail.go b/.example/net/gsmtp/gsmtp_sendMail.go deleted file mode 100644 index 307dbe24f..000000000 --- a/.example/net/gsmtp/gsmtp_sendMail.go +++ /dev/null @@ -1,24 +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 main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gsmtp" -) - -func main() { - - // create the SMTP connection - smtpConnection := gsmtp.New("smtp.exmail.qq.com", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - // or you can specify the port explicitly - // smtpConnection := smtp.New("smtp.exmail.qq.com:25", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - - // send the Email - fmt.Println(smtpConnection.SendMail("sender@local.host", "recipient1@domain.com;recipientN@anotherDomain.cn", "This is subject", "Hi!

This is body")) - -} diff --git a/.example/net/gtcp/gtcp_conn.go b/.example/net/gtcp/gtcp_conn.go deleted file mode 100644 index 855c10901..000000000 --- a/.example/net/gtcp/gtcp_conn.go +++ /dev/null @@ -1,56 +0,0 @@ -package main - -import ( - "bytes" - "fmt" - "os" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - conn, err := gtcp.NewConn("www.baidu.com:80") - if err != nil { - panic(err) - } - defer conn.Close() - - if err := conn.Send([]byte("GET / HTTP/1.1\r\n\r\n")); err != nil { - panic(err) - } - - header := make([]byte, 0) - content := make([]byte, 0) - contentLength := 0 - for { - data, err := conn.RecvLine() - // header读取,解析文本长度 - if len(data) > 0 { - array := bytes.Split(data, []byte(": ")) - // 获得页面内容长度 - if contentLength == 0 && len(array) == 2 && bytes.EqualFold([]byte("Content-Length"), array[0]) { - // http 以\r\n换行,需要把\r也去掉 - contentLength = gconv.Int(string(array[1][:len(array[1])-1])) - } - header = append(header, data...) - header = append(header, '\n') - } - // header读取完毕,读取文本内容, 1为\r - if contentLength > 0 && len(data) == 1 { - content, _ = conn.Recv(contentLength) - break - } - if err != nil { - fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error()) - break - } - } - - if len(header) > 0 { - fmt.Println(string(header)) - } - if len(content) > 0 { - fmt.Println(string(content)) - } -} diff --git a/.example/net/gtcp/gtcp_echo_server.go b/.example/net/gtcp/gtcp_echo_server.go deleted file mode 100644 index 85f60832c..000000000 --- a/.example/net/gtcp/gtcp_echo_server.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - } - }).Run() -} diff --git a/.example/net/gtcp/gtcp_func.go b/.example/net/gtcp/gtcp_func.go deleted file mode 100644 index 79217a973..000000000 --- a/.example/net/gtcp/gtcp_func.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - "os" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - dstConn, err := gtcp.NewPoolConn("www.medlinker.com:80") - _, err = dstConn.Write([]byte("HEAD / HTTP/1.1\n\n")) - if err != nil { - fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error()) - } - fmt.Println(dstConn.RecvLine()) -} diff --git a/.example/net/gtcp/gtcp_pool1.go b/.example/net/gtcp/gtcp_pool1.go deleted file mode 100644 index 200d5e5dd..000000000 --- a/.example/net/gtcp/gtcp_pool1.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gtcp.NewPoolConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - fmt.Println(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/gtcp_pool2.go b/.example/net/gtcp/gtcp_pool2.go deleted file mode 100644 index 3032ebfa9..000000000 --- a/.example/net/gtcp/gtcp_pool2.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - return - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gtcp.NewPoolConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - fmt.Println(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/gtcp_server_client1.go b/.example/net/gtcp/gtcp_server_client1.go deleted file mode 100644 index 076d455d6..000000000 --- a/.example/net/gtcp/gtcp_server_client1.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - // client closed, err will be: EOF - fmt.Println(err) - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.Send([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(time.Second) - if i == 5 { - conn.Close() - break - } - } - - // exit after 5 seconds - time.Sleep(5 * time.Second) -} diff --git a/.example/net/gtcp/gtcp_server_client2.go b/.example/net/gtcp/gtcp_server_client2.go deleted file mode 100644 index 5ff8fc79d..000000000 --- a/.example/net/gtcp/gtcp_server_client2.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - fmt.Println(err) - } - } - if err != nil { - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gtcp.NewConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - fmt.Println(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/gtcp_timeout_client.go b/.example/net/gtcp/gtcp_timeout_client.go deleted file mode 100644 index b3777f72f..000000000 --- a/.example/net/gtcp/gtcp_timeout_client.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - - if err := conn.Send([]byte(gtime.Now().String())); err != nil { - glog.Error(err) - } - - time.Sleep(time.Minute) -} diff --git a/.example/net/gtcp/gtcp_timeout_server.go b/.example/net/gtcp/gtcp_timeout_server.go deleted file mode 100644 index 69c8592da..000000000 --- a/.example/net/gtcp/gtcp_timeout_server.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - conn.SetRecvDeadline(time.Now().Add(10 * time.Second)) - for { - data, err := conn.Recv(-1) - fmt.Println(err) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - break - } - } - }).Run() -} diff --git a/.example/net/gtcp/pkg_operations/common/funcs/funcs.go b/.example/net/gtcp/pkg_operations/common/funcs/funcs.go deleted file mode 100644 index dfa2eb883..000000000 --- a/.example/net/gtcp/pkg_operations/common/funcs/funcs.go +++ /dev/null @@ -1,39 +0,0 @@ -package funcs - -import ( - "encoding/json" - "fmt" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/types" - "github.com/gogf/gf/v2/net/gtcp" -) - -// 自定义格式发送消息包 -func SendPkg(conn *gtcp.Conn, act string, data ...string) error { - s := "" - if len(data) > 0 { - s = data[0] - } - msg, err := json.Marshal(types.Msg{ - Act: act, - Data: s, - }) - if err != nil { - panic(err) - } - return conn.SendPkg(msg) -} - -// 自定义格式接收消息包 -func RecvPkg(conn *gtcp.Conn) (msg *types.Msg, err error) { - if data, err := conn.RecvPkg(); err != nil { - return nil, err - } else { - msg = &types.Msg{} - err = json.Unmarshal(data, msg) - if err != nil { - return nil, fmt.Errorf("invalid package structure: %s", err.Error()) - } - return msg, err - } -} diff --git a/.example/net/gtcp/pkg_operations/common/gtcp_common_client.go b/.example/net/gtcp/pkg_operations/common/gtcp_common_client.go deleted file mode 100644 index 160878d39..000000000 --- a/.example/net/gtcp/pkg_operations/common/gtcp_common_client.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/funcs" - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/types" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - // 心跳消息 - gtimer.SetInterval(time.Second, func() { - if err := funcs.SendPkg(conn, "heartbeat"); err != nil { - panic(err) - } - }) - // 测试消息, 3秒后向服务端发送hello消息 - gtimer.SetTimeout(3*time.Second, func() { - if err := funcs.SendPkg(conn, "hello", "My name's John!"); err != nil { - panic(err) - } - }) - for { - msg, err := funcs.RecvPkg(conn) - if err != nil { - if err.Error() == "EOF" { - glog.Print("server closed") - } - break - } - switch msg.Act { - case "hello": - onServerHello(conn, msg) - case "doexit": - onServerDoExit(conn, msg) - case "heartbeat": - onServerHeartBeat(conn, msg) - default: - glog.Errorf("invalid message: %v", msg) - break - } - } -} - -func onServerHello(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("hello response message from [%s]: %s", conn.RemoteAddr().String(), msg.Data) -} - -func onServerHeartBeat(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("heartbeat from [%s]", conn.RemoteAddr().String()) -} - -func onServerDoExit(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("exit command from [%s]", conn.RemoteAddr().String()) - conn.Close() -} diff --git a/.example/net/gtcp/pkg_operations/common/gtcp_common_server.go b/.example/net/gtcp/pkg_operations/common/gtcp_common_server.go deleted file mode 100644 index b335db92e..000000000 --- a/.example/net/gtcp/pkg_operations/common/gtcp_common_server.go +++ /dev/null @@ -1,48 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/funcs" - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/common/types" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - // 测试消息, 10秒后让客户端主动退出 - gtimer.SetTimeout(10*time.Second, func() { - funcs.SendPkg(conn, "doexit") - }) - for { - msg, err := funcs.RecvPkg(conn) - if err != nil { - if err.Error() == "EOF" { - glog.Print("client closed") - } - break - } - switch msg.Act { - case "hello": - onClientHello(conn, msg) - case "heartbeat": - onClientHeartBeat(conn, msg) - default: - glog.Errorf("invalid message: %v", msg) - break - } - } - }).Run() -} - -func onClientHello(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("hello message from [%s]: %s", conn.RemoteAddr().String(), msg.Data) - funcs.SendPkg(conn, msg.Act, "Nice to meet you!") -} - -func onClientHeartBeat(conn *gtcp.Conn, msg *types.Msg) { - glog.Printf("heartbeat from [%s]", conn.RemoteAddr().String()) -} diff --git a/.example/net/gtcp/pkg_operations/common/types/types.go b/.example/net/gtcp/pkg_operations/common/types/types.go deleted file mode 100644 index f2f712fe4..000000000 --- a/.example/net/gtcp/pkg_operations/common/types/types.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -type Msg struct { - Act string // 操作 - Data string // 数据 -} diff --git a/.example/net/gtcp/pkg_operations/gtcp_basic.go b/.example/net/gtcp/pkg_operations/gtcp_basic.go deleted file mode 100644 index 88c314b50..000000000 --- a/.example/net/gtcp/pkg_operations/gtcp_basic.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg() - if err != nil { - fmt.Println(err) - break - } - fmt.Println("receive:", data) - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.SendPkg([]byte(gconv.String(i))); err != nil { - glog.Error(err.Error()) - } - time.Sleep(1 * time.Second) - } -} diff --git a/.example/net/gtcp/pkg_operations/gtcp_empty_data.go b/.example/net/gtcp/pkg_operations/gtcp_empty_data.go deleted file mode 100644 index ba20cbad6..000000000 --- a/.example/net/gtcp/pkg_operations/gtcp_empty_data.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg() - if err != nil { - fmt.Println(err) - break - } - fmt.Println("RecvPkg:", string(data)) - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.SendPkg(nil); err != nil { - glog.Error(err) - } - time.Sleep(1 * time.Second) - } -} diff --git a/.example/net/gtcp/pkg_operations/gtcp_pkg_option.go b/.example/net/gtcp/pkg_operations/gtcp_pkg_option.go deleted file mode 100644 index 41c6ba20b..000000000 --- a/.example/net/gtcp/pkg_operations/gtcp_pkg_option.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Server - go gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg(gtcp.PkgOption{MaxSize: 1}) - if err != nil { - fmt.Println(err) - break - } - fmt.Println("RecvPkg:", string(data)) - } - }).Run() - - time.Sleep(time.Second) - - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10000; i++ { - if err := conn.SendPkg([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(1 * time.Second) - } -} diff --git a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_client.go b/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_client.go deleted file mode 100644 index 6f150f410..000000000 --- a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_client.go +++ /dev/null @@ -1,43 +0,0 @@ -package main - -import ( - "encoding/json" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/monitor/types" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // 数据上报客户端 - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - // 使用JSON格式化数据字段 - info, err := json.Marshal(types.NodeInfo{ - Cpu: float32(66.66), - Host: "localhost", - Ip: g.Map{ - "etho": "192.168.1.100", - "eth1": "114.114.10.11", - }, - MemUsed: 15560320, - MemTotal: 16333788, - Time: int(gtime.Timestamp()), - }) - if err != nil { - panic(err) - } - // 使用 SendRecvPkg 发送消息包并接受返回 - if result, err := conn.SendRecvPkg(info); err != nil { - if err.Error() == "EOF" { - glog.Print("server closed") - } - } else { - glog.Print(string(result)) - } -} diff --git a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_server.go b/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_server.go deleted file mode 100644 index 056c0a498..000000000 --- a/.example/net/gtcp/pkg_operations/monitor/gtcp_monitor_server.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "encoding/json" - - "github.com/gogf/gf/v2/.example/net/gtcp/pkg_operations/monitor/types" - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 服务端,接收客户端数据并格式化为指定数据结构,打印 - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.RecvPkg() - if err != nil { - if err.Error() == "EOF" { - glog.Print("client closed") - } - break - } - info := &types.NodeInfo{} - if err := json.Unmarshal(data, info); err != nil { - glog.Errorf("invalid package structure: %s", err.Error()) - } else { - glog.Print(info) - conn.SendPkg([]byte("ok")) - } - } - }).Run() -} diff --git a/.example/net/gtcp/pkg_operations/monitor/types/types.go b/.example/net/gtcp/pkg_operations/monitor/types/types.go deleted file mode 100644 index 2d6b6b7cf..000000000 --- a/.example/net/gtcp/pkg_operations/monitor/types/types.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -import "github.com/gogf/gf/v2/frame/g" - -type NodeInfo struct { - Cpu float32 // CPU百分比(%) - Host string // 主机名称 - Ip g.Map // IP地址信息(可能多个) - MemUsed int // 内存使用(byte) - MemTotal int // 内存总量(byte) - Time int // 上报时间(时间戳) -} diff --git a/.example/net/gtcp/server_client/gtcp_client.go b/.example/net/gtcp/server_client/gtcp_client.go deleted file mode 100644 index be580a6ef..000000000 --- a/.example/net/gtcp/server_client/gtcp_client.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - // Client - conn, err := gtcp.NewConn("127.0.0.1:8999") - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 3; i++ { - if err := conn.Send([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gtcp/server_client/gtcp_server.go b/.example/net/gtcp/server_client/gtcp_server.go deleted file mode 100644 index 92df614f7..000000000 --- a/.example/net/gtcp/server_client/gtcp_server.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gtcp" -) - -func main() { - // Server - gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - // client closed, err will be: EOF - fmt.Println(err) - break - } - } - }).Run() -} diff --git a/.example/net/gtcp/tcp_server_client.go b/.example/net/gtcp/tcp_server_client.go deleted file mode 100644 index 068ddfb13..000000000 --- a/.example/net/gtcp/tcp_server_client.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "fmt" - "net" - "time" -) - -func main() { - addr := "127.0.0.1:8999" - - // Server - go func() { - tcpaddr, err := net.ResolveTCPAddr("tcp4", addr) - if err != nil { - panic(err) - } - listen, err := net.ListenTCP("tcp", tcpaddr) - if err != nil { - panic(err) - } - for { - if conn, err := listen.Accept(); err != nil { - panic(err) - } else if conn != nil { - go func(conn net.Conn) { - for { - buffer := make([]byte, 1024) - n, err := conn.Read(buffer) - if err != nil { - fmt.Println(err) - break - } else { - fmt.Println(">", string(buffer[0:n])) - conn.Close() - } - } - - }(conn) - } - } - }() - - time.Sleep(time.Second) - - // Client - if conn, err := net.Dial("tcp", addr); err == nil { - // first write - _, err := conn.Write([]byte("hello1")) - if err != nil { - fmt.Println(err) - conn.Close() - return - } else { - fmt.Println("ok") - } - - // sleep 10 seconds and re-send - time.Sleep(10 * time.Second) - - // second write - _, err = conn.Write([]byte("hello2")) - if err != nil { - fmt.Println(err) - conn.Close() - return - } else { - fmt.Println("ok") - } - // sleep 10 seconds and re-send - time.Sleep(10 * time.Second) - } else { - panic(err) - } - -} diff --git a/.example/net/gtcp/tls/gtcp_server_client.go b/.example/net/gtcp/tls/gtcp_server_client.go deleted file mode 100644 index 87d5bb981..000000000 --- a/.example/net/gtcp/tls/gtcp_server_client.go +++ /dev/null @@ -1,59 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gtcp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - address := "127.0.0.1:8999" - crtFile := "server.crt" - keyFile := "server.key" - // TLS Server - go gtcp.NewServerKeyCrt(address, crtFile, keyFile, func(conn *gtcp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - fmt.Println(string(data)) - } - if err != nil { - // if client closes, err will be: EOF - glog.Error(err) - break - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - tlsConfig, err := gtcp.LoadKeyCrt(crtFile, keyFile) - if err != nil { - panic(err) - } - tlsConfig.InsecureSkipVerify = true - - conn, err := gtcp.NewConnTLS(address, tlsConfig) - if err != nil { - panic(err) - } - defer conn.Close() - for i := 0; i < 10; i++ { - if err := conn.Send([]byte(gconv.String(i))); err != nil { - glog.Error(err) - } - time.Sleep(time.Second) - if i == 5 { - conn.Close() - break - } - } - - // exit after 5 seconds - time.Sleep(5 * time.Second) -} diff --git a/.example/net/gtcp/tls/server.crt b/.example/net/gtcp/tls/server.crt deleted file mode 100644 index 4d254ea21..000000000 --- a/.example/net/gtcp/tls/server.crt +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDzzCCAregAwIBAgIJAJYpWLkC2lEXMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV -BAYTAkNIMRAwDgYDVQQIDAdTaUNodWFuMRAwDgYDVQQHDAdDaGVuZ2R1MRAwDgYD -VQQKDAdKb2huLmNuMQwwCgYDVQQLDANEZXYxDTALBgNVBAMMBEpvaG4xHDAaBgkq -hkiG9w0BCQEWDWpvaG5Aam9obmcuY24wHhcNMTgwNDIzMTMyNjA4WhcNMTkwNDIz -MTMyNjA4WjB+MQswCQYDVQQGEwJDSDEQMA4GA1UECAwHU2lDaHVhbjEQMA4GA1UE -BwwHQ2hlbmdkdTEQMA4GA1UECgwHSm9obi5jbjEMMAoGA1UECwwDRGV2MQ0wCwYD -VQQDDARKb2huMRwwGgYJKoZIhvcNAQkBFg1qb2huQGpvaG5nLmNuMIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlS -F/tCPyKINhsePGqHkR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg -+Vps/RimBpiz+RU3FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMz -CRKoZ2dQ+98o5LwES+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJIN -DIp5Ypszg1cPs0gIr5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIO -NcqaHeGaTUVjzX9XwRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABo1Aw -TjAdBgNVHQ4EFgQU1/tUQpOK0xEwLLlYDiNrckqPlDowHwYDVR0jBBgwFoAU1/tU -QpOK0xEwLLlYDiNrckqPlDowDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC -AQEA5MbG2xU3s/GDU1MV4f0wKhWCNhXfrLaYSwNYGT/eb8ZG2iHSTO0dvl0+pjO2 -EK63PDMvMhUtL1Zlyvl+OqssYcDhVfDzdFoYX6TZNbYxFwSzcx78mO6boAADk9ro -GEQWN+VHsl984SzBRZRJbtNbiw5iVuPruofeKHrrk4dLMiCsStyUaz9lUZxjo2Fi -vVJOY+mRNOBqz1HgU2+RilFTl04zWadCWPJMugQSgJcUPgxRXQ96PkC8uYevEnmR -2DUReSRULIOYEjHw0DZ6yGlqUkJcUGge3XAQEx3LlCpJasOC8Xpsh5i6WBnDPbMh -kPBjRRTooSrJOQJC5v3QW+0Kgw== ------END CERTIFICATE----- diff --git a/.example/net/gtcp/tls/server.key b/.example/net/gtcp/tls/server.key deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/gtcp/tls/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/gtcp/tls/server.key.public b/.example/net/gtcp/tls/server.key.public deleted file mode 100644 index e0f909629..000000000 --- a/.example/net/gtcp/tls/server.key.public +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA6cngPUrDgBhiNfn+7MMHPzOoO+oVavlSF/tCPyKINhsePGqH -kR4ILkHu9IuoBiPYR1JgrMz5goQ6mkrvq/LMfo4dCuA29ZRg+Vps/RimBpiz+RU3 -FDGyqc7d+fk74dElGk6NhJJ6XO3qHqgIg1yc6d5DiZfEnlMzCRKoZ2dQ+98o5LwE -S+XJBVWfZiC1pEfyppIh+ci7fXajxkRPJ+5qYWaS5cIHmJINDIp5Ypszg1cPs0gI -r5EgPeGwZzOeqMMzsbLLE8kjSw59Pt1/+Jkdm1e0GhO18qIONcqaHeGaTUVjzX9X -wRj8cw+q3kRoqD5aWMjUzAg9+IDrMqvo6VZQ5QIDAQABAoIBAHF7cMHPvL49F88j -nr7GnIntRUhwBB19EIBbknibBotc9nxVKaEjds0dbCSAdfslAyL7tbmrdaIJFXk3 -zsckgGceDLLuyz7B26CuaCEjCdRB43qQ9b9zsEoFBHMGrC6dGul+H+uuPn9FbVOc -NSWumuxa22W6qdJAiJFq4RvwZrsbVnYs5V29Y4Y20IlVUj3siJpAny//UUHequW9 -A/U7RvVssDsEEbbKvCpfcS7STNJKU7GlgV5l5hMKN2xLs1bVG5OKiZN82Zh9r7e1 -m2irxu/ehu6rENxZN0gsfPE4vqoQpbRMNAJlCfq9a3k0PH0TOy5oOVJXPGTIDQab -E3PeAwECgYEA9wh4+bPgMuO04hsAqsoO0DJ9Cwa+BzoDPYOvENobDzmcMErSDLKb -ekl1ej+fBTHRHVaBkuOf/9neLjhjMLad1B+I5gLksqwoMh87odDRCCpkO/B20ln8 -IN6RFiMiNjOaZqjPCCUobgzjbaIz3I69lCQQnMNPwjllSgZs9Lh/PjUCgYEA8kZU -hhUN6ctHIo8ocnmqa4AUPbt2l4qOoBGHCMmhjthyft6g8y6cQlACVJzbco37MhjY -uCOhhOClyUS1tyfds3NXdzAxXPl8SwQJGvl3zqkDQG7/GhCh6AzvHhZR8u7UaweC -kVnAG87Ck6Qqo5ZNbjhMIUm0ujm2cdVd3vyV3fECgYEAmJSMHDck8GnCzLE+/T5m -XeQBZfEZKF+FptYSKId+lS3RMebUzHD5JVQAEqz/LHczoTpQOAkORzorSEMdyPXS -kDWWGfOJjG5XOXYfH/hZVADS/k6tJYnc9/RgitrSg8XlxSjZDz/cM/UT+CBqhf1I -TRrlg94DAoTu8gT8AT9/oE0CgYB5CSPO/JO/2jtGi6iUUC4QmKMEGDRuDt2kID2K -6ViaCY5hzY0xEHcmNdyEMvz7JO16oKkcjUhzHtwUSgxSXUtIDHaE6AGxRj6PJ4v4 -+uqcxxkFxq4Rcn/Acz2+lT4JlMFwWwci4Gi2O7w/kENxCHTUfLGj67OrWYvJIORN -s3iXsQKBgD1I+v+simBvKZKmozzv99EgGfxkRxmrUQsclg1V8a1VTNfE5X9oNaE5 -kjp+dTnwbtmFl3SHVdFUzX/L6FvQIQ9FIwWI2bsszPm4rw8FBeOvH+8lXwVhCwPs -y9him/PhdjBPX0zydDI+h+fmrxH/XbmryZcq1rNmEtFRHBsUs5jg ------END RSA PRIVATE KEY----- diff --git a/.example/net/gudp/gudp_server.go b/.example/net/gudp/gudp_server.go deleted file mode 100644 index ba59eaf75..000000000 --- a/.example/net/gudp/gudp_server.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/net/gudp" -) - -func main() { - gudp.NewServer("127.0.0.1:8999", func(conn *gudp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - fmt.Println(err, string(data)) - } - }).Run() -} diff --git a/.example/net/gudp/gudp_server_client.go b/.example/net/gudp/gudp_server_client.go deleted file mode 100644 index a19512ee0..000000000 --- a/.example/net/gudp/gudp_server_client.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/net/gudp" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // Server - go gudp.NewServer("127.0.0.1:8999", func(conn *gudp.Conn) { - defer conn.Close() - for { - data, err := conn.Recv(-1) - if len(data) > 0 { - if err := conn.Send(append([]byte("> "), data...)); err != nil { - glog.Error(err) - } - } - if err != nil { - glog.Error(err) - } - } - }).Run() - - time.Sleep(time.Second) - - // Client - for { - if conn, err := gudp.NewConn("127.0.0.1:8999"); err == nil { - if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil { - fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr()) - } else { - glog.Error(err) - } - conn.Close() - } else { - glog.Error(err) - } - time.Sleep(time.Second) - } -} diff --git a/.example/net/gudp/udp_client.go b/.example/net/gudp/udp_client.go deleted file mode 100644 index a49f1d48e..000000000 --- a/.example/net/gudp/udp_client.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "net" - "os" -) - -func main() { - conn, err := net.Dial("udp", "127.0.0.1:8999") - defer conn.Close() - if err != nil { - os.Exit(1) - } - - conn.Write([]byte("Hello world!")) - - buffer := make([]byte, 100) - - conn.Read(buffer) - - fmt.Println(string(buffer)) -} diff --git a/.example/net/gudp/udp_server.go b/.example/net/gudp/udp_server.go deleted file mode 100644 index 7ebf85562..000000000 --- a/.example/net/gudp/udp_server.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - "net" -) - -func main() { - listener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8999}) - if err != nil { - fmt.Println(err) - return - } - fmt.Println("Local:", listener.LocalAddr().String()) - - data := make([]byte, 1024) - for { - n, remoteAddr, err := listener.ReadFromUDP(data) - if err != nil { - fmt.Println(err) - } - fmt.Println(remoteAddr, string(data[:n])) - - _, err = listener.WriteToUDP([]byte("world"), remoteAddr) - if err != nil { - fmt.Printf(err.Error()) - } - } -} diff --git a/.example/os/gbuild/config.toml b/.example/os/gbuild/config.toml deleted file mode 100644 index db7e02a1c..000000000 --- a/.example/os/gbuild/config.toml +++ /dev/null @@ -1,9 +0,0 @@ - - -# custom gf build setting. -[compiler] - name = "app" - [compiler.varmap] - name = "GoFrame" - version = "1.10.1" - home-site = "https://goframe.org" \ No newline at end of file diff --git a/.example/os/gbuild/gbuild.go b/.example/os/gbuild/gbuild.go deleted file mode 100644 index 5759c3d18..000000000 --- a/.example/os/gbuild/gbuild.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gbuild" -) - -func main() { - g.Dump(gbuild.Info()) - g.Dump(gbuild.Map()) -} diff --git a/.example/os/gcache/getorset_func_lock.go b/.example/os/gcache/getorset_func_lock.go deleted file mode 100644 index 1d909597d..000000000 --- a/.example/os/gcache/getorset_func_lock.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gcache" - "github.com/gogf/gf/v2/os/gctx" - "time" -) - -func main() { - var ( - ch = make(chan struct{}, 0) - ctx = gctx.New() - key = `key` - value = `value` - ) - for i := 0; i < 10; i++ { - go func(index int) { - <-ch - _, _ = gcache.Ctx(ctx).GetOrSetFuncLock(key, func() (interface{}, error) { - fmt.Println(index, "entered") - return value, nil - }, 0) - }(i) - } - close(ch) - time.Sleep(time.Second) -} diff --git a/.example/os/gcache/note_interface_key.go b/.example/os/gcache/note_interface_key.go deleted file mode 100644 index 08733d7ec..000000000 --- a/.example/os/gcache/note_interface_key.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gcache" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - var ( - ctx = gctx.New() - key1 int32 = 1 - key2 float64 = 1 - value = `value` - ) - _ = gcache.Ctx(ctx).Set(key1, value, 0) - fmt.Println(gcache.Ctx(ctx).Get(key1)) - fmt.Println(gcache.Ctx(ctx).Get(key2)) -} diff --git a/.example/os/gcache/note_interface_value.go b/.example/os/gcache/note_interface_value.go deleted file mode 100644 index 1d121c9ab..000000000 --- a/.example/os/gcache/note_interface_value.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gcache" - "github.com/gogf/gf/v2/os/gctx" -) - -func main() { - type User struct { - Id int - Name string - Site string - } - var ( - ctx = gctx.New() - user *User - key = `UserKey` - value = &User{ - Id: 1, - Name: "GoFrame", - Site: "https://goframe.org", - } - ) - _ = gcache.Ctx(ctx).Set(key, value, 0) - v, _ := gcache.Ctx(ctx).GetVar(key) - _ = v.Scan(&user) - fmt.Printf(`%#v`, user) -} diff --git a/.example/os/gcache/usage_basic.go b/.example/os/gcache/usage_basic.go deleted file mode 100644 index cc1fa632e..000000000 --- a/.example/os/gcache/usage_basic.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gcache" -) - -func main() { - // 创建一个缓存对象,当然也可以直接使用gcache包方法 - c := gcache.New() - - // 设置缓存,不过期 - c.Set("k1", "v1", 0) - - // 获取缓存 - fmt.Println(c.Get("k1")) - - // 获取缓存大小 - fmt.Println(c.Size()) - - // 缓存中是否存在指定键名 - fmt.Println(c.Contains("k1")) - - // 删除并返回被删除的键值 - fmt.Println(c.Remove("k1")) - - // 关闭缓存对象,让GC回收资源 - c.Close() -} diff --git a/.example/os/gcache/usage_lru.go b/.example/os/gcache/usage_lru.go deleted file mode 100644 index bbf897530..000000000 --- a/.example/os/gcache/usage_lru.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gcache" -) - -func main() { - // 设置LRU淘汰数量 - c := gcache.New(2) - - // 添加10个元素,不过期 - for i := 0; i < 10; i++ { - c.Set(i, i, 0) - } - fmt.Println(c.Size()) - fmt.Println(c.Keys()) - - // 读取键名1,保证该键名是优先保留 - fmt.Println(c.Get(1)) - - // 等待一定时间后(默认1秒检查一次),元素会被按照从旧到新的顺序进行淘汰 - time.Sleep(2 * time.Second) - fmt.Println(c.Size()) - fmt.Println(c.Keys()) -} diff --git a/.example/os/gcache/usage_senior.go b/.example/os/gcache/usage_senior.go deleted file mode 100644 index ac5b4f113..000000000 --- a/.example/os/gcache/usage_senior.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gcache" -) - -func main() { - // 当键名不存在时写入,设置过期时间1000毫秒 - gcache.SetIfNotExist("k1", "v1", 1000) - - // 打印当前的键名列表 - fmt.Println(gcache.Keys()) - - // 打印当前的键值列表 - fmt.Println(gcache.Values()) - - // 获取指定键值,如果不存在时写入,并返回键值 - fmt.Println(gcache.GetOrSet("k2", "v2", 0)) - - // 打印当前的键值对 - fmt.Println(gcache.Data()) - - // 等待1秒,以便k1:v1自动过期 - time.Sleep(time.Second) - - // 再次打印当前的键值对,发现k1:v1已经过期,只剩下k2:v2 - fmt.Println(gcache.Data()) -} diff --git a/.example/os/gcfg/basic/config.json b/.example/os/gcfg/basic/config.json deleted file mode 100644 index c10a4cdb6..000000000 --- a/.example/os/gcfg/basic/config.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "viewpath" : "/home/www/templates/", - "database" : { - "default" : [ - { - "host" : "127.0.0.1", - "port" : "3306", - "user" : "root", - "pass" : "123456", - "name" : "test", - "type" : "mysql", - "role" : "master", - "charset" : "utf8", - "priority" : "1" - }, - { - "host" : "127.0.0.1", - "port" : "3306", - "user" : "root", - "pass" : "123456", - "name" : "test", - "type" : "mysql", - "role" : "master", - "charset" : "utf8", - "priority" : "1" - } - ] - }, - "redis" : { - "disk" : "127.0.0.1:6379,0", - "cache" : "127.0.0.1:6379,1" - } -} \ No newline at end of file diff --git a/.example/os/gcfg/basic/config.toml b/.example/os/gcfg/basic/config.toml deleted file mode 100644 index 384011b2f..000000000 --- a/.example/os/gcfg/basic/config.toml +++ /dev/null @@ -1,33 +0,0 @@ - - -# redis配置 -[[redis-cache]] - db = 0 - host = "192.168.0.100" - port = 6379 - -[[redis-cache]] - db = 1 - host = "192.168.0.100" - port = 6379 - -[[redis-disk]] - db = 0 - host = "192.168.0.100" - port = 6380 - -[[redis-disk]] - db = 1 - host = "192.168.0.100" - port = 6380 - -# memcache配置 -[[memcache]] - host = "192.168.0.101" - port = 11211 - expire = 60 - -[[memcache]] - host = "192.168.0.102" - port = 11211 - expire = 60 \ No newline at end of file diff --git a/.example/os/gcfg/basic/gcfg1.go b/.example/os/gcfg/basic/gcfg1.go deleted file mode 100644 index 2665ebbba..000000000 --- a/.example/os/gcfg/basic/gcfg1.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用第二个参数指定读取的配置文件 -func main() { - c := g.Config() - redisConfig := c.GetArray("redis-cache", "redis.toml") - memConfig := c.GetArray("", "memcache.yml") - fmt.Println(redisConfig) - fmt.Println(memConfig) -} diff --git a/.example/os/gcfg/basic/gcfg2.go b/.example/os/gcfg/basic/gcfg2.go deleted file mode 100644 index 3ccbe7e12..000000000 --- a/.example/os/gcfg/basic/gcfg2.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用默认的config.toml配置文件读取配置 -func main() { - c := g.Config() - fmt.Println(c.GetArray("memcache")) -} diff --git a/.example/os/gcfg/basic/gcfg3.go b/.example/os/gcfg/basic/gcfg3.go deleted file mode 100644 index fc95f57c1..000000000 --- a/.example/os/gcfg/basic/gcfg3.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用GetVar获取动态变量 -func main() { - fmt.Println(g.Config().GetVar("memcache.0").String()) -} diff --git a/.example/os/gcfg/basic/gcfg4.go b/.example/os/gcfg/basic/gcfg4.go deleted file mode 100644 index a2af5a2d9..000000000 --- a/.example/os/gcfg/basic/gcfg4.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 使用g.Config方法获取配置管理对象,并指定默认的配置文件名称 -func main() { - fmt.Println(g.Config().Get("viewpath")) -} diff --git a/.example/os/gcfg/basic/gcfg_auto_update.go b/.example/os/gcfg/basic/gcfg_auto_update.go deleted file mode 100644 index cd01884d1..000000000 --- a/.example/os/gcfg/basic/gcfg_auto_update.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtimer" - - "github.com/gogf/gf/v2/frame/g" -) - -// 配置文件热更新示例 -func main() { - c := g.Config() - // 每隔1秒打印当前配置项值,用户可手动在外部修改文件内容,gcfg读取到的配置项值会即时得到更新 - gtimer.SetInterval(time.Second, func() { - fmt.Println(c.Get("viewpath")) - }) - - select {} -} diff --git a/.example/os/gcfg/basic/gcfg_error.go b/.example/os/gcfg/basic/gcfg_error.go deleted file mode 100644 index 2df606679..000000000 --- a/.example/os/gcfg/basic/gcfg_error.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - fmt.Println(g.Config().Get("none")) -} diff --git a/.example/os/gcfg/basic/memcache.yml b/.example/os/gcfg/basic/memcache.yml deleted file mode 100644 index 056433dd1..000000000 --- a/.example/os/gcfg/basic/memcache.yml +++ /dev/null @@ -1,7 +0,0 @@ -# memcache配置 -- host: 192.168.0.101 - port: 11211 - expire: 60 -- host: 192.168.0.102 - port: 11211 - expire: 60 diff --git a/.example/os/gcfg/basic/redis.toml b/.example/os/gcfg/basic/redis.toml deleted file mode 100644 index 61a45a64d..000000000 --- a/.example/os/gcfg/basic/redis.toml +++ /dev/null @@ -1,20 +0,0 @@ -# redis配置 -[[redis-cache]] - db = 0 - host = "192.168.0.100" - port = 6379 - -[[redis-cache]] - db = 1 - host = "192.168.0.100" - port = 6379 - -[[redis-disk]] - db = 0 - host = "192.168.0.100" - port = 6380 - -[[redis-disk]] - db = 1 - host = "192.168.0.100" - port = 6380 \ No newline at end of file diff --git a/.example/os/gcfg/resource/resource.go b/.example/os/gcfg/resource/resource.go deleted file mode 100644 index 9f646fc3e..000000000 --- a/.example/os/gcfg/resource/resource.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - g.Res().Dump() - g.Dump(g.Config().Get("redis")) - - g.Config().SetFileName("my.ini") - g.Dump(g.Config().Get("redis")) - - g.Config().SetPath("config-custom") - g.Config().SetFileName("my.ini") - g.Dump(g.Config().Get("redis")) - - g.Config().SetFileName("config.toml") - g.Dump(g.Config().Get("redis")) -} diff --git a/.example/os/gcmd/main.go b/.example/os/gcmd/main.go deleted file mode 100644 index 21f1d1a54..000000000 --- a/.example/os/gcmd/main.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gcmd" -) - -func main() { - p, err := gcmd.Parse(g.MapStrBool{ - "n,name": true, - "p,prefix": true, - "f,force": false, - "t,tail": false, - "i,interactive": false, - }) - if err != nil { - fmt.Println(err) - } - g.Dump(p) -} diff --git a/.example/os/gcron/gcron-log.go b/.example/os/gcron/gcron-log.go deleted file mode 100644 index d77aa1a4b..000000000 --- a/.example/os/gcron/gcron-log.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gcron" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - gcron.SetLogLevel(glog.LEVEL_ALL) - gcron.Add("* * * * * ?", func() { - glog.Print("test") - }) - time.Sleep(3 * time.Second) -} diff --git a/.example/os/gcron/gcron1.go b/.example/os/gcron/gcron1.go deleted file mode 100644 index 6b90aec61..000000000 --- a/.example/os/gcron/gcron1.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gcron" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - gcron.Add("0 30 * * * *", func() { glog.Print("Every hour on the half hour") }) - gcron.Add("* * * * * *", func() { glog.Print("Every second, pattern") }, "second-cron") - gcron.Add("*/5 * * * * *", func() { glog.Print("Every 5 seconds, pattern") }) - - gcron.Add("@hourly", func() { glog.Print("Every hour") }) - gcron.Add("@every 1h30m", func() { glog.Print("Every hour thirty") }) - gcron.Add("@every 1s", func() { glog.Print("Every 1 second") }) - gcron.Add("@every 5s", func() { glog.Print("Every 5 seconds") }) - - time.Sleep(3 * time.Second) - - gcron.Stop("second-cron") - - time.Sleep(3 * time.Second) - - gcron.Start("second-cron") - - time.Sleep(10 * time.Second) -} diff --git a/.example/os/gcron/gcron2.go b/.example/os/gcron/gcron2.go deleted file mode 100644 index bc032dba1..000000000 --- a/.example/os/gcron/gcron2.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gcron" - "github.com/gogf/gf/v2/os/glog" -) - -func test() { - glog.Print(111) -} - -func main() { - _, err := gcron.AddOnce("@every 2s", test) - if err != nil { - panic(err) - } - time.Sleep(10 * time.Second) -} diff --git a/.example/os/gfile/gfile.go b/.example/os/gfile/gfile.go deleted file mode 100644 index b84ca4a97..000000000 --- a/.example/os/gfile/gfile.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/util/gutil" -) - -var dirpath1 = "/home/john/Workspace/temp/" -var dirpath2 = "/home/john/Workspace/temp/1" -var filepath1 = "/home/john/Workspace/temp/test.php" -var filepath2 = "/tmp/tmp.test" - -type BinData struct { - name string - age int -} - -func info() { - fmt.Println(gfile.Info(dirpath1)) -} - -func scanDir() { - gutil.Dump(gfile.ScanDir(dirpath1, "*")) -} - -func getContents() { - fmt.Printf("%s\n", gfile.GetContents(filepath1)) -} - -func putContents() { - fmt.Println(gfile.PutContentsAppend(filepath2, "123")) -} - -func putBinContents() { - fmt.Println(gfile.PutBytes(filepath2, []byte("abc"))) -} - -func main() { - //info() - //getContents() - //putContents() - putBinContents() - //scanDir() -} diff --git a/.example/os/gfile/gfile_contents.go b/.example/os/gfile/gfile_contents.go deleted file mode 100644 index cfd8eda7f..000000000 --- a/.example/os/gfile/gfile_contents.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - path := "/tmp/temp" - content := `123 -456 -789 -` - gfile.PutContents(path, content) - fmt.Println(gfile.Size(path)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 0)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 3)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 8)) - fmt.Println(gfile.GetBytesTilCharByPath(path, '\n', 12)) -} diff --git a/.example/os/gfile/gfile_scan.go b/.example/os/gfile/gfile_scan.go deleted file mode 100644 index bb032562a..000000000 --- a/.example/os/gfile/gfile_scan.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.Dump(gfile.ScanDir("/Users/john/Documents", "*.*")) - gutil.Dump(gfile.ScanDir("/home/john/temp/newproject", "*", true)) -} diff --git a/.example/os/gfpool/gfpool.go b/.example/os/gfpool/gfpool.go deleted file mode 100644 index dbbae303f..000000000 --- a/.example/os/gfpool/gfpool.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "os" - "time" - - "github.com/gogf/gf/v2/os/gfpool" -) - -func main() { - for { - time.Sleep(time.Second) - if f, err := gfpool.Open("/home/john/temp/log.log", os.O_RDONLY, 0666, time.Hour); err == nil { - fmt.Println(f.Name()) - f.Close() - } else { - fmt.Println(err) - } - } -} diff --git a/.example/os/gfsnotify/fsnotify.go b/.example/os/gfsnotify/fsnotify.go deleted file mode 100644 index 729fcd1b9..000000000 --- a/.example/os/gfsnotify/fsnotify.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "context" - "log" - - "github.com/fsnotify/fsnotify" - - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - // 创建一个监控对象 - watch, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - defer watch.Close() - // 添加要监控的对象,文件或文件夹 - // err = watch.Add("D:\\Workspace\\Go\\GOPATH\\src\\gitee.com\\johng\\gf\\geg\\other\\test.go") - err = watch.Add("/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/other/test.go") - if err != nil { - log.Fatal(err) - } - // 我们另启一个goroutine来处理监控对象的事件 - go func() { - for { - select { - case ev := <-watch.Events: - glog.Print(context.Background(), ev) - - case err := <-watch.Errors: - log.Println("error : ", err) - return - - } - } - }() - - // 循环 - select {} -} diff --git a/.example/os/gfsnotify/gfsnotify.go b/.example/os/gfsnotify/gfsnotify.go deleted file mode 100644 index deedea686..000000000 --- a/.example/os/gfsnotify/gfsnotify.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - //path := `D:\temp` - path := "/Users/john/Temp" - _, err := gfsnotify.Add(path, func(event *gfsnotify.Event) { - glog.Print(event) - }) - if err != nil { - glog.Fatal(err) - } else { - select {} - } -} diff --git a/.example/os/gfsnotify/gfsnotify_callback.go b/.example/os/gfsnotify/gfsnotify_callback.go deleted file mode 100644 index f6e864d9e..000000000 --- a/.example/os/gfsnotify/gfsnotify_callback.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - c1, err := gfsnotify.Add("/home/john/temp/log", func(event *gfsnotify.Event) { - glog.Print("callback1") - }) - if err != nil { - panic(err) - } - c2, err := gfsnotify.Add("/home/john/temp/log", func(event *gfsnotify.Event) { - glog.Print("callback2") - }) - if err != nil { - panic(err) - } - // 5秒后移除c1的回调函数注册,仅剩c2 - gtimer.SetTimeout(5*time.Second, func() { - gfsnotify.RemoveCallback(c1.Id) - glog.Print("remove callback c1") - }) - // 10秒后移除c2的回调函数注册,所有的回调都移除,不再有任何打印信息输出 - gtimer.SetTimeout(10*time.Second, func() { - gfsnotify.RemoveCallback(c2.Id) - glog.Print("remove callback c2") - }) - - select {} - -} diff --git a/.example/os/gfsnotify/gfsnotify_callback_folder.go b/.example/os/gfsnotify/gfsnotify_callback_folder.go deleted file mode 100644 index a12d70f89..000000000 --- a/.example/os/gfsnotify/gfsnotify_callback_folder.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "context" - "time" - - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - var ( - ctx = context.Background() - ) - callback, err := gfsnotify.Add("/home/john/temp", func(event *gfsnotify.Event) { - glog.Print(ctx, "callback") - }) - if err != nil { - panic(err) - } - - // 在此期间创建文件、目录、修改文件、删除文件 - - // 20秒后移除回调函数注册,所有的回调都移除,不再有任何打印信息输出 - gtimer.SetTimeout(ctx, 20*time.Second, func(ctx context.Context) { - gfsnotify.RemoveCallback(callback.Id) - glog.Print(ctx, "remove callback") - }) - - select {} -} diff --git a/.example/os/gfsnotify/gfsnotify_limit.go b/.example/os/gfsnotify/gfsnotify_limit.go deleted file mode 100644 index 33522de5c..000000000 --- a/.example/os/gfsnotify/gfsnotify_limit.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gfsnotify" - "github.com/gogf/gf/v2/os/glog" -) - -// 对同一个文件多次Add是否超过系统inotify限制 -func main() { - path := "/Users/john/temp/log" - for i := 0; i < 9999999; i++ { - _, err := gfsnotify.Add(path, func(event *gfsnotify.Event) { - glog.Print(event) - }) - if err != nil { - glog.Fatal(err) - } - } -} diff --git a/.example/os/glog/glog_CtxKeys.go b/.example/os/glog/glog_CtxKeys.go deleted file mode 100644 index dff0efc78..000000000 --- a/.example/os/glog/glog_CtxKeys.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().SetCtxKeys("TraceId", "SpanId", "Test") - ctx := context.WithValue(context.Background(), "TraceId", "1234567890") - ctx = context.WithValue(ctx, "SpanId", "abcdefg") - - g.Log().Ctx(ctx).Print(1, 2, 3) -} diff --git a/.example/os/glog/glog_SetConfigWithMap.go b/.example/os/glog/glog_SetConfigWithMap.go deleted file mode 100644 index d20e70882..000000000 --- a/.example/os/glog/glog_SetConfigWithMap.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - err := g.Log().SetConfigWithMap(g.Map{ - "prefix": "[TEST]", - }) - if err != nil { - panic(err) - } - glog.Info(1) -} diff --git a/.example/os/glog/glog_async_chaining.go b/.example/os/glog/glog_async_chaining.go deleted file mode 100644 index e5bd8088a..000000000 --- a/.example/os/glog/glog_async_chaining.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" -) - -func main() { - for i := 0; i < 10; i++ { - g.Log().Async().Print("async log", i) - } - time.Sleep(time.Second) -} diff --git a/.example/os/glog/glog_async_configure.go b/.example/os/glog/glog_async_configure.go deleted file mode 100644 index ed4071e92..000000000 --- a/.example/os/glog/glog_async_configure.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" -) - -func main() { - g.Log().SetAsync(true) - for i := 0; i < 10; i++ { - g.Log().Print("async log", i) - } - time.Sleep(time.Second) -} diff --git a/.example/os/glog/glog_category.go b/.example/os/glog/glog_category.go deleted file mode 100644 index 1aa9a7e8f..000000000 --- a/.example/os/glog/glog_category.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - path := "/tmp/glog-cat" - g.Log().SetPath(path) - g.Log().Stdout(false).Cat("cat1").Cat("cat2").Print("test") - list, err := gfile.ScanDir(path, "*", true) - g.Dump(err) - g.Dump(list) -} diff --git a/.example/os/glog/glog_color.go b/.example/os/glog/glog_color.go deleted file mode 100644 index aa64f1e89..000000000 --- a/.example/os/glog/glog_color.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().Print("Print") - g.Log().Debug("Debug") - g.Log().Info("Info") - g.Log().Notice("Notice") - g.Log().Warning("Warning") - g.Log().Error("Error") - g.Log().Critical("Critical") -} diff --git a/.example/os/glog/glog_debug.go b/.example/os/glog/glog_debug.go deleted file mode 100644 index 1129b0f3d..000000000 --- a/.example/os/glog/glog_debug.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" - - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - gtimer.SetTimeout(3*time.Second, func() { - g.Log().SetDebug(false) - }) - for { - g.Log().Debug(gtime.Datetime()) - time.Sleep(time.Second) - } -} diff --git a/.example/os/glog/glog_error.go b/.example/os/glog/glog_error.go deleted file mode 100644 index 15e811fb7..000000000 --- a/.example/os/glog/glog_error.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import "github.com/gogf/gf/v2/os/glog" - -func Test() { - glog.Error("This is error!") -} - -func main() { - Test() -} diff --git a/.example/os/glog/glog_file.go b/.example/os/glog/glog_file.go deleted file mode 100644 index 6aa1cb7f6..000000000 --- a/.example/os/glog/glog_file.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -// 设置日志等级 -func main() { - var ( - ctx = context.TODO() - path = "/tmp/glog" - ) - - g.Log().SetPath(path) - g.Log().SetStdoutPrint(false) - - // 使用默认文件名称格式 - g.Log().Print(ctx, "标准文件名称格式,使用当前时间时期") - - // 通过SetFile设置文件名称格式 - g.Log().SetFile("stdout.log") - g.Log().Print(ctx, "设置日志输出文件名称格式为同一个文件") - - // 链式操作设置文件名称格式 - g.Log().File("stderr.log").Print(ctx, "支持链式操作") - g.Log().File("error-{Ymd}.log").Print(ctx, "文件名称支持带gtime日期格式") - g.Log().File("access-{Ymd}.log").Print(ctx, "文件名称支持带gtime日期格式") - - list, err := gfile.ScanDir(path, "*") - g.Dump(err) - g.Dump(list) -} diff --git a/.example/os/glog/glog_flags.go b/.example/os/glog/glog_flags.go deleted file mode 100644 index 3ab7ea82e..000000000 --- a/.example/os/glog/glog_flags.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - g.Log().SetFlags(glog.F_TIME_TIME | glog.F_FILE_SHORT) - g.Log().Print("time and short line number") - g.Log().SetFlags(glog.F_TIME_MILLI | glog.F_FILE_LONG) - g.Log().Print("time with millisecond and long line number") - g.Log().SetFlags(glog.F_TIME_STD | glog.F_FILE_LONG) - g.Log().Print("standard time format and long line number") -} diff --git a/.example/os/glog/glog_gerror.go b/.example/os/glog/glog_gerror.go deleted file mode 100644 index 018a31b08..000000000 --- a/.example/os/glog/glog_gerror.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "errors" - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/errors/gerror" -) - -func MakeError() error { - return errors.New("connection closed with normal error") -} - -func MakeGError() error { - return gerror.New("connection closed with gerror") -} - -func TestGError() { - err1 := MakeError() - err2 := MakeGError() - g.Log().Error(err1) - g.Log().Error(err2) -} - -func main() { - TestGError() -} diff --git a/.example/os/glog/glog_json.go b/.example/os/glog/glog_json.go deleted file mode 100644 index e9285d8fe..000000000 --- a/.example/os/glog/glog_json.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().Debug(g.Map{"uid": 100, "name": "john"}) - - type User struct { - Uid int `json:"uid"` - Name string `json:"name"` - } - g.Log().Debug(User{100, "john"}) -} diff --git a/.example/os/glog/glog_level.go b/.example/os/glog/glog_level.go deleted file mode 100644 index 701f1132a..000000000 --- a/.example/os/glog/glog_level.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -// 设置日志等级,过滤掉Info日志信息 -func main() { - g.Log().Info("info1") - g.Log().SetLevel(glog.LEVEL_ALL ^ glog.LEVEL_INFO) - g.Log().Info("info2") -} diff --git a/.example/os/glog/glog_level_prefix.go b/.example/os/glog/glog_level_prefix.go deleted file mode 100644 index c15687866..000000000 --- a/.example/os/glog/glog_level_prefix.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/glog" -) - -func main() { - g.Log().SetLevelPrefix(glog.LEVEL_DEBU, "debug") - g.Log().Debug("test") -} diff --git a/.example/os/glog/glog_line.go b/.example/os/glog/glog_line.go deleted file mode 100644 index 2d7648343..000000000 --- a/.example/os/glog/glog_line.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().Line().Debug("this is the short file name with its line number") - g.Log().Line(true).Debug("lone file name with line number") -} diff --git a/.example/os/glog/glog_line2.go b/.example/os/glog/glog_line2.go deleted file mode 100644 index ea0011462..000000000 --- a/.example/os/glog/glog_line2.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func PrintLog(content string) { - g.Log().Skip(0).Line().Print("line number with skip:", content) - g.Log().Line(true).Print("line number without skip:", content) -} - -func main() { - PrintLog("just test") -} diff --git a/.example/os/glog/glog_path.go b/.example/os/glog/glog_path.go deleted file mode 100644 index 64b40be32..000000000 --- a/.example/os/glog/glog_path.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -// 设置日志输出路径 -func main() { - path := "/tmp/glog" - g.Log().SetPath(path) - g.Log().Print("日志内容") - list, err := gfile.ScanDir(path, "*") - g.Dump(err) - g.Dump(list) -} diff --git a/.example/os/glog/glog_pool.go b/.example/os/glog/glog_pool.go deleted file mode 100644 index 565848e93..000000000 --- a/.example/os/glog/glog_pool.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -// 测试删除日志文件是否会重建日志文件 -func main() { - path := "/Users/john/Temp/test" - g.Log().SetPath(path) - for { - g.Log().Print(gtime.Now().String()) - time.Sleep(time.Second) - } -} diff --git a/.example/os/glog/glog_prefix.go b/.example/os/glog/glog_prefix.go deleted file mode 100644 index 90c114354..000000000 --- a/.example/os/glog/glog_prefix.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().SetPrefix("[API]") - g.Log().Print("hello world") - g.Log().Error("error occurred") -} diff --git a/.example/os/glog/glog_stack.go b/.example/os/glog/glog_stack.go deleted file mode 100644 index 854793408..000000000 --- a/.example/os/glog/glog_stack.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - g.Log().PrintStack() - - fmt.Println(g.Log().GetStack()) -} diff --git a/.example/os/glog/glog_stdout.go b/.example/os/glog/glog_stdout.go deleted file mode 100644 index 801d65732..000000000 --- a/.example/os/glog/glog_stdout.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "sync" -) - -func main() { - var ( - wg = sync.WaitGroup{} - ch = make(chan struct{}) - ) - wg.Add(3000) - for i := 0; i < 3000; i++ { - go func() { - <-ch - g.Log().Print("abcdefghijklmnopqrstuvwxyz1234567890") - wg.Done() - }() - } - close(ch) - wg.Wait() -} diff --git a/.example/os/glog/glog_writer_greylog.go b/.example/os/glog/glog_writer_greylog.go deleted file mode 100644 index 4f0824a47..000000000 --- a/.example/os/glog/glog_writer_greylog.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -//import ( -// "github.com/gogf/gf/v2/os/glog" -// "github.com/robertkowalski/graylog-golang" -//) -// -//type MyGrayLogWriter struct { -// gelf *gelf.Gelf -// logger *glog.Logger -//} -// -//func (w *MyGrayLogWriter) Write(p []byte) (n int, err error) { -// w.gelf.Send(p) -// return w.logger.Write(p) -//} -// -//func main() { -// glog.SetWriter(&MyGrayLogWriter{ -// logger : glog.New(), -// gelf : gelf.New(gelf.Config{ -// GraylogPort : 80, -// GraylogHostname : "graylog-host.com", -// Connection : "wan", -// MaxChunkSizeWan : 42, -// MaxChunkSizeLan : 1337, -// }), -// }) -// glog.Print("test log") -//} diff --git a/.example/os/glog/glog_writer_hook.go b/.example/os/glog/glog_writer_hook.go deleted file mode 100644 index e3a6e4526..000000000 --- a/.example/os/glog/glog_writer_hook.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/text/gregex" -) - -type MyWriter struct { - logger *glog.Logger -} - -func (w *MyWriter) Write(p []byte) (n int, err error) { - s := string(p) - if gregex.IsMatchString(`\[(PANI|FATA)\]`, s) { - fmt.Println("SERIOUS ISSUE OCCURRED!! I'd better tell monitor in first time!") - g.Client().PostContent("http://monitor.mydomain.com", s) - } - return w.logger.Write(p) -} - -func main() { - glog.SetWriter(&MyWriter{ - logger: glog.New(), - }) - glog.Debug("DEBUG") - glog.Fatal("FATAL ERROR") - -} diff --git a/.example/os/glog/handler/glog_handler_greylog.go b/.example/os/glog/handler/glog_handler_greylog.go deleted file mode 100644 index 295ea11f9..000000000 --- a/.example/os/glog/handler/glog_handler_greylog.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -//import ( -// "context" -// "github.com/gogf/gf/v2/frame/g" -// "github.com/gogf/gf/v2/os/glog" -// "github.com/robertkowalski/graylog-golang" -//) -// -//var greyLogClient = gelf.New(gelf.Config{ -// GraylogPort: 80, -// GraylogHostname: "graylog-host.com", -// Connection: "wan", -// MaxChunkSizeWan: 42, -// MaxChunkSizeLan: 1337, -//}) -// -//// LoggingGreyLogHandler is an example handler for logging content to remote GreyLog service. -//var LoggingGreyLogHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) { -// in.Next() -// greyLogClient.Log(in.Buffer.String()) -//} -// -//func main() { -// g.Log().SetHandlers(LoggingGreyLogHandler) -// -// g.Log().Debug("Debugging...") -// g.Log().Warning("It is warning info") -// g.Log().Error("Error occurs, please have a check") -// glog.Print("test log") -//} diff --git a/.example/os/glog/handler/glog_handler_json.go b/.example/os/glog/handler/glog_handler_json.go deleted file mode 100644 index 2e53212a8..000000000 --- a/.example/os/glog/handler/glog_handler_json.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/internal/json" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/text/gstr" - "os" -) - -// JsonOutputsForLogger is for JSON marshaling in sequence. -type JsonOutputsForLogger struct { - Time string `json:"time"` - Level string `json:"level"` - Content string `json:"content"` -} - -// LoggingJsonHandler is an example handler for logging JSON format content. -var LoggingJsonHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) { - jsonForLogger := JsonOutputsForLogger{ - Time: in.TimeFormat, - Level: in.LevelFormat, - Content: gstr.Trim(in.String()), - } - jsonBytes, err := json.Marshal(jsonForLogger) - if err != nil { - _, _ = os.Stderr.WriteString(err.Error()) - return - } - in.Buffer.Write(jsonBytes) - in.Buffer.WriteString("\n") - in.Next() -} - -func main() { - g.Log().SetHandlers(LoggingJsonHandler) - - g.Log().Debug("Debugging...") - g.Log().Warning("It is warning info") - g.Log().Error("Error occurs, please have a check") -} diff --git a/.example/os/gmlock/1.lock&unlock.go b/.example/os/gmlock/1.lock&unlock.go deleted file mode 100644 index caaba0916..000000000 --- a/.example/os/gmlock/1.lock&unlock.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "sync" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmlock" -) - -// 内存锁基本使用 -func main() { - var ( - key = "lock" - wg = sync.WaitGroup{} - ) - for i := 0; i < 10; i++ { - wg.Add(1) - go func(i int) { - gmlock.Lock(key) - glog.Print(i) - time.Sleep(time.Second) - gmlock.Unlock(key) - wg.Done() - }(i) - } - wg.Wait() -} diff --git a/.example/os/gmlock/2.trylock.go b/.example/os/gmlock/2.trylock.go deleted file mode 100644 index 7fe2c421c..000000000 --- a/.example/os/gmlock/2.trylock.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "sync" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmlock" -) - -// 内存锁 - TryLock -func main() { - key := "lock" - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func(i int) { - if gmlock.TryLock(key) { - glog.Print(i) - time.Sleep(time.Second) - gmlock.Unlock(key) - } else { - glog.Print(false) - } - wg.Done() - }(i) - } - wg.Wait() -} diff --git a/.example/os/gmlock/3.lock_conflicts.go b/.example/os/gmlock/3.lock_conflicts.go deleted file mode 100644 index 712080a4a..000000000 --- a/.example/os/gmlock/3.lock_conflicts.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmlock" -) - -// 内存锁 - 手动Unlock与计时Unlock冲突校验 -func main() { - key := "key" - - // 第一次锁带时间 - gmlock.Lock(key) - glog.Print("lock1") - // 这个时候上一次的计时解锁已失效 - gmlock.Unlock(key) - glog.Print("unlock1") - - fmt.Println() - - // 第二次锁,不带时间,且在执行过程中钱一个Lock的定时解锁生效 - gmlock.Lock(key) - glog.Print("lock2") - go func() { - // 正常情况下3秒后才能执行这句 - gmlock.Lock(key) - glog.Print("lock by goroutine") - }() - time.Sleep(3 * time.Second) - // 这时再解锁 - gmlock.Unlock(key) - // 注意3秒之后才会执行这一句 - glog.Print("unlock2") - - select {} -} diff --git a/.example/os/gmlock/4.test_deadlock.go b/.example/os/gmlock/4.test_deadlock.go deleted file mode 100644 index 9bc74976f..000000000 --- a/.example/os/gmlock/4.test_deadlock.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "fmt" - "math/rand" - "sync" - "time" - - "github.com/gogf/gf/v2/os/gmlock" -) - -// 测试Locker是否会产生死锁 -func main() { - var ( - l = gmlock.New() - wg = sync.WaitGroup{} - key = "test" - event = make(chan int) - number = 100000 - ) - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - l.Lock(key) - //fmt.Println("get lock") - l.Unlock(key) - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - l.RLock(key) - //fmt.Println("get rlock") - l.RUnlock(key) - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryLock(key) { - //fmt.Println("get lock") - l.Unlock(key) - } - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryRLock(key) { - //fmt.Println("get rlock") - l.RUnlock(key) - } - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryLock(key) { - // 模拟业务逻辑的随机处理间隔 - time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) - l.Unlock(key) - } - wg.Done() - }() - } - - for i := 0; i < number; i++ { - wg.Add(1) - go func() { - <-event - if l.TryRLock(key) { - // 模拟业务逻辑的随机处理间隔 - time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) - l.RUnlock(key) - } - wg.Done() - }() - } - // 使用chan作为事件发送测试指令,让所有的goroutine同时执行 - close(event) - wg.Wait() - - fmt.Println("done!") -} diff --git a/.example/os/gmutex/gmutex_basic.go b/.example/os/gmutex/gmutex_basic.go deleted file mode 100644 index 5ca0944fa..000000000 --- a/.example/os/gmutex/gmutex_basic.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gmutex" -) - -func main() { - mu := gmutex.New() - for i := 0; i < 10; i++ { - go func(n int) { - mu.Lock() - defer mu.Unlock() - glog.Print("Lock:", n) - time.Sleep(time.Second) - }(i) - } - for i := 0; i < 10; i++ { - go func(n int) { - mu.RLock() - defer mu.RUnlock() - glog.Print("RLock:", n) - time.Sleep(time.Second) - }(i) - } - time.Sleep(11 * time.Second) -} diff --git a/.example/os/gmutex/gmutex_func.go b/.example/os/gmutex/gmutex_func.go deleted file mode 100644 index cc2515883..000000000 --- a/.example/os/gmutex/gmutex_func.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - - "github.com/gogf/gf/v2/os/gmutex" -) - -func main() { - mu := gmutex.New() - go mu.LockFunc(func() { - glog.Print("lock func1") - time.Sleep(1 * time.Second) - }) - time.Sleep(time.Millisecond) - go mu.LockFunc(func() { - glog.Print("lock func2") - }) - time.Sleep(2 * time.Second) -} diff --git a/.example/os/gproc/gproc.go b/.example/os/gproc/gproc.go deleted file mode 100644 index 743f45979..000000000 --- a/.example/os/gproc/gproc.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "os" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" -) - -// 父子进程基本演示 -func main() { - if gproc.IsChild() { - glog.Printf("%d: Hi, I am child, waiting 3 seconds to die", gproc.Pid()) - time.Sleep(time.Second) - glog.Printf("%d: 1", gproc.Pid()) - time.Sleep(time.Second) - glog.Printf("%d: 2", gproc.Pid()) - time.Sleep(time.Second) - glog.Printf("%d: 3", gproc.Pid()) - } else { - m := gproc.NewManager() - p := m.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - p.Wait() - glog.Printf("%d: child died", gproc.Pid()) - } -} diff --git a/.example/os/gproc/gproc3.go b/.example/os/gproc/gproc3.go deleted file mode 100644 index 49acaa0e0..000000000 --- a/.example/os/gproc/gproc3.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "os" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" -) - -// 父进程销毁后,使用进程管理器查看存活的子进程。 -// 请使用go build编译后运行,不要使用IDE运行,因为IDE大多采用的是子进程方式执行。 -func main() { - if gproc.IsChild() { - glog.Printf("%d: I am child, waiting 10 seconds to die", gproc.Pid()) - //p, err := os.FindProcess(os.Getppid()) - //fmt.Println(err) - //p.Kill() - time.Sleep(2 * time.Second) - glog.Printf("%d: 2", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: 4", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: 6", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: 8", gproc.Pid()) - time.Sleep(2 * time.Second) - glog.Printf("%d: died", gproc.Pid()) - } else { - p := gproc.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - glog.Printf("%d: I am main, waiting 3 seconds to die", gproc.Pid()) - time.Sleep(3 * time.Second) - glog.Printf("%d: died", gproc.Pid()) - } -} diff --git a/.example/os/gproc/gproc4.go b/.example/os/gproc/gproc4.go deleted file mode 100644 index 2fd2855fd..000000000 --- a/.example/os/gproc/gproc4.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "os" - "time" - - "github.com/gogf/gf/v2/os/genv" - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" -) - -// 查看父子进程的环境变量 -func main() { - time.Sleep(5 * time.Second) - glog.Printf("%d: %v", gproc.Pid(), genv.All()) - p := gproc.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() -} diff --git a/.example/os/gproc/gproc_comm.go b/.example/os/gproc/gproc_comm.go deleted file mode 100644 index ca95ee290..000000000 --- a/.example/os/gproc/gproc_comm.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "fmt" - "os" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gproc" - "github.com/gogf/gf/v2/os/gtime" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - fmt.Printf("%d: I am child? %v\n", gproc.Pid(), gproc.IsChild()) - if gproc.IsChild() { - gtimer.SetInterval(time.Second, func() { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime())); err != nil { - glog.Error(err) - } - }) - select {} - } else { - m := gproc.NewManager() - p := m.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - for { - msg := gproc.Receive() - fmt.Printf("%d: receive from %d, data: %s\n", gproc.Pid(), msg.SendPid, string(msg.Data)) - } - } -} diff --git a/.example/os/gproc/gproc_comm_group.go b/.example/os/gproc/gproc_comm_group.go deleted file mode 100644 index 90e216944..000000000 --- a/.example/os/gproc/gproc_comm_group.go +++ /dev/null @@ -1,58 +0,0 @@ -// 该示例是gproc_comm.go的改进,增加了分组消息的演示。 -package main - -import ( - "fmt" - "os" - "time" - - "github.com/gogf/gf/v2/os/gproc" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - fmt.Printf("%d: I am child? %v\n", gproc.Pid(), gproc.IsChild()) - if gproc.IsChild() { - // sending group: test1 - gtime.SetInterval(time.Second, func() bool { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime()), "test1"); err != nil { - fmt.Printf("test1: error - %s\n", err.Error()) - } - return true - }) - // sending group: test2 - gtime.SetInterval(time.Second, func() bool { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime()), "test2"); err != nil { - fmt.Printf("test2: error - %s\n", err.Error()) - } - return true - }) - // sending group: test3, will cause error - gtime.SetInterval(time.Second, func() bool { - if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime()), "test3"); err != nil { - fmt.Printf("test3: error - %s\n", err.Error()) - } - return true - }) - select {} - } else { - m := gproc.NewManager() - p := m.NewProcess(os.Args[0], os.Args, os.Environ()) - p.Start() - // receiving group: test1 - go func() { - for { - msg := gproc.Receive("test1") - fmt.Printf("test1: receive from %d, data: %s\n", msg.Pid, string(msg.Data)) - } - }() - // receiving group: test2 - go func() { - for { - msg := gproc.Receive("test2") - fmt.Printf("test1: receive from %d, data: %s\n", msg.Pid, string(msg.Data)) - } - }() - select {} - } -} diff --git a/.example/os/gproc/gproc_comm_send.go b/.example/os/gproc/gproc_comm_send.go deleted file mode 100644 index a3f6c92b5..000000000 --- a/.example/os/gproc/gproc_comm_send.go +++ /dev/null @@ -1,13 +0,0 @@ -// 向指定进程发送进程消息。 -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - err := gproc.Send(22988, []byte{30}) - fmt.Println(err) -} diff --git a/.example/os/gproc/gproc_kill.go b/.example/os/gproc/gproc_kill.go deleted file mode 100644 index cb438e0f3..000000000 --- a/.example/os/gproc/gproc_kill.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - pid := 32556 - m := gproc.NewManager() - m.AddProcess(pid) - err := m.KillAll() - fmt.Println(err) - m.WaitAll() - fmt.Printf("%d was killed\n", pid) -} diff --git a/.example/os/gproc/gproc_shellexec.go b/.example/os/gproc/gproc_shellexec.go deleted file mode 100644 index ed6600839..000000000 --- a/.example/os/gproc/gproc_shellexec.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gproc" -) - -// 执行shell指令 -func main() { - r, err := gproc.ShellExec(`sleep 3s; echo "hello gf!";`) - fmt.Println("result:", r) - fmt.Println(err) -} diff --git a/.example/os/gproc/gproc_sleep.go b/.example/os/gproc/gproc_sleep.go deleted file mode 100644 index 66aaadea2..000000000 --- a/.example/os/gproc/gproc_sleep.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gproc" -) - -func main() { - fmt.Println(gproc.Pid()) - err := gproc.ShellRun("sleep 99999s") - fmt.Println(err) -} diff --git a/.example/os/gproc/signal/signal_handler.go b/.example/os/gproc/signal/signal_handler.go deleted file mode 100644 index a1d495347..000000000 --- a/.example/os/gproc/signal/signal_handler.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "fmt" - "os" - "os/signal" - "syscall" - "time" -) - -func signalHandlerForMQ() { - var ( - sig os.Signal - receivedChan = make(chan os.Signal) - ) - signal.Notify( - receivedChan, - syscall.SIGINT, - syscall.SIGQUIT, - syscall.SIGKILL, - syscall.SIGTERM, - syscall.SIGABRT, - ) - for { - sig = <-receivedChan - fmt.Println("MQ is shutting down due to signal:", sig.String()) - time.Sleep(time.Second) - fmt.Println("MQ is shut down smoothly") - return - } -} - -func main() { - fmt.Println("Process start, pid:", os.Getpid()) - go signalHandlerForMQ() - - var ( - sig os.Signal - receivedChan = make(chan os.Signal) - ) - signal.Notify( - receivedChan, - syscall.SIGINT, - syscall.SIGQUIT, - syscall.SIGKILL, - syscall.SIGTERM, - syscall.SIGABRT, - ) - for { - sig = <-receivedChan - fmt.Println("MainProcess is shutting down due to signal:", sig.String()) - return - } -} diff --git a/.example/os/gproc/signal/signal_handler_gproc.go b/.example/os/gproc/signal/signal_handler_gproc.go deleted file mode 100644 index 06cde3386..000000000 --- a/.example/os/gproc/signal/signal_handler_gproc.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/os/gproc" - "os" - "time" -) - -func signalHandlerForMQ(sig os.Signal) { - fmt.Println("MQ is shutting down due to signal:", sig.String()) - time.Sleep(time.Second) - fmt.Println("MQ is shut down smoothly") -} - -func signalHandlerForMain(sig os.Signal) { - fmt.Println("MainProcess is shutting down due to signal:", sig.String()) -} - -func main() { - fmt.Println("Process start, pid:", os.Getpid()) - gproc.AddSigHandlerShutdown( - signalHandlerForMQ, - signalHandlerForMain, - ) - gproc.Listen() -} diff --git a/.example/os/gres/gres_example.go b/.example/os/gres/gres_example.go deleted file mode 100644 index cf2084107..000000000 --- a/.example/os/gres/gres_example.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - _ "github.com/gogf/gf/v2/os/gres/testdata/example/boot" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.GET("/template", func(r *ghttp.Request) { - r.Response.WriteTplDefault(g.Map{ - "name": "GoFrame", - }) - }) - }) - s.Run() -} diff --git a/.example/os/gres/gres_pack.go b/.example/os/gres/gres_pack.go deleted file mode 100644 index 28c6e237e..000000000 --- a/.example/os/gres/gres_pack.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/crypto/gaes" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gres" -) - -var ( - CryptoKey = []byte("x76cgqt36i9c863bzmotuf8626dxiwu0") -) - -func main() { - binContent, err := gres.Pack("public,config") - if err != nil { - panic(err) - } - binContent, err = gaes.Encrypt(binContent, CryptoKey) - if err != nil { - panic(err) - } - if err := gfile.PutBytes("data.bin", binContent); err != nil { - panic(err) - } -} diff --git a/.example/os/gres/gres_unpack.go b/.example/os/gres/gres_unpack.go deleted file mode 100644 index cec200e3b..000000000 --- a/.example/os/gres/gres_unpack.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/crypto/gaes" - "github.com/gogf/gf/v2/os/gfile" - "github.com/gogf/gf/v2/os/gres" -) - -var ( - CryptoKey = []byte("x76cgqt36i9c863bzmotuf8626dxiwu0") -) - -func main() { - binContent := gfile.GetBytes("data.bin") - binContent, err := gaes.Decrypt(binContent, CryptoKey) - if err != nil { - panic(err) - } - if err := gres.Add(binContent); err != nil { - panic(err) - } - gres.Dump() -} diff --git a/.example/os/grpool/goroutine.go b/.example/os/grpool/goroutine.go deleted file mode 100644 index 2bbcc1468..000000000 --- a/.example/os/grpool/goroutine.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "sync" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - start := gtime.TimestampMilli() - wg := sync.WaitGroup{} - for i := 0; i < 100000; i++ { - wg.Add(1) - go func() { - time.Sleep(time.Second) - wg.Done() - }() - } - wg.Wait() - fmt.Println("time spent:", gtime.TimestampMilli()-start) -} diff --git a/.example/os/grpool/grpool.go b/.example/os/grpool/grpool.go deleted file mode 100644 index 9e02a0952..000000000 --- a/.example/os/grpool/grpool.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - "sync" - "time" - - "github.com/gogf/gf/v2/os/grpool" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - start := gtime.TimestampMilli() - wg := sync.WaitGroup{} - for i := 0; i < 100000; i++ { - wg.Add(1) - grpool.Add(func() { - time.Sleep(time.Second) - wg.Done() - }) - } - wg.Wait() - fmt.Println(grpool.Size()) - fmt.Println("time spent:", gtime.TimestampMilli()-start) -} diff --git a/.example/os/grpool/grpool1.go b/.example/os/grpool/grpool1.go deleted file mode 100644 index a71a1d0b2..000000000 --- a/.example/os/grpool/grpool1.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/grpool" - "github.com/gogf/gf/v2/os/gtimer" -) - -func job() { - time.Sleep(1 * time.Second) -} - -func main() { - pool := grpool.New(100) - for i := 0; i < 1000; i++ { - pool.Add(job) - } - fmt.Println("worker:", pool.Size()) - fmt.Println(" jobs:", pool.Jobs()) - gtimer.SetInterval(time.Second, func() { - fmt.Println("worker:", pool.Size()) - fmt.Println(" jobs:", pool.Jobs()) - fmt.Println() - gtimer.Exit() - }) - - select {} -} diff --git a/.example/os/grpool/grpool2.go b/.example/os/grpool/grpool2.go deleted file mode 100644 index 4cb3933dc..000000000 --- a/.example/os/grpool/grpool2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "sync" - - "github.com/gogf/gf/v2/os/grpool" -) - -func main() { - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - v := i - grpool.Add(func() { - fmt.Println(v) - wg.Done() - }) - } - wg.Wait() -} diff --git a/.example/os/grpool/grpool3.go b/.example/os/grpool/grpool3.go deleted file mode 100644 index a91e14641..000000000 --- a/.example/os/grpool/grpool3.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "sync" - - "github.com/gogf/gf/v2/os/grpool" -) - -func main() { - p := grpool.New(1) - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - v := i - p.Add(func() { - fmt.Println(v) - wg.Done() - }) - } - wg.Wait() -} diff --git a/.example/os/grpool/grpool4.go b/.example/os/grpool/grpool4.go deleted file mode 100644 index 4a2fd6773..000000000 --- a/.example/os/grpool/grpool4.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - "sync" -) - -func main() { - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func(v int) { - fmt.Println(v) - wg.Done() - }(i) - } - wg.Wait() -} diff --git a/.example/os/grpool/grpool5.go b/.example/os/grpool/grpool5.go deleted file mode 100644 index 0b9c1aeff..000000000 --- a/.example/os/grpool/grpool5.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/grpool" -) - -func main() { - p := grpool.New(1) - for i := 0; i < 10; i++ { - v := i - p.Add(func() { - fmt.Println(v) - time.Sleep(3 * time.Second) - }) - } - time.Sleep(time.Minute) -} diff --git a/.example/os/gsession/storage-file/file.go b/.example/os/gsession/storage-file/file.go deleted file mode 100644 index 513ddf0d3..000000000 --- a/.example/os/gsession/storage-file/file.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gsession/storage-memory/memory.go b/.example/os/gsession/storage-memory/memory.go deleted file mode 100644 index 13821122f..000000000 --- a/.example/os/gsession/storage-memory/memory.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - "SessionStorage": gsession.NewStorageMemory(), - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gsession/storage-redis-hashtable/config.toml b/.example/os/gsession/storage-redis-hashtable/config.toml deleted file mode 100644 index 5632e6444..000000000 --- a/.example/os/gsession/storage-redis-hashtable/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/os/gsession/storage-redis-hashtable/redis-hashtable.go b/.example/os/gsession/storage-redis-hashtable/redis-hashtable.go deleted file mode 100644 index 4a83c8793..000000000 --- a/.example/os/gsession/storage-redis-hashtable/redis-hashtable.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - "SessionStorage": gsession.NewStorageRedisHashTable(g.Redis()), - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gsession/storage-redis/config.toml b/.example/os/gsession/storage-redis/config.toml deleted file mode 100644 index 5632e6444..000000000 --- a/.example/os/gsession/storage-redis/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -# Redis数据库配置 -[redis] - default = "127.0.0.1:6379,0" - cache = "127.0.0.1:6379,1" \ No newline at end of file diff --git a/.example/os/gsession/storage-redis/redis.go b/.example/os/gsession/storage-redis/redis.go deleted file mode 100644 index 5b7068c3e..000000000 --- a/.example/os/gsession/storage-redis/redis.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gsession" - "github.com/gogf/gf/v2/os/gtime" - "time" -) - -func main() { - s := g.Server() - s.SetConfigWithMap(g.Map{ - "SessionMaxAge": time.Minute, - "SessionStorage": gsession.NewStorageRedis(g.Redis()), - }) - s.Group("/", func(group *ghttp.RouterGroup) { - group.ALL("/set", func(r *ghttp.Request) { - r.Session.Set("time", gtime.Timestamp()) - r.Response.Write("ok") - }) - group.ALL("/get", func(r *ghttp.Request) { - r.Response.Write(r.Session.Map()) - }) - group.ALL("/del", func(r *ghttp.Request) { - r.Session.Clear() - r.Response.Write("ok") - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gspath/gspath.go b/.example/os/gspath/gspath.go deleted file mode 100644 index 8e3eccc5d..000000000 --- a/.example/os/gspath/gspath.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gspath" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - sp := gspath.New() - path := "/Users/john/Temp" - rp, err := sp.Add(path) - fmt.Println(err) - fmt.Println(rp) - fmt.Println(sp) - - gtime.SetInterval(5*time.Second, func() bool { - g.Dump(sp.AllPaths()) - return true - }) - - select {} -} diff --git a/.example/os/gtime/gtime_format.go b/.example/os/gtime/gtime_format.go deleted file mode 100644 index b0bdc9322..000000000 --- a/.example/os/gtime/gtime_format.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - formats := []string{ - "Y-m-d H:i:s.u", - "D M d H:i:s T O Y", - "\\T\\i\\m\\e \\i\\s: h:i:s a", - "2006-01-02T15:04:05.000000000Z07:00", - } - t := gtime.Now() - for _, f := range formats { - fmt.Println(t.Format(f)) - } -} diff --git a/.example/os/gtime/gtime_func.go b/.example/os/gtime/gtime_func.go deleted file mode 100644 index d362ac25e..000000000 --- a/.example/os/gtime/gtime_func.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - fmt.Println("Date :", gtime.Date()) - fmt.Println("Datetime :", gtime.Datetime()) - fmt.Println("Second :", gtime.Timestamp()) - fmt.Println("Millisecond:", gtime.TimestampMilli()) - fmt.Println("Microsecond:", gtime.TimestampMicro()) - fmt.Println("Nanosecond :", gtime.TimestampNano()) -} diff --git a/.example/os/gtime/gtime_json.go b/.example/os/gtime/gtime_json.go deleted file mode 100644 index 66209af74..000000000 --- a/.example/os/gtime/gtime_json.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - t := gtime.Now() - b, err := json.Marshal(t) - fmt.Println(err) - fmt.Println(string(b)) -} diff --git a/.example/os/gtime/gtime_layout.go b/.example/os/gtime/gtime_layout.go deleted file mode 100644 index a75f0b90d..000000000 --- a/.example/os/gtime/gtime_layout.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - formats := []string{ - "2006-01-02 15:04:05.000", - "Mon Jan _2 15:04:05 MST 2006", - "Time is: 03:04:05 PM", - "2006-01-02T15:04:05.000000000Z07:00 MST", - } - t := gtime.Now() - for _, f := range formats { - fmt.Println(t.Layout(f)) - } -} diff --git a/.example/os/gtime/gtime_linkop.go b/.example/os/gtime/gtime_linkop.go deleted file mode 100644 index d708bffc9..000000000 --- a/.example/os/gtime/gtime_linkop.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // 去年今日 - fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d")) - - // 去年今日,UTC时间 - fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d H:i:s T")) - fmt.Println(gtime.Now().AddDate(-1, 0, 0).UTC().Format("Y-m-d H:i:s T")) - - // 下个月1号凌晨0点整 - fmt.Println(gtime.Now().AddDate(0, 1, 0).Format("Y-m-d 00:00:00")) - - // 2个小时前 - fmt.Println(gtime.Now().Add(-time.Hour).Format("Y-m-d H:i:s")) -} diff --git a/.example/os/gtime/gtime_parsertime.go b/.example/os/gtime/gtime_parsertime.go deleted file mode 100644 index 740df565b..000000000 --- a/.example/os/gtime/gtime_parsertime.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - content := ` - -2018-11-01 14:30:39 -- 67 -- assignDoctor:request -- {"问诊ID":"1017467","操作类型":2,"操作ID":52339491,"医生ID":52339491,"是否主动接单":"是"} -2018-11-01 14:35:55 -- 73 -- throwIntoPool:request -- {"问诊Id":1017474,"当前Id":null,"当前角色":null} -` - if t := gtime.ParseTimeFromContent(content); t != nil { - fmt.Println(t.String()) - fmt.Println(t.UTC()) - fmt.Println(gtime.Now().UTC()) - } else { - panic("cannot parse time from content") - } - - //if t := gtime.ParseTimeFromContent(content, "d/M/Y:H:i:s +0800"); t != nil { - // fmt.Println(t.String()) - //} else { - // panic("cannot parse time from content") - //} -} diff --git a/.example/os/gtime/gtime_regex1.go b/.example/os/gtime/gtime_regex1.go deleted file mode 100644 index 4f0826af9..000000000 --- a/.example/os/gtime/gtime_regex1.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "regexp" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - timeRegex, err := regexp.Compile(gtime.TIME_REAGEX_PATTERN1) - if err != nil { - panic(err) - } - array := []string{ - "2017-12-14 04:51:34 +0805 LMT", - "2006-01-02T15:04:05Z07:00", - "2014-01-17T01:19:15+08:00", - "2018-02-09T20:46:17.897Z", - "2018-02-09 20:46:17.897", - "2018-02-09T20:46:17Z", - "2018-02-09 20:46:17", - "2018/10/31 - 16:38:46", - "2018-02-09", - "2017/12/14 04:51:34 +0805 LMT", - "2018/02/09 12:00:15", - "18/02/09 12:16", - "18/02/09 12", - "18/02/09 +0805 LMT", - } - for _, s := range array { - fmt.Println(s) - match := timeRegex.FindStringSubmatch(s) - for k, v := range match { - fmt.Println(k, v) - } - fmt.Println() - } -} diff --git a/.example/os/gtime/gtime_regex2.go b/.example/os/gtime/gtime_regex2.go deleted file mode 100644 index 99c07859e..000000000 --- a/.example/os/gtime/gtime_regex2.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - "regexp" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - timeRegex, err := regexp.Compile(gtime.TIME_REAGEX_PATTERN2) - if err != nil { - panic(err) - } - array := []string{ - "01-Nov-2018 11:50:28 +0805 LMT", - "01-Nov-2018T15:04:05Z07:00", - "01-Nov-2018T01:19:15+08:00", - "01-Nov-2018 11:50:28 +0805 LMT", - "01/Nov/18 11:50:28", - "01/Nov/2018 11:50:28", - "01/Nov/2018:11:50:28", - "01/Nov/2018", - } - for _, s := range array { - fmt.Println(s) - match := timeRegex.FindStringSubmatch(s) - for k, v := range match { - fmt.Println(k, v) - } - fmt.Println() - } -} diff --git a/.example/os/gtime/gtime_strtotime.go b/.example/os/gtime/gtime_strtotime.go deleted file mode 100644 index 4169e66f2..000000000 --- a/.example/os/gtime/gtime_strtotime.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "context" - "fmt" - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - array := []string{ - "2017-12-14 04:51:34 +0805 LMT", - "2006-01-02T15:04:05Z07:00", - "2014-01-17T01:19:15+08:00", - "2018-02-09T20:46:17.897Z", - "2018-02-09 20:46:17.897", - "2018-02-09T20:46:17Z", - "2018-02-09 20:46:17", - "2018.02.09 20:46:17", - "2018-02-09", - "2017/12/14 04:51:34 +0805 LMT", - "2018/02/09 12:00:15", - "01/Nov/2018:13:28:13 +0800", - "01-Nov-2018 11:50:28 +0805 LMT", - "01-Nov-2018T15:04:05Z07:00", - "01-Nov-2018T01:19:15+08:00", - "01-Nov-2018 11:50:28 +0805 LMT", - "01/Nov/2018 11:50:28", - "01/Nov/2018:11:50:28", - "01.Nov.2018:11:50:28", - "01/Nov/2018", - } - cstLocal, _ := time.LoadLocation("Asia/Shanghai") - for _, s := range array { - if t, err := gtime.StrToTime(s); err == nil { - fmt.Println(s) - fmt.Println(t.UTC().String()) - fmt.Println(t.In(cstLocal).String()) - } else { - glog.Error(context.Background(), s, err) - } - fmt.Println() - } -} diff --git a/.example/os/gtime/gtime_strtotime2.go b/.example/os/gtime/gtime_strtotime2.go deleted file mode 100644 index 7b3e0e86f..000000000 --- a/.example/os/gtime/gtime_strtotime2.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - if t, err := gtime.StrToTimeFormat("Tue Oct 16 15:55:59 CST 2018", "D M d H:i:s T Y"); err == nil { - fmt.Println(t.String()) - } else { - panic(err) - } -} diff --git a/.example/os/gtime/gtime_zone.go b/.example/os/gtime/gtime_zone.go deleted file mode 100644 index e34c5f988..000000000 --- a/.example/os/gtime/gtime_zone.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - // 先使用标准库打印当前时间 - fmt.Println(time.Now().String()) - // 设置进程时区,全局有效 - err := gtime.SetTimeZone("Asia/Tokyo") - if err != nil { - panic(err) - } - // 使用gtime获取当前时间 - fmt.Println(gtime.Now().String()) - // 使用标准库获取当前时间 - fmt.Println(time.Now().String()) -} diff --git a/.example/os/gtimer/gtimer-batch.go b/.example/os/gtimer/gtimer-batch.go deleted file mode 100644 index cbc902ef8..000000000 --- a/.example/os/gtimer/gtimer-batch.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - for i := 0; i < 100000; i++ { - gtimer.Add(time.Second, func() { - - }) - } - fmt.Println("start") - time.Sleep(48 * time.Hour) -} diff --git a/.example/os/gtimer/gtimer1.go b/.example/os/gtimer/gtimer1.go deleted file mode 100644 index 1f965f6ea..000000000 --- a/.example/os/gtimer/gtimer1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - now := time.Now() - interval := 510 * time.Millisecond - gtimer.Add(interval, func() { - fmt.Println(time.Now(), time.Duration(time.Now().UnixNano()-now.UnixNano())) - now = time.Now() - }) - time.Sleep(time.Hour) - select {} -} diff --git a/.example/os/gtimer/gtimer2.go b/.example/os/gtimer/gtimer2.go deleted file mode 100644 index 3844e6bd5..000000000 --- a/.example/os/gtimer/gtimer2.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/container/gtype" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - v := gtype.NewInt() - //w := gtimer.New(10, 10*time.Millisecond) - fmt.Println("start:", time.Now()) - for i := 0; i < 1000000; i++ { - gtimer.AddTimes(time.Second, 1, func() { - v.Add(1) - }) - } - fmt.Println("end :", time.Now()) - time.Sleep(1000 * time.Millisecond) - fmt.Println(v.Val(), time.Now()) - - //gtimer.AddSingleton(time.Second, func() { - // fmt.Println(time.Now().String()) - //}) - //select { } -} diff --git a/.example/os/gtimer/gtimer3.go b/.example/os/gtimer/gtimer3.go deleted file mode 100644 index aa726c704..000000000 --- a/.example/os/gtimer/gtimer3.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - interval := time.Second - gtimer.AddSingleton(interval, func() { - glog.Print("doing") - time.Sleep(5 * time.Second) - }) - - select {} -} diff --git a/.example/os/gtimer/gtimer4.go b/.example/os/gtimer/gtimer4.go deleted file mode 100644 index 88dea15bf..000000000 --- a/.example/os/gtimer/gtimer4.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "time" - - "github.com/gogf/gf/v2/os/glog" - "github.com/gogf/gf/v2/os/gtimer" -) - -func main() { - interval := time.Second - gtimer.AddTimes(interval, 2, func() { - glog.Print("doing1") - }) - gtimer.AddTimes(interval, 2, func() { - glog.Print("doing2") - }) - - select {} -} diff --git a/.example/os/gtimer/sleep1.go b/.example/os/gtimer/sleep1.go deleted file mode 100644 index e7dffddba..000000000 --- a/.example/os/gtimer/sleep1.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - "runtime" - "time" -) - -func main() { - go func() { - for { - time.Sleep(time.Microsecond) - go func() { - n := 0 - for i := 0; i < 100000000; i++ { - n += i - } - }() - } - }() - i := 0 - t := time.Now() - for { - time.Sleep(100 * time.Millisecond) - i++ - n := time.Now() - fmt.Println(i, runtime.NumGoroutine(), n, (n.UnixNano()-t.UnixNano())/1000000) - t = n - if i == 100 { - break - } - } -} diff --git a/.example/os/gtimer/sleep2.go b/.example/os/gtimer/sleep2.go deleted file mode 100644 index 429ca72f0..000000000 --- a/.example/os/gtimer/sleep2.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - i := 0 - for { - time.Sleep(10 * time.Millisecond) - fmt.Println(time.Now()) - i++ - if i == 100 { - break - } - } -} diff --git a/.example/os/gtimer/ticker1.go b/.example/os/gtimer/ticker1.go deleted file mode 100644 index 8db944a17..000000000 --- a/.example/os/gtimer/ticker1.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - fmt.Println("start:", time.Now()) - index := 0 - ticker := time.NewTicker(10 * time.Millisecond) - for { - <-ticker.C - index++ - fmt.Println(index) - if index == 100 { - break - } - } - fmt.Println(" end:", time.Now()) -} diff --git a/.example/os/gtimer/ticker2.go b/.example/os/gtimer/ticker2.go deleted file mode 100644 index 8db944a17..000000000 --- a/.example/os/gtimer/ticker2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - fmt.Println("start:", time.Now()) - index := 0 - ticker := time.NewTicker(10 * time.Millisecond) - for { - <-ticker.C - index++ - fmt.Println(index) - if index == 100 { - break - } - } - fmt.Println(" end:", time.Now()) -} diff --git a/.example/os/gview/assign/assign.go b/.example/os/gview/assign/assign.go deleted file mode 100644 index af0389af6..000000000 --- a/.example/os/gview/assign/assign.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - g.View().Assigns(gview.Params{ - "k1": "v1", - "k2": "v2", - }) - b, err := g.View().ParseContent(`{{.k1}} - {{.k2}}`, nil) - fmt.Println(err) - fmt.Println(string(b)) -} diff --git a/.example/os/gview/basic/gview.go b/.example/os/gview/basic/gview.go deleted file mode 100644 index 53b31222c..000000000 --- a/.example/os/gview/basic/gview.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - v := g.View() - b, err := v.Parse("gview.tpl", map[string]interface{}{ - "k": "v", - }) - if err != nil { - panic(err) - } - fmt.Println(string(b)) -} diff --git a/.example/os/gview/basic/gview.tpl b/.example/os/gview/basic/gview.tpl deleted file mode 100644 index 26d34e666..000000000 --- a/.example/os/gview/basic/gview.tpl +++ /dev/null @@ -1 +0,0 @@ -test.tpl content, vars: {{.}} \ No newline at end of file diff --git a/.example/os/gview/bind_func/gview_func1.go b/.example/os/gview/bind_func/gview_func1.go deleted file mode 100644 index bbbe8cb33..000000000 --- a/.example/os/gview/bind_func/gview_func1.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gview" -) - -// 用于测试的内置函数 -func funcTest() string { - return "test content" -} - -func main() { - // 解析模板的时候传递模板函数映射Map,仅会在当前模板解析生效 - parsed, err := g.View().ParseContent(`call build-in function test: {{test}}`, nil, gview.FuncMap{ - "test": funcTest, - }) - if err != nil { - panic(err) - } - fmt.Println(string(parsed)) -} diff --git a/.example/os/gview/bind_func/gview_func2.go b/.example/os/gview/bind_func/gview_func2.go deleted file mode 100644 index ca711b6a3..000000000 --- a/.example/os/gview/bind_func/gview_func2.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -// 用于测试的带参数的内置函数 -func funcHello(name string) string { - return fmt.Sprintf(`Hello %s`, name) -} - -func main() { - // 绑定全局的模板函数 - g.View().BindFunc("hello", funcHello) - - // 普通方式传参 - parsed1, err := g.View().ParseContent(`{{hello "GoFrame"}}`, nil) - if err != nil { - panic(err) - } - fmt.Println(string(parsed1)) - - // 通过管道传参 - parsed2, err := g.View().ParseContent(`{{"GoFrame" | hello}}`, nil) - if err != nil { - panic(err) - } - fmt.Println(string(parsed2)) -} diff --git a/.example/os/gview/bind_func/index.html b/.example/os/gview/bind_func/index.html deleted file mode 100644 index c905f153c..000000000 --- a/.example/os/gview/bind_func/index.html +++ /dev/null @@ -1 +0,0 @@ -{{test}} \ No newline at end of file diff --git a/.example/os/gview/build_in_funcs/build_in_funcs1.go b/.example/os/gview/build_in_funcs/build_in_funcs1.go deleted file mode 100644 index 3f365ec83..000000000 --- a/.example/os/gview/build_in_funcs/build_in_funcs1.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - tplContent := ` -{{"
测试
"|text}} -{{"
测试
"|html}} -{{"<div>测试</div>"|htmldecode}} -{{"https://goframe.org"|url}} -{{"https%3A%2F%2Fgoframe.org"|urldecode}} -{{1540822968 | date "Y-m-d"}} -{{"1540822968" | date "Y-m-d H:i:s"}} -{{date "Y-m-d H:i:s"}} -{{compare "A" "B"}} -{{compare "1" "2"}} -{{compare 2 1}} -{{compare 1 1}} -{{"我是中国人" | substr 2 -1}} -{{"我是中国人" | substr 2 2}} -{{"我是中国人" | strlimit 2 "..."}} -{{"热爱GF热爱生活" | hidestr 20 "*"}} -{{"热爱GF热爱生活" | hidestr 50 "*"}} -{{"热爱GF热爱生活" | highlight "GF" "red"}} -{{"gf" | toupper}} -{{"GF" | tolower}} -{{"Go\nFrame" | nl2br}} -` - content, err := g.View().ParseContent(tplContent, nil) - fmt.Println(err) - fmt.Println(string(content)) -} diff --git a/.example/os/gview/build_in_funcs/build_in_funcs2.go b/.example/os/gview/build_in_funcs/build_in_funcs2.go deleted file mode 100644 index 9fc8c34ee..000000000 --- a/.example/os/gview/build_in_funcs/build_in_funcs2.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - tplContent := ` -eq: -eq "a" "a": {{eq "a" "a"}} -eq "1" "1": {{eq "1" "1"}} -eq 1 "1": {{eq 1 "1"}} - -ne: -ne 1 "1": {{ne 1 "1"}} -ne "a" "a": {{ne "a" "a"}} -ne "a" "b": {{ne "a" "b"}} - -lt: -lt 1 "2": {{lt 1 "2"}} -lt 2 2 : {{lt 2 2 }} -lt "a" "b": {{lt "a" "b"}} - -le: -le 1 "2": {{le 1 "2"}} -le 2 1 : {{le 2 1 }} -le "a" "a": {{le "a" "a"}} - -gt: -gt 1 "2": {{gt 1 "2"}} -gt 2 1 : {{gt 2 1 }} -gt "a" "a": {{gt "a" "a"}} - -ge: -ge 1 "2": {{ge 1 "2"}} -ge 2 1 : {{ge 2 1 }} -ge "a" "a": {{ge "a" "a"}} -` - content, err := g.View().ParseContent(tplContent, nil) - if err != nil { - panic(err) - } - fmt.Println(content) -} diff --git a/.example/os/gview/build_in_funcs/issue359-1.go b/.example/os/gview/build_in_funcs/issue359-1.go deleted file mode 100644 index 842910e4d..000000000 --- a/.example/os/gview/build_in_funcs/issue359-1.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - tplContent := ` -{{"我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人"| strlimit 10 "..."}} -` - content, err := g.View().ParseContent(tplContent, nil) - fmt.Println(err) - fmt.Println(content) -} diff --git a/.example/os/gview/build_in_funcs/issue359-2.go b/.example/os/gview/build_in_funcs/issue359-2.go deleted file mode 100644 index f05041bee..000000000 --- a/.example/os/gview/build_in_funcs/issue359-2.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - s := "我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人我是中国人" - tplContent := ` -{{.str | strlimit 10 "..."}} -` - content, err := g.View().ParseContent(tplContent, g.Map{ - "str": s, - }) - fmt.Println(err) - fmt.Println(content) -} diff --git a/.example/os/gview/define/main.go b/.example/os/gview/define/main.go deleted file mode 100644 index 95a9c87b7..000000000 --- a/.example/os/gview/define/main.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - v := g.View() - v.AddPath(gfile.MainPkgPath() + gfile.Separator + "template") - b, err := v.Parse("index.html", map[string]interface{}{ - "k": "v", - }) - if err != nil { - panic(err) - } - fmt.Println(string(b)) - -} diff --git a/.example/os/gview/define/template/index.html b/.example/os/gview/define/template/index.html deleted file mode 100644 index 88d49c89d..000000000 --- a/.example/os/gview/define/template/index.html +++ /dev/null @@ -1,8 +0,0 @@ -{{define "test"}} - test content {{.}} -{{end}} - - -1{{.var}}2 -{{include "subs/sub.html" .}} - diff --git a/.example/os/gview/define/template/subs/sub.html b/.example/os/gview/define/template/subs/sub.html deleted file mode 100644 index 0be3088c3..000000000 --- a/.example/os/gview/define/template/subs/sub.html +++ /dev/null @@ -1,4 +0,0 @@ -3 -{{template "test" .}} -4 -{{.var2}} \ No newline at end of file diff --git a/.example/os/gview/delimiters/gview_delimiters.go b/.example/os/gview/delimiters/gview_delimiters.go deleted file mode 100644 index 139c198d6..000000000 --- a/.example/os/gview/delimiters/gview_delimiters.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - v := g.View() - v.SetDelimiters("${", "}") - b, err := v.Parse("gview_delimiters.tpl", map[string]interface{}{ - "k": "v", - }) - fmt.Println(err) - fmt.Println(string(b)) -} diff --git a/.example/os/gview/delimiters/gview_delimiters.tpl b/.example/os/gview/delimiters/gview_delimiters.tpl deleted file mode 100644 index d5e4b51e6..000000000 --- a/.example/os/gview/delimiters/gview_delimiters.tpl +++ /dev/null @@ -1 +0,0 @@ -test.tpl content, vars: ${.} \ No newline at end of file diff --git a/.example/os/gview/func_html/func_html.go b/.example/os/gview/func_html/func_html.go deleted file mode 100644 index 0f75aa607..000000000 --- a/.example/os/gview/func_html/func_html.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - if c, err := gview.ParseContent(`{{"
测试
模板引擎默认处理HTML标签\n"}}`, nil); err == nil { - g.Dump(c) - } else { - g.Dump(c) - } - if c, err := gview.ParseContent(`{{"
测试
去掉HTML标签\n"|text}}`, nil); err == nil { - g.Dump(c) - } else { - g.Dump(c) - } - if c, err := gview.ParseContent(`{{"
测试
保留HTML标签\n"|html}}`, nil); err == nil { - g.Dump(c) - } else { - g.Dump(c) - } -} diff --git a/.example/os/gview/func_text/func_text.go b/.example/os/gview/func_text/func_text.go deleted file mode 100644 index 390df9cbc..000000000 --- a/.example/os/gview/func_text/func_text.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/os/gview" - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.Dump(gview.ParseContent(`{{"
测试
去掉HTML标签"|text}}`, nil)) -} diff --git a/.example/os/gview/hot_update/controller_hot_update.go b/.example/os/gview/hot_update/controller_hot_update.go deleted file mode 100644 index e3734482c..000000000 --- a/.example/os/gview/hot_update/controller_hot_update.go +++ /dev/null @@ -1,27 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/frame/gmvc" -) - -func init() { - g.View().SetPath(`D:\Workspace\Go\GOPATH\src\gitee.com\johng\gf\geg\os\gview`) -} - -// 测试控制器注册模板热更新机制 -type Controller struct { - gmvc.Controller -} - -// 测试模板热更新机制 -func (c *Controller) Test() { - b, _ := c.View.Parse("gview.tpl") - c.Response.Write(b) -} - -func main() { - s := g.Server() - s.BindController("/", &Controller{}) - s.Run() -} diff --git a/.example/os/gview/hot_update/gview_hot_update.go b/.example/os/gview/hot_update/gview_hot_update.go deleted file mode 100644 index 70b7f1415..000000000 --- a/.example/os/gview/hot_update/gview_hot_update.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gtime" -) - -func main() { - v := g.View() - v.SetPath(`D:\Workspace\Go\GOPATH\src\gitee.com\johng\gf\geg\os\gview`) - gtime.SetInterval(time.Second, func() bool { - b, _ := v.Parse("gview.tpl", nil) - fmt.Println(string(b)) - return true - }) - select {} -} diff --git a/.example/os/gview/hot_update/web_hot_update.go b/.example/os/gview/hot_update/web_hot_update.go deleted file mode 100644 index 31aab9192..000000000 --- a/.example/os/gview/hot_update/web_hot_update.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - g.View().SetPath(`D:\Workspace\Go\GOPATH\src\gitee.com\johng\gf\geg\os\gview`) - b, _ := g.View().Parse("gview.tpl", nil) - r.Response.Write(b) - }) - s.Run() -} diff --git a/.example/os/gview/i18n/i18n.go b/.example/os/gview/i18n/i18n.go deleted file mode 100644 index c6fa628db..000000000 --- a/.example/os/gview/i18n/i18n.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/frame/g" -) - -func main() { - content := `{{.name}} says "a{#hello}{#world}!"` - result1, _ := g.View().ParseContent(content, g.Map{ - "name": "john", - "I18nLanguage": "zh-CN", - }) - fmt.Println(result1) - - result2, _ := g.View().ParseContent(content, g.Map{ - "name": "john", - "I18nLanguage": "ja", - }) - fmt.Println(result2) -} diff --git a/.example/os/gview/include/main.go b/.example/os/gview/include/main.go deleted file mode 100644 index 0fdd1d642..000000000 --- a/.example/os/gview/include/main.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gfile" -) - -func main() { - v := g.View() - // 设置模板目录为当前main.go所在目录下的template目录 - v.AddPath(gfile.MainPkgPath() + gfile.Separator + "template2") - b, err := v.Parse("index.html", map[string]interface{}{ - "k": "v", - }) - if err != nil { - panic(err) - } - fmt.Println(string(b)) -} diff --git a/.example/os/gview/include/template/index.html b/.example/os/gview/include/template/index.html deleted file mode 100644 index f534c4417..000000000 --- a/.example/os/gview/include/template/index.html +++ /dev/null @@ -1,2 +0,0 @@ -{{include "subs/sub.html" .}} - diff --git a/.example/os/gview/include/template/subs/sub.html b/.example/os/gview/include/template/subs/sub.html deleted file mode 100644 index 91012a681..000000000 --- a/.example/os/gview/include/template/subs/sub.html +++ /dev/null @@ -1 +0,0 @@ -{{.}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/main.go b/.example/os/gview/layout/layout1/main.go deleted file mode 100644 index 644e59568..000000000 --- a/.example/os/gview/layout/layout1/main.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "header": "This is header", - "container": "This is container", - "footer": "This is footer", - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gview/layout/layout1/template/container.html b/.example/os/gview/layout/layout1/template/container.html deleted file mode 100644 index 4f6af6313..000000000 --- a/.example/os/gview/layout/layout1/template/container.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "container"}} -

{{.container}}

-{{end}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/template/footer.html b/.example/os/gview/layout/layout1/template/footer.html deleted file mode 100644 index 8a5f09a53..000000000 --- a/.example/os/gview/layout/layout1/template/footer.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "footer"}} -

{{.footer}}

-{{end}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/template/header.html b/.example/os/gview/layout/layout1/template/header.html deleted file mode 100644 index bc500316a..000000000 --- a/.example/os/gview/layout/layout1/template/header.html +++ /dev/null @@ -1,3 +0,0 @@ -{{define "header"}} -

{{.header}}

-{{end}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout1/template/layout.html b/.example/os/gview/layout/layout1/template/layout.html deleted file mode 100644 index 223fce6b8..000000000 --- a/.example/os/gview/layout/layout1/template/layout.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - GoFrame Layout - {{template "header" .}} - - -
- {{template "container" .}} -
- - - \ No newline at end of file diff --git a/.example/os/gview/layout/layout2/main.go b/.example/os/gview/layout/layout2/main.go deleted file mode 100644 index 5f7d8779f..000000000 --- a/.example/os/gview/layout/layout2/main.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" -) - -func main() { - s := g.Server() - s.BindHandler("/main1", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "name": "smith", - "mainTpl": "main/main1.html", - }) - }) - s.BindHandler("/main2", func(r *ghttp.Request) { - r.Response.WriteTpl("layout.html", g.Map{ - "name": "john", - "mainTpl": "main/main2.html", - }) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/os/gview/layout/layout2/template/footer.html b/.example/os/gview/layout/layout2/template/footer.html deleted file mode 100644 index 83ae25b65..000000000 --- a/.example/os/gview/layout/layout2/template/footer.html +++ /dev/null @@ -1 +0,0 @@ -

FOOTER

\ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/header.html b/.example/os/gview/layout/layout2/template/header.html deleted file mode 100644 index b9cb0a77c..000000000 --- a/.example/os/gview/layout/layout2/template/header.html +++ /dev/null @@ -1 +0,0 @@ -

HEADER

\ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/layout.html b/.example/os/gview/layout/layout2/template/layout.html deleted file mode 100644 index 9f58c21a0..000000000 --- a/.example/os/gview/layout/layout2/template/layout.html +++ /dev/null @@ -1,3 +0,0 @@ -{{include "header.html" .}} -{{include .mainTpl .}} -{{include "footer.html" .}} \ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/main/main1.html b/.example/os/gview/layout/layout2/template/main/main1.html deleted file mode 100644 index fdb0016f3..000000000 --- a/.example/os/gview/layout/layout2/template/main/main1.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN1

\ No newline at end of file diff --git a/.example/os/gview/layout/layout2/template/main/main2.html b/.example/os/gview/layout/layout2/template/main/main2.html deleted file mode 100644 index 608512269..000000000 --- a/.example/os/gview/layout/layout2/template/main/main2.html +++ /dev/null @@ -1 +0,0 @@ -

MAIN2

\ No newline at end of file diff --git a/.example/os/gview/object/object.go b/.example/os/gview/object/object.go deleted file mode 100644 index 594a41ab2..000000000 --- a/.example/os/gview/object/object.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" -) - -type T struct { - Name string -} - -func (t *T) Hello(name string) string { - return "Hello " + name -} - -func (t *T) Test() string { - return "This is test" -} - -func main() { - t := &T{"John"} - v := g.View() - content := `{{.t.Hello "there"}}, my name's {{.t.Name}}. {{.t.Test}}.` - if r, err := v.ParseContent(content, g.Map{"t": t}); err != nil { - g.Dump(err) - } else { - g.Dump(r) - } -} diff --git a/.example/os/gview/resource/main1.go b/.example/os/gview/resource/main1.go deleted file mode 100644 index 88b96590e..000000000 --- a/.example/os/gview/resource/main1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - gres.Dump() - - v := g.View() - v.SetPath("files/template/layout1") - s, err := v.Parse("layout.html") - fmt.Println(err) - fmt.Println(s) -} diff --git a/.example/os/gview/resource/main2.go b/.example/os/gview/resource/main2.go deleted file mode 100644 index 9892c4fc8..000000000 --- a/.example/os/gview/resource/main2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - gres.Dump() - - v := g.View() - v.SetPath("files/template/layout2") - s, err := v.Parse("layout.html", g.Map{ - "mainTpl": "main/main1.html", - }) - fmt.Println(err) - fmt.Println(s) -} diff --git a/.example/os/gview/resource/main3.go b/.example/os/gview/resource/main3.go deleted file mode 100644 index db3e029ed..000000000 --- a/.example/os/gview/resource/main3.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gres" - _ "github.com/gogf/gf/v2/os/gres/testdata" -) - -func main() { - gres.Dump() - - v := g.View() - s, err := v.Parse("index.html") - fmt.Println(err) - fmt.Println(s) -} diff --git a/.example/text/gregex/gregex.go b/.example/text/gregex/gregex.go deleted file mode 100644 index 5c807daa8..000000000 --- a/.example/text/gregex/gregex.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/text/gregex" -) - -func main() { - match, _ := gregex.MatchString(`(\w+).+\-\-\s*(.+)`, `GF is best! -- John`) - fmt.Printf(`%s says "%s" is the one he loves!`, match[2], match[1]) -} diff --git a/.example/text/gstr/gstr_hidestr.go b/.example/text/gstr/gstr_hidestr.go deleted file mode 100644 index 1b7e9b268..000000000 --- a/.example/text/gstr/gstr_hidestr.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/text/gstr" -) - -func main() { - fmt.Println(gstr.HideStr("热爱GF热爱生活", 20, "*")) - fmt.Println(gstr.HideStr("热爱GF热爱生活", 50, "*")) -} diff --git a/.example/text/gstr/gstr_substr.go b/.example/text/gstr/gstr_substr.go deleted file mode 100644 index 75898a51e..000000000 --- a/.example/text/gstr/gstr_substr.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/text/gstr" -) - -func main() { - fmt.Println(gstr.SubStr("我是中国人", 2)) - fmt.Println(gstr.SubStr("我是中国人", 2, 2)) -} diff --git a/.example/util/gconv/gconv.go b/.example/util/gconv/gconv.go deleted file mode 100644 index 1f148d906..000000000 --- a/.example/util/gconv/gconv.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - i := 123.456 - fmt.Printf("%10s %v\n", "Int:", gconv.Int(i)) - fmt.Printf("%10s %v\n", "Int8:", gconv.Int8(i)) - fmt.Printf("%10s %v\n", "Int16:", gconv.Int16(i)) - fmt.Printf("%10s %v\n", "Int32:", gconv.Int32(i)) - fmt.Printf("%10s %v\n", "Int64:", gconv.Int64(i)) - fmt.Printf("%10s %v\n", "Uint:", gconv.Uint(i)) - fmt.Printf("%10s %v\n", "Uint8:", gconv.Uint8(i)) - fmt.Printf("%10s %v\n", "Uint16:", gconv.Uint16(i)) - fmt.Printf("%10s %v\n", "Uint32:", gconv.Uint32(i)) - fmt.Printf("%10s %v\n", "Uint64:", gconv.Uint64(i)) - fmt.Printf("%10s %v\n", "Float32:", gconv.Float32(i)) - fmt.Printf("%10s %v\n", "Float64:", gconv.Float64(i)) - fmt.Printf("%10s %v\n", "Bool:", gconv.Bool(i)) - fmt.Printf("%10s %v\n", "String:", gconv.String(i)) - - fmt.Printf("%10s %v\n", "Bytes:", gconv.Bytes(i)) - fmt.Printf("%10s %v\n", "Strings:", gconv.Strings(i)) - fmt.Printf("%10s %v\n", "Ints:", gconv.Ints(i)) - fmt.Printf("%10s %v\n", "Floats:", gconv.Floats(i)) - fmt.Printf("%10s %v\n", "Interfaces:", gconv.Interfaces(i)) -} diff --git a/.example/util/gconv/gconv_map1.go b/.example/util/gconv/gconv_map1.go deleted file mode 100644 index e1ca4658a..000000000 --- a/.example/util/gconv/gconv_map1.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Uid int `json:"uid"` - Name string `json:"name"` - } - // 对象 - fmt.Println(gconv.Map(User{ - Uid: 1, - Name: "john", - })) - // 对象指针 - fmt.Println(gconv.Map(&User{ - Uid: 1, - Name: "john", - })) - - // 任意map类型 - fmt.Println(gconv.Map(map[int]int{ - 100: 10000, - })) -} diff --git a/.example/util/gconv/gconv_map2.go b/.example/util/gconv/gconv_map2.go deleted file mode 100644 index 52a3c4564..000000000 --- a/.example/util/gconv/gconv_map2.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Uid int - Name string `gconv:"-"` - NickName string `gconv:"nickname, omitempty"` - Pass1 string `gconv:"password1"` - Pass2 string `gconv:"password2"` - } - user := User{ - Uid: 100, - Name: "john", - Pass1: "123", - Pass2: "456", - } - fmt.Println(gconv.Map(user)) -} diff --git a/.example/util/gconv/gconv_map_deep.go b/.example/util/gconv/gconv_map_deep.go deleted file mode 100644 index 80a2a82ce..000000000 --- a/.example/util/gconv/gconv_map_deep.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Ids struct { - Id int `c:"id"` - Uid int `c:"uid"` - } - type Base struct { - Ids - CreateTime string `c:"create_time"` - } - type User struct { - Base - Passport string `c:"passport"` - Password string `c:"password"` - Nickname string `c:"nickname"` - } - user := new(User) - user.Id = 1 - user.Uid = 100 - user.Nickname = "John" - user.Passport = "johng" - user.Password = "123456" - user.CreateTime = "2019" - g.Dump(gconv.Map(user)) - g.Dump(gconv.MapDeep(user)) -} diff --git a/.example/util/gconv/gconv_map_tag.go b/.example/util/gconv/gconv_map_tag.go deleted file mode 100644 index 727f4bf83..000000000 --- a/.example/util/gconv/gconv_map_tag.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Id int `json:"uid"` - Name string `my-tag:"nick-name" json:"name"` - } - user := &User{ - Id: 1, - Name: "john", - } - g.Dump(gconv.Map(user, "my-tag")) -} diff --git a/.example/util/gconv/gconv_slice.go b/.example/util/gconv/gconv_slice.go deleted file mode 100644 index c306e2cac..000000000 --- a/.example/util/gconv/gconv_slice.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -// struct转slice -func main() { - type User struct { - Uid int - Name string - } - // 对象 - fmt.Println(gconv.Interfaces(User{ - Uid: 1, - Name: "john", - })) - // 指针 - fmt.Println(gconv.Interfaces(&User{ - Uid: 1, - Name: "john", - })) -} diff --git a/.example/util/gconv/gconv_struct1.go b/.example/util/gconv/gconv_struct1.go deleted file mode 100644 index 1cd680b5d..000000000 --- a/.example/util/gconv/gconv_struct1.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -type User struct { - Uid int - Name string - Site_Url string - NickName string - Pass1 string `gconv:"password1"` - Pass2 string `gconv:"password2"` -} - -func main() { - user := (*User)(nil) - - // 使用默认映射规则绑定属性值到对象 - user = new(User) - params1 := g.Map{ - "uid": 1, - "Name": "john", - "siteurl": "https://goframe.org", - "nick_name": "johng", - "PASS1": "123", - "PASS2": "456", - } - if err := gconv.Struct(params1, user); err == nil { - g.Dump(user) - } - - // 使用struct tag映射绑定属性值到对象 - user = new(User) - params2 := g.Map{ - "uid": 2, - "name": "smith", - "site-url": "https://goframe.org", - "nick name": "johng", - "password1": "111", - "password2": "222", - } - if err := gconv.Struct(params2, user); err == nil { - g.Dump(user) - } -} diff --git a/.example/util/gconv/gconv_struct2.go b/.example/util/gconv/gconv_struct2.go deleted file mode 100644 index 5d09c723b..000000000 --- a/.example/util/gconv/gconv_struct2.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -// 使用默认映射规则绑定属性值到对象 -func main() { - type User struct { - Uid int - Name string - SiteUrl string - Pass1 string - Pass2 string - } - user := new(User) - params := g.Map{ - "uid": 1, - "Name": "john", - "site_url": "https://goframe.org", - "PASS1": "123", - "PASS2": "456", - } - if err := gconv.Struct(params, user); err == nil { - fmt.Println(user) - } -} diff --git a/.example/util/gconv/gconv_struct4.go b/.example/util/gconv/gconv_struct4.go deleted file mode 100644 index c9dba3445..000000000 --- a/.example/util/gconv/gconv_struct4.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Score struct { - Name string - Result int - } - type User1 struct { - Scores Score - } - type User2 struct { - Scores *Score - } - - user1 := new(User1) - user2 := new(User2) - scores := g.Map{ - "Scores": g.Map{ - "Name": "john", - "Result": 100, - }, - } - - if err := gconv.Struct(scores, user1); err != nil { - fmt.Println(err) - } else { - g.Dump(user1) - } - if err := gconv.Struct(scores, user2); err != nil { - fmt.Println(err) - } else { - g.Dump(user2) - } -} diff --git a/.example/util/gconv/gconv_struct5.go b/.example/util/gconv/gconv_struct5.go deleted file mode 100644 index 2351653a7..000000000 --- a/.example/util/gconv/gconv_struct5.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Score struct { - Name string - Result int - } - type User struct { - Scores []Score - } - - user := new(User) - scores := g.Map{ - "Scores": g.Map{ - "Name": "john", - "Result": 100, - }, - } - - // 嵌套struct转换,属性为slice类型,数值为map类型 - if err := gconv.Struct(scores, user); err != nil { - fmt.Println(err) - } else { - g.Dump(user) - } -} diff --git a/.example/util/gconv/gconv_struct6.go b/.example/util/gconv/gconv_struct6.go deleted file mode 100644 index a7681a0e1..000000000 --- a/.example/util/gconv/gconv_struct6.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Score struct { - Name string - Result int - } - type User struct { - Scores []*Score - } - - user := new(User) - scores := g.Map{ - "Scores": g.Slice{ - g.Map{ - "Name": "john", - "Result": 100, - }, - g.Map{ - "Name": "smith", - "Result": 60, - }, - }, - } - - // 嵌套struct转换,属性为slice类型,数值为slice map类型 - if err := gconv.Struct(scores, user); err != nil { - fmt.Println(err) - } else { - g.Dump(user) - } -} diff --git a/.example/util/gconv/gconv_struct_create.go b/.example/util/gconv/gconv_struct_create.go deleted file mode 100644 index 211cfea46..000000000 --- a/.example/util/gconv/gconv_struct_create.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Uid int - Name string - } - user := (*User)(nil) - params := g.Map{ - "uid": 1, - "name": "john", - } - err := gconv.Struct(params, &user) - if err != nil { - panic(err) - } - g.Dump(user) -} diff --git a/.example/util/gconv/gconv_struct_deep.go b/.example/util/gconv/gconv_struct_deep.go deleted file mode 100644 index 565766321..000000000 --- a/.example/util/gconv/gconv_struct_deep.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type Ids struct { - Id int `json:"id"` - Uid int `json:"uid"` - } - type Base struct { - Ids - CreateTime string `json:"create_time"` - } - type User struct { - Base - Passport string `json:"passport"` - Password string `json:"password"` - Nickname string `json:"nickname"` - } - data := g.Map{ - "id": 1, - "uid": 100, - "passport": "johng", - "password": "123456", - "nickname": "John", - "create_time": "2019", - } - user := new(User) - gconv.StructDeep(data, user) - g.Dump(user) -} diff --git a/.example/util/gconv/strings.go b/.example/util/gconv/strings.go deleted file mode 100644 index 258d6d638..000000000 --- a/.example/util/gconv/strings.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - fmt.Println(gconv.Strings([]int{1, 2, 3})) -} diff --git a/.example/util/gconv/time1.go b/.example/util/gconv/time1.go deleted file mode 100644 index 825d49f5f..000000000 --- a/.example/util/gconv/time1.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - now := time.Now() - t := gconv.Time(now.UnixNano() / 100) - fmt.Println(now.UnixNano()) - fmt.Println(t.Nanosecond()) - fmt.Println(now.Nanosecond()) -} diff --git a/.example/util/gconv/time2.go b/.example/util/gconv/time2.go deleted file mode 100644 index c7d77a406..000000000 --- a/.example/util/gconv/time2.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - fmt.Println(gconv.Time("2018-06-07").String()) - - fmt.Println(gconv.Time("2018-06-07 13:01:02").String()) - - fmt.Println(gconv.Time("2018-06-07 13:01:02.096").String()) - -} diff --git a/.example/util/gpage/gpage.go b/.example/util/gpage/gpage.go deleted file mode 100644 index cc39411aa..000000000 --- a/.example/util/gpage/gpage.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/demo", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_ajax.go b/.example/util/gpage/gpage_ajax.go deleted file mode 100644 index 5451472a1..000000000 --- a/.example/util/gpage/gpage_ajax.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/ajax", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - page.AjaxActionName = "DoAjax" - buffer, _ := gview.ParseContent(r.Context(), ` - - - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_custom1.go b/.example/util/gpage/gpage_custom1.go deleted file mode 100644 index a9a0f9a60..000000000 --- a/.example/util/gpage/gpage_custom1.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" - "github.com/gogf/gf/v2/text/gstr" - "github.com/gogf/gf/v2/util/gpage" -) - -// wrapContent wraps each of the page tag with html li and ul. -func wrapContent(page *gpage.Page) string { - content := page.GetContent(4) - content = gstr.ReplaceByMap(content, map[string]string{ - "": "/span>", - "": "/a>", - }) - return "
    " + content + "
" -} - -func main() { - s := g.Server() - s.BindHandler("/page/custom1/*page", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - content := wrapContent(page) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page}}
- - - `, g.Map{ - "page": content, - }) - r.Response.Write(buffer) - }) - s.SetPort(10000) - s.Run() -} diff --git a/.example/util/gpage/gpage_custom2.go b/.example/util/gpage/gpage_custom2.go deleted file mode 100644 index 44b012456..000000000 --- a/.example/util/gpage/gpage_custom2.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" - "github.com/gogf/gf/v2/util/gpage" -) - -// pageContent customizes the page tag name. -func pageContent(page *gpage.Page) string { - page.NextPageTag = "NextPage" - page.PrevPageTag = "PrevPage" - page.FirstPageTag = "HomePage" - page.LastPageTag = "LastPage" - pageStr := page.FirstPage() - pageStr += page.PrevPage() - pageStr += page.PageBar() - pageStr += page.NextPage() - pageStr += page.LastPage() - return pageStr -} - -func main() { - s := g.Server() - s.BindHandler("/page/custom2/*page", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page}}
- - - `, g.Map{ - "page": pageContent(page), - }) - r.Response.Write(buffer) - }) - s.SetPort(10000) - s.Run() -} diff --git a/.example/util/gpage/gpage_static1.go b/.example/util/gpage/gpage_static1.go deleted file mode 100644 index 0d852d31a..000000000 --- a/.example/util/gpage/gpage_static1.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/static/*page", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_static2.go b/.example/util/gpage/gpage_static2.go deleted file mode 100644 index e3a1e4680..000000000 --- a/.example/util/gpage/gpage_static2.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/:obj/*action/{page}.html", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/gpage/gpage_template.go b/.example/util/gpage/gpage_template.go deleted file mode 100644 index ba6e1a3a6..000000000 --- a/.example/util/gpage/gpage_template.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/os/gview" -) - -func main() { - s := g.Server() - s.BindHandler("/page/template/{page}.html", func(r *ghttp.Request) { - page := r.GetPage(100, 10) - page.UrlTemplate = "/order/list/{.page}.html" - buffer, _ := gview.ParseContent(` - - - - - -
{{.page1}}
-
{{.page2}}
-
{{.page3}}
-
{{.page4}}
- - - `, g.Map{ - "page1": page.GetContent(1), - "page2": page.GetContent(2), - "page3": page.GetContent(3), - "page4": page.GetContent(4), - }) - r.Response.Write(buffer) - }) - s.SetPort(8199) - s.Run() -} diff --git a/.example/util/grand/grand.go b/.example/util/grand/grand.go deleted file mode 100644 index f36b13bad..000000000 --- a/.example/util/grand/grand.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/grand" -) - -func main() { - for i := 0; i < 100; i++ { - fmt.Println(grand.S(16)) - } - for i := 0; i < 100; i++ { - fmt.Println(grand.N(0, 99999999)) - } -} diff --git a/.example/util/grand/rand.go b/.example/util/grand/rand.go deleted file mode 100644 index 9cfc28459..000000000 --- a/.example/util/grand/rand.go +++ /dev/null @@ -1,83 +0,0 @@ -package main - -import ( - crand "crypto/rand" - "encoding/binary" - "fmt" - mrand "math/rand" - "os" - "time" - - "github.com/gogf/gf/v2/os/gtime" -) - -// int 随机 -func a1() { - s1 := mrand.NewSource(time.Now().UnixNano()) - r1 := mrand.New(s1) - for i := 0; i < 10; i++ { - fmt.Printf("%d ", r1.Intn(100)) - } - fmt.Printf("\n") -} - -// 0/1 true/false 随机 -func a2() { - // Go编程这本书上例子. - ch := make(chan int, 1) - for i := 0; i < 10; i++ { - select { - case ch <- 0: - case ch <- 1: - } - r := <-ch - fmt.Printf("%d ", r) - } - fmt.Printf("\n") -} - -//真随机 -- 用标准库封装好的 -func a3() { - b := make([]byte, 16) - // On Unix-like systems, Reader reads from /dev/urandom. - // On Windows systems, Reader uses the CryptGenRandom API. - _, err := crand.Read(b) //返回长度为0 - 32 的值 - if err != nil { - fmt.Println("[a3] ", err) - return - } - fmt.Println("[a3] b:", b) -} - -//真随机 -- 我们直接调真随机文件生成了事。 但注意,它是阻塞式的。 -func a4() { - f, err := os.Open("/dev/random") - if err != nil { - fmt.Println("[a4] ", err) - return - } - defer f.Close() - - b1 := make([]byte, 16) - _, err = f.Read(b1) - if err != nil { - fmt.Println("[a4] ", err) - return - } - fmt.Println("[a4] Read /dev/random:", b1) -} - -// a3 的另一种实现方式 -func a5() { - var ret int32 - binary.Read(crand.Reader, binary.LittleEndian, &ret) - fmt.Println("[a5] ret:", ret) -} - -func main() { - fmt.Println("a1:", gtime.FuncCost(a1)) - fmt.Println("a2:", gtime.FuncCost(a2)) - fmt.Println("a3:", gtime.FuncCost(a3)) - fmt.Println("a4:", gtime.FuncCost(a4)) - fmt.Println("a5:", gtime.FuncCost(a5)) -} diff --git a/.example/util/guid/guid.go b/.example/util/guid/guid.go deleted file mode 100644 index f88c37985..000000000 --- a/.example/util/guid/guid.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/util/guid" -) - -func main() { - for i := 0; i < 100; i++ { - s := guid.S() - fmt.Println(s, len(s)) - } -} diff --git a/.example/util/guid/guid_length.go b/.example/util/guid/guid_length.go deleted file mode 100644 index c04c594f8..000000000 --- a/.example/util/guid/guid_length.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "math" - "strconv" -) - -func main() { - // 36*36^2+36*36+36 - var s string - fmt.Println(strconv.ParseUint("zzz", 36, 3)) - fmt.Println(1 << 1) - // MaxInt64 - s = strconv.FormatUint(math.MaxUint64, 16) - fmt.Println(s, len(s)) - // PID - s = strconv.FormatInt(1000000, 36) - fmt.Println(s, len(s)) -} diff --git a/.example/util/guid/guid_unique.go b/.example/util/guid/guid_unique.go deleted file mode 100644 index f804c45a6..000000000 --- a/.example/util/guid/guid_unique.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "github.com/gogf/gf/v2/util/guid" -) - -func main() { - for i := 0; i < 100; i++ { - s := guid.S([]byte("123")) - fmt.Println(s, len(s)) - } - fmt.Println() - for i := 0; i < 100; i++ { - s := guid.S([]byte("123"), []byte("456")) - fmt.Println(s, len(s)) - } - fmt.Println() - for i := 0; i < 100; i++ { - s := guid.S([]byte("123"), []byte("456"), []byte("789")) - fmt.Println(s, len(s)) - } -} diff --git a/.example/util/gutil/dump.go b/.example/util/gutil/dump.go deleted file mode 100644 index 5fa013bd4..000000000 --- a/.example/util/gutil/dump.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.Dump(map[interface{}]interface{}{ - 1: "john", - }) -} diff --git a/.example/util/gutil/stack.go b/.example/util/gutil/stack.go deleted file mode 100644 index 93e89cc68..000000000 --- a/.example/util/gutil/stack.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/util/gutil" -) - -func Test(s *interface{}) { - //debug.PrintStack() - gutil.PrintStack() -} - -func main() { - Test(nil) -} diff --git a/.example/util/gutil/try_catch.go b/.example/util/gutil/try_catch.go deleted file mode 100644 index b4c5e5487..000000000 --- a/.example/util/gutil/try_catch.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/gogf/gf/v2/util/gutil" -) - -func main() { - gutil.TryCatch(func() { - fmt.Println(1) - gutil.Throw("error") - fmt.Println(2) - }, func(err error) { - fmt.Println(err) - }) -} diff --git a/.example/util/gvalid/config.toml b/.example/util/gvalid/config.toml deleted file mode 100644 index 26beac3a7..000000000 --- a/.example/util/gvalid/config.toml +++ /dev/null @@ -1,14 +0,0 @@ - - - -# MySQL. -[database] - [database.default] - link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test" - debug = true - - - - - - diff --git a/.example/util/gvalid/gvalid.go b/.example/util/gvalid/gvalid.go deleted file mode 100644 index 96c52b835..000000000 --- a/.example/util/gvalid/gvalid.go +++ /dev/null @@ -1,71 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - //rule := "length:6,16" - //if m := gvalid.Check(context.TODO(), "123456", rule, nil); m != nil { - // fmt.Println(m) - //} - //if m := gvalid.Check(context.TODO(), "12345", rule, nil); m != nil { - // fmt.Println(m) - // // map[length:字段长度为6到16个字符] - //} - - //rule := "integer|between:6,16" - //msgs := "请输入一个整数|参数大小不对啊老铁" - //fmt.Println(gvalid.Check(context.TODO(), "5.66", rule, msgs)) - //// map[integer:请输入一个整数 between:参数大小不对啊老铁] - - //// 参数长度至少为6个数字或者6个字母,但是总长度不能超过16个字符 - //rule := `regex:\d{6,}|\D{6,}|max-length:16` - //if m := gvalid.Check(context.TODO(), "123456", rule, nil); m != nil { - // fmt.Println(m) - //} - //if m := gvalid.Check(context.TODO(), "abcde6", rule, nil); m != nil { - // fmt.Println(m) - // // map[regex:字段值不合法] - //} - - //params := map[string]string { - // "passport" : "john", - // "password" : "123456", - // "password2" : "1234567", - //} - //rules := map[string]string { - // "passport" : "required|length:6,16", - // "password" : "required|length:6,16|same:password2", - // "password2" : "required|length:6,16", - //} - //fmt.Println(gvalid.CheckMap(context.TODO(), params, rules)) - //// map[passport:map[length:字段长度为6到16个字符] password:map[same:字段值不合法]] - - params := map[string]interface{}{ - "passport": "john", - "password": "123456", - "password2": "1234567", - "name": "gf", - } - rules := map[string]string{ - "passport": "required|length:6,16", - "password": "required|length:6,16|same:password2", - "password2": "required|length:6,16", - "name": "size:5", - } - msgs := map[string]interface{}{ - "passport": "账号不能为空|账号长度应当在:min到:max之间", - "password": map[string]string{ - "required": "密码不能为空", - "same": "两次密码输入不相等", - }, - "name": "名字长度必须为:size", - } - if e := gvalid.CheckMap(context.TODO(), params, rules, msgs); e != nil { - g.Dump(e.Maps()) - } - // map[passport:map[length:账号长度应当在6到16之间] password:map[same:两次密码输入不相等]] -} diff --git a/.example/util/gvalid/gvalid_checkstructwithdata.go b/.example/util/gvalid/gvalid_checkstructwithdata.go deleted file mode 100644 index a281a8cd5..000000000 --- a/.example/util/gvalid/gvalid_checkstructwithdata.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gconv" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - type User struct { - Name string `v:"required#请输入用户姓名"` - Type int `v:"required#请选择用户类型"` - } - data := g.Map{ - "name": "john", - } - user := User{} - if err := gconv.Scan(data, &user); err != nil { - panic(err) - } - err := gvalid.CheckStructWithData(context.TODO(), user, data, nil) - // 也可以使用 - // err := g.Validator().Data(data).CheckStruct(user) - if err != nil { - g.Dump(err.Items()) - } -} diff --git a/.example/util/gvalid/gvalid_custom_message.go b/.example/util/gvalid/gvalid_custom_message.go deleted file mode 100644 index e19a7beca..000000000 --- a/.example/util/gvalid/gvalid_custom_message.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - g.I18n().SetLanguage("cn") - err := gvalid.Check(context.TODO(), "", "required", nil) - fmt.Println(err.String()) -} diff --git a/.example/util/gvalid/gvalid_error.go b/.example/util/gvalid/gvalid_error.go deleted file mode 100644 index 0d02396e0..000000000 --- a/.example/util/gvalid/gvalid_error.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -// 返回结果方法示例 -func main() { - type User struct { - Password string `gvalid:"password@password"` - ConfiemPassword string `gvalid:"confirm_password@password|same:password#|密码与确认密码不一致"` - } - - user := &User{ - Password: "123456", - ConfiemPassword: "", - } - - e := gvalid.CheckStruct(context.TODO(), user, nil) - g.Dump(e.Map()) - g.Dump(e.Maps()) - g.Dump(e.String()) - g.Dump(e.Strings()) - g.Dump(e.FirstItem()) - g.Dump(e.FirstRule()) - g.Dump(e.FirstString()) -} diff --git a/.example/util/gvalid/gvalid_i18n.go b/.example/util/gvalid/gvalid_i18n.go deleted file mode 100644 index 492b37174..000000000 --- a/.example/util/gvalid/gvalid_i18n.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "context" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" - "github.com/gogf/gf/v2/util/gconv" -) - -func main() { - type User struct { - Name string `v:"required#ReuiredUserName"` - Type int `v:"required#ReuiredUserType"` - Project string `v:"size:10#MustSize"` - } - var ( - data = g.Map{ - "name": "john", - "project": "gf", - } - user = User{} - ctxEn = gi18n.WithLanguage(context.TODO(), "en") - ctxCh = gi18n.WithLanguage(context.TODO(), "zh-CN") - ) - - if err := gconv.Scan(data, &user); err != nil { - panic(err) - } - // 英文 - if err := g.Validator().Ctx(ctxEn).Data(data).CheckStruct(user); err != nil { - g.Dump(err.String()) - } - // 中文 - if err := g.Validator().Ctx(ctxCh).Data(data).CheckStruct(user); err != nil { - g.Dump(err.String()) - } -} diff --git a/.example/util/gvalid/gvalid_i18n_http.go b/.example/util/gvalid/gvalid_i18n_http.go deleted file mode 100644 index 308dcbbf1..000000000 --- a/.example/util/gvalid/gvalid_i18n_http.go +++ /dev/null @@ -1,35 +0,0 @@ -package main - -import ( - "github.com/gogf/gf/v2/net/ghttp" - - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/i18n/gi18n" -) - -func main() { - type User struct { - Name string `v:"required#ReuiredUserName"` - Type int `v:"required#ReuiredUserType"` - Project string `v:"size:10#MustSize"` - } - s := g.Server() - s.Group("/", func(group *ghttp.RouterGroup) { - group.Middleware(func(r *ghttp.Request) { - lang := r.GetString("lang", "zh-CN") - r.SetCtx(gi18n.WithLanguage(r.Context(), lang)) - r.Middleware.Next() - }) - group.GET("/validate", func(r *ghttp.Request) { - var ( - err error - user = User{} - ) - if err = r.Parse(&user); err != nil { - r.Response.WriteExit(err) - } - r.Response.WriteExit(user) - }) - }) - s.SetPort(8199) -} diff --git a/.example/util/gvalid/gvalid_result.go b/.example/util/gvalid/gvalid_result.go deleted file mode 100644 index f65a7fc41..000000000 --- a/.example/util/gvalid/gvalid_result.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - type User struct { - Name string `gvalid:"name @required|length:6,30#请输入用户名称|用户名称长度不够哦"` - Pass1 string `gvalid:"password1@required|password3"` - Pass2 string `gvalid:"password2@required|password3|same:password1#||两次密码不一致,请重新输入"` - } - - user := &User{ - Name: "john", - Pass1: "Abc123!@#", - Pass2: "123", - } - - e := gvalid.CheckStruct(context.TODO(), user, nil) - g.Dump(e.String()) - g.Dump(e.FirstString()) -} diff --git a/.example/util/gvalid/gvalid_sequence.go b/.example/util/gvalid/gvalid_sequence.go deleted file mode 100644 index 5545b09a7..000000000 --- a/.example/util/gvalid/gvalid_sequence.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "context" - "fmt" - - "github.com/gogf/gf/v2/util/gvalid" -) - -func main() { - params := map[string]interface{}{ - "passport": "", - "password": "123456", - "password2": "1234567", - } - rules := []string{ - "passport@required|length:6,16#账号不能为空|账号长度应当在:min到:max之间", - "password@required|length:6,16|same:password2#密码不能为空}|两次密码输入不相等", - "password2@required|length:6,16#", - } - if e := gvalid.CheckMap(context.TODO(), params, rules); e != nil { - fmt.Println(e.Map()) - fmt.Println(e.FirstItem()) - fmt.Println(e.FirstString()) - } - // map[required:账号不能为空 length:账号长度应当在6到16之间] - // passport map[required:账号不能为空 length:账号长度应当在6到16之间] - // 账号不能为空 -} diff --git a/.example/util/gvalid/gvalid_struct1.go b/.example/util/gvalid/gvalid_struct1.go deleted file mode 100644 index 4b8678dba..000000000 --- a/.example/util/gvalid/gvalid_struct1.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -type User struct { - Uid int `gvalid:"uid @integer|min:1#用户UID不能为空"` - Name string `gvalid:"name @required|length:6,30#请输入用户名称|用户名称长度非法"` - Pass1 string `gvalid:"password1@required|password3"` - Pass2 string `gvalid:"password2@required|password3|same:password1#||两次密码不一致,请重新输入"` -} - -func main() { - user := &User{ - Name: "john", - Pass1: "Abc123!@#", - Pass2: "123", - } - - // 使用结构体定义的校验规则和错误提示进行校验 - g.Dump(gvalid.CheckStruct(context.TODO(), user, nil).Map()) - - // 自定义校验规则和错误提示,对定义的特定校验规则和错误提示进行覆盖 - rules := map[string]string{ - "Uid": "required", - } - msgs := map[string]interface{}{ - "Pass2": map[string]string{ - "password3": "名称不能为空", - }, - } - g.Dump(gvalid.CheckStruct(context.TODO(), user, rules, msgs).Map()) -} diff --git a/.example/util/gvalid/gvalid_struct2.go b/.example/util/gvalid/gvalid_struct2.go deleted file mode 100644 index 8c0511899..000000000 --- a/.example/util/gvalid/gvalid_struct2.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -// string默认值校验 -func main() { - type User struct { - Uid string `gvalid:"uid@integer"` - } - - user := &User{} - - g.Dump(gvalid.CheckStruct(context.TODO(), user, nil)) -} diff --git a/.example/util/gvalid/gvalid_struct3.go b/.example/util/gvalid/gvalid_struct3.go deleted file mode 100644 index 7262a6b08..000000000 --- a/.example/util/gvalid/gvalid_struct3.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "context" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gvalid" -) - -// same校验 -func main() { - type User struct { - Pass string `gvalid:"passwd1 @required|length:2,20|password3||密码强度不足"` - } - - user := &User{ - Pass: "1", - } - - g.Dump(gvalid.CheckStruct(context.TODO(), user, nil).Maps()) -} diff --git a/.example/util/gvalid/gvalid_struct_meta.go b/.example/util/gvalid/gvalid_struct_meta.go deleted file mode 100644 index e7d251fe5..000000000 --- a/.example/util/gvalid/gvalid_struct_meta.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "context" - "fmt" - "github.com/gogf/gf/v2/errors/gerror" - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/util/gmeta" -) - -type UserCreateReq struct { - gmeta.Meta `v:"UserCreateReq"` - Name string - Pass string -} - -func UserCreateReqChecker(ctx context.Context, rule string, value interface{}, message string, data interface{}) error { - user := &UserCreateReq{} - if v, ok := data.(*UserCreateReq); ok { - user = v - } - // SELECT COUNT(*) FROM `user` WHERE `name` = xxx - count, err := g.Model("user").Ctx(ctx).Where("name", user.Name).Count() - if err != nil { - return err - } - if count > 0 { - return gerror.Newf(`The name "%s" is already token`, user.Name) - } - return nil -} - -func main() { - user := &UserCreateReq{ - Name: "john", - Pass: "123456", - } - err := g.Validator().RuleFunc("UserCreateReq", UserCreateReqChecker).CheckStruct(user) - fmt.Println(err) -} diff --git a/.example/util/gvalid/i18n/en.toml b/.example/util/gvalid/i18n/en.toml deleted file mode 100644 index 7574fd595..000000000 --- a/.example/util/gvalid/i18n/en.toml +++ /dev/null @@ -1,7 +0,0 @@ -"gf.gvalid.required" = "字段不能为空" - - -"ReuiredUserName" = "Please input user name" -"ReuiredUserType" = "Please select user type" -"MustSize" = "Size of :attribute must be :size" - diff --git a/.example/util/gvalid/i18n/zh-CN.toml b/.example/util/gvalid/i18n/zh-CN.toml deleted file mode 100644 index 3db393e20..000000000 --- a/.example/util/gvalid/i18n/zh-CN.toml +++ /dev/null @@ -1,16 +0,0 @@ - - -"gf.gvalid.required" = "字段不能为空" - -"ReuiredUserName" = "请输入用户名称" -"ReuiredUserType" = "请选择用户类型" -"MustSize" = ":attribute长度必须为:size" - - - - - - - - - diff --git a/.gitignore b/.gitignore index fdb500de8..5af57e523 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,6 @@ bin/ cbuild **/.DS_Store .vscode/ -.example/other/ +.test/ main gf \ No newline at end of file diff --git a/text/gstr/gstr_trim.go b/text/gstr/gstr_trim.go index bdd937ebf..ea46102f1 100644 --- a/text/gstr/gstr_trim.go +++ b/text/gstr/gstr_trim.go @@ -7,8 +7,9 @@ package gstr import ( - "github.com/gogf/gf/v2/internal/utils" "strings" + + "github.com/gogf/gf/v2/internal/utils" ) // Trim strips whitespace (or other characters) from the beginning and end of a string. From 266a4214c5468f0037198195e1362484dbd55a50 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 16 Nov 2021 21:40:04 +0800 Subject: [PATCH 10/11] fix example for package gregex --- text/gregex/gregex_z_example_test.go | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/text/gregex/gregex_z_example_test.go b/text/gregex/gregex_z_example_test.go index 789751444..afcefbe37 100644 --- a/text/gregex/gregex_z_example_test.go +++ b/text/gregex/gregex_z_example_test.go @@ -7,6 +7,7 @@ package gregex_test import ( "bytes" + "fmt" "strings" "github.com/gogf/gf/v2/frame/g" @@ -119,10 +120,10 @@ func ExampleMatchAllString() { func ExampleQuote() { result := gregex.Quote(`[1-9]\d+`) - g.Dump(result) + fmt.Println(result) // Output: - // "\[1-9\]\\d\+" + // \[1-9\]\\d\+ } func ExampleReplace() { @@ -268,14 +269,11 @@ func ExampleSplit() { func ExampleValidate() { // Valid match statement - g.Dump(gregex.Validate(`\d+`)) + fmt.Println(gregex.Validate(`\d+`)) // Mismatched statement - g.Dump(gregex.Validate(`[a-9]\d+`)) + fmt.Println(gregex.Validate(`[a-9]\d+`)) // Output: // - // { - // Code: "invalid character class range", - // Expr: "a-9", - // } + // error parsing regexp: invalid character class range: `a-9` } From 6ad7baeb2c27c74e21633f88bbe971c03bf1fe12 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 16 Nov 2021 23:39:45 +0800 Subject: [PATCH 11/11] remove gsmtp --- net/gsmtp/gsmtp.go | 118 ---------------------------------------- net/gsmtp/gsmtp_test.go | 78 -------------------------- text/gregex/gregex.go | 2 +- 3 files changed, 1 insertion(+), 197 deletions(-) delete mode 100644 net/gsmtp/gsmtp.go delete mode 100644 net/gsmtp/gsmtp_test.go diff --git a/net/gsmtp/gsmtp.go b/net/gsmtp/gsmtp.go deleted file mode 100644 index d7c437536..000000000 --- a/net/gsmtp/gsmtp.go +++ /dev/null @@ -1,118 +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 gsmtp provides a simple SMTP client to access remote mail server. -// -// Eg: -// s := smtp.New("smtp.exmail.qq.com:25", "notify@a.com", "password") -// glog.Print(s.SendMail("notify@a.com", "ulric@b.com;rain@c.com", "subject", "body, red")) -package gsmtp - -import ( - "encoding/base64" - "fmt" - "net/smtp" - "strings" - - "github.com/gogf/gf/v2/errors/gcode" - "github.com/gogf/gf/v2/errors/gerror" -) - -// SMTP is the structure for smtp connection. -type SMTP struct { - Address string - Username string - Password string -} - -// New creates and returns a new SMTP object. -func New(address, username, password string) *SMTP { - return &SMTP{ - Address: address, - Username: username, - Password: password, - } -} - -var ( - // contentEncoding is the BASE64 encoding object for mail content. - contentEncoding = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") -) - -// SendMail connects to the server at addr, switches to TLS if -// possible, authenticates with the optional mechanism an if possible, -// and then sends an email from address `from`, to addresses `to`, with -// message msg. -// -// The parameter `contentType` specifies the content type of the mail, eg: html. -func (s *SMTP) SendMail(from, tos, subject, body string, contentType ...string) error { - var ( - server = "" - address = "" - hp = strings.Split(s.Address, ":") - ) - if s.Address == "" || len(hp) > 2 { - return gerror.NewCodef( - gcode.CodeInvalidParameter, - "server address is either empty or incorrect: %s", - s.Address, - ) - } else if len(hp) == 1 { - server = s.Address - address = server + ":25" - } else if len(hp) == 2 { - if (hp[0] == "") || (hp[1] == "") { - return gerror.NewCodef( - gcode.CodeInvalidParameter, - "server address is either empty or incorrect: %s", - s.Address, - ) - } - server = hp[0] - address = s.Address - } - var ( - tosArr []string - arr = strings.Split(tos, ";") - ) - for _, to := range arr { - // TODO: replace with regex - if strings.Contains(to, "@") { - tosArr = append(tosArr, to) - } - } - if len(tosArr) == 0 { - return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid parameter "tos": %s`, tos) - } - - if !strings.Contains(from, "@") { - return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid parameter "from": %s`, from) - } - - header := map[string]string{ - "From": from, - "To": strings.Join(tosArr, ";"), - "Subject": fmt.Sprintf("=?UTF-8?B?%s?=", contentEncoding.EncodeToString([]byte(subject))), - "MIME-Version": "1.0", - "Content-Type": "text/plain; charset=UTF-8", - "Content-Transfer-Encoding": "base64", - } - if len(contentType) > 0 && contentType[0] == "html" { - header["Content-Type"] = "text/html; charset=UTF-8" - } - message := "" - for k, v := range header { - message += fmt.Sprintf("%s: %s\r\n", k, v) - } - message += "\r\n" + contentEncoding.EncodeToString([]byte(body)) - return smtp.SendMail( - address, - smtp.PlainAuth("", s.Username, s.Password, server), - from, - tosArr, - []byte(message), - ) -} diff --git a/net/gsmtp/gsmtp_test.go b/net/gsmtp/gsmtp_test.go deleted file mode 100644 index dd0aea9c3..000000000 --- a/net/gsmtp/gsmtp_test.go +++ /dev/null @@ -1,78 +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 gsmtp_test - -import ( - "strings" - "testing" - - "github.com/gogf/gf/v2/net/gsmtp" -) - -func TestAddress(t *testing.T) { - errMessage := "address is either empty or incorrect" - - errValues := []string{ - "", - ":", - ":25", - "localhost:", - "local.host:25:28", - } - - for _, errValue := range errValues { - smtpConnection := gsmtp.New(errValue, "smtpUser@smtp.exmail.qq.com", "smtpPassword") - res := smtpConnection.SendMail("sender@local.host", "recipient1@domain.com;recipientN@anotherDomain.cn", "This is subject", "Hi!

This is body") - if !strings.Contains(res.Error(), errMessage) { - t.Errorf("Test failed on Address: %s", errValue) - } - } -} - -func TestFrom(t *testing.T) { - errMessage := `invalid parameter "from"` - - errValues := []string{ - "", - "qwerty", - // "qwe@rty@com", - // "@rty", - // "qwe@", - } - - for _, errValue := range errValues { - smtpConnection := gsmtp.New("smtp.exmail.qq.com", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - res := smtpConnection.SendMail(errValue, "recipient1@domain.com;recipientN@anotherDomain.cn", "This is subject", "Hi!

This is body") - if !strings.Contains(res.Error(), errMessage) { - t.Errorf("Test failed on From: %s", errValue) - } - } - -} - -func TestTos(t *testing.T) { - errMessage := `invalid parameter "tos"` - - errValues := []string{ - "", - "qwerty", - "qwe;rty", - "qwe;rty;com", - // "qwe@rty@com", - // "@rty", - // "qwe@", - } - - for _, errValue := range errValues { - smtpConnection := gsmtp.New("smtp.exmail.qq.com", "smtpUser@smtp.exmail.qq.com", "smtpPassword") - res := smtpConnection.SendMail("from@domain.com", errValue, "This is subject", "Hi!

This is body") - if !strings.Contains(res.Error(), errMessage) { - t.Errorf("Test failed on Tos: %s", errValue) - } - } - -} diff --git a/text/gregex/gregex.go b/text/gregex/gregex.go index f23fe5936..a1dfc9686 100644 --- a/text/gregex/gregex.go +++ b/text/gregex/gregex.go @@ -75,7 +75,7 @@ func MatchAllString(pattern string, src string) ([][]string, error) { } } -// Replace replace all matched `pattern` in bytes `src` with bytes `replace`. +// Replace replaces all matched `pattern` in bytes `src` with bytes `replace`. func Replace(pattern string, replace, src []byte) ([]byte, error) { if r, err := getRegexp(pattern); err == nil { return r.ReplaceAll(src, replace), nil