feat: init

This commit is contained in:
micah 2026-03-28 19:31:44 +08:00
commit 241b23b92e
28 changed files with 2181 additions and 0 deletions

34
.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
# ---> Go
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
go.work.sum
# env file
.env
# ide
.idea
standard
# local files
conf/local
logs

73
LICENSE Normal file
View File

@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2025 micah
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.

39
README.md Normal file
View File

@ -0,0 +1,39 @@
# standard
## 目录结构
```
standard
├── conf // 配置文件包
│ ├── dev // 开发环境配置
│ ├── online // 线上环境配置
│ ├── test // 测试环境配置
│ ├── conf.go
│ └── ……
├── generate // 自动生成包
│ └── mysql
│ └── gorm.go // gorm 生成bean、query的代码
├── gosafe // 对go的一些方法的封装方便调用减少重复代码
├── idl // thrift存放的地方
├── initialize // 初始化项目汇总
├── internal // 内部逻辑
│ ├── dal // 数据库相关逻辑
│ │ ├── model // mysql对应的bean struct
│ │ ├── mysql // mysql
│ │ ├── query // service相关逻辑
│ │ └── init.go // service相关逻辑
│ ├── service // service相关逻辑
│ │ └── xxx // service相关逻辑
│ └── ……
├── pkg // 对外部的库的封装
│ ├── json
│ ├── log
│ ├── toml
│ ├── yaml
│ └── ……
├── router // 对外部的库的封装
├── template // hertz的自定义模版
├── go.mod
├── go.sum
├── ……
└── README.md
```

89
conf/conf.go Normal file
View File

@ -0,0 +1,89 @@
package conf
import (
"fmt"
"os"
"gitea.micah.com/micah/standard/pkg/json"
"gitea.micah.com/micah/standard/pkg/toml"
"gitea.micah.com/micah/standard/pkg/yaml"
)
var (
conf *Config
configTypeYaml = "yaml"
configTypeJson = "json"
configTypeToml = "toml"
configTypeMap = map[string]func(name string, obj interface{}) error{
configTypeYaml: yaml.Parse,
configTypeJson: json.Parse,
configTypeToml: toml.Parse,
}
)
type MySQL struct {
LogLevel string `json:"log_level" yaml:"log_level" toml:"log_level"`
DSN string `json:"dsn" yaml:"dsn" toml:"dsn"`
ReplicasDSN []string `json:"replicas_dsn" yaml:"replicas_dsn" toml:"replicas_dsn"`
}
type Redis struct {
Address string `json:"address" yaml:"address" toml:"address"`
Password string `json:"password" yaml:"password" toml:"password"`
}
type Hertz struct {
Address string `json:"address" yaml:"address" toml:"address"`
EnablePprof bool `json:"enable_pprof" yaml:"enable_pprof" toml:"enable_pprof"`
EnableGzip bool `json:"enable_gzip" yaml:"enable_gzip" toml:"enable_gzip"`
EnableAccessLog bool `json:"enable_access_log" yaml:"enable_access_log" toml:"enable_access_log"`
LogLevel string `json:"log_level" yaml:"log_level" toml:"log_level"`
LogFileName string `json:"log_file_name" yaml:"log_file_name" toml:"log_file_name"`
LogMaxSize int `json:"log_max_size" yaml:"log_max_size" toml:"log_max_size"`
LogMaxBackups int `json:"log_max_backups" yaml:"log_max_backups" toml:"log_max_backups"`
LogMaxAge int `json:"log_max_age" yaml:"log_max_age" toml:"log_max_age"`
}
type Config struct {
Env string
Hertz *Hertz `json:"hertz" yaml:"hertz" toml:"hertz"`
MySQL *MySQL `json:"mysql" yaml:"mysql" toml:"mysql"`
Redis *Redis `json:"redis" yaml:"redis" toml:"redis"`
}
func GetConf() *Config {
if conf == nil {
return &Config{}
}
return conf
}
func ParseConfig() error {
if conf != nil {
return nil
}
c := &Config{}
for ct, fn := range configTypeMap {
configPath := fmt.Sprintf("./conf/%s/conf.%s", GetEnv(), ct)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
continue
}
err := fn(configPath, c)
if err != nil {
return err
}
break
}
conf = c
return nil
}
func GetEnv() string {
e := os.Getenv("GO_ENV")
if len(e) == 0 {
return "test"
}
return e
}

5
conf/dev/conf.yaml Normal file
View File

@ -0,0 +1,5 @@
mysql:
log_level: 4
dsn: xxx:xxx@tcp(xxx:3306)/gorm?charset=utf8&parseTime=True&loc=Local
replicas_dsn:
- xxx:xxx@tcp(xxx:3306)/gorm?charset=utf8&parseTime=True&loc=Local

5
conf/online/conf.yaml Normal file
View File

@ -0,0 +1,5 @@
mysql:
log_level: 4
dsn: xxx:xxx@tcp(xxx:3306)/gorm?charset=utf8&parseTime=True&loc=Local
replicas_dsn:
- xxx:xxx@tcp(xxx:3306)/gorm?charset=utf8&parseTime=True&loc=Local

5
conf/test/conf.yaml Normal file
View File

@ -0,0 +1,5 @@
mysql:
log_level: 4
dsn: xxx:xxx@tcp(xxx:3306)/gorm?charset=utf8&parseTime=True&loc=Local
replicas_dsn:
- xxx:xxx@tcp(xxx:3306)/gorm?charset=utf8&parseTime=True&loc=Local

25
generate/mysql/gorm.go Normal file
View File

@ -0,0 +1,25 @@
package main
import (
"gorm.io/gen"
"gitea.micah.com/micah/standard/initialize"
"gitea.micah.com/micah/standard/internal/dal"
)
func main() {
g := gen.NewGenerator(gen.Config{
OutPath: "./internal/dal/query",
Mode: gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
})
// 初始化
initialize.Init()
g.UseDB(dal.GetDB())
// Generate struct `User` based on table `users`
// Generate basic type-safe DAO API for struct `model.User` following conventions
g.ApplyBasic(g.GenerateModel("user"))
// Generate the code
g.Execute()
}

43
go.mod Normal file
View File

@ -0,0 +1,43 @@
module gitea.micah.com/micah/standard
go 1.18
require (
github.com/BurntSushi/toml v1.5.0
github.com/cloudwego/hertz v0.9.7
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/mysql v1.5.7
gorm.io/gen v0.3.27
gorm.io/gorm v1.25.12
gorm.io/plugin/dbresolver v1.5.3
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/gopkg v0.1.0 // indirect
github.com/bytedance/sonic v1.13.2 // indirect
github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/cloudwego/netpoll v0.6.4 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-sql-driver/mysql v1.8.1 // indirect
github.com/golang/protobuf v1.5.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
github.com/nyaruka/phonenumbers v1.0.55 // indirect
github.com/tidwall/gjson v1.14.4 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/sync v0.9.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.20.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
google.golang.org/protobuf v1.27.1 // indirect
gorm.io/datatypes v1.2.4 // indirect
gorm.io/hints v1.1.0 // indirect
)

153
go.sum Normal file
View File

@ -0,0 +1,153 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/bytedance/gopkg v0.1.0 h1:aAxB7mm1qms4Wz4sp8e1AtKDOeFLtdqvGiUe7aonRJs=
github.com/bytedance/gopkg v0.1.0/go.mod h1:FtQG3YbQG9L/91pbKSw787yBQPutC+457AvDW77fgUQ=
github.com/bytedance/mockey v1.2.12 h1:aeszOmGw8CPX8CRx1DZ/Glzb1yXvhjDh6jdFBNZjsU4=
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/hertz v0.9.7 h1:tAVaiO+vTf+ZkQhvNhKbDJ0hmC4oJ7bzwDi1KhvhHy4=
github.com/cloudwego/hertz v0.9.7/go.mod h1:t6d7NcoQxPmETvzPMMIVPHMn5C5QzpqIiFsaavoLJYQ=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/cloudwego/netpoll v0.6.4 h1:z/dA4sOTUQof6zZIO4QNnLBXsDFFFEos9OOGloR6kno=
github.com/cloudwego/netpoll v0.6.4/go.mod h1:BtM+GjKTdwKoC8IOzD08/+8eEn2gYoiNLipFca6BVXQ=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI=
github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0 h1:LUVKkCeviFUMKqHa4tXIIij/lbhnMbP7Fn5wKdKkRh4=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA=
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
github.com/microsoft/go-mssqldb v0.17.0 h1:Fto83dMZPnYv1Zwx5vHHxpNraeEaUlQ/hhHLgZiaenE=
github.com/nyaruka/phonenumbers v1.0.55 h1:bj0nTO88Y68KeUQ/n3Lo2KgK7lM1hF7L9NFuwcCl3yg=
github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM=
github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/datatypes v1.2.4 h1:uZmGAcK/QZ0uyfCuVg0VQY1ZmV9h1fuG0tMwKByO1z4=
gorm.io/datatypes v1.2.4/go.mod h1:f4BsLcFAX67szSv8svwLRjklArSHAvHLeE3pXAS5DZI=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/postgres v1.5.0 h1:u2FXTy14l45qc3UeCJ7QaAXZmZfDDv0YrthvmRq1l0U=
gorm.io/driver/sqlite v1.1.6/go.mod h1:W8LmC/6UvVbHKah0+QOC7Ja66EaZXHwUTjgXY8YNWX8=
gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU=
gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0=
gorm.io/gen v0.3.27 h1:ziocAFLpE7e0g4Rum69pGfB9S6DweTxK8gAun7cU8as=
gorm.io/gen v0.3.27/go.mod h1:9zquz2xD1f3Eb/eHq4oLn2z6vDVvQlCY5S3uMBLv4EA=
gorm.io/gorm v1.21.15/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
gorm.io/gorm v1.22.2/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
gorm.io/hints v1.1.0 h1:Lp4z3rxREufSdxn4qmkK3TLDltrM10FLTHiuqwDPvXw=
gorm.io/hints v1.1.0/go.mod h1:lKQ0JjySsPBj3uslFzY3JhYDtqEwzm+G1hv8rWujB6Y=
gorm.io/plugin/dbresolver v1.5.3 h1:wFwINGZZmttuu9h7XpvbDHd8Lf9bb8GNzp/NpAMV2wU=
gorm.io/plugin/dbresolver v1.5.3/go.mod h1:TSrVhaUg2DZAWP3PrHlDlITEJmNOkL0tFTjvTEsQ4XE=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=

11
gosafe/gorouting.go Normal file
View File

@ -0,0 +1,11 @@
package gosafe
import "context"
// Go safe goroutine.
func Go(ctx context.Context, fn func()) {
go func() {
defer Recovery(ctx)
fn()
}()
}

22
gosafe/recovery.go Normal file
View File

@ -0,0 +1,22 @@
package gosafe
import (
"context"
"runtime/debug"
"gitea.micah.com/micah/standard/pkg/log"
)
// Recovery .
func Recovery(ctx context.Context) {
e := recover()
if e == nil {
return
}
if ctx == nil {
ctx = context.Background()
}
log.Errorf("catch panic err=%v\nstacktrace=%s", e, debug.Stack())
}

14
idl/hello.thrift Normal file
View File

@ -0,0 +1,14 @@
namespace go hello
struct HelloReq {
1: string Name (api.query="name");
}
struct HelloResp {
1: string RespBody;
}
service HelloService {
HelloResp HelloMethod(1: HelloReq request) (api.get="/hello");
}

14
initialize/init.go Normal file
View File

@ -0,0 +1,14 @@
package initialize
import (
"gitea.micah.com/micah/standard/conf"
"gitea.micah.com/micah/standard/internal/dal"
)
func Init() {
err := conf.ParseConfig()
if err != nil {
panic(err)
}
dal.Init()
}

74
internal/dal/init.go Normal file
View File

@ -0,0 +1,74 @@
package dal
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/plugin/dbresolver"
"gitea.micah.com/micah/standard/conf"
"gitea.micah.com/micah/standard/internal/dal/query"
)
var DB *gorm.DB
func Init() {
c := conf.GetConf()
var err error
loggerLevel := getLogLevel(c.MySQL.LogLevel)
if loggerLevel < logger.Silent || loggerLevel > logger.Info {
loggerLevel = logger.Info
}
DB, err = gorm.Open(mysql.Open(c.MySQL.DSN), &gorm.Config{
SkipDefaultTransaction: true,
PrepareStmt: true,
Logger: logger.Default.LogMode(loggerLevel),
})
if err != nil {
panic(fmt.Sprintf("注册 DB DSN 失败, %+v", err))
}
if len(c.MySQL.ReplicasDSN) > 0 {
dialects := make([]gorm.Dialector, len(c.MySQL.ReplicasDSN))
for i, s := range c.MySQL.ReplicasDSN {
dialects[i] = mysql.Open(s)
}
// 注册 DB Resolver 插件
err = DB.Use(dbresolver.Register(dbresolver.Config{
// 主库(写操作)
Sources: []gorm.Dialector{mysql.Open(c.MySQL.DSN)},
// 从库(读操作)
Replicas: dialects,
// 负载均衡策略(默认轮询)
Policy: dbresolver.RandomPolicy{}, // 可选:随机、轮询、加权等
// 自动检查连接健康
TraceResolverMode: true, // 记录解析器日志
}).SetMaxOpenConns(100))
if err != nil {
panic(fmt.Sprintf("注册 DB Resolver 失败, %+v", err))
}
}
query.SetDefault(DB)
}
func getLogLevel(level string) logger.LogLevel {
switch level {
case "info":
return logger.Info
case "warn":
return logger.Warn
case "error":
return logger.Error
default:
return logger.Silent
}
}
func GetDB() *gorm.DB {
return DB
}

View File

@ -0,0 +1,30 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package model
import (
"time"
"gorm.io/gorm"
)
const TableNameUser = "user"
// User User information table
type User struct {
ID int64 `gorm:"column:id;primaryKey;autoIncrement:true;comment:PK" json:"id"` // PK
Name string `gorm:"column:name;not null;comment:User name" json:"name"` // User name
Gender int32 `gorm:"column:gender;not null;comment:User gender" json:"gender"` // User gender
Age int32 `gorm:"column:age;not null;comment:User age" json:"age"` // User age
Introduce string `gorm:"column:introduce;comment:User introduce" json:"introduce"` // User introduce
CreatedAt time.Time `gorm:"column:created_at;not null;default:CURRENT_TIMESTAMP;comment:User information create time" json:"created_at"` // User information create time
UpdatedAt time.Time `gorm:"column:updated_at;not null;default:CURRENT_TIMESTAMP;comment:User information update time" json:"updated_at"` // User information update time
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;comment:User information delete time" json:"deleted_at"` // User information delete time
}
// TableName User's table name
func (*User) TableName() string {
return TableNameUser
}

103
internal/dal/query/gen.go Normal file
View File

@ -0,0 +1,103 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package query
import (
"context"
"database/sql"
"gorm.io/gorm"
"gorm.io/gen"
"gorm.io/plugin/dbresolver"
)
var (
Q = new(Query)
User *user
)
func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
*Q = *Use(db, opts...)
User = &Q.User
}
func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
return &Query{
db: db,
User: newUser(db, opts...),
}
}
type Query struct {
db *gorm.DB
User user
}
func (q *Query) Available() bool { return q.db != nil }
func (q *Query) clone(db *gorm.DB) *Query {
return &Query{
db: db,
User: q.User.clone(db),
}
}
func (q *Query) ReadDB() *Query {
return q.ReplaceDB(q.db.Clauses(dbresolver.Read))
}
func (q *Query) WriteDB() *Query {
return q.ReplaceDB(q.db.Clauses(dbresolver.Write))
}
func (q *Query) ReplaceDB(db *gorm.DB) *Query {
return &Query{
db: db,
User: q.User.replaceDB(db),
}
}
type queryCtx struct {
User IUserDo
}
func (q *Query) WithContext(ctx context.Context) *queryCtx {
return &queryCtx{
User: q.User.WithContext(ctx),
}
}
func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error {
return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...)
}
func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx {
tx := q.db.Begin(opts...)
return &QueryTx{Query: q.clone(tx), Error: tx.Error}
}
type QueryTx struct {
*Query
Error error
}
func (q *QueryTx) Commit() error {
return q.db.Commit().Error
}
func (q *QueryTx) Rollback() error {
return q.db.Rollback().Error
}
func (q *QueryTx) SavePoint(name string) error {
return q.db.SavePoint(name).Error
}
func (q *QueryTx) RollbackTo(name string) error {
return q.db.RollbackTo(name).Error
}

View File

@ -0,0 +1,412 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package query
import (
"context"
"database/sql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
"gitea.micah.com/micah/standard/internal/dal/model"
)
func newUser(db *gorm.DB, opts ...gen.DOOption) user {
_user := user{}
_user.userDo.UseDB(db, opts...)
_user.userDo.UseModel(&model.User{})
tableName := _user.userDo.TableName()
_user.ALL = field.NewAsterisk(tableName)
_user.ID = field.NewInt64(tableName, "id")
_user.Name = field.NewString(tableName, "name")
_user.Gender = field.NewInt32(tableName, "gender")
_user.Age = field.NewInt32(tableName, "age")
_user.Introduce = field.NewString(tableName, "introduce")
_user.CreatedAt = field.NewTime(tableName, "created_at")
_user.UpdatedAt = field.NewTime(tableName, "updated_at")
_user.DeletedAt = field.NewField(tableName, "deleted_at")
_user.fillFieldMap()
return _user
}
// user User information table
type user struct {
userDo
ALL field.Asterisk
ID field.Int64 // PK
Name field.String // User name
Gender field.Int32 // User gender
Age field.Int32 // User age
Introduce field.String // User introduce
CreatedAt field.Time // User information create time
UpdatedAt field.Time // User information update time
DeletedAt field.Field // User information delete time
fieldMap map[string]field.Expr
}
func (u user) Table(newTableName string) *user {
u.userDo.UseTable(newTableName)
return u.updateTableName(newTableName)
}
func (u user) As(alias string) *user {
u.userDo.DO = *(u.userDo.As(alias).(*gen.DO))
return u.updateTableName(alias)
}
func (u *user) updateTableName(table string) *user {
u.ALL = field.NewAsterisk(table)
u.ID = field.NewInt64(table, "id")
u.Name = field.NewString(table, "name")
u.Gender = field.NewInt32(table, "gender")
u.Age = field.NewInt32(table, "age")
u.Introduce = field.NewString(table, "introduce")
u.CreatedAt = field.NewTime(table, "created_at")
u.UpdatedAt = field.NewTime(table, "updated_at")
u.DeletedAt = field.NewField(table, "deleted_at")
u.fillFieldMap()
return u
}
func (u *user) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := u.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (u *user) fillFieldMap() {
u.fieldMap = make(map[string]field.Expr, 8)
u.fieldMap["id"] = u.ID
u.fieldMap["name"] = u.Name
u.fieldMap["gender"] = u.Gender
u.fieldMap["age"] = u.Age
u.fieldMap["introduce"] = u.Introduce
u.fieldMap["created_at"] = u.CreatedAt
u.fieldMap["updated_at"] = u.UpdatedAt
u.fieldMap["deleted_at"] = u.DeletedAt
}
func (u user) clone(db *gorm.DB) user {
u.userDo.ReplaceConnPool(db.Statement.ConnPool)
return u
}
func (u user) replaceDB(db *gorm.DB) user {
u.userDo.ReplaceDB(db)
return u
}
type userDo struct{ gen.DO }
type IUserDo interface {
gen.SubQuery
Debug() IUserDo
WithContext(ctx context.Context) IUserDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() IUserDo
WriteDB() IUserDo
As(alias string) gen.Dao
Session(config *gorm.Session) IUserDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) IUserDo
Not(conds ...gen.Condition) IUserDo
Or(conds ...gen.Condition) IUserDo
Select(conds ...field.Expr) IUserDo
Where(conds ...gen.Condition) IUserDo
Order(conds ...field.Expr) IUserDo
Distinct(cols ...field.Expr) IUserDo
Omit(cols ...field.Expr) IUserDo
Join(table schema.Tabler, on ...field.Expr) IUserDo
LeftJoin(table schema.Tabler, on ...field.Expr) IUserDo
RightJoin(table schema.Tabler, on ...field.Expr) IUserDo
Group(cols ...field.Expr) IUserDo
Having(conds ...gen.Condition) IUserDo
Limit(limit int) IUserDo
Offset(offset int) IUserDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) IUserDo
Unscoped() IUserDo
Create(values ...*model.User) error
CreateInBatches(values []*model.User, batchSize int) error
Save(values ...*model.User) error
First() (*model.User, error)
Take() (*model.User, error)
Last() (*model.User, error)
Find() ([]*model.User, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.User, err error)
FindInBatches(result *[]*model.User, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*model.User) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) IUserDo
Assign(attrs ...field.AssignExpr) IUserDo
Joins(fields ...field.RelationField) IUserDo
Preload(fields ...field.RelationField) IUserDo
FirstOrInit() (*model.User, error)
FirstOrCreate() (*model.User, error)
FindByPage(offset int, limit int) (result []*model.User, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Rows() (*sql.Rows, error)
Row() *sql.Row
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) IUserDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (u userDo) Debug() IUserDo {
return u.withDO(u.DO.Debug())
}
func (u userDo) WithContext(ctx context.Context) IUserDo {
return u.withDO(u.DO.WithContext(ctx))
}
func (u userDo) ReadDB() IUserDo {
return u.Clauses(dbresolver.Read)
}
func (u userDo) WriteDB() IUserDo {
return u.Clauses(dbresolver.Write)
}
func (u userDo) Session(config *gorm.Session) IUserDo {
return u.withDO(u.DO.Session(config))
}
func (u userDo) Clauses(conds ...clause.Expression) IUserDo {
return u.withDO(u.DO.Clauses(conds...))
}
func (u userDo) Returning(value interface{}, columns ...string) IUserDo {
return u.withDO(u.DO.Returning(value, columns...))
}
func (u userDo) Not(conds ...gen.Condition) IUserDo {
return u.withDO(u.DO.Not(conds...))
}
func (u userDo) Or(conds ...gen.Condition) IUserDo {
return u.withDO(u.DO.Or(conds...))
}
func (u userDo) Select(conds ...field.Expr) IUserDo {
return u.withDO(u.DO.Select(conds...))
}
func (u userDo) Where(conds ...gen.Condition) IUserDo {
return u.withDO(u.DO.Where(conds...))
}
func (u userDo) Order(conds ...field.Expr) IUserDo {
return u.withDO(u.DO.Order(conds...))
}
func (u userDo) Distinct(cols ...field.Expr) IUserDo {
return u.withDO(u.DO.Distinct(cols...))
}
func (u userDo) Omit(cols ...field.Expr) IUserDo {
return u.withDO(u.DO.Omit(cols...))
}
func (u userDo) Join(table schema.Tabler, on ...field.Expr) IUserDo {
return u.withDO(u.DO.Join(table, on...))
}
func (u userDo) LeftJoin(table schema.Tabler, on ...field.Expr) IUserDo {
return u.withDO(u.DO.LeftJoin(table, on...))
}
func (u userDo) RightJoin(table schema.Tabler, on ...field.Expr) IUserDo {
return u.withDO(u.DO.RightJoin(table, on...))
}
func (u userDo) Group(cols ...field.Expr) IUserDo {
return u.withDO(u.DO.Group(cols...))
}
func (u userDo) Having(conds ...gen.Condition) IUserDo {
return u.withDO(u.DO.Having(conds...))
}
func (u userDo) Limit(limit int) IUserDo {
return u.withDO(u.DO.Limit(limit))
}
func (u userDo) Offset(offset int) IUserDo {
return u.withDO(u.DO.Offset(offset))
}
func (u userDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IUserDo {
return u.withDO(u.DO.Scopes(funcs...))
}
func (u userDo) Unscoped() IUserDo {
return u.withDO(u.DO.Unscoped())
}
func (u userDo) Create(values ...*model.User) error {
if len(values) == 0 {
return nil
}
return u.DO.Create(values)
}
func (u userDo) CreateInBatches(values []*model.User, batchSize int) error {
return u.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (u userDo) Save(values ...*model.User) error {
if len(values) == 0 {
return nil
}
return u.DO.Save(values)
}
func (u userDo) First() (*model.User, error) {
if result, err := u.DO.First(); err != nil {
return nil, err
} else {
return result.(*model.User), nil
}
}
func (u userDo) Take() (*model.User, error) {
if result, err := u.DO.Take(); err != nil {
return nil, err
} else {
return result.(*model.User), nil
}
}
func (u userDo) Last() (*model.User, error) {
if result, err := u.DO.Last(); err != nil {
return nil, err
} else {
return result.(*model.User), nil
}
}
func (u userDo) Find() ([]*model.User, error) {
result, err := u.DO.Find()
return result.([]*model.User), err
}
func (u userDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.User, err error) {
buf := make([]*model.User, 0, batchSize)
err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (u userDo) FindInBatches(result *[]*model.User, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return u.DO.FindInBatches(result, batchSize, fc)
}
func (u userDo) Attrs(attrs ...field.AssignExpr) IUserDo {
return u.withDO(u.DO.Attrs(attrs...))
}
func (u userDo) Assign(attrs ...field.AssignExpr) IUserDo {
return u.withDO(u.DO.Assign(attrs...))
}
func (u userDo) Joins(fields ...field.RelationField) IUserDo {
for _, _f := range fields {
u = *u.withDO(u.DO.Joins(_f))
}
return &u
}
func (u userDo) Preload(fields ...field.RelationField) IUserDo {
for _, _f := range fields {
u = *u.withDO(u.DO.Preload(_f))
}
return &u
}
func (u userDo) FirstOrInit() (*model.User, error) {
if result, err := u.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*model.User), nil
}
}
func (u userDo) FirstOrCreate() (*model.User, error) {
if result, err := u.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*model.User), nil
}
}
func (u userDo) FindByPage(offset int, limit int) (result []*model.User, count int64, err error) {
result, err = u.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = u.Offset(-1).Limit(-1).Count()
return
}
func (u userDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = u.Count()
if err != nil {
return
}
err = u.Offset(offset).Limit(limit).Scan(result)
return
}
func (u userDo) Scan(result interface{}) (err error) {
return u.DO.Scan(result)
}
func (u userDo) Delete(models ...*model.User) (result gen.ResultInfo, err error) {
return u.DO.Delete(models)
}
func (u *userDo) withDO(do gen.Dao) *userDo {
u.DO = *do.(*gen.DO)
return u
}

13
main.go Normal file
View File

@ -0,0 +1,13 @@
package main
import (
"gitea.micah.com/micah/standard/initialize"
"gitea.micah.com/micah/standard/server"
)
func main() {
// init
initialize.Init()
// run
server.Run()
}

25
pkg/json/json.go Normal file
View File

@ -0,0 +1,25 @@
package json
import (
"encoding/json"
"os"
)
var (
Marshal = json.Marshal
Unmarshal = json.Unmarshal
MarshalIndent = json.MarshalIndent
NewDecoder = json.NewDecoder
NewEncoder = json.NewEncoder
)
// Parse Parses the given JSON file
func Parse(name string, obj interface{}) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
return NewDecoder(f).Decode(obj)
}

122
pkg/log/log.go Normal file
View File

@ -0,0 +1,122 @@
package log
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
)
type logger struct {
mu sync.Mutex
*log.Logger
logCh chan Message
}
type Message struct {
Level string
Msg string
}
const (
infoLevel = 1
warnLevel = 2
errLevel = 3
)
var (
lg *logger
lgOnce sync.Once
)
func InitLogger() (logCh chan Message) {
lgOnce.Do(func() {
lg = &logger{
Logger: log.New(os.Stdout, "", log.LstdFlags|log.Lshortfile),
mu: sync.Mutex{},
logCh: make(chan Message, 1000),
}
})
return lg.logCh
}
func CtxInfof(_ context.Context, format string, args ...interface{}) {
Infof(format, args...)
}
func CtxWarnf(_ context.Context, format string, args ...interface{}) {
Warnf(format, args...)
}
func CtxErrorf(_ context.Context, format string, args ...interface{}) {
Errorf(format, args...)
}
func Infof(format string, v ...any) {
printLog(infoLevel, 3, format, v...)
sendLogMsg(infoLevel, fmt.Sprintf(format, v...))
}
func Warnf(format string, v ...any) {
printLog(warnLevel, 3, format, v...)
sendLogMsg(warnLevel, fmt.Sprintf(format, v...))
}
func Errorf(format string, v ...any) {
printLog(errLevel, 3, format, v...)
sendLogMsg(errLevel, fmt.Sprintf(format, v...))
}
func printLog(level int, depth int, format string, v ...any) {
if lg == nil {
return
}
lg.mu.Lock()
defer lg.mu.Unlock()
switch level {
case infoLevel:
lg.SetOutput(os.Stdout)
lg.SetPrefix("[eino devops][INFO] ")
case warnLevel:
lg.SetOutput(os.Stderr)
lg.SetPrefix("[eino devops][WARN] ")
case errLevel:
lg.SetOutput(os.Stderr)
lg.SetPrefix("[eino devops][ERROR] ")
default:
lg.SetOutput(os.Stdout)
lg.SetPrefix("[eino devops][INFO] ")
}
_ = lg.Output(depth, fmt.Sprintf(format, v...))
}
func sendLogMsg(level int, msg string) {
if lg == nil {
return
}
logMsg := fmt.Sprintf("%s %s", time.Now().Format("2006/01/02 15:04:05.999"), msg)
var message Message
switch level {
case infoLevel:
message = Message{Msg: fmt.Sprintf("[INFO] %s", logMsg), Level: "INFO"}
case warnLevel:
message = Message{Msg: fmt.Sprintf("[WARN] %s", logMsg), Level: "WARN"}
case errLevel:
message = Message{Msg: fmt.Sprintf("[ERROR] %s", logMsg), Level: "ERROR"}
default:
message = Message{Msg: fmt.Sprintf("[INFO] %s", logMsg), Level: "INFO"}
}
select {
case lg.logCh <- message:
default:
printLog(warnLevel, 4, "too many log, will drop\nlog=%s", logMsg)
}
}

26
pkg/toml/toml.go Normal file
View File

@ -0,0 +1,26 @@
package toml
import (
"os"
"github.com/BurntSushi/toml"
)
var (
Unmarshal = toml.Unmarshal
DecodeFile = toml.DecodeFile
Decode = toml.Decode
NewEncoder = toml.NewEncoder
NewDecoder = toml.NewDecoder
)
// Parse Parses the given TOML file
func Parse(name string, obj interface{}) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
_, err = NewDecoder(f).Decode(obj)
return err
}

25
pkg/yaml/yaml.go Normal file
View File

@ -0,0 +1,25 @@
package yaml
import (
"os"
"gopkg.in/yaml.v3"
)
var (
Marshal = yaml.Marshal
Unmarshal = yaml.Unmarshal
NewDecoder = yaml.NewDecoder
NewEncoder = yaml.NewEncoder
)
// Parse Parses the given YAML file
func Parse(name string, obj interface{}) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
return NewDecoder(f).Decode(obj)
}

1
router/hertz/register.go Normal file
View File

@ -0,0 +1 @@
package hertz

9
server/hertz.go Normal file
View File

@ -0,0 +1,9 @@
package server
import (
"gitea.micah.com/micah/standard/server/hertz"
)
func Run() {
hertz.Run()
}

73
server/hertz/main.go Normal file
View File

@ -0,0 +1,73 @@
package hertz
import (
"compress/gzip"
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/middlewares/server/recovery"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"gitea.micah.com/micah/standard/conf"
"gitea.micah.com/micah/standard/initialize"
)
func Run() {
main()
}
func main() {
// init
initialize.Init()
address := conf.GetConf().Hertz.Address
h := server.New(server.WithHostPorts(address))
// add a ping route to test
h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
})
router.GeneratedRegister(h)
// do what you wanted
// add some render data: <no value>
registerMiddleware(h)
h.Spin()
}
func registerMiddleware(h *server.Hertz) {
// pprof
if conf.GetConf().Hertz.EnablePprof {
pprof.Register(h)
}
// gzip
if conf.GetConf().Hertz.EnableGzip {
h.Use(gzip.Gzip(gzip.DefaultCompression))
}
// access log
if conf.GetConf().Hertz.EnableAccessLog {
h.Use(accesslog.New())
}
// log
logger := hertzlogrus.NewLogger()
hlog.SetLogger(logger)
hlog.SetLevel(conf.LogLevel())
hlog.SetOutput(&lumberjack.Logger{
Filename: conf.GetConf().Hertz.LogFileName,
MaxSize: conf.GetConf().Hertz.LogMaxSize,
MaxBackups: conf.GetConf().Hertz.LogMaxBackups,
MaxAge: conf.GetConf().Hertz.LogMaxAge,
})
// recovery
h.Use(recovery.Recovery())
// cores
h.Use(cors.Default())
}

554
template/layout.yaml Normal file
View File

@ -0,0 +1,554 @@
layouts:
- path: main.go
delims:
- ""
- ""
body: |-
// Code generated by hertz generator.
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/middlewares/server/recovery"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/hertz-contrib/cors"
"github.com/hertz-contrib/gzip"
"github.com/hertz-contrib/logger/accesslog"
hertzlogrus "github.com/hertz-contrib/logger/logrus"
"github.com/hertz-contrib/pprof"
"{{.GoModule}}/biz/router"
"{{.GoModule}}/conf"
"gopkg.in/natefinch/lumberjack.v2"
)
func main() {
// init
initialize.Init()
address := conf.GetConf().Hertz.Address
h := server.New(server.WithHostPorts(address))
// add a ping route to test
h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
})
router.GeneratedRegister(h)
// do what you wanted
// add some render data: <no value>
registerMiddleware(h)
h.Spin()
}
func registerMiddleware(h *server.Hertz) {
// pprof
if conf.GetConf().Hertz.EnablePprof {
pprof.Register(h)
}
// gzip
if conf.GetConf().Hertz.EnableGzip {
h.Use(gzip.Gzip(gzip.DefaultCompression))
}
// access log
if conf.GetConf().Hertz.EnableAccessLog {
h.Use(accesslog.New())
}
// log
logger := hertzlogrus.NewLogger()
hlog.SetLogger(logger)
hlog.SetLevel(conf.LogLevel())
hlog.SetOutput(&lumberjack.Logger{
Filename: conf.GetConf().Hertz.LogFileName,
MaxSize: conf.GetConf().Hertz.LogMaxSize,
MaxBackups: conf.GetConf().Hertz.LogMaxBackups,
MaxAge: conf.GetConf().Hertz.LogMaxAge,
})
// recovery
h.Use(recovery.Recovery())
// cores
h.Use(cors.Default())
}
- path: go.mod
delims:
- '{{'
- '}}'
body: |-
module {{.GoModule}}
{{- if .UseApacheThrift}}
replace github.com/apache/thrift => github.com/apache/thrift v0.13.0
{{- end}}
- path: router/hertz/register.go
delims:
- ""
- ""
body: |-
// Code generated by hertz generator. DO NOT EDIT.
package router
import (
"github.com/cloudwego/hertz/pkg/app/server"
)
// GeneratedRegister registers routers generated by IDL.
func GeneratedRegister(r *server.Hertz){
//INSERT_POINT: DO NOT DELETE THIS LINE!
}
- path: conf/conf.go
delims:
- ""
- ""
body: |-
package conf
import (
"fmt"
"os"
"gitea.micah.com/micah/standard/pkg/json"
"gitea.micah.com/micah/standard/pkg/toml"
"gitea.micah.com/micah/standard/pkg/yaml"
)
var (
conf *Config
configTypeYaml = "yaml"
configTypeJson = "json"
configTypeToml = "toml"
configTypeMap = map[string]func(name string, obj interface{}) error{
configTypeYaml: yaml.Parse,
configTypeJson: json.Parse,
configTypeToml: toml.Parse,
}
)
type MySQL struct {
LogLevel string `json:"log_level" yaml:"log_level" toml:"log_level"`
DSN string `json:"dsn" yaml:"dsn" toml:"dsn"`
ReplicasDSN []string `json:"replicas_dsn" yaml:"replicas_dsn" toml:"replicas_dsn"`
}
type Redis struct {
Address string `json:"address" yaml:"address" toml:"address"`
Password string `json:"password" yaml:"password" toml:"password"`
}
type Hertz struct {
Address string `json:"address" yaml:"address" toml:"address"`
EnablePprof bool `json:"enable_pprof" yaml:"enable_pprof" toml:"enable_pprof"`
EnableGzip bool `json:"enable_gzip" yaml:"enable_gzip" toml:"enable_gzip"`
EnableAccessLog bool `json:"enable_access_log" yaml:"enable_access_log" toml:"enable_access_log"`
LogLevel string `json:"log_level" yaml:"log_level" toml:"log_level"`
LogFileName string `json:"log_file_name" yaml:"log_file_name" toml:"log_file_name"`
LogMaxSize int `json:"log_max_size" yaml:"log_max_size" toml:"log_max_size"`
LogMaxBackups int `json:"log_max_backups" yaml:"log_max_backups" toml:"log_max_backups"`
LogMaxAge int `json:"log_max_age" yaml:"log_max_age" toml:"log_max_age"`
}
type Config struct {
Env string
Hertz *Hertz `json:"hertz" yaml:"hertz" toml:"hertz"`
MySQL *MySQL `json:"mysql" yaml:"mysql" toml:"mysql"`
Redis *Redis `json:"redis" yaml:"redis" toml:"redis"`
}
func GetConf() *Config {
if conf == nil {
return &Config{}
}
return conf
}
func ParseConfig() error {
if conf != nil {
return nil
}
c := &Config{}
for ct, fn := range configTypeMap {
configPath := fmt.Sprintf("./conf/%s/conf.%s", GetEnv(), ct)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
continue
}
err := fn(configPath, c)
if err != nil {
return err
}
break
}
conf = c
return nil
}
func GetEnv() string {
e := os.Getenv("GO_ENV")
if len(e) == 0 {
return "test"
}
return e
}
- path: conf/dev/conf.yaml
delims:
- ""
- ""
body: |-
hertz:
address: ":8080"
enable_pprof: true
enable_gzip: true
enable_access_log: true
log_level: info
log_file_name: "log/hertz.log"
log_max_size: 10
log_max_age: 3
log_max_backups: 50
mysql:
log_level: info
dsn: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
replicas_dsn:
- "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
redis:
address: "127.0.0.1:6379"
password: ""
- path: conf/online/conf.yaml
delims:
- ""
- ""
body: |-
hertz:
address: ":8080"
enable_pprof: true
enable_gzip: true
enable_access_log: true
log_level: info
log_file_name: "log/hertz.log"
log_max_size: 10
log_max_age: 3
log_max_backups: 50
mysql:
log_level: info
dsn: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
replicas_dsn:
- "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
redis:
address: "127.0.0.1:6379"
password: ""
- path: conf/test/conf.yaml
delims:
- ""
- ""
body: |-
hertz:
address: ":8080"
enable_pprof: true
enable_gzip: true
enable_access_log: true
log_level: info
log_file_name: "log/hertz.log"
log_max_size: 10
log_max_age: 3
log_max_backups: 50
mysql:
log_level: info
dsn: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
replicas_dsn:
- "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
redis:
address: "127.0.0.1:6379"
password: ""
- path: biz/dal/init.go
delims:
- ""
- ""
body: |-
package dal
import (
"{{.GoModule}}/biz/dal/mysql"
"{{.GoModule}}/biz/dal/redis"
)
func Init() {
redis.Init()
mysql.Init()
}
- path: biz/dal/mysql/init.go
delims:
- ""
- ""
body: |-
package mysql
import (
"{{.GoModule}}/conf"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var (
DB *gorm.DB
err error
)
func Init() {
DB, err = gorm.Open(mysql.Open(conf.GetConf().MySQL.DSN),
&gorm.Config{
PrepareStmt: true,
SkipDefaultTransaction: true,
},
)
if err != nil {
panic(err)
}
}
- path: biz/dal/redis/init.go
delims:
- ""
- ""
body: |-
package redis
import (
"context"
"github.com/go-redis/redis/v8"
"{{.GoModule}}/conf"
)
var RedisClient *redis.Client
func Init() {
RedisClient = redis.NewClient(&redis.Options{
Addr: conf.GetConf().Redis.Address,
Password: conf.GetConf().Redis.Password,
})
if err := RedisClient.Ping(context.Background()).Err(); err != nil {
panic(err)
}
}
- path: docker-compose.yaml
delims:
- ""
- ""
body: |-
version: '3'
services:
mysql:
image: 'mysql:latest'
ports:
- 3306:3306
environment:
- MYSQL_DATABASE=gorm
- MYSQL_USER=gorm
- MYSQL_PASSWORD=gorm
- MYSQL_RANDOM_ROOT_PASSWORD="yes"
redis:
image: 'redis:latest'
ports:
- 6379:6379
- path: readme.md
delims:
- ""
- ""
body: |-
# *** Project
## introduce
- Use the [Hertz](https://github.com/cloudwego/hertz/) framework
- Integration of pprof, cors, recovery, access_log, gzip and other extensions of Hertz.
- Generating the base code for unit tests.
- Provides basic profile functions.
- Provides the most basic MVC code hierarchy.
## Directory structure
| catalog | introduce |
| ---- | ---- |
| conf | Configuration files |
| main.go | Startup file |
| hertz_gen | Hertz generated model |
| biz/handler | Used for request processing, validation and return of response. |
| biz/service | The actual business logic. |
| biz/dal | Logic for operating the storage layer |
| biz/route | Routing and middleware registration |
| biz/utils | Wrapped some common methods |
## How to run
```shell
sh build.sh
sh output/bootstrap.sh
```
- path: .gitignore
delims:
- ""
- ""
body: |-
*.o
*.a
*.so
_obj
_test
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.exe~
*.test
*.prof
*.rar
*.zip
*.gz
*.psd
*.bmd
*.cfg
*.pptx
*.log
*nohup.out
*settings.pyc
*.sublime-project
*.sublime-workspace
!.gitkeep
.DS_Store
/.idea
/.vscode
/output
*.local.yml
- path: .hz
delims:
- "{{"
- "}}"
body: |-
// Code generated by hz. DO NOT EDIT.
hz version: {{.hzVersion}},
- path: .gitignore
delims:
- ""
- ""
body: |-
*.o
*.a
*.so
_obj
_test
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.exe~
*.test
*.prof
*.rar
*.zip
*.gz
*.psd
*.bmd
*.cfg
*.pptx
*.log
*nohup.out
*settings.pyc
*.sublime-project
*.sublime-workspace
!.gitkeep
.DS_Store
/.idea
/.vscode
/output
*.local.yml
- path: biz/utils/resp.go
delims:
- "{{"
- "}}"
body: |-
package utils
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
)
// SendErrResponse pack error response
func SendErrResponse(ctx context.Context, c *app.RequestContext, code int, err error) {
// todo edit custom code
c.String(code, err.Error())
}
// SendSuccessResponse pack success response
func SendSuccessResponse(ctx context.Context, c *app.RequestContext, code int, data interface{}) {
// todo edit custom code
c.JSON(code, data)
}
- path: build.sh
delims:
- "{{"
- "}}"
body: |-
#!/bin/bash
RUN_NAME={{.ServiceName}}
mkdir -p output/bin output/conf
cp script/bootstrap.sh output 2>/dev/null
chmod +x output/bootstrap.sh
cp -r conf/* output/conf
go build -o output/bin/${RUN_NAME}
- path: script/bootstrap.sh
delims:
- "{{"
- "}}"
body: |-
#!/bin/bash
CURDIR=$(cd $(dirname $0); pwd)
BinaryName={{.ServiceName}}
echo "$CURDIR/bin/${BinaryName}"
exec $CURDIR/bin/${BinaryName}

182
template/package.yaml Normal file
View File

@ -0,0 +1,182 @@
layouts:
- path: handler.go
body: |-
{{$OutDirs := GetUniqueHandlerOutDir .Methods}}
package {{.PackageName}}
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
{{- range $k, $v := .Imports}}
{{$k}} "{{$v.Package}}"
{{- end}}
{{- range $_, $OutDir := $OutDirs}}
{{if eq $OutDir "" -}}
"{{$.ProjPackage}}/biz/service"
{{- else -}}
"{{$.ProjPackage}}/biz/service/{{$OutDir}}"
{{- end -}}
{{- end}}
"{{$.ProjPackage}}/biz/utils"
)
{{range $_, $MethodInfo := .Methods}}
{{$MethodInfo.Comment}}
func {{$MethodInfo.Name}}(ctx context.Context, c *app.RequestContext) {
var err error
{{if ne $MethodInfo.RequestTypeName "" -}}
var req {{$MethodInfo.RequestTypeName}}
err = c.BindAndValidate(&req)
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}
{{end}}
{{if eq $MethodInfo.OutputDir "" -}}
resp,err := service.New{{$MethodInfo.Name}}Service(ctx, c).Run(&req)
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}
{{else}}
resp,err := {{$MethodInfo.OutputDir}}.New{{$MethodInfo.Name}}Service(ctx, c).Run(&req)
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}
{{end}}
utils.SendSuccessResponse(ctx, c, consts.StatusOK, resp)
}
{{end}}
update_behavior:
import_tpl:
- |-
{{$OutDirs := GetUniqueHandlerOutDir .Methods}}
{{- range $_, $OutDir := $OutDirs}}
{{if eq $OutDir "" -}}
"{{$.ProjPackage}}/biz/service"
{{- else -}}
"{{$.ProjPackage}}/biz/service/{{$OutDir}}"
{{end}}
{{- end}}
- path: handler_single.go
body: |+
{{.Comment}}
func {{.Name}}(ctx context.Context, c *app.RequestContext) {
var err error
{{if ne .RequestTypeName "" -}}
var req {{.RequestTypeName}}
err = c.BindAndValidate(&req)
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}
{{end}}
{{if eq .OutputDir "" -}}
resp,err := service.New{{.Name}}Service(ctx, c).Run(&req)
{{else}}
resp,err := {{.OutputDir}}.New{{.Name}}Service(ctx, c).Run(&req)
{{end}}
if err != nil {
utils.SendErrResponse(ctx, c, consts.StatusOK, err)
return
}
utils.SendSuccessResponse(ctx, c, consts.StatusOK, resp)
}
- path: "biz/service/{{.HandlerGenPath}}/{{ToSnakeCase .MethodName}}.go"
loop_method: true
update_behavior:
type: "skip"
body: |-
package {{.FilePackage}}
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
{{- range $k, $v := .Models}}
{{$k}} "{{$v.Package}}"
{{- end}}
)
type {{.Name}}Service struct {
RequestContext *app.RequestContext
Context context.Context
}
func New{{.Name}}Service(Context context.Context, RequestContext *app.RequestContext) *{{.Name}}Service {
return &{{.Name}}Service{RequestContext: RequestContext, Context: Context}
}
func (h *{{.Name}}Service) Run(req *{{.RequestTypeName}}) ( resp *{{.ReturnTypeName}}, err error) {
//defer func() {
// hlog.CtxInfof(h.Context, "req = %+v", req)
// hlog.CtxInfof(h.Context, "resp = %+v", resp)
//}()
// todo edit your code
return
}
- path: "biz/service/{{.HandlerGenPath}}/{{ToSnakeCase .MethodName}}_test.go"
loop_method: true
update_behavior:
type: "skip"
body: |-
package {{.FilePackage}}
import (
"context"
"testing"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/test/assert"
{{- range $k, $v := .Models}}
{{$k}} "{{$v.Package}}"
{{- end}}
)
func Test{{.Name}}Service_Run(t *testing.T) {
ctx := context.Background()
c := app.NewContext(1)
s := New{{.Name}}Service(ctx, c)
// init req and assert value
req := &{{.RequestTypeName}}{}
resp, err := s.Run(req)
assert.DeepEqual(t, nil, resp)
assert.DeepEqual(t, nil, err)
// todo edit your unit test.
}
- path: "{{.HandlerDir}}/{{.GenPackage}}/{{ToSnakeCase .ServiceName}}_test.go"
loop_service: true
update_behavior:
type: "append"
append_key: "method"
insert_key: "Test{{$.Name}}"
append_tpl: |-
func Test{{.Name}}(t *testing.T) {
h := server.Default()
h.GET("{{.Path}}", {{.Name}})
w := ut.PerformRequest(h.Engine, "{{.HTTPMethod}}", "{{.Path}}", &ut.Body{Body: bytes.NewBufferString(""), Len: 1},
ut.Header{})
resp := w.Result()
assert.DeepEqual(t, 201, resp.StatusCode())
assert.DeepEqual(t, "", string(resp.Body()))
// todo edit your unit test.
}
body: |-
package {{.FilePackage}}
import (
"bytes"
"testing"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/test/assert"
"github.com/cloudwego/hertz/pkg/common/ut"
)
{{range $_, $MethodInfo := $.Methods}}
func Test{{$MethodInfo.Name}}(t *testing.T) {
h := server.Default()
h.GET("{{$MethodInfo.Path}}", {{$MethodInfo.Name}})
w := ut.PerformRequest(h.Engine, "{{$MethodInfo.HTTPMethod}}", "{{$MethodInfo.Path}}", &ut.Body{Body: bytes.NewBufferString(""), Len: 1},
ut.Header{})
resp := w.Result()
assert.DeepEqual(t, 201, resp.StatusCode())
assert.DeepEqual(t, "", string(resp.Body()))
// todo edit your unit test.
}
{{end}}