repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/migrate/migrate.go | tools/goctl/migrate/migrate.go | package migrate
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"github.com/gookit/color"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
"github.com/zeromicro/go-zero/tools/goctl/util/ctx"
)
const defaultMigrateVersion = "v1.3.0"
const (
confirmUnknown = iota
confirmAll
confirmIgnore
)
var (
fset = token.NewFileSet()
builderxConfirm = confirmUnknown
)
func migrate(_ *cobra.Command, _ []string) error {
if len(stringVarVersion) == 0 {
stringVarVersion = defaultMigrateVersion
}
err := editMod(stringVarVersion, boolVarVerbose)
if err != nil {
return err
}
err = rewriteImport(boolVarVerbose)
if err != nil {
return err
}
err = tidy(boolVarVerbose)
if err != nil {
return err
}
if boolVarVerbose {
console.Success("[OK] refactor finish, execute %q on project root to check status.",
"go test -race ./...")
}
return nil
}
func rewriteImport(verbose bool) error {
if verbose {
console.Info("preparing to rewrite import ...")
time.Sleep(200 * time.Millisecond)
}
cancelOnSignals()
wd, err := os.Getwd()
if err != nil {
return err
}
project, err := ctx.Prepare(wd)
if err != nil {
return err
}
root := project.Dir
fsys := os.DirFS(root)
var final []*ast.Package
err = fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if !d.IsDir() {
return nil
}
if verbose {
console.Info("walking to %q", path)
}
pkgs, err := parser.ParseDir(fset, path, func(info fs.FileInfo) bool {
return strings.HasSuffix(info.Name(), ".go")
}, parser.ParseComments)
if err != nil {
return err
}
err = rewriteFile(pkgs, verbose)
if err != nil {
return err
}
for _, v := range pkgs {
final = append(final, v)
}
return nil
})
if err != nil {
return err
}
if verbose {
console.Info("start to write files ... ")
}
return writeFile(final, verbose)
}
func rewriteFile(pkgs map[string]*ast.Package, verbose bool) error {
for _, pkg := range pkgs {
for filename, file := range pkg.Files {
var containsDeprecatedBuilderxPkg bool
for _, imp := range file.Imports {
if !strings.Contains(imp.Path.Value, deprecatedGoZeroMod) {
continue
}
if verbose {
console.Debug("[...] migrating %q ... ", filepath.Base(filename))
}
if strings.Contains(imp.Path.Value, deprecatedBuilderx) {
containsDeprecatedBuilderxPkg = true
var doNext bool
refactorBuilderx(deprecatedBuilderx, replacementBuilderx, func(allow bool) {
doNext = !allow
if allow {
newPath := strings.ReplaceAll(imp.Path.Value, deprecatedBuilderx, replacementBuilderx)
imp.EndPos = imp.End()
imp.Path.Value = newPath
}
})
if !doNext {
continue
}
}
newPath := strings.ReplaceAll(imp.Path.Value, deprecatedGoZeroMod, goZeroMod)
imp.EndPos = imp.End()
imp.Path.Value = newPath
}
if containsDeprecatedBuilderxPkg {
replacePkg(file)
}
}
}
return nil
}
func writeFile(pkgs []*ast.Package, verbose bool) error {
for _, pkg := range pkgs {
for filename, file := range pkg.Files {
w := bytes.NewBuffer(nil)
err := format.Node(w, fset, file)
if err != nil {
return fmt.Errorf("[rewriteImport] format file %s error: %w", filename, err)
}
err = os.WriteFile(filename, w.Bytes(), os.ModePerm)
if err != nil {
return fmt.Errorf("[rewriteImport] write file %s error: %w", filename, err)
}
if verbose {
console.Success("[OK] migrated %q successfully", filepath.Base(filename))
}
}
}
return nil
}
func replacePkg(file *ast.File) {
scope := file.Scope
if scope == nil {
return
}
obj := scope.Objects
for _, v := range obj {
decl := v.Decl
if decl == nil {
continue
}
vs, ok := decl.(*ast.ValueSpec)
if !ok {
continue
}
values := vs.Values
if len(values) != 1 {
continue
}
value := values[0]
callExpr, ok := value.(*ast.CallExpr)
if !ok {
continue
}
fn := callExpr.Fun
if fn == nil {
continue
}
selector, ok := fn.(*ast.SelectorExpr)
if !ok {
continue
}
x := selector.X
sel := selector.Sel
if x == nil || sel == nil {
continue
}
ident, ok := x.(*ast.Ident)
if !ok {
continue
}
if ident.Name == "builderx" {
ident.Name = "builder"
ident.NamePos = ident.End()
}
if sel.Name == "FieldNames" {
sel.Name = "RawFieldNames"
sel.NamePos = sel.End()
}
}
}
func refactorBuilderx(deprecated, replacement string, fn func(allow bool)) {
switch builderxConfirm {
case confirmAll:
fn(true)
return
case confirmIgnore:
fn(false)
return
}
msg := fmt.Sprintf(`Detects a deprecated package in the source code,
Deprecated package: %q
Replacement package: %q
It's recommended to use the replacement package, do you want to replace?
['Y' for yes, 'N' for no, 'A' for all, 'I' for ignore]: `,
deprecated, replacement)
fmt.Print(color.Yellow.Render(msg))
for {
var in string
fmt.Scanln(&in)
switch {
case strings.EqualFold(in, "Y"):
fn(true)
return
case strings.EqualFold(in, "N"):
fn(false)
return
case strings.EqualFold(in, "A"):
fn(true)
builderxConfirm = confirmAll
return
case strings.EqualFold(in, "I"):
fn(false)
builderxConfirm = confirmIgnore
return
default:
console.Warning("['Y' for yes, 'N' for no, 'A' for all, 'I' for ignore]: ")
}
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/migrate/cancel+polyfill.go | tools/goctl/migrate/cancel+polyfill.go | //go:build windows
package migrate
func cancelOnSignals() {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/migrate/mod.go | tools/goctl/migrate/mod.go | package migrate
import (
"errors"
"fmt"
"os"
"slices"
"time"
"github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
"github.com/zeromicro/go-zero/tools/goctl/util/ctx"
)
const (
deprecatedGoZeroMod = "github.com/tal-tech/go-zero"
deprecatedBuilderx = "github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
replacementBuilderx = "github.com/zeromicro/go-zero/core/stores/builder"
goZeroMod = "github.com/zeromicro/go-zero"
)
var errInvalidGoMod = errors.New("it's only working for go module")
func editMod(version string, verbose bool) error {
wd, err := os.Getwd()
if err != nil {
return err
}
isGoMod, _ := ctx.IsGoMod(wd)
if !isGoMod {
return nil
}
latest, err := getLatest(goZeroMod, verbose)
if err != nil {
return err
}
if !slices.Contains(latest, version) {
return fmt.Errorf("release version %q is not found", version)
}
mod := fmt.Sprintf("%s@%s", goZeroMod, version)
err = removeRequire(deprecatedGoZeroMod, verbose)
if err != nil {
return err
}
return addRequire(mod, verbose)
}
func addRequire(mod string, verbose bool) error {
if verbose {
console.Info("adding require %s ...", mod)
time.Sleep(200 * time.Millisecond)
}
wd, err := os.Getwd()
if err != nil {
return err
}
isGoMod, _ := ctx.IsGoMod(wd)
if !isGoMod {
return errInvalidGoMod
}
_, err = execx.Run("go mod edit -require "+mod, wd)
return err
}
func removeRequire(mod string, verbose bool) error {
if verbose {
console.Info("remove require %s ...", mod)
time.Sleep(200 * time.Millisecond)
}
wd, err := os.Getwd()
if err != nil {
return err
}
_, err = execx.Run("go mod edit -droprequire "+mod, wd)
return err
}
func tidy(verbose bool) error {
if verbose {
console.Info("go mod tidy ...")
time.Sleep(200 * time.Millisecond)
}
wd, err := os.Getwd()
if err != nil {
return err
}
isGoMod, _ := ctx.IsGoMod(wd)
if !isGoMod {
return nil
}
_, err = execx.Run("go mod tidy", wd)
return err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/migrate/cmd.go | tools/goctl/migrate/cmd.go | package migrate
import "github.com/zeromicro/go-zero/tools/goctl/internal/cobrax"
var (
boolVarVerbose bool
stringVarVersion string
// Cmd describes a migrate command.
Cmd = cobrax.NewCommand("migrate", cobrax.WithRunE(migrate))
)
func init() {
migrateCmdFlags := Cmd.Flags()
migrateCmdFlags.BoolVarP(&boolVarVerbose, "verbose", "v")
migrateCmdFlags.StringVarWithDefaultValue(&stringVarVersion, "version", defaultMigrateVersion)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/migrate/version.go | tools/goctl/migrate/version.go | package migrate
import (
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
)
var client = http.Client{
Timeout: 5 * time.Second,
}
func getLatest(repo string, verbose bool) ([]string, error) {
log := func(err error) {
console.Warning("get latest versions failed, error: %+v", err)
}
resp, err := client.Get(fmt.Sprintf("%s/@v/list", repo))
if err != nil {
log(err)
return nil, err
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("%s", resp.Status)
log(err)
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
log(err)
return nil, err
}
versionStr := string(data)
versions := strings.Fields(versionStr)
return versions, nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/kube/kube.go | tools/goctl/kube/kube.go | package kube
import (
_ "embed"
"errors"
"fmt"
"text/template"
"github.com/gookit/color"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
category = "kube"
deployTemplateFile = "deployment.tpl"
jobTemplateFile = "job.tpl"
basePort = 30000
portLimit = 32767
)
var (
//go:embed deployment.tpl
deploymentTemplate string
//go:embed job.tpl
jobTemplate string
)
// Deployment describes the k8s deployment yaml
type Deployment struct {
Name string
Namespace string
Image string
Secret string
Replicas int
Revisions int
Port int
TargetPort int
NodePort int
UseNodePort bool
RequestCpu int
RequestMem int
LimitCpu int
LimitMem int
MinReplicas int
MaxReplicas int
ServiceAccount string
ImagePullPolicy string
}
// deploymentCommand is used to generate the kubernetes deployment yaml files.
func deploymentCommand(_ *cobra.Command, _ []string) error {
nodePort := varIntNodePort
home := varStringHome
remote := varStringRemote
branch := varStringBranch
if len(remote) > 0 {
repo, _ := util.CloneIntoGitHome(remote, branch)
if len(repo) > 0 {
home = repo
}
}
if len(home) > 0 {
pathx.RegisterGoctlHome(home)
}
// 0 to disable the nodePort type
if nodePort != 0 && (nodePort < basePort || nodePort > portLimit) {
return errors.New("nodePort should be between 30000 and 32767")
}
text, err := pathx.LoadTemplate(category, deployTemplateFile, deploymentTemplate)
if err != nil {
return err
}
out, err := pathx.CreateIfNotExist(varStringO)
if err != nil {
return err
}
defer out.Close()
if varIntTargetPort == 0 {
varIntTargetPort = varIntPort
}
t := template.Must(template.New("deploymentTemplate").Parse(text))
err = t.Execute(out, Deployment{
Name: varStringName,
Namespace: varStringNamespace,
Image: varStringImage,
Secret: varStringSecret,
Replicas: varIntReplicas,
Revisions: varIntRevisions,
Port: varIntPort,
TargetPort: varIntTargetPort,
NodePort: nodePort,
UseNodePort: nodePort > 0,
RequestCpu: varIntRequestCpu,
RequestMem: varIntRequestMem,
LimitCpu: varIntLimitCpu,
LimitMem: varIntLimitMem,
MinReplicas: varIntMinReplicas,
MaxReplicas: varIntMaxReplicas,
ServiceAccount: varStringServiceAccount,
ImagePullPolicy: varStringImagePullPolicy,
})
if err != nil {
return err
}
fmt.Println(color.Green.Render("Done."))
return nil
}
// Category returns the category of the deployments.
func Category() string {
return category
}
// Clean cleans the generated deployment files.
func Clean() error {
return pathx.Clean(category)
}
// GenTemplates generates the deployment template files.
func GenTemplates() error {
return pathx.InitTemplates(category, map[string]string{
deployTemplateFile: deploymentTemplate,
jobTemplateFile: jobTemplate,
})
}
// RevertTemplate reverts the given template file to the default value.
func RevertTemplate(name string) error {
return pathx.CreateTemplate(category, name, deploymentTemplate)
}
// Update updates the template files to the templates built in current goctl.
func Update() error {
err := Clean()
if err != nil {
return err
}
return pathx.InitTemplates(category, map[string]string{
deployTemplateFile: deploymentTemplate,
jobTemplateFile: jobTemplate,
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/kube/cmd.go | tools/goctl/kube/cmd.go | package kube
import "github.com/zeromicro/go-zero/tools/goctl/internal/cobrax"
var (
varStringName string
varStringNamespace string
varStringImage string
varStringSecret string
varIntRequestCpu int
varIntRequestMem int
varIntLimitCpu int
varIntLimitMem int
varStringO string
varIntReplicas int
varIntRevisions int
varIntPort int
varIntNodePort int
varIntTargetPort int
varIntMinReplicas int
varIntMaxReplicas int
varStringHome string
varStringRemote string
varStringBranch string
varStringServiceAccount string
varStringImagePullPolicy string
// Cmd describes a kube command.
Cmd = cobrax.NewCommand("kube")
deployCmd = cobrax.NewCommand("deploy", cobrax.WithRunE(deploymentCommand))
)
func init() {
deployCmdFlags := deployCmd.Flags()
deployCmdFlags.StringVar(&varStringName, "name")
deployCmdFlags.StringVar(&varStringNamespace, "namespace")
deployCmdFlags.StringVar(&varStringImage, "image")
deployCmdFlags.StringVar(&varStringSecret, "secret")
deployCmdFlags.IntVarWithDefaultValue(&varIntRequestCpu, "requestCpu", 500)
deployCmdFlags.IntVarWithDefaultValue(&varIntRequestMem, "requestMem", 512)
deployCmdFlags.IntVarWithDefaultValue(&varIntLimitCpu, "limitCpu", 1000)
deployCmdFlags.IntVarWithDefaultValue(&varIntLimitMem, "limitMem", 1024)
deployCmdFlags.StringVar(&varStringO, "o")
deployCmdFlags.IntVarWithDefaultValue(&varIntReplicas, "replicas", 3)
deployCmdFlags.IntVarWithDefaultValue(&varIntRevisions, "revisions", 5)
deployCmdFlags.IntVar(&varIntPort, "port")
deployCmdFlags.IntVar(&varIntNodePort, "nodePort")
deployCmdFlags.IntVar(&varIntTargetPort, "targetPort")
deployCmdFlags.IntVarWithDefaultValue(&varIntMinReplicas, "minReplicas", 3)
deployCmdFlags.IntVarWithDefaultValue(&varIntMaxReplicas, "maxReplicas", 10)
deployCmdFlags.StringVar(&varStringImagePullPolicy, "imagePullPolicy")
deployCmdFlags.StringVar(&varStringHome, "home")
deployCmdFlags.StringVar(&varStringRemote, "remote")
deployCmdFlags.StringVar(&varStringBranch, "branch")
deployCmdFlags.StringVar(&varStringServiceAccount, "serviceAccount")
_ = deployCmd.MarkFlagRequired("name")
_ = deployCmd.MarkFlagRequired("namespace")
_ = deployCmd.MarkFlagRequired("o")
_ = deployCmd.MarkFlagRequired("port")
Cmd.AddCommand(deployCmd)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/quickstart/quickstart.go | tools/goctl/quickstart/quickstart.go | package quickstart
import (
"fmt"
"os"
"path/filepath"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
"github.com/zeromicro/go-zero/tools/goctl/util/ctx"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const baseDir = "greet"
var (
log = console.NewColorConsole(true)
projectDir string
)
func cleanWorkSpace(projectDir string) {
var command string
var breakeState bool
fmt.Printf("Detected that the %q already exists, do you clean up?"+
" [y: YES, n: NO]: ", projectDir)
for {
fmt.Scanln(&command)
switch command {
case "y":
log.Debug("Clean workspace...")
_ = os.RemoveAll(projectDir)
breakeState = true
break
case "n":
log.Error("User canceled")
os.Exit(1)
default:
fmt.Println("Invalid command, try again...")
}
if breakeState {
break
}
}
}
func initProject() {
wd, err := os.Getwd()
logx.Must(err)
projectDir = filepath.Join(wd, baseDir)
if exists := pathx.FileExists(projectDir); exists {
cleanWorkSpace(projectDir)
}
log.Must(pathx.MkdirIfNotExist(projectDir))
_, err = ctx.Prepare(projectDir)
logx.Must(err)
}
func run(_ *cobra.Command, _ []string) error {
initProject()
switch varStringServiceType {
case serviceTypeMono:
newMonoService(false).start()
case serviceTypeMicro:
newMicroService().start()
default:
return fmt.Errorf("invalid service type, expected %s | %s",
serviceTypeMono, serviceTypeMicro)
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/quickstart/cmd.go | tools/goctl/quickstart/cmd.go | package quickstart
import "github.com/zeromicro/go-zero/tools/goctl/internal/cobrax"
const (
serviceTypeMono = "mono"
serviceTypeMicro = "micro"
)
var (
varStringServiceType string
// Cmd describes the command to run.
Cmd = cobrax.NewCommand("quickstart", cobrax.WithRunE(run))
)
func init() {
Cmd.Flags().StringVarPWithDefaultValue(&varStringServiceType, "service-type", "t", "mono")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/quickstart/mono.go | tools/goctl/quickstart/mono.go | package quickstart
import (
_ "embed"
"os"
"path/filepath"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/api/gogen"
"github.com/zeromicro/go-zero/tools/goctl/pkg/golang"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
//go:embed idl/greet.api
apiContent string
//go:embed idl/svc.tpl
svcContent string
//go:embed idl/apilogic.tpl
apiLogicContent string
//go:embed idl/api.yaml
apiEtcContent string
apiWorkDir string
rpcWorkDir string
)
func initAPIFlags() error {
rpcWorkDir = filepath.Join(projectDir, "rpc")
apiWorkDir = filepath.Join(projectDir, "api")
if err := pathx.MkdirIfNotExist(apiWorkDir); err != nil {
return err
}
apiFilename := filepath.Join(apiWorkDir, "greet.api")
apiBytes := []byte(apiContent)
if err := os.WriteFile(apiFilename, apiBytes, 0o666); err != nil {
return err
}
gogen.VarStringDir = apiWorkDir
gogen.VarStringAPI = apiFilename
return nil
}
type mono struct {
callRPC bool
}
func newMonoService(callRPC bool) mono {
m := mono{callRPC}
m.createAPIProject()
return m
}
func (m mono) createAPIProject() {
logx.Must(initAPIFlags())
log.Debug(">> Generating quickstart api project...")
logx.Must(gogen.GoCommand(nil, nil))
etcFile := filepath.Join(apiWorkDir, "etc", "greet.yaml")
logx.Must(os.WriteFile(etcFile, []byte(apiEtcContent), 0o666))
logicFile := filepath.Join(apiWorkDir, "internal", "logic", "pinglogic.go")
svcFile := filepath.Join(apiWorkDir, "internal", "svc", "servicecontext.go")
configPath := filepath.Join(apiWorkDir, "internal", "config")
svcPath := filepath.Join(apiWorkDir, "internal", "svc")
typesPath := filepath.Join(apiWorkDir, "internal", "types")
svcPkg, _, err := golang.GetParentPackage(svcPath)
logx.Must(err)
typesPkg, _, err := golang.GetParentPackage(typesPath)
logx.Must(err)
configPkg, _, err := golang.GetParentPackage(configPath)
logx.Must(err)
var rpcClientPkg string
if m.callRPC {
rpcClientPath := filepath.Join(rpcWorkDir, "greet")
rpcClientPkg, _, err = golang.GetParentPackage(rpcClientPath)
logx.Must(err)
}
logx.Must(util.With("logic").Parse(apiLogicContent).SaveTo(map[string]any{
"svcPkg": svcPkg,
"typesPkg": typesPkg,
"rpcClientPkg": rpcClientPkg,
"callRPC": m.callRPC,
}, logicFile, true))
logx.Must(util.With("svc").Parse(svcContent).SaveTo(map[string]any{
"rpcClientPkg": rpcClientPkg,
"configPkg": configPkg,
"callRPC": m.callRPC,
}, svcFile, true))
}
func (m mono) start() {
if !m.callRPC {
goModTidy(projectDir)
}
log.Debug(">> Ready to start an API server...")
log.Debug(">> Run 'curl http://127.0.0.1:8888/ping' after service startup...")
goStart(apiWorkDir)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/quickstart/run.go | tools/goctl/quickstart/run.go | package quickstart
import (
"os"
"os/exec"
"runtime"
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
func goStart(dir string) {
execCommand(dir, "go run .")
}
func goModTidy(dir string) int {
log.Debug(">> go mod tidy")
return execCommand(dir, "go mod tidy")
}
func execCommand(dir, arg string, envArgs ...string) int {
cmd := exec.Command("sh", "-c", arg)
if runtime.GOOS == vars.OsWindows {
cmd = exec.Command("cmd.exe", "/c", arg)
}
env := append([]string(nil), os.Environ()...)
env = append(env, envArgs...)
cmd.Env = env
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run()
return cmd.ProcessState.ExitCode()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/quickstart/micro.go | tools/goctl/quickstart/micro.go | package quickstart
import (
_ "embed"
"os"
"path/filepath"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const protoName = "greet.proto"
var (
//go:embed idl/greet.proto
protocContent string
//go:embed idl/rpc.yaml
rpcEtcContent string
zrpcWorkDir string
)
type serviceImpl struct {
starter func()
}
func (s serviceImpl) Start() {
s.starter()
}
func (s serviceImpl) Stop() {}
func initRPCProto() error {
zrpcWorkDir = filepath.Join(projectDir, "rpc")
if err := pathx.MkdirIfNotExist(zrpcWorkDir); err != nil {
return err
}
protoFilename := filepath.Join(zrpcWorkDir, protoName)
rpcBytes := []byte(protocContent)
return os.WriteFile(protoFilename, rpcBytes, 0o666)
}
type micro struct{}
func newMicroService() micro {
m := micro{}
m.mustStartRPCProject()
return m
}
func (m micro) mustStartRPCProject() {
logx.Must(initRPCProto())
log.Debug(">> Generating quickstart zRPC project...")
arg := "goctl rpc protoc " + protoName + " --go_out=. --go-grpc_out=. --zrpc_out=. --verbose"
execCommand(zrpcWorkDir, arg)
etcFile := filepath.Join(zrpcWorkDir, "etc", "greet.yaml")
logx.Must(os.WriteFile(etcFile, []byte(rpcEtcContent), 0o666))
}
func (m micro) start() {
mono := newMonoService(true)
goModTidy(projectDir)
sg := service.NewServiceGroup()
sg.Add(serviceImpl{func() {
log.Debug(">> Ready to start a zRPC server...")
goStart(zrpcWorkDir)
}})
sg.Add(serviceImpl{func() {
mono.start()
}})
sg.Start()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/vars/settings.go | tools/goctl/vars/settings.go | package vars
const (
// ProjectName the const value of zero
ProjectName = "zero"
// ProjectOpenSourceURL the github url of go-zero
ProjectOpenSourceURL = "github.com/zeromicro/go-zero"
// OsWindows represents os windows
OsWindows = "windows"
// OsMac represents os mac
OsMac = "darwin"
// OsLinux represents os linux
OsLinux = "linux"
// OsJs represents os js
OsJs = "js"
// OsIOS represents os ios
OsIOS = "ios"
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/server_test.go | gateway/server_test.go | package gateway
import (
"context"
"errors"
"io"
"log"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/discov"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/logx/logtest"
"github.com/zeromicro/go-zero/internal/mock"
"github.com/zeromicro/go-zero/rest/httpc"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/test/bufconn"
)
func init() {
logx.Disable()
}
func dialer() func(context.Context, string) (net.Conn, error) {
listener := bufconn.Listen(1024 * 1024)
server := grpc.NewServer()
mock.RegisterDepositServiceServer(server, &mock.DepositServer{})
reflection.Register(server)
go func() {
if err := server.Serve(listener); err != nil {
log.Fatal(err)
}
}()
return func(context.Context, string) (net.Conn, error) {
return listener.Dial()
}
}
func TestMustNewServer(t *testing.T) {
var c GatewayConf
assert.NoError(t, conf.FillDefault(&c))
// avoid popup alert on MacOS for asking permissions
c.DevServer.Host = "localhost"
c.Host = "localhost"
c.Port = 18881
s := MustNewServer(c, withDialer(func(conf zrpc.RpcClientConf) zrpc.Client {
return zrpc.MustNewClient(conf, zrpc.WithDialOption(grpc.WithContextDialer(dialer())))
}), WithHeaderProcessor(func(header http.Header) []string {
return []string{"foo"}
}))
s.upstreams = []Upstream{
{
Mappings: []RouteMapping{
{
Method: "get",
Path: "/deposit/:amount",
RpcPath: "mock.DepositService/Deposit",
},
},
Grpc: &zrpc.RpcClientConf{
Endpoints: []string{"foo"},
Timeout: 1000,
Middlewares: zrpc.ClientMiddlewaresConf{
Trace: true,
Duration: true,
Prometheus: true,
Breaker: true,
Timeout: true,
},
},
},
}
assert.NoError(t, s.build())
go s.Server.Start()
defer s.Stop()
time.Sleep(time.Millisecond * 200)
resp, err := httpc.Do(context.Background(), http.MethodGet, "http://localhost:18881/deposit/100", nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp, err = httpc.Do(context.Background(), http.MethodGet, "http://localhost:18881/deposit_fail/100", nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
}
func TestServer_ensureUpstreamNames(t *testing.T) {
var s = Server{
upstreams: []Upstream{
{
Grpc: &zrpc.RpcClientConf{
Target: "target",
},
},
},
}
assert.NoError(t, s.ensureUpstreamNames())
assert.Equal(t, "target", s.upstreams[0].Name)
}
func TestServer_ensureUpstreamNames_badEtcd(t *testing.T) {
var s = Server{
upstreams: []Upstream{
{
Grpc: &zrpc.RpcClientConf{
Etcd: discov.EtcdConf{},
},
},
},
}
logtest.PanicOnFatal(t)
assert.Panics(t, func() {
s.Start()
})
}
func TestHttpToHttp(t *testing.T) {
server := startTestServer(t)
defer server.Close()
var c GatewayConf
assert.NoError(t, conf.FillDefault(&c))
c.DevServer.Host = "localhost"
c.Host = "localhost"
c.Port = 18882
s := MustNewServer(c)
s.upstreams = []Upstream{
{
Name: "test",
Mappings: []RouteMapping{
{
Method: "get",
Path: "/api/ping",
},
},
Http: &HttpClientConf{
Target: "localhost:45678",
Timeout: 3000,
},
},
{
Mappings: []RouteMapping{
{
Method: "get",
Path: "/ping",
},
},
Http: &HttpClientConf{
Target: "localhost:45678",
Prefix: "/api",
},
},
}
go s.Start()
defer s.Stop()
time.Sleep(time.Millisecond * 200)
t.Run("/api/ping", func(t *testing.T) {
resp, err := httpc.Do(context.Background(), http.MethodGet,
"http://localhost:18882/api/ping", nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
if assert.NoError(t, err) {
assert.Equal(t, "pong", string(body))
}
})
t.Run("/ping", func(t *testing.T) {
resp, err := httpc.Do(context.Background(), http.MethodGet,
"http://localhost:18882/ping", nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
if assert.NoError(t, err) {
assert.Equal(t, "pong", string(body))
}
})
t.Run("no upstream", func(t *testing.T) {
resp, err := httpc.Do(context.Background(), http.MethodGet,
"http://localhost:18882/ping/bad", nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
})
t.Run("method not allowed", func(t *testing.T) {
resp, err := httpc.Do(context.Background(), http.MethodPost,
"http://localhost:18882/api/ping", nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusMethodNotAllowed, resp.StatusCode)
})
}
func TestHttpToHttpBadUpstream(t *testing.T) {
var c GatewayConf
assert.NoError(t, conf.FillDefault(&c))
c.DevServer.Host = "localhost"
c.Host = "localhost"
c.Port = 18883
s := MustNewServer(c)
s.upstreams = []Upstream{
{
Mappings: []RouteMapping{
{
Method: "get",
Path: "/api/ping",
},
},
Http: &HttpClientConf{
Target: "localhost:45678",
Prefix: "\x7f/api",
},
},
}
go s.Start()
defer s.Stop()
time.Sleep(time.Millisecond * 200)
t.Run("/api/ping", func(t *testing.T) {
resp, err := httpc.Do(context.Background(), http.MethodGet,
"http://localhost:18883/api/ping", nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
}
func TestHttpToHttpBadWriter(t *testing.T) {
t.Run("bad url", func(t *testing.T) {
handler := new(Server).buildHttpHandler(&HttpClientConf{
Target: "http://example.com",
Timeout: 3000,
})
w := httptest.NewRecorder()
handler.ServeHTTP(&badResponseWriter{w},
httptest.NewRequest(http.MethodGet, "http://localhost:18884", nil))
assert.Equal(t, http.StatusBadRequest, w.Code)
})
t.Run("bad url", func(t *testing.T) {
var c GatewayConf
assert.NoError(t, conf.FillDefault(&c))
c.DevServer.Host = "localhost"
c.Host = "localhost"
c.Port = 18884
s := MustNewServer(c)
s.upstreams = []Upstream{
{
Mappings: []RouteMapping{
{
Method: "get",
Path: "/api/ping",
},
},
Http: &HttpClientConf{
Target: "localhost:45678",
Prefix: "\x7f/api",
},
},
}
go s.Start()
defer s.Stop()
handler := new(Server).buildHttpHandler(&HttpClientConf{
Target: "localhost:18884",
Timeout: 3000,
})
w := httptest.NewRecorder()
handler.ServeHTTP(&badResponseWriter{w},
httptest.NewRequest(http.MethodGet, "http://localhost:18884/api/ping", nil))
assert.Equal(t, http.StatusBadRequest, w.Code)
})
}
// Handler function for the root route
func pingHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("pong"))
}
func startTestServer(t *testing.T) *http.Server {
http.HandleFunc("/api/ping", pingHandler)
server := &http.Server{
Addr: ":45678",
Handler: http.DefaultServeMux,
}
go func() {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
t.Errorf("failed to start server: %v", err)
}
}()
return server
}
type badResponseWriter struct {
http.ResponseWriter
}
func (w *badResponseWriter) Write([]byte) (int, error) {
return 0, errors.New("bad writer")
}
func TestWithMiddleware(t *testing.T) {
var callOrder []string
firstMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
callOrder = append(callOrder, "first-start")
w.Header().Set("X-First-Middleware", "called")
next(w, r)
callOrder = append(callOrder, "first-end")
}
}
secondMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
callOrder = append(callOrder, "second-start")
w.Header().Set("X-Second-Middleware", "called")
next(w, r)
callOrder = append(callOrder, "second-end")
}
}
var c GatewayConf
err := conf.FillDefault(&c)
assert.Nil(t, err)
// Test multiple middlewares in one call
server1 := MustNewServer(c, WithMiddleware(firstMiddleware, secondMiddleware))
assert.Len(t, server1.middlewares, 2, "Should have 2 middlewares from one call")
// Test multiple middleware calls
server2 := MustNewServer(c, WithMiddleware(firstMiddleware), WithMiddleware(secondMiddleware))
assert.Len(t, server2.middlewares, 2, "Should have 2 middlewares from separate calls")
// Test execution order (onion model)
finalHandler := func(w http.ResponseWriter, r *http.Request) {
callOrder = append(callOrder, "handler")
w.WriteHeader(http.StatusOK)
}
testHandler := server1.buildChainHandler(finalHandler)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/test", nil)
testHandler(w, r)
expectedOrder := []string{"first-start", "second-start", "handler", "second-end", "first-end"}
assert.Equal(t, expectedOrder, callOrder, "Middleware execution should follow onion model")
assert.Equal(t, "called", w.Header().Get("X-First-Middleware"))
assert.Equal(t, "called", w.Header().Get("X-Second-Middleware"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/config.go | gateway/config.go | package gateway
import (
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/zrpc"
)
type (
// GatewayConf is the configuration for gateway.
GatewayConf struct {
rest.RestConf
Upstreams []Upstream
}
// HttpClientConf is the configuration for an HTTP client.
HttpClientConf struct {
Target string
Prefix string `json:",optional"`
Timeout int64 `json:",default=3000"`
}
// RouteMapping is a mapping between a gateway route and an upstream rpc method.
RouteMapping struct {
// Method is the HTTP method, like GET, POST, PUT, DELETE.
Method string
// Path is the HTTP path.
Path string
// RpcPath is the gRPC rpc method, with format of package.service/method, optional.
// If the mapping is for HTTP, it's not necessary.
RpcPath string `json:",optional"`
}
// Upstream is the configuration for an upstream.
Upstream struct {
// Name is the name of the upstream.
Name string `json:",optional"`
// Grpc is the target of the upstream.
Grpc *zrpc.RpcClientConf `json:",optional"`
// Http is the target of the upstream.
Http *HttpClientConf `json:",optional=!grpc"`
// ProtoSets is the file list of proto set, like [hello.pb].
// if your proto file import another proto file, you need to write multi-file slice,
// like [hello.pb, common.pb].
ProtoSets []string `json:",optional"`
// Mappings is the mapping between gateway routes and Upstream methods.
// Keep it blank if annotations are added in rpc methods.
Mappings []RouteMapping `json:",optional"`
}
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/server.go | gateway/server.go | package gateway
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/fullstorydev/grpcurl"
"github.com/golang/protobuf/jsonpb"
"github.com/jhump/protoreflect/grpcreflect"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
"github.com/zeromicro/go-zero/core/threading"
"github.com/zeromicro/go-zero/gateway/internal"
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/rest/httpc"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc/codes"
)
const defaultHttpScheme = "http"
type (
// Server is a gateway server.
Server struct {
*rest.Server
upstreams []Upstream
conns []zrpc.Client
processHeader func(http.Header) []string
dialer func(conf zrpc.RpcClientConf) zrpc.Client
middlewares []rest.Middleware
}
// Option defines the method to customize Server.
Option func(svr *Server)
)
// MustNewServer creates a new gateway server.
func MustNewServer(c GatewayConf, opts ...Option) *Server {
svr := &Server{
upstreams: c.Upstreams,
Server: rest.MustNewServer(c.RestConf),
}
for _, opt := range opts {
opt(svr)
}
return svr
}
// Start starts the gateway server.
func (s *Server) Start() {
logx.Must(s.build())
s.Server.Start()
}
// Stop stops the gateway server.
// To get a graceful shutdown, it stops the HTTP server first, then closes gRPC connections.
func (s *Server) Stop() {
// stop the HTTP server first, then close gRPC connections.
// in case the gRPC server is stopped first,
// the HTTP server may still be running to accept requests.
s.Server.Stop()
group := threading.NewRoutineGroup()
for _, conn := range s.conns {
// new variable to avoid closure problems, can be removed after go 1.22
// see https://golang.org/doc/faq#closures_and_goroutines
conn := conn
group.Run(func() {
// ignore the error when closing the connection
_ = conn.Conn().Close()
})
}
group.Wait()
}
func (s *Server) build() error {
if err := s.ensureUpstreamNames(); err != nil {
return err
}
return mr.MapReduceVoid(func(source chan<- Upstream) {
for _, up := range s.upstreams {
source <- up
}
}, func(up Upstream, writer mr.Writer[rest.Route], cancel func(error)) {
// up.Grpc and up.Http are exclusive
if up.Grpc != nil {
s.buildGrpcRoute(up, writer, cancel)
} else if up.Http != nil {
s.buildHttpRoute(up, writer)
}
}, func(pipe <-chan rest.Route, cancel func(error)) {
for route := range pipe {
s.Server.AddRoute(route)
}
})
}
func (s *Server) buildChainHandler(handler http.HandlerFunc) http.HandlerFunc {
for i := len(s.middlewares) - 1; i >= 0; i-- {
handler = s.middlewares[i](handler)
}
return handler
}
func (s *Server) buildGrpcHandler(source grpcurl.DescriptorSource, resolver jsonpb.AnyResolver,
cli zrpc.Client, rpcPath string) func(http.ResponseWriter, *http.Request) {
handler := func(w http.ResponseWriter, r *http.Request) {
parser, err := internal.NewRequestParser(r, resolver)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
w.Header().Set(httpx.ContentType, httpx.JsonContentType)
handler := internal.NewEventHandler(w, resolver)
if err := grpcurl.InvokeRPC(r.Context(), source, cli.Conn(), rpcPath, s.prepareMetadata(r.Header),
handler, parser.Next); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
}
st := handler.Status
if st.Code() != codes.OK {
httpx.ErrorCtx(r.Context(), w, st.Err())
}
}
return s.buildChainHandler(handler)
}
func (s *Server) buildGrpcRoute(up Upstream, writer mr.Writer[rest.Route], cancel func(error)) {
var cli zrpc.Client
if s.dialer != nil {
cli = s.dialer(*up.Grpc)
} else {
cli = zrpc.MustNewClient(*up.Grpc)
}
s.conns = append(s.conns, cli)
source, err := createDescriptorSource(cli, up)
if err != nil {
cancel(fmt.Errorf("%s: %w", up.Name, err))
return
}
methods, err := internal.GetMethods(source)
if err != nil {
cancel(fmt.Errorf("%s: %w", up.Name, err))
return
}
resolver := grpcurl.AnyResolverFromDescriptorSource(source)
for _, m := range methods {
if len(m.HttpMethod) > 0 && len(m.HttpPath) > 0 {
writer.Write(rest.Route{
Method: m.HttpMethod,
Path: m.HttpPath,
Handler: s.buildGrpcHandler(source, resolver, cli, m.RpcPath),
})
}
}
methodSet := make(map[string]struct{})
for _, m := range methods {
methodSet[m.RpcPath] = struct{}{}
}
for _, m := range up.Mappings {
if _, ok := methodSet[m.RpcPath]; !ok {
cancel(fmt.Errorf("%s: rpc method %s not found", up.Name, m.RpcPath))
return
}
writer.Write(rest.Route{
Method: strings.ToUpper(m.Method),
Path: m.Path,
Handler: s.buildGrpcHandler(source, resolver, cli, m.RpcPath),
})
}
}
func (s *Server) buildHttpHandler(target *HttpClientConf) http.HandlerFunc {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(httpx.ContentType, httpx.JsonContentType)
req, err := buildRequestWithNewTarget(r, target)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
// set the timeout if it's configured, take effect only if it's greater than 0
// and less than the deadline of the original request
if target.Timeout > 0 {
timeout := time.Duration(target.Timeout) * time.Millisecond
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
req = req.WithContext(ctx)
}
resp, err := httpc.DoRequest(req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
defer resp.Body.Close()
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)
if _, err = io.Copy(w, resp.Body); err != nil {
// log the error with original request info
logc.Error(r.Context(), err)
}
}
return s.buildChainHandler(handler)
}
func (s *Server) buildHttpRoute(up Upstream, writer mr.Writer[rest.Route]) {
for _, m := range up.Mappings {
writer.Write(rest.Route{
Method: strings.ToUpper(m.Method),
Path: m.Path,
Handler: s.buildHttpHandler(up.Http),
})
}
}
func (s *Server) ensureUpstreamNames() error {
for i := 0; i < len(s.upstreams); i++ {
if len(s.upstreams[i].Name) > 0 {
continue
}
if s.upstreams[i].Grpc != nil {
target, err := s.upstreams[i].Grpc.BuildTarget()
if err != nil {
return err
}
s.upstreams[i].Name = target
} else if s.upstreams[i].Http != nil {
s.upstreams[i].Name = s.upstreams[i].Http.Target
}
}
return nil
}
func (s *Server) prepareMetadata(header http.Header) []string {
vals := internal.ProcessHeaders(header)
if s.processHeader != nil {
vals = append(vals, s.processHeader(header)...)
}
return vals
}
// WithHeaderProcessor sets a processor to process request headers.
// The returned headers are used as metadata to invoke the RPC.
func WithHeaderProcessor(processHeader func(http.Header) []string) func(*Server) {
return func(s *Server) {
s.processHeader = processHeader
}
}
// WithMiddleware adds one or more middleware functions to process HTTP requests.
// Multiple middlewares will be executed in the order they were passed (like an onion model).
func WithMiddleware(middlewares ...rest.Middleware) func(*Server) {
return func(s *Server) {
s.middlewares = append(s.middlewares, middlewares...)
}
}
func buildRequestWithNewTarget(r *http.Request, target *HttpClientConf) (*http.Request, error) {
u := *r.URL
u.Host = target.Target
if len(u.Scheme) == 0 {
u.Scheme = defaultHttpScheme
}
if len(target.Prefix) > 0 {
var err error
u.Path, err = url.JoinPath(target.Prefix, u.Path)
if err != nil {
return nil, err
}
}
newReq := &http.Request{
Method: r.Method,
URL: &u,
Header: r.Header.Clone(),
Proto: r.Proto,
ProtoMajor: r.ProtoMajor,
ProtoMinor: r.ProtoMinor,
ContentLength: r.ContentLength,
Body: io.NopCloser(r.Body),
}
// make sure the context is passed to the new request
return newReq.WithContext(r.Context()), nil
}
func createDescriptorSource(cli zrpc.Client, up Upstream) (grpcurl.DescriptorSource, error) {
var source grpcurl.DescriptorSource
var err error
if len(up.ProtoSets) > 0 {
source, err = grpcurl.DescriptorSourceFromProtoSets(up.ProtoSets...)
if err != nil {
return nil, err
}
} else {
client := grpcreflect.NewClientAuto(context.Background(), cli.Conn())
source = grpcurl.DescriptorSourceFromServer(context.Background(), client)
}
return source, nil
}
// withDialer sets a dialer to create a gRPC client.
func withDialer(dialer func(conf zrpc.RpcClientConf) zrpc.Client) func(*Server) {
return func(s *Server) {
s.dialer = dialer
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/eventhandler_test.go | gateway/internal/eventhandler_test.go | package internal
import (
"io"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func TestEventHandler(t *testing.T) {
h := NewEventHandler(io.Discard, nil)
h.OnResolveMethod(nil)
h.OnSendHeaders(nil)
h.OnReceiveHeaders(nil)
h.OnReceiveTrailers(status.New(codes.OK, ""), nil)
assert.Equal(t, codes.OK, h.Status.Code())
h.OnReceiveResponse(nil)
}
func TestEventHandler_OnReceiveTrailers(t *testing.T) {
tests := []struct {
name string
writer io.Writer
status *status.Status
metadata metadata.MD
expectedStatus codes.Code
expectedHeader map[string][]string
}{
{
name: "with http.ResponseWriter and metadata",
writer: httptest.NewRecorder(),
status: status.New(codes.OK, "success"),
metadata: metadata.MD{
"x-custom-header": []string{"value1", "value2"},
"x-another-header": []string{"single-value"},
},
expectedStatus: codes.OK,
expectedHeader: map[string][]string{
"Grpc-Trailer-X-Custom-Header": {"value1", "value2"},
"Grpc-Trailer-X-Another-Header": {"single-value"},
},
},
{
name: "with http.ResponseWriter and nil metadata",
writer: httptest.NewRecorder(),
status: status.New(codes.Internal, "error"),
metadata: nil,
expectedStatus: codes.Internal,
expectedHeader: map[string][]string{},
},
{
name: "with non-http.ResponseWriter",
writer: io.Discard,
status: status.New(codes.OK, "success"),
metadata: metadata.MD{"x-header": []string{"value"}},
expectedStatus: codes.OK,
expectedHeader: nil, // headers should not be set
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := NewEventHandler(tt.writer, nil)
h.OnReceiveTrailers(tt.status, tt.metadata)
// Check status is set correctly
assert.Equal(t, tt.expectedStatus, h.Status.Code())
// Check headers are set correctly if writer is http.ResponseWriter
if recorder, ok := tt.writer.(*httptest.ResponseRecorder); ok {
if tt.expectedHeader != nil {
for key, expectedValues := range tt.expectedHeader {
actualValues := recorder.Header()[key]
assert.Equal(t, expectedValues, actualValues, "Header %s should match", key)
}
}
}
})
}
}
func TestEventHandler_OnReceiveHeaders(t *testing.T) {
tests := []struct {
name string
writer io.Writer
metadata metadata.MD
expectedHeader map[string][]string
}{
{
name: "with http.ResponseWriter and metadata",
writer: httptest.NewRecorder(),
metadata: metadata.MD{
"content-type": []string{"application/json"},
"x-custom-header": []string{"value1", "value2"},
"x-another-header": []string{"single-value"},
},
expectedHeader: map[string][]string{
"Grpc-Metadata-Content-Type": {"application/json"},
"Grpc-Metadata-X-Custom-Header": {"value1", "value2"},
"Grpc-Metadata-X-Another-Header": {"single-value"},
},
},
{
name: "with http.ResponseWriter and nil metadata",
writer: httptest.NewRecorder(),
metadata: nil,
expectedHeader: map[string][]string{},
},
{
name: "with http.ResponseWriter and empty metadata",
writer: httptest.NewRecorder(),
metadata: metadata.MD{},
expectedHeader: map[string][]string{},
},
{
name: "with non-http.ResponseWriter",
writer: io.Discard,
metadata: metadata.MD{"x-header": []string{"value"}},
expectedHeader: nil, // headers should not be set
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := NewEventHandler(tt.writer, nil)
h.OnReceiveHeaders(tt.metadata)
// Check headers are set correctly if writer is http.ResponseWriter
if recorder, ok := tt.writer.(*httptest.ResponseRecorder); ok {
if tt.expectedHeader != nil {
for key, expectedValues := range tt.expectedHeader {
actualValues := recorder.Header()[key]
assert.Equal(t, expectedValues, actualValues, "Header %s should match", key)
}
}
}
})
}
}
func TestEventHandler_OnReceiveHeaders_MultipleValues(t *testing.T) {
recorder := httptest.NewRecorder()
h := NewEventHandler(recorder, nil)
// Test that multiple calls to OnReceiveHeaders accumulate headers
h.OnReceiveHeaders(metadata.MD{
"x-header-1": []string{"value1"},
})
h.OnReceiveHeaders(metadata.MD{
"x-header-1": []string{"value2"}, // Should add to existing header
"x-header-2": []string{"value3"},
})
// Check that headers are accumulated (not overwritten) with proper prefix
assert.Equal(t, []string{"value1", "value2"}, recorder.Header()["Grpc-Metadata-X-Header-1"])
assert.Equal(t, []string{"value3"}, recorder.Header()["Grpc-Metadata-X-Header-2"])
}
func TestEventHandler_OnReceiveHeaders_MetadataPrefix(t *testing.T) {
tests := []struct {
name string
metadata metadata.MD
expectedHeader map[string][]string
}{
{
name: "all metadata headers should be prefixed with Grpc-Metadata-",
metadata: metadata.MD{
"content-type": []string{"application/grpc"},
"x-custom-header": []string{"value1"},
"authorization": []string{"Bearer token"},
},
expectedHeader: map[string][]string{
"Grpc-Metadata-Content-Type": {"application/grpc"},
"Grpc-Metadata-X-Custom-Header": {"value1"},
"Grpc-Metadata-Authorization": {"Bearer token"},
},
},
{
name: "mixed case headers should be prefixed",
metadata: metadata.MD{
"Content-Type": []string{"APPLICATION/JSON"},
"X-Custom-Header": []string{"value1"},
},
expectedHeader: map[string][]string{
"Grpc-Metadata-Content-Type": {"APPLICATION/JSON"},
"Grpc-Metadata-X-Custom-Header": {"value1"},
},
},
{
name: "multiple values for same header",
metadata: metadata.MD{
"x-multi-header": []string{"value1", "value2", "value3"},
},
expectedHeader: map[string][]string{
"Grpc-Metadata-X-Multi-Header": {"value1", "value2", "value3"},
},
},
{
name: "empty metadata",
metadata: metadata.MD{},
expectedHeader: map[string][]string{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
h := NewEventHandler(recorder, nil)
h.OnReceiveHeaders(tt.metadata)
// Check that headers are set correctly
for key, expectedValues := range tt.expectedHeader {
actualValues := recorder.Header()[key]
assert.Equal(t, expectedValues, actualValues, "Header %s should match", key)
}
// Ensure no unexpected headers are set
for actualKey := range recorder.Header() {
found := false
for expectedKey := range tt.expectedHeader {
if actualKey == expectedKey {
found = true
break
}
}
assert.True(t, found, "Unexpected header found: %s", actualKey)
}
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/requestparser.go | gateway/internal/requestparser.go | package internal
import (
"bytes"
"encoding/json"
"io"
"net/http"
"github.com/fullstorydev/grpcurl"
"github.com/golang/protobuf/jsonpb"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/pathvar"
)
// NewRequestParser creates a new request parser from the given http.Request and resolver.
func NewRequestParser(r *http.Request, resolver jsonpb.AnyResolver) (grpcurl.RequestParser, error) {
vars := pathvar.Vars(r)
params, err := httpx.GetFormValues(r)
if err != nil {
return nil, err
}
for k, v := range vars {
params[k] = v
}
body, ok := getBody(r)
if !ok {
return buildJsonRequestParserFromMap(params, resolver)
}
if len(params) == 0 {
return buildJsonRequestParserFromReader(body, resolver)
}
m := make(map[string]any)
if err := json.NewDecoder(body).Decode(&m); err != nil && err != io.EOF {
return nil, err
}
for k, v := range params {
m[k] = v
}
return buildJsonRequestParserFromMap(m, resolver)
}
func buildJsonRequestParserFromMap(data map[string]any, resolver jsonpb.AnyResolver) (
grpcurl.RequestParser, error) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(data); err != nil {
return nil, err
}
return buildJsonRequestParserFromReader(&buf, resolver)
}
// buildJsonRequestParserFromReader creates a JSON request parser with ignoring unknown fields.
func buildJsonRequestParserFromReader(data io.Reader, resolver jsonpb.AnyResolver) (
grpcurl.RequestParser, error) {
unmarshaler := jsonpb.Unmarshaler{
AllowUnknownFields: true,
AnyResolver: resolver,
}
return grpcurl.NewJSONRequestParserWithUnmarshaler(data, unmarshaler), nil
}
func getBody(r *http.Request) (io.Reader, bool) {
if r.Body == nil {
return nil, false
}
if r.ContentLength == 0 {
return nil, false
}
if r.ContentLength > 0 {
return r.Body, true
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, r.Body); err != nil {
return nil, false
}
if buf.Len() > 0 {
return &buf, true
}
return nil, false
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/headerprocessor.go | gateway/internal/headerprocessor.go | package internal
import (
"fmt"
"net/http"
"strings"
)
const (
metadataHeaderPrefix = "Grpc-Metadata-"
metadataPrefix = "gateway-"
)
// OpenTelemetry trace propagation headers that need to be forwarded to gRPC metadata.
// These headers are used by the W3C Trace Context standard for distributed tracing.
var traceHeaders = map[string]bool{
"traceparent": true,
"tracestate": true,
"baggage": true,
}
// ProcessHeaders builds the headers for the gateway from HTTP headers.
// It forwards both custom metadata headers (with Grpc-Metadata- prefix)
// and OpenTelemetry trace propagation headers (traceparent, tracestate, baggage)
// to ensure distributed tracing works correctly across the gateway.
func ProcessHeaders(header http.Header) []string {
var headers []string
for k, v := range header {
// Forward OpenTelemetry trace propagation headers
// These must be lowercase per gRPC metadata conventions
if lowerKey := strings.ToLower(k); traceHeaders[lowerKey] {
for _, vv := range v {
headers = append(headers, lowerKey+":"+vv)
}
continue
}
// Forward custom metadata headers with Grpc-Metadata- prefix
if !strings.HasPrefix(k, metadataHeaderPrefix) {
continue
}
// gRPC metadata keys are case-insensitive and stored as lowercase,
// so we lowercase the key to match gRPC conventions
trimmedKey := strings.TrimPrefix(k, metadataHeaderPrefix)
key := strings.ToLower(fmt.Sprintf("%s%s", metadataPrefix, trimmedKey))
for _, vv := range v {
headers = append(headers, key+":"+vv)
}
}
return headers
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/eventhandler.go | gateway/internal/eventhandler.go | package internal
import (
"io"
"net/http"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/jhump/protoreflect/desc"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
// MetadataHeaderPrefix is the http prefix that represents custom metadata
// parameters to or from a gRPC call.
MetadataHeaderPrefix = "Grpc-Metadata-"
// MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to
// HTTP headers in a response handled by go-zero gateway
MetadataTrailerPrefix = "Grpc-Trailer-"
)
type EventHandler struct {
Status *status.Status
writer io.Writer
marshaler jsonpb.Marshaler
}
func NewEventHandler(writer io.Writer, resolver jsonpb.AnyResolver) *EventHandler {
return &EventHandler{
writer: writer,
marshaler: jsonpb.Marshaler{
EmitDefaults: true,
AnyResolver: resolver,
},
}
}
func (h *EventHandler) OnReceiveHeaders(md metadata.MD) {
w, ok := h.writer.(http.ResponseWriter)
if ok {
for k, vs := range md {
header := defaultOutgoingHeaderMatcher(k)
for _, v := range vs {
w.Header().Add(header, v)
}
}
}
}
func (h *EventHandler) OnReceiveResponse(message proto.Message) {
if err := h.marshaler.Marshal(h.writer, message); err != nil {
logx.Error(err)
}
}
func (h *EventHandler) OnReceiveTrailers(status *status.Status, md metadata.MD) {
w, ok := h.writer.(http.ResponseWriter)
if ok {
for k, vs := range md {
header := defaultOutgoingTrailerMatcher(k)
for _, v := range vs {
w.Header().Add(header, v)
}
}
}
h.Status = status
}
func (h *EventHandler) OnResolveMethod(_ *desc.MethodDescriptor) {
}
func (h *EventHandler) OnSendHeaders(_ metadata.MD) {
}
func defaultOutgoingHeaderMatcher(key string) string {
return MetadataHeaderPrefix + key
}
func defaultOutgoingTrailerMatcher(key string) string {
return MetadataTrailerPrefix + key
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/timeout_test.go | gateway/internal/timeout_test.go | package internal
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestGetTimeout(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Set(grpcTimeoutHeader, "1s")
timeout := GetTimeout(req.Header, time.Second*5)
assert.Equal(t, time.Second, timeout)
}
func TestGetTimeoutDefault(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
timeout := GetTimeout(req.Header, time.Second*5)
assert.Equal(t, time.Second*5, timeout)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/requestparser_test.go | gateway/internal/requestparser_test.go | package internal
import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/rest/pathvar"
)
func TestNewRequestParserNoVar(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserWithVars(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req = pathvar.WithVars(req, map[string]string{"a": "b"})
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserNoVarWithBody(t *testing.T) {
req := httptest.NewRequest("GET", "/", strings.NewReader(`{"a": "b"}`))
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserWithNegativeContentLength(t *testing.T) {
req := httptest.NewRequest("GET", "/", strings.NewReader(`{"a": "b"}`))
req.ContentLength = -1
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserWithVarsWithBody(t *testing.T) {
req := httptest.NewRequest("GET", "/", strings.NewReader(`{"a": "b"}`))
req = pathvar.WithVars(req, map[string]string{"c": "d"})
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserWithVarsWithWrongBody(t *testing.T) {
req := httptest.NewRequest("GET", "/", strings.NewReader(`{"a": "b"`))
req = pathvar.WithVars(req, map[string]string{"c": "d"})
parser, err := NewRequestParser(req, nil)
assert.NotNil(t, err)
assert.Nil(t, parser)
}
func TestNewRequestParserWithForm(t *testing.T) {
req := httptest.NewRequest("GET", "/val?a=b", nil)
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserWithNilBody(t *testing.T) {
req := httptest.NewRequest("GET", "/val?a=b", http.NoBody)
req.Body = nil
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserWithBadBody(t *testing.T) {
req := httptest.NewRequest("GET", "/val?a=b", badBody{})
req.Body = badBody{}
parser, err := NewRequestParser(req, nil)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
func TestNewRequestParserWithBadForm(t *testing.T) {
req := httptest.NewRequest("GET", "/val?a%1=b", http.NoBody)
parser, err := NewRequestParser(req, nil)
assert.NotNil(t, err)
assert.Nil(t, parser)
}
func TestRequestParser_buildJsonRequestParserFromMap(t *testing.T) {
parser, err := buildJsonRequestParserFromMap(map[string]any{"a": make(chan int)}, nil)
assert.NotNil(t, err)
assert.Nil(t, parser)
}
// mockAnyResolver is a simple implementation of jsonpb.AnyResolver for testing
type mockAnyResolver struct{}
func (m *mockAnyResolver) Resolve(typeUrl string) (proto.Message, error) {
return nil, nil
}
func TestNewRequestParserWithIgnoreUnknownFields(t *testing.T) {
// Create a concrete resolver for testing
resolver := &mockAnyResolver{}
// Test case 1: No body, no vars - should work with both true and false
req1 := httptest.NewRequest("GET", "/", http.NoBody)
parser1, err1 := NewRequestParser(req1, resolver)
assert.Nil(t, err1)
assert.NotNil(t, parser1)
req2 := httptest.NewRequest("GET", "/", http.NoBody)
parser2, err2 := NewRequestParser(req2, resolver)
assert.Nil(t, err2)
assert.NotNil(t, parser2)
// Test case 2: With JSON body - tests the body parsing path
req3 := httptest.NewRequest("POST", "/", strings.NewReader(`{"field": "value"}`))
parser3, err3 := NewRequestParser(req3, resolver)
assert.Nil(t, err3)
assert.NotNil(t, parser3)
req4 := httptest.NewRequest("POST", "/", strings.NewReader(`{"field": "value"}`))
parser4, err4 := NewRequestParser(req4, resolver)
assert.Nil(t, err4)
assert.NotNil(t, parser4)
}
func TestNewRequestParserWithVarsAndIgnoreUnknownFields(t *testing.T) {
resolver := &mockAnyResolver{}
// Test with path variables and ignoreUnknownFields = true
req := httptest.NewRequest("GET", "/", http.NoBody)
req = pathvar.WithVars(req, map[string]string{"a": "b"})
parser, err := NewRequestParser(req, resolver)
assert.Nil(t, err)
assert.NotNil(t, parser)
// Test with path variables and ignoreUnknownFields = false
req2 := httptest.NewRequest("GET", "/", http.NoBody)
req2 = pathvar.WithVars(req2, map[string]string{"c": "d"})
parser2, err2 := NewRequestParser(req2, resolver)
assert.Nil(t, err2)
assert.NotNil(t, parser2)
}
func TestNewRequestParserWithBodyAndIgnoreUnknownFields(t *testing.T) {
resolver := &mockAnyResolver{}
// Test with body and ignoreUnknownFields = true
req := httptest.NewRequest("POST", "/", strings.NewReader(`{"a": "b"}`))
parser, err := NewRequestParser(req, resolver)
assert.Nil(t, err)
assert.NotNil(t, parser)
// Test with body and ignoreUnknownFields = false
req2 := httptest.NewRequest("POST", "/", strings.NewReader(`{"c": "d"}`))
parser2, err2 := NewRequestParser(req2, resolver)
assert.Nil(t, err2)
assert.NotNil(t, parser2)
}
func TestNewRequestParserWithVarsBodyAndIgnoreUnknownFields(t *testing.T) {
resolver := &mockAnyResolver{}
// Test with both path variables and body, ignoreUnknownFields = true
req := httptest.NewRequest("POST", "/", strings.NewReader(`{"a": "b"}`))
req = pathvar.WithVars(req, map[string]string{"c": "d"})
parser, err := NewRequestParser(req, resolver)
assert.Nil(t, err)
assert.NotNil(t, parser)
// Test with both path variables and body, ignoreUnknownFields = false
req2 := httptest.NewRequest("POST", "/", strings.NewReader(`{"e": "f"}`))
req2 = pathvar.WithVars(req2, map[string]string{"g": "h"})
parser2, err2 := NewRequestParser(req2, resolver)
assert.Nil(t, err2)
assert.NotNil(t, parser2)
}
func TestBuildJsonRequestParserFromMapWithIgnoreUnknownFields(t *testing.T) {
resolver := &mockAnyResolver{}
// Test buildJsonRequestParserFromMap with ignoreUnknownFields = true
data := map[string]any{"key": "value"}
parser, err := buildJsonRequestParserFromMap(data, resolver)
assert.Nil(t, err)
assert.NotNil(t, parser)
// Test buildJsonRequestParserFromMap with ignoreUnknownFields = false
parser2, err2 := buildJsonRequestParserFromMap(data, resolver)
assert.Nil(t, err2)
assert.NotNil(t, parser2)
}
func TestBuildJsonRequestParserWithUnknownFields(t *testing.T) {
resolver := &mockAnyResolver{}
// Test buildJsonRequestParserWithUnknownFields
data := strings.NewReader(`{"test": "value"}`)
parser, err := buildJsonRequestParserFromReader(data, resolver)
assert.Nil(t, err)
assert.NotNil(t, parser)
}
type badBody struct{}
func (badBody) Read([]byte) (int, error) { return 0, errors.New("something bad") }
func (badBody) Close() error { return nil }
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/timeout.go | gateway/internal/timeout.go | package internal
import (
"net/http"
"time"
)
const grpcTimeoutHeader = "Grpc-Timeout"
// GetTimeout returns the timeout from the header, if not set, returns the default timeout.
func GetTimeout(header http.Header, defaultTimeout time.Duration) time.Duration {
if timeout := header.Get(grpcTimeoutHeader); len(timeout) > 0 {
if t, err := time.ParseDuration(timeout); err == nil {
return t
}
}
return defaultTimeout
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/headerprocessor_test.go | gateway/internal/headerprocessor_test.go | package internal
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBuildHeadersNoValue(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Add("a", "b")
assert.Nil(t, ProcessHeaders(req.Header))
}
func TestBuildHeadersWithValues(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Add("grpc-metadata-a", "b")
req.Header.Add("grpc-metadata-b", "b")
assert.ElementsMatch(t, []string{"gateway-a:b", "gateway-b:b"}, ProcessHeaders(req.Header))
}
func TestProcessHeadersWithTraceContext(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
req.Header.Set("tracestate", "key1=value1,key2=value2")
req.Header.Set("baggage", "userId=alice,serverNode=DF:28")
headers := ProcessHeaders(req.Header)
assert.Len(t, headers, 3)
assert.Contains(t, headers, "traceparent:00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
assert.Contains(t, headers, "tracestate:key1=value1,key2=value2")
assert.Contains(t, headers, "baggage:userId=alice,serverNode=DF:28")
}
func TestProcessHeadersWithMixedHeaders(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
req.Header.Set("grpc-metadata-custom", "value1")
req.Header.Set("content-type", "application/json")
req.Header.Set("tracestate", "key1=value1")
headers := ProcessHeaders(req.Header)
// Should include trace headers and grpc-metadata headers, but not regular headers
assert.Len(t, headers, 3)
assert.Contains(t, headers, "traceparent:00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
assert.Contains(t, headers, "tracestate:key1=value1")
assert.Contains(t, headers, "gateway-custom:value1")
}
func TestProcessHeadersTraceparentCaseInsensitive(t *testing.T) {
tests := []struct {
name string
headerKey string
headerVal string
expectedKey string
}{
{
name: "lowercase traceparent",
headerKey: "traceparent",
headerVal: "00-trace-span-01",
expectedKey: "traceparent",
},
{
name: "uppercase Traceparent",
headerKey: "Traceparent",
headerVal: "00-trace-span-01",
expectedKey: "traceparent",
},
{
name: "mixed case TraceParent",
headerKey: "TraceParent",
headerVal: "00-trace-span-01",
expectedKey: "traceparent",
},
{
name: "lowercase tracestate",
headerKey: "tracestate",
headerVal: "key=value",
expectedKey: "tracestate",
},
{
name: "mixed case TraceState",
headerKey: "TraceState",
headerVal: "key=value",
expectedKey: "tracestate",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Set(tt.headerKey, tt.headerVal)
headers := ProcessHeaders(req.Header)
assert.Len(t, headers, 1)
assert.Contains(t, headers, tt.expectedKey+":"+tt.headerVal)
})
}
}
func TestProcessHeadersEmptyHeaders(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
headers := ProcessHeaders(req.Header)
assert.Empty(t, headers)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/descriptorsource.go | gateway/internal/descriptorsource.go | package internal
import (
"fmt"
"net/http"
"strings"
"github.com/fullstorydev/grpcurl"
"github.com/jhump/protoreflect/desc"
"google.golang.org/genproto/googleapis/api/annotations"
"google.golang.org/protobuf/proto"
)
type Method struct {
HttpMethod string
HttpPath string
RpcPath string
}
// GetMethods returns all methods of the given grpcurl.DescriptorSource.
func GetMethods(source grpcurl.DescriptorSource) ([]Method, error) {
svcs, err := source.ListServices()
if err != nil {
return nil, err
}
var methods []Method
for _, svc := range svcs {
d, err := source.FindSymbol(svc)
if err != nil {
return nil, err
}
switch val := d.(type) {
case *desc.ServiceDescriptor:
svcMethods := val.GetMethods()
for _, method := range svcMethods {
rpcPath := fmt.Sprintf("%s/%s", svc, method.GetName())
ext := proto.GetExtension(method.GetMethodOptions(), annotations.E_Http)
switch rule := ext.(type) {
case *annotations.HttpRule:
if rule == nil {
methods = append(methods, Method{
RpcPath: rpcPath,
})
continue
}
switch httpRule := rule.GetPattern().(type) {
case *annotations.HttpRule_Get:
methods = append(methods, Method{
HttpMethod: http.MethodGet,
HttpPath: adjustHttpPath(httpRule.Get),
RpcPath: rpcPath,
})
case *annotations.HttpRule_Post:
methods = append(methods, Method{
HttpMethod: http.MethodPost,
HttpPath: adjustHttpPath(httpRule.Post),
RpcPath: rpcPath,
})
case *annotations.HttpRule_Put:
methods = append(methods, Method{
HttpMethod: http.MethodPut,
HttpPath: adjustHttpPath(httpRule.Put),
RpcPath: rpcPath,
})
case *annotations.HttpRule_Delete:
methods = append(methods, Method{
HttpMethod: http.MethodDelete,
HttpPath: adjustHttpPath(httpRule.Delete),
RpcPath: rpcPath,
})
case *annotations.HttpRule_Patch:
methods = append(methods, Method{
HttpMethod: http.MethodPatch,
HttpPath: adjustHttpPath(httpRule.Patch),
RpcPath: rpcPath,
})
default:
methods = append(methods, Method{
RpcPath: rpcPath,
})
}
default:
methods = append(methods, Method{
RpcPath: rpcPath,
})
}
}
}
}
return methods, nil
}
func adjustHttpPath(path string) string {
path = strings.ReplaceAll(path, "{", ":")
path = strings.ReplaceAll(path, "}", "")
return path
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/gateway/internal/descriptorsource_test.go | gateway/internal/descriptorsource_test.go | package internal
import (
"encoding/base64"
"errors"
"net/http"
"os"
"testing"
"github.com/fullstorydev/grpcurl"
"github.com/jhump/protoreflect/desc"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/hash"
)
const (
b64pb = `CpgBCgtoZWxsby5wcm90bxIFaGVsbG8iHQoHUmVxdWVzdBISCgRwaW5nGAEgASgJUgRwaW5nIh4KCFJlc3BvbnNlEhIKBHBvbmcYASABKAlSBHBvbmcyMAoFSGVsbG8SJwoEUGluZxIOLmhlbGxvLlJlcXVlc3QaDy5oZWxsby5SZXNwb25zZUIJWgcuL2hlbGxvYgZwcm90bzM=`
b64pbWithAnnotations = `Cs4EChVnb29nbGUvYXBpL2h0dHAucHJvdG8SCmdvb2dsZS5hcGkieQoESHR0cBIqCgVydWxlcxgBIAMoCzIULmdvb2dsZS5hcGkuSHR0cFJ1bGVSBXJ1bGVzEkUKH2Z1bGx5X2RlY29kZV9yZXNlcnZlZF9leHBhbnNpb24YAiABKAhSHGZ1bGx5RGVjb2RlUmVzZXJ2ZWRFeHBhbnNpb24i2gIKCEh0dHBSdWxlEhoKCHNlbGVjdG9yGAEgASgJUghzZWxlY3RvchISCgNnZXQYAiABKAlIAFIDZ2V0EhIKA3B1dBgDIAEoCUgAUgNwdXQSFAoEcG9zdBgEIAEoCUgAUgRwb3N0EhgKBmRlbGV0ZRgFIAEoCUgAUgZkZWxldGUSFgoFcGF0Y2gYBiABKAlIAFIFcGF0Y2gSNwoGY3VzdG9tGAggASgLMh0uZ29vZ2xlLmFwaS5DdXN0b21IdHRwUGF0dGVybkgAUgZjdXN0b20SEgoEYm9keRgHIAEoCVIEYm9keRIjCg1yZXNwb25zZV9ib2R5GAwgASgJUgxyZXNwb25zZUJvZHkSRQoTYWRkaXRpb25hbF9iaW5kaW5ncxgLIAMoCzIULmdvb2dsZS5hcGkuSHR0cFJ1bGVSEmFkZGl0aW9uYWxCaW5kaW5nc0IJCgdwYXR0ZXJuIjsKEUN1c3RvbUh0dHBQYXR0ZXJuEhIKBGtpbmQYASABKAlSBGtpbmQSEgoEcGF0aBgCIAEoCVIEcGF0aEIMWgpnb29nbGUvYXBpYgZwcm90bzMK8zsKIGdvb2dsZS9wcm90b2J1Zi9kZXNjcmlwdG9yLnByb3RvEg9nb29nbGUucHJvdG9idWYiTQoRRmlsZURlc2NyaXB0b3JTZXQSOAoEZmlsZRgBIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5GaWxlRGVzY3JpcHRvclByb3RvUgRmaWxlIuQEChNGaWxlRGVzY3JpcHRvclByb3RvEhIKBG5hbWUYASABKAlSBG5hbWUSGAoHcGFja2FnZRgCIAEoCVIHcGFja2FnZRIeCgpkZXBlbmRlbmN5GAMgAygJUgpkZXBlbmRlbmN5EisKEXB1YmxpY19kZXBlbmRlbmN5GAogAygFUhBwdWJsaWNEZXBlbmRlbmN5EicKD3dlYWtfZGVwZW5kZW5jeRgLIAMoBVIOd2Vha0RlcGVuZGVuY3kSQwoMbWVzc2FnZV90eXBlGAQgAygLMiAuZ29vZ2xlLnByb3RvYnVmLkRlc2NyaXB0b3JQcm90b1ILbWVzc2FnZVR5cGUSQQoJZW51bV90eXBlGAUgAygLMiQuZ29vZ2xlLnByb3RvYnVmLkVudW1EZXNjcmlwdG9yUHJvdG9SCGVudW1UeXBlEkEKB3NlcnZpY2UYBiADKAsyJy5nb29nbGUucHJvdG9idWYuU2VydmljZURlc2NyaXB0b3JQcm90b1IHc2VydmljZRJDCglleHRlbnNpb24YByADKAsyJS5nb29nbGUucHJvdG9idWYuRmllbGREZXNjcmlwdG9yUHJvdG9SCWV4dGVuc2lvbhI2CgdvcHRpb25zGAggASgLMhwuZ29vZ2xlLnByb3RvYnVmLkZpbGVPcHRpb25zUgdvcHRpb25zEkkKEHNvdXJjZV9jb2RlX2luZm8YCSABKAsyHy5nb29nbGUucHJvdG9idWYuU291cmNlQ29kZUluZm9SDnNvdXJjZUNvZGVJbmZvEhYKBnN5bnRheBgMIAEoCVIGc3ludGF4IrkGCg9EZXNjcmlwdG9yUHJvdG8SEgoEbmFtZRgBIAEoCVIEbmFtZRI7CgVmaWVsZBgCIAMoCzIlLmdvb2dsZS5wcm90b2J1Zi5GaWVsZERlc2NyaXB0b3JQcm90b1IFZmllbGQSQwoJZXh0ZW5zaW9uGAYgAygLMiUuZ29vZ2xlLnByb3RvYnVmLkZpZWxkRGVzY3JpcHRvclByb3RvUglleHRlbnNpb24SQQoLbmVzdGVkX3R5cGUYAyADKAsyIC5nb29nbGUucHJvdG9idWYuRGVzY3JpcHRvclByb3RvUgpuZXN0ZWRUeXBlEkEKCWVudW1fdHlwZRgEIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5FbnVtRGVzY3JpcHRvclByb3RvUghlbnVtVHlwZRJYCg9leHRlbnNpb25fcmFuZ2UYBSADKAsyLy5nb29nbGUucHJvdG9idWYuRGVzY3JpcHRvclByb3RvLkV4dGVuc2lvblJhbmdlUg5leHRlbnNpb25SYW5nZRJECgpvbmVvZl9kZWNsGAggAygLMiUuZ29vZ2xlLnByb3RvYnVmLk9uZW9mRGVzY3JpcHRvclByb3RvUglvbmVvZkRlY2wSOQoHb3B0aW9ucxgHIAEoCzIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9uc1IHb3B0aW9ucxJVCg5yZXNlcnZlZF9yYW5nZRgJIAMoCzIuLmdvb2dsZS5wcm90b2J1Zi5EZXNjcmlwdG9yUHJvdG8uUmVzZXJ2ZWRSYW5nZVINcmVzZXJ2ZWRSYW5nZRIjCg1yZXNlcnZlZF9uYW1lGAogAygJUgxyZXNlcnZlZE5hbWUaegoORXh0ZW5zaW9uUmFuZ2USFAoFc3RhcnQYASABKAVSBXN0YXJ0EhAKA2VuZBgCIAEoBVIDZW5kEkAKB29wdGlvbnMYAyABKAsyJi5nb29nbGUucHJvdG9idWYuRXh0ZW5zaW9uUmFuZ2VPcHRpb25zUgdvcHRpb25zGjcKDVJlc2VydmVkUmFuZ2USFAoFc3RhcnQYASABKAVSBXN0YXJ0EhAKA2VuZBgCIAEoBVIDZW5kInwKFUV4dGVuc2lvblJhbmdlT3B0aW9ucxJYChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvblITdW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIACIsEGChRGaWVsZERlc2NyaXB0b3JQcm90bxISCgRuYW1lGAEgASgJUgRuYW1lEhYKBm51bWJlchgDIAEoBVIGbnVtYmVyEkEKBWxhYmVsGAQgASgOMisuZ29vZ2xlLnByb3RvYnVmLkZpZWxkRGVzY3JpcHRvclByb3RvLkxhYmVsUgVsYWJlbBI+CgR0eXBlGAUgASgOMiouZ29vZ2xlLnByb3RvYnVmLkZpZWxkRGVzY3JpcHRvclByb3RvLlR5cGVSBHR5cGUSGwoJdHlwZV9uYW1lGAYgASgJUgh0eXBlTmFtZRIaCghleHRlbmRlZRgCIAEoCVIIZXh0ZW5kZWUSIwoNZGVmYXVsdF92YWx1ZRgHIAEoCVIMZGVmYXVsdFZhbHVlEh8KC29uZW9mX2luZGV4GAkgASgFUgpvbmVvZkluZGV4EhsKCWpzb25fbmFtZRgKIAEoCVIIanNvbk5hbWUSNwoHb3B0aW9ucxgIIAEoCzIdLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlvbnNSB29wdGlvbnMSJwoPcHJvdG8zX29wdGlvbmFsGBEgASgIUg5wcm90bzNPcHRpb25hbCK2AgoEVHlwZRIPCgtUWVBFX0RPVUJMRRABEg4KClRZUEVfRkxPQVQQAhIOCgpUWVBFX0lOVDY0EAMSDwoLVFlQRV9VSU5UNjQQBBIOCgpUWVBFX0lOVDMyEAUSEAoMVFlQRV9GSVhFRDY0EAYSEAoMVFlQRV9GSVhFRDMyEAcSDQoJVFlQRV9CT09MEAgSDwoLVFlQRV9TVFJJTkcQCRIOCgpUWVBFX0dST1VQEAoSEAoMVFlQRV9NRVNTQUdFEAsSDgoKVFlQRV9CWVRFUxAMEg8KC1RZUEVfVUlOVDMyEA0SDQoJVFlQRV9FTlVNEA4SEQoNVFlQRV9TRklYRUQzMhAPEhEKDVRZUEVfU0ZJWEVENjQQEBIPCgtUWVBFX1NJTlQzMhAREg8KC1RZUEVfU0lOVDY0EBIiQwoFTGFiZWwSEgoOTEFCRUxfT1BUSU9OQUwQARISCg5MQUJFTF9SRVFVSVJFRBACEhIKDkxBQkVMX1JFUEVBVEVEEAMiYwoUT25lb2ZEZXNjcmlwdG9yUHJvdG8SEgoEbmFtZRgBIAEoCVIEbmFtZRI3CgdvcHRpb25zGAIgASgLMh0uZ29vZ2xlLnByb3RvYnVmLk9uZW9mT3B0aW9uc1IHb3B0aW9ucyLjAgoTRW51bURlc2NyaXB0b3JQcm90bxISCgRuYW1lGAEgASgJUgRuYW1lEj8KBXZhbHVlGAIgAygLMikuZ29vZ2xlLnByb3RvYnVmLkVudW1WYWx1ZURlc2NyaXB0b3JQcm90b1IFdmFsdWUSNgoHb3B0aW9ucxgDIAEoCzIcLmdvb2dsZS5wcm90b2J1Zi5FbnVtT3B0aW9uc1IHb3B0aW9ucxJdCg5yZXNlcnZlZF9yYW5nZRgEIAMoCzI2Lmdvb2dsZS5wcm90b2J1Zi5FbnVtRGVzY3JpcHRvclByb3RvLkVudW1SZXNlcnZlZFJhbmdlUg1yZXNlcnZlZFJhbmdlEiMKDXJlc2VydmVkX25hbWUYBSADKAlSDHJlc2VydmVkTmFtZRo7ChFFbnVtUmVzZXJ2ZWRSYW5nZRIUCgVzdGFydBgBIAEoBVIFc3RhcnQSEAoDZW5kGAIgASgFUgNlbmQigwEKGEVudW1WYWx1ZURlc2NyaXB0b3JQcm90bxISCgRuYW1lGAEgASgJUgRuYW1lEhYKBm51bWJlchgCIAEoBVIGbnVtYmVyEjsKB29wdGlvbnMYAyABKAsyIS5nb29nbGUucHJvdG9idWYuRW51bVZhbHVlT3B0aW9uc1IHb3B0aW9ucyKnAQoWU2VydmljZURlc2NyaXB0b3JQcm90bxISCgRuYW1lGAEgASgJUgRuYW1lEj4KBm1ldGhvZBgCIAMoCzImLmdvb2dsZS5wcm90b2J1Zi5NZXRob2REZXNjcmlwdG9yUHJvdG9SBm1ldGhvZBI5CgdvcHRpb25zGAMgASgLMh8uZ29vZ2xlLnByb3RvYnVmLlNlcnZpY2VPcHRpb25zUgdvcHRpb25zIokCChVNZXRob2REZXNjcmlwdG9yUHJvdG8SEgoEbmFtZRgBIAEoCVIEbmFtZRIdCgppbnB1dF90eXBlGAIgASgJUglpbnB1dFR5cGUSHwoLb3V0cHV0X3R5cGUYAyABKAlSCm91dHB1dFR5cGUSOAoHb3B0aW9ucxgEIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zUgdvcHRpb25zEjAKEGNsaWVudF9zdHJlYW1pbmcYBSABKAg6BWZhbHNlUg9jbGllbnRTdHJlYW1pbmcSMAoQc2VydmVyX3N0cmVhbWluZxgGIAEoCDoFZmFsc2VSD3NlcnZlclN0cmVhbWluZyKRCQoLRmlsZU9wdGlvbnMSIQoMamF2YV9wYWNrYWdlGAEgASgJUgtqYXZhUGFja2FnZRIwChRqYXZhX291dGVyX2NsYXNzbmFtZRgIIAEoCVISamF2YU91dGVyQ2xhc3NuYW1lEjUKE2phdmFfbXVsdGlwbGVfZmlsZXMYCiABKAg6BWZhbHNlUhFqYXZhTXVsdGlwbGVGaWxlcxJECh1qYXZhX2dlbmVyYXRlX2VxdWFsc19hbmRfaGFzaBgUIAEoCEICGAFSGWphdmFHZW5lcmF0ZUVxdWFsc0FuZEhhc2gSOgoWamF2YV9zdHJpbmdfY2hlY2tfdXRmOBgbIAEoCDoFZmFsc2VSE2phdmFTdHJpbmdDaGVja1V0ZjgSUwoMb3B0aW1pemVfZm9yGAkgASgOMikuZ29vZ2xlLnByb3RvYnVmLkZpbGVPcHRpb25zLk9wdGltaXplTW9kZToFU1BFRURSC29wdGltaXplRm9yEh0KCmdvX3BhY2thZ2UYCyABKAlSCWdvUGFja2FnZRI1ChNjY19nZW5lcmljX3NlcnZpY2VzGBAgASgIOgVmYWxzZVIRY2NHZW5lcmljU2VydmljZXMSOQoVamF2YV9nZW5lcmljX3NlcnZpY2VzGBEgASgIOgVmYWxzZVITamF2YUdlbmVyaWNTZXJ2aWNlcxI1ChNweV9nZW5lcmljX3NlcnZpY2VzGBIgASgIOgVmYWxzZVIRcHlHZW5lcmljU2VydmljZXMSNwoUcGhwX2dlbmVyaWNfc2VydmljZXMYKiABKAg6BWZhbHNlUhJwaHBHZW5lcmljU2VydmljZXMSJQoKZGVwcmVjYXRlZBgXIAEoCDoFZmFsc2VSCmRlcHJlY2F0ZWQSLgoQY2NfZW5hYmxlX2FyZW5hcxgfIAEoCDoEdHJ1ZVIOY2NFbmFibGVBcmVuYXMSKgoRb2JqY19jbGFzc19wcmVmaXgYJCABKAlSD29iamNDbGFzc1ByZWZpeBIpChBjc2hhcnBfbmFtZXNwYWNlGCUgASgJUg9jc2hhcnBOYW1lc3BhY2USIQoMc3dpZnRfcHJlZml4GCcgASgJUgtzd2lmdFByZWZpeBIoChBwaHBfY2xhc3NfcHJlZml4GCggASgJUg5waHBDbGFzc1ByZWZpeBIjCg1waHBfbmFtZXNwYWNlGCkgASgJUgxwaHBOYW1lc3BhY2USNAoWcGhwX21ldGFkYXRhX25hbWVzcGFjZRgsIAEoCVIUcGhwTWV0YWRhdGFOYW1lc3BhY2USIQoMcnVieV9wYWNrYWdlGC0gASgJUgtydWJ5UGFja2FnZRJYChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvblITdW5pbnRlcnByZXRlZE9wdGlvbiI6CgxPcHRpbWl6ZU1vZGUSCQoFU1BFRUQQARINCglDT0RFX1NJWkUQAhIQCgxMSVRFX1JVTlRJTUUQAyoJCOgHEICAgIACSgQIJhAnIuMCCg5NZXNzYWdlT3B0aW9ucxI8ChdtZXNzYWdlX3NldF93aXJlX2Zvcm1hdBgBIAEoCDoFZmFsc2VSFG1lc3NhZ2VTZXRXaXJlRm9ybWF0EkwKH25vX3N0YW5kYXJkX2Rlc2NyaXB0b3JfYWNjZXNzb3IYAiABKAg6BWZhbHNlUhxub1N0YW5kYXJkRGVzY3JpcHRvckFjY2Vzc29yEiUKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlUgpkZXByZWNhdGVkEhsKCW1hcF9lbnRyeRgHIAEoCFIIbWFwRW50cnkSWAoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb25SE3VuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAQQBUoECAUQBkoECAYQB0oECAgQCUoECAkQCiKSBAoMRmllbGRPcHRpb25zEkEKBWN0eXBlGAEgASgOMiMuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlwZToGU1RSSU5HUgVjdHlwZRIWCgZwYWNrZWQYAiABKAhSBnBhY2tlZBJHCgZqc3R5cGUYBiABKA4yJC5nb29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zLkpTVHlwZToJSlNfTk9STUFMUgZqc3R5cGUSGQoEbGF6eRgFIAEoCDoFZmFsc2VSBGxhenkSLgoPdW52ZXJpZmllZF9sYXp5GA8gASgIOgVmYWxzZVIOdW52ZXJpZmllZExhenkSJQoKZGVwcmVjYXRlZBgDIAEoCDoFZmFsc2VSCmRlcHJlY2F0ZWQSGQoEd2VhaxgKIAEoCDoFZmFsc2VSBHdlYWsSWAoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb25SE3VuaW50ZXJwcmV0ZWRPcHRpb24iLwoFQ1R5cGUSCgoGU1RSSU5HEAASCAoEQ09SRBABEhAKDFNUUklOR19QSUVDRRACIjUKBkpTVHlwZRINCglKU19OT1JNQUwQABINCglKU19TVFJJTkcQARINCglKU19OVU1CRVIQAioJCOgHEICAgIACSgQIBBAFInMKDE9uZW9mT3B0aW9ucxJYChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvblITdW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIACIsABCgtFbnVtT3B0aW9ucxIfCgthbGxvd19hbGlhcxgCIAEoCFIKYWxsb3dBbGlhcxIlCgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZVIKZGVwcmVjYXRlZBJYChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvblITdW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIACSgQIBRAGIp4BChBFbnVtVmFsdWVPcHRpb25zEiUKCmRlcHJlY2F0ZWQYASABKAg6BWZhbHNlUgpkZXByZWNhdGVkElgKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uUhN1bmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIinAEKDlNlcnZpY2VPcHRpb25zEiUKCmRlcHJlY2F0ZWQYISABKAg6BWZhbHNlUgpkZXByZWNhdGVkElgKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uUhN1bmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi4AIKDU1ldGhvZE9wdGlvbnMSJQoKZGVwcmVjYXRlZBghIAEoCDoFZmFsc2VSCmRlcHJlY2F0ZWQScQoRaWRlbXBvdGVuY3lfbGV2ZWwYIiABKA4yLy5nb29nbGUucHJvdG9idWYuTWV0aG9kT3B0aW9ucy5JZGVtcG90ZW5jeUxldmVsOhNJREVNUE9URU5DWV9VTktOT1dOUhBpZGVtcG90ZW5jeUxldmVsElgKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uUhN1bmludGVycHJldGVkT3B0aW9uIlAKEElkZW1wb3RlbmN5TGV2ZWwSFwoTSURFTVBPVEVOQ1lfVU5LTk9XThAAEhMKD05PX1NJREVfRUZGRUNUUxABEg4KCklERU1QT1RFTlQQAioJCOgHEICAgIACIpoDChNVbmludGVycHJldGVkT3B0aW9uEkEKBG5hbWUYAiADKAsyLS5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbi5OYW1lUGFydFIEbmFtZRIpChBpZGVudGlmaWVyX3ZhbHVlGAMgASgJUg9pZGVudGlmaWVyVmFsdWUSLAoScG9zaXRpdmVfaW50X3ZhbHVlGAQgASgEUhBwb3NpdGl2ZUludFZhbHVlEiwKEm5lZ2F0aXZlX2ludF92YWx1ZRgFIAEoA1IQbmVnYXRpdmVJbnRWYWx1ZRIhCgxkb3VibGVfdmFsdWUYBiABKAFSC2RvdWJsZVZhbHVlEiEKDHN0cmluZ192YWx1ZRgHIAEoDFILc3RyaW5nVmFsdWUSJwoPYWdncmVnYXRlX3ZhbHVlGAggASgJUg5hZ2dyZWdhdGVWYWx1ZRpKCghOYW1lUGFydBIbCgluYW1lX3BhcnQYASACKAlSCG5hbWVQYXJ0EiEKDGlzX2V4dGVuc2lvbhgCIAIoCFILaXNFeHRlbnNpb24ipwIKDlNvdXJjZUNvZGVJbmZvEkQKCGxvY2F0aW9uGAEgAygLMiguZ29vZ2xlLnByb3RvYnVmLlNvdXJjZUNvZGVJbmZvLkxvY2F0aW9uUghsb2NhdGlvbhrOAQoITG9jYXRpb24SFgoEcGF0aBgBIAMoBUICEAFSBHBhdGgSFgoEc3BhbhgCIAMoBUICEAFSBHNwYW4SKQoQbGVhZGluZ19jb21tZW50cxgDIAEoCVIPbGVhZGluZ0NvbW1lbnRzEisKEXRyYWlsaW5nX2NvbW1lbnRzGAQgASgJUhB0cmFpbGluZ0NvbW1lbnRzEjoKGWxlYWRpbmdfZGV0YWNoZWRfY29tbWVudHMYBiADKAlSF2xlYWRpbmdEZXRhY2hlZENvbW1lbnRzItEBChFHZW5lcmF0ZWRDb2RlSW5mbxJNCgphbm5vdGF0aW9uGAEgAygLMi0uZ29vZ2xlLnByb3RvYnVmLkdlbmVyYXRlZENvZGVJbmZvLkFubm90YXRpb25SCmFubm90YXRpb24abQoKQW5ub3RhdGlvbhIWCgRwYXRoGAEgAygFQgIQAVIEcGF0aBIfCgtzb3VyY2VfZmlsZRgCIAEoCVIKc291cmNlRmlsZRIUCgViZWdpbhgDIAEoBVIFYmVnaW4SEAoDZW5kGAQgASgFUgNlbmRCfgoTY29tLmdvb2dsZS5wcm90b2J1ZkIQRGVzY3JpcHRvclByb3Rvc0gBWi1nb29nbGUuZ29sYW5nLm9yZy9wcm90b2J1Zi90eXBlcy9kZXNjcmlwdG9ycGL4AQGiAgNHUEKqAhpHb29nbGUuUHJvdG9idWYuUmVmbGVjdGlvbgrYAQocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxIKZ29vZ2xlLmFwaRoVZ29vZ2xlL2FwaS9odHRwLnByb3RvGiBnb29nbGUvcHJvdG9idWYvZGVzY3JpcHRvci5wcm90bzpLCgRodHRwEh4uZ29vZ2xlLnByb3RvYnVmLk1ldGhvZE9wdGlvbnMYsMq8IiABKAsyFC5nb29nbGUuYXBpLkh0dHBSdWxlUgRodHRwQh5aHHByb3RvL3RoaXJkX3BhcnR5L2dvb2dsZS9hcGliBnByb3RvMwrcAwoHYS5wcm90bxIFaGVsbG8aHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8iHQoHUmVxdWVzdBISCgRwaW5nGAEgASgJUgRwaW5nIh4KCFJlc3BvbnNlEhIKBHBvbmcYASABKAlSBHBvbmcy2QIKBUhlbGxvEkQKB1BpbmdHZXQSDi5oZWxsby5SZXF1ZXN0Gg8uaGVsbG8uUmVzcG9uc2UiGILT5JMCEhINL3YxL2dldC97Zm9vfToBKhJACghQaW5nUG9zdBIOLmhlbGxvLlJlcXVlc3QaDy5oZWxsby5SZXNwb25zZSITgtPkkwINIggvdjEvcG9zdDoBKhI+CgdQaW5nUHV0Eg4uaGVsbG8uUmVxdWVzdBoPLmhlbGxvLlJlc3BvbnNlIhKC0+STAgwaBy92MS9wdXQ6ASoSRAoKUGluZ0RlbGV0ZRIOLmhlbGxvLlJlcXVlc3QaDy5oZWxsby5SZXNwb25zZSIVgtPkkwIPKgovdjEvZGVsZXRlOgEqEkIKCVBpbmdQYXRjaBIOLmhlbGxvLlJlcXVlc3QaDy5oZWxsby5SZXNwb25zZSIUgtPkkwIOMgkvdjEvcGF0Y2g6ASpCCVoHLi9oZWxsb2IGcHJvdG8z`
)
func TestGetMethods(t *testing.T) {
tmpfile, err := os.CreateTemp(os.TempDir(), hash.Md5Hex([]byte(b64pb)))
assert.Nil(t, err)
b, err := base64.StdEncoding.DecodeString(b64pb)
assert.Nil(t, err)
assert.Nil(t, os.WriteFile(tmpfile.Name(), b, os.ModeTemporary))
defer os.Remove(tmpfile.Name())
source, err := grpcurl.DescriptorSourceFromProtoSets(tmpfile.Name())
assert.Nil(t, err)
methods, err := GetMethods(source)
assert.Nil(t, err)
assert.EqualValues(t, []Method{
{
RpcPath: "hello.Hello/Ping",
},
}, methods)
}
func TestGetMethodsWithAnnotations(t *testing.T) {
tmpfile, err := os.CreateTemp(os.TempDir(), hash.Md5Hex([]byte(b64pb)))
assert.Nil(t, err)
b, err := base64.StdEncoding.DecodeString(b64pbWithAnnotations)
assert.Nil(t, err)
assert.Nil(t, os.WriteFile(tmpfile.Name(), b, os.ModeTemporary))
defer os.Remove(tmpfile.Name())
source, err := grpcurl.DescriptorSourceFromProtoSets(tmpfile.Name())
assert.Nil(t, err)
methods, err := GetMethods(source)
assert.Nil(t, err)
assert.EqualValues(t, []Method{
{
HttpMethod: http.MethodGet,
HttpPath: "/v1/get/:foo",
RpcPath: "hello.Hello/PingGet",
},
{
HttpMethod: http.MethodPost,
HttpPath: "/v1/post",
RpcPath: "hello.Hello/PingPost",
},
{
HttpMethod: http.MethodPut,
HttpPath: "/v1/put",
RpcPath: "hello.Hello/PingPut",
},
{
HttpMethod: http.MethodDelete,
HttpPath: "/v1/delete",
RpcPath: "hello.Hello/PingDelete",
},
{
HttpMethod: http.MethodPatch,
HttpPath: "/v1/patch",
RpcPath: "hello.Hello/PingPatch",
},
}, methods)
}
func TestGetMethodsBadCases(t *testing.T) {
t.Run("no services", func(t *testing.T) {
source := &mockDescriptorSource{
servicesErr: errors.New("no services"),
}
_, err := GetMethods(source)
assert.NotNil(t, err)
})
t.Run("no symbol in services", func(t *testing.T) {
source := &mockDescriptorSource{
services: []string{"hello.Hello"},
symbolErr: errors.New("no symbol"),
}
_, err := GetMethods(source)
assert.NotNil(t, err)
})
t.Run("no symbol in services", func(t *testing.T) {
source := &mockDescriptorSource{
services: []string{"hello.Hello"},
symbolErr: errors.New("no symbol"),
}
_, err := GetMethods(source)
assert.NotNil(t, err)
})
}
type mockDescriptorSource struct {
symbolDesc desc.Descriptor
symbolErr error
services []string
servicesErr error
}
func (m *mockDescriptorSource) AllExtensionsForType(_ string) ([]*desc.FieldDescriptor, error) {
return nil, nil
}
func (m *mockDescriptorSource) FindSymbol(_ string) (desc.Descriptor, error) {
return m.symbolDesc, m.symbolErr
}
func (m *mockDescriptorSource) ListServices() ([]string, error) {
return m.services, m.servicesErr
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/encoding/encoding_test.go | internal/encoding/encoding_test.go | package encoding
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTomlToJson(t *testing.T) {
tests := []struct {
input string
expect string
}{
{
input: "a = \"foo\"\nb = 1\nc = \"${FOO}\"\nd = \"abcd!@#$112\"",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a = \"foo\"\nb = 1\nc = \"${FOO}\"\nd = \"abcd!@#$112\"",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a = \"foo\"\nb = 1\nc = \"${FOO}\"\nd = \"abcd!@#$112\"",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a = \"foo\"\nb = 1\nc = \"${FOO}\"\nd = \"abcd!@#$112\"",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a = \"foo\"\nb = 1\nc = \"${FOO}\"\nd = \"abcd!@#$112\"",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a = \"foo\"\nb = 1\nc = \"${FOO}\"\nd = \"abcd!@#$112\"\n",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a = \"foo\"\nb = 1\nc = \"${FOO}\"\nd = \"abcd!@#$112\"\n",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
}
for _, test := range tests {
test := test
t.Run(test.input, func(t *testing.T) {
t.Parallel()
got, err := TomlToJson([]byte(test.input))
assert.NoError(t, err)
assert.Equal(t, test.expect, string(got))
})
}
}
func TestTomlToJsonError(t *testing.T) {
_, err := TomlToJson([]byte("foo"))
assert.Error(t, err)
}
func TestYamlToJson(t *testing.T) {
tests := []struct {
input string
expect string
}{
{
input: "a: foo\nb: 1\nc: ${FOO}\nd: abcd!@#$112",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a: foo\nb: 1\nc: ${FOO}\nd: abcd!@#$112",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a: foo\nb: 1\nc: ${FOO}\nd: abcd!@#$112",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a: foo\nb: 1\nc: ${FOO}\nd: abcd!@#$112",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a: foo\nb: 1\nc: ${FOO}\nd: abcd!@#$112",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a: foo\nb: 1\nc: ${FOO}\nd: abcd!@#$112\n",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
{
input: "a: foo\nb: 1\nc: ${FOO}\nd: abcd!@#$112\n",
expect: "{\"a\":\"foo\",\"b\":1,\"c\":\"${FOO}\",\"d\":\"abcd!@#$112\"}\n",
},
}
for _, test := range tests {
test := test
t.Run(test.input, func(t *testing.T) {
t.Parallel()
got, err := YamlToJson([]byte(test.input))
assert.NoError(t, err)
assert.Equal(t, test.expect, string(got))
})
}
}
func TestYamlToJsonError(t *testing.T) {
_, err := YamlToJson([]byte("':foo"))
assert.Error(t, err)
}
func TestYamlToJsonSlice(t *testing.T) {
b, err := YamlToJson([]byte(`foo:
- bar
- baz`))
assert.NoError(t, err)
assert.Equal(t, `{"foo":["bar","baz"]}
`, string(b))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/encoding/encoding.go | internal/encoding/encoding.go | package encoding
import (
"bytes"
"encoding/json"
"github.com/pelletier/go-toml/v2"
"github.com/zeromicro/go-zero/core/lang"
"gopkg.in/yaml.v2"
)
// TomlToJson converts TOML data into its JSON representation.
func TomlToJson(data []byte) ([]byte, error) {
var val any
if err := toml.NewDecoder(bytes.NewReader(data)).Decode(&val); err != nil {
return nil, err
}
return encodeToJSON(val)
}
// YamlToJson converts YAML data into its JSON representation.
func YamlToJson(data []byte) ([]byte, error) {
var val any
if err := yaml.Unmarshal(data, &val); err != nil {
return nil, err
}
return encodeToJSON(toStringKeyMap(val))
}
// convertKeyToString ensures all keys of the map are of type string.
func convertKeyToString(in map[any]any) map[string]any {
res := make(map[string]any)
for k, v := range in {
res[lang.Repr(k)] = toStringKeyMap(v)
}
return res
}
// convertNumberToJsonNumber converts numbers into json.Number type for compatibility.
func convertNumberToJsonNumber(in any) json.Number {
return json.Number(lang.Repr(in))
}
// convertSlice processes slice items to ensure key compatibility.
func convertSlice(in []any) []any {
res := make([]any, len(in))
for i, v := range in {
res[i] = toStringKeyMap(v)
}
return res
}
// encodeToJSON encodes the given value into its JSON representation.
func encodeToJSON(val any) ([]byte, error) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(val); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// toStringKeyMap processes the data to ensure that all map keys are of type string.
func toStringKeyMap(v any) any {
switch v := v.(type) {
case []any:
return convertSlice(v)
case map[any]any:
return convertKeyToString(v)
case bool, string:
return v
case int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64, float32, float64:
return convertNumberToJsonNumber(v)
default:
return lang.Repr(v)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/health/health.go | internal/health/health.go | package health
import (
"fmt"
"net/http"
"strings"
"sync"
"github.com/zeromicro/go-zero/core/syncx"
)
// defaultHealthManager is global comboHealthManager.
var defaultHealthManager = newComboHealthManager()
type (
// Probe represents readiness status of a given component.
Probe interface {
// MarkReady sets a ready state for the endpoint handlers.
MarkReady()
// MarkNotReady sets a not ready state for the endpoint handlers.
MarkNotReady()
// IsReady return inner state for the component.
IsReady() bool
// Name return probe name identifier
Name() string
}
// healthManager manage app healthy.
healthManager struct {
ready syncx.AtomicBool
name string
}
// comboHealthManager folds given probes into one, reflects their statuses in a thread-safe way.
comboHealthManager struct {
mu sync.Mutex
probes []Probe
}
)
// AddProbe add components probe to global comboHealthManager.
func AddProbe(probe Probe) {
defaultHealthManager.addProbe(probe)
}
// CreateHttpHandler creates a health http handler based on the given probe.
func CreateHttpHandler(healthResponse string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
if defaultHealthManager.IsReady() {
_, _ = w.Write([]byte(healthResponse))
} else {
http.Error(w, "Service Unavailable\n"+defaultHealthManager.verboseInfo(),
http.StatusServiceUnavailable)
}
}
}
// NewHealthManager returns a new healthManager.
func NewHealthManager(name string) Probe {
return &healthManager{
name: name,
}
}
// MarkReady sets a ready state for the endpoint handlers.
func (h *healthManager) MarkReady() {
h.ready.Set(true)
}
// MarkNotReady sets a not ready state for the endpoint handlers.
func (h *healthManager) MarkNotReady() {
h.ready.Set(false)
}
// IsReady return inner state for the component.
func (h *healthManager) IsReady() bool {
return h.ready.True()
}
// Name return probe name identifier
func (h *healthManager) Name() string {
return h.name
}
func newComboHealthManager() *comboHealthManager {
return &comboHealthManager{}
}
// MarkReady sets components status to ready.
func (p *comboHealthManager) MarkReady() {
p.mu.Lock()
defer p.mu.Unlock()
for _, probe := range p.probes {
probe.MarkReady()
}
}
// MarkNotReady sets components status to not ready with given error as a cause.
func (p *comboHealthManager) MarkNotReady() {
p.mu.Lock()
defer p.mu.Unlock()
for _, probe := range p.probes {
probe.MarkNotReady()
}
}
// IsReady return composed status of all components.
func (p *comboHealthManager) IsReady() bool {
p.mu.Lock()
defer p.mu.Unlock()
if len(p.probes) == 0 {
return false
}
for _, probe := range p.probes {
if !probe.IsReady() {
return false
}
}
return true
}
func (p *comboHealthManager) verboseInfo() string {
p.mu.Lock()
defer p.mu.Unlock()
var info strings.Builder
for _, probe := range p.probes {
if probe.IsReady() {
info.WriteString(fmt.Sprintf("%s is ready\n", probe.Name()))
} else {
info.WriteString(fmt.Sprintf("%s is not ready\n", probe.Name()))
}
}
return info.String()
}
// addProbe add components probe to comboHealthManager.
func (p *comboHealthManager) addProbe(probe Probe) {
p.mu.Lock()
defer p.mu.Unlock()
p.probes = append(p.probes, probe)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/health/health_test.go | internal/health/health_test.go | package health
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
const probeName = "probe"
func TestHealthManager(t *testing.T) {
hm := NewHealthManager(probeName)
assert.False(t, hm.IsReady())
hm.MarkReady()
assert.True(t, hm.IsReady())
hm.MarkNotReady()
assert.False(t, hm.IsReady())
t.Run("concurrent should works", func(t *testing.T) {
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
hm.MarkReady()
wg.Done()
}()
}
wg.Wait()
assert.True(t, hm.IsReady())
})
}
func TestComboHealthManager(t *testing.T) {
t.Run("base", func(t *testing.T) {
chm := newComboHealthManager()
hm1 := NewHealthManager(probeName)
hm2 := NewHealthManager(probeName + "2")
assert.False(t, chm.IsReady())
chm.addProbe(hm1)
chm.addProbe(hm2)
assert.False(t, chm.IsReady())
hm1.MarkReady()
assert.False(t, chm.IsReady())
hm2.MarkReady()
assert.True(t, chm.IsReady())
})
t.Run("is ready verbose", func(t *testing.T) {
chm := newComboHealthManager()
hm := NewHealthManager(probeName)
assert.False(t, chm.IsReady())
chm.addProbe(hm)
assert.False(t, chm.IsReady())
hm.MarkReady()
assert.True(t, chm.IsReady())
assert.Contains(t, chm.verboseInfo(), probeName)
assert.Contains(t, chm.verboseInfo(), "is ready")
})
t.Run("concurrent add probes", func(t *testing.T) {
chm := newComboHealthManager()
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
hm := NewHealthManager(probeName)
hm.MarkReady()
chm.addProbe(hm)
wg.Done()
}()
}
wg.Wait()
assert.True(t, chm.IsReady())
})
t.Run("markReady and markNotReady", func(t *testing.T) {
chm := newComboHealthManager()
for i := 0; i < 10; i++ {
hm := NewHealthManager(probeName)
chm.addProbe(hm)
}
assert.False(t, chm.IsReady())
chm.MarkReady()
assert.True(t, chm.IsReady())
chm.MarkNotReady()
assert.False(t, chm.IsReady())
})
}
func TestAddGlobalProbes(t *testing.T) {
cleanupForTest(t)
t.Run("concurrent add probes", func(t *testing.T) {
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
hm := NewHealthManager(probeName)
hm.MarkReady()
AddProbe(hm)
wg.Done()
}()
}
wg.Wait()
assert.True(t, defaultHealthManager.IsReady())
})
}
func TestCreateHttpHandler(t *testing.T) {
cleanupForTest(t)
srv := httptest.NewServer(CreateHttpHandler("OK"))
defer srv.Close()
resp, err := http.Get(srv.URL)
assert.Nil(t, err)
_ = resp.Body.Close()
assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
hm := NewHealthManager(probeName)
defaultHealthManager.addProbe(hm)
resp, err = http.Get(srv.URL)
assert.Nil(t, err)
assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
content, _ := io.ReadAll(resp.Body)
assert.True(t, strings.HasPrefix(string(content), "Service Unavailable"))
_ = resp.Body.Close()
hm.MarkReady()
resp, err = http.Get(srv.URL)
assert.Nil(t, err)
_ = resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func cleanupForTest(t *testing.T) {
t.Cleanup(func() {
defaultHealthManager = &comboHealthManager{}
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/mock/deposit.pb.go | internal/mock/deposit.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.8.0
// source: deposit.proto
package mock
import (
context "context"
reflect "reflect"
sync "sync"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type DepositRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Amount float32 `protobuf:"fixed32,1,opt,name=amount,proto3" json:"amount,omitempty"`
}
func (x *DepositRequest) Reset() {
*x = DepositRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_deposit_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DepositRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DepositRequest) ProtoMessage() {}
func (x *DepositRequest) ProtoReflect() protoreflect.Message {
mi := &file_deposit_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DepositRequest.ProtoReflect.Descriptor instead.
func (*DepositRequest) Descriptor() ([]byte, []int) {
return file_deposit_proto_rawDescGZIP(), []int{0}
}
func (x *DepositRequest) GetAmount() float32 {
if x != nil {
return x.Amount
}
return 0
}
type DepositResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Ok bool `protobuf:"varint,1,opt,name=ok,proto3" json:"ok,omitempty"`
}
func (x *DepositResponse) Reset() {
*x = DepositResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_deposit_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DepositResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DepositResponse) ProtoMessage() {}
func (x *DepositResponse) ProtoReflect() protoreflect.Message {
mi := &file_deposit_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DepositResponse.ProtoReflect.Descriptor instead.
func (*DepositResponse) Descriptor() ([]byte, []int) {
return file_deposit_proto_rawDescGZIP(), []int{1}
}
func (x *DepositResponse) GetOk() bool {
if x != nil {
return x.Ok
}
return false
}
var File_deposit_proto protoreflect.FileDescriptor
var file_deposit_proto_rawDesc = []byte{
0x0a, 0x0d, 0x64, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
0x04, 0x6d, 0x6f, 0x63, 0x6b, 0x22, 0x28, 0x0a, 0x0e, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e,
0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x02, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22,
0x21, 0x0a, 0x0f, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x6f, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x02,
0x6f, 0x6b, 0x32, 0x48, 0x0a, 0x0e, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x53, 0x65, 0x72,
0x76, 0x69, 0x63, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x12,
0x14, 0x2e, 0x6d, 0x6f, 0x63, 0x6b, 0x2e, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x15, 0x2e, 0x6d, 0x6f, 0x63, 0x6b, 0x2e, 0x44, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x08, 0x5a, 0x06,
0x2e, 0x3b, 0x6d, 0x6f, 0x63, 0x6b, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_deposit_proto_rawDescOnce sync.Once
file_deposit_proto_rawDescData = file_deposit_proto_rawDesc
)
func file_deposit_proto_rawDescGZIP() []byte {
file_deposit_proto_rawDescOnce.Do(func() {
file_deposit_proto_rawDescData = protoimpl.X.CompressGZIP(file_deposit_proto_rawDescData)
})
return file_deposit_proto_rawDescData
}
var (
file_deposit_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
file_deposit_proto_goTypes = []any{
(*DepositRequest)(nil), // 0: mock.DepositRequest
(*DepositResponse)(nil), // 1: mock.DepositResponse
}
)
var file_deposit_proto_depIdxs = []int32{
0, // 0: mock.DepositService.Deposit:input_type -> mock.DepositRequest
1, // 1: mock.DepositService.Deposit:output_type -> mock.DepositResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_deposit_proto_init() }
func file_deposit_proto_init() {
if File_deposit_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_deposit_proto_msgTypes[0].Exporter = func(v any, i int) any {
switch v := v.(*DepositRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_deposit_proto_msgTypes[1].Exporter = func(v any, i int) any {
switch v := v.(*DepositResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_deposit_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_deposit_proto_goTypes,
DependencyIndexes: file_deposit_proto_depIdxs,
MessageInfos: file_deposit_proto_msgTypes,
}.Build()
File_deposit_proto = out.File
file_deposit_proto_rawDesc = nil
file_deposit_proto_goTypes = nil
file_deposit_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var (
_ context.Context
_ grpc.ClientConnInterface
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// DepositServiceClient is the client API for DepositService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type DepositServiceClient interface {
Deposit(ctx context.Context, in *DepositRequest, opts ...grpc.CallOption) (*DepositResponse, error)
}
type depositServiceClient struct {
cc grpc.ClientConnInterface
}
func NewDepositServiceClient(cc grpc.ClientConnInterface) DepositServiceClient {
return &depositServiceClient{cc}
}
func (c *depositServiceClient) Deposit(ctx context.Context, in *DepositRequest, opts ...grpc.CallOption) (*DepositResponse, error) {
out := new(DepositResponse)
err := c.cc.Invoke(ctx, "/mock.DepositService/Deposit", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// DepositServiceServer is the server API for DepositService service.
type DepositServiceServer interface {
Deposit(context.Context, *DepositRequest) (*DepositResponse, error)
}
// UnimplementedDepositServiceServer can be embedded to have forward compatible implementations.
type UnimplementedDepositServiceServer struct{}
func (*UnimplementedDepositServiceServer) Deposit(context.Context, *DepositRequest) (*DepositResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented")
}
func RegisterDepositServiceServer(s *grpc.Server, srv DepositServiceServer) {
s.RegisterService(&_DepositService_serviceDesc, srv)
}
func _DepositService_Deposit_Handler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := new(DepositRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(DepositServiceServer).Deposit(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/mock.DepositService/Deposit",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(DepositServiceServer).Deposit(ctx, req.(*DepositRequest))
}
return interceptor(ctx, in, info, handler)
}
var _DepositService_serviceDesc = grpc.ServiceDesc{
ServiceName: "mock.DepositService",
HandlerType: (*DepositServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Deposit",
Handler: _DepositService_Deposit_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "deposit.proto",
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/mock/depositserver.go | internal/mock/depositserver.go | package mock
import (
"context"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// DepositServer is used for mocking.
type DepositServer struct{}
// Deposit handles the deposit requests.
func (*DepositServer) Deposit(_ context.Context, req *DepositRequest) (*DepositResponse, error) {
if req.GetAmount() < 0 {
return nil, status.Errorf(codes.InvalidArgument, "cannot deposit %v", req.GetAmount())
}
time.Sleep(time.Duration(req.GetAmount()) * time.Millisecond)
return &DepositResponse{Ok: true}, nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/devserver/config.go | internal/devserver/config.go | package devserver
// Config is config for inner http server.
type Config struct {
Enabled bool `json:",default=true"`
Host string `json:",optional"`
Port int `json:",default=6060"`
MetricsPath string `json:",default=/metrics"`
HealthPath string `json:",default=/healthz"`
EnableMetrics bool `json:",default=true"`
EnablePprof bool `json:",default=true"`
HealthResponse string `json:",default=OK"`
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/devserver/server.go | internal/devserver/server.go | package devserver
import (
"encoding/json"
"fmt"
"net/http"
"net/http/pprof"
"sync"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/prometheus"
"github.com/zeromicro/go-zero/core/threading"
"github.com/zeromicro/go-zero/internal/health"
)
var once sync.Once
// Server is an inner http server, expose some useful observability information of app.
// For example, health check, metrics and pprof.
type Server struct {
config Config
server *http.ServeMux
routes []string
}
// NewServer returns a new inner http Server.
func NewServer(config Config) *Server {
return &Server{
config: config,
server: http.NewServeMux(),
}
}
func (s *Server) addRoutes(c Config) {
// route path, routes list
s.handleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(s.routes)
})
// health
s.handleFunc(s.config.HealthPath, health.CreateHttpHandler(c.HealthResponse))
// metrics
if s.config.EnableMetrics {
// enable prometheus global switch
prometheus.Enable()
s.handleFunc(s.config.MetricsPath, promhttp.Handler().ServeHTTP)
}
// pprof
if s.config.EnablePprof {
s.handleFunc("/debug/pprof/", pprof.Index)
s.handleFunc("/debug/pprof/cmdline", pprof.Cmdline)
s.handleFunc("/debug/pprof/profile", pprof.Profile)
s.handleFunc("/debug/pprof/symbol", pprof.Symbol)
s.handleFunc("/debug/pprof/trace", pprof.Trace)
}
}
func (s *Server) handleFunc(pattern string, handler http.HandlerFunc) {
s.server.HandleFunc(pattern, handler)
s.routes = append(s.routes, pattern)
}
// StartAsync start inner http server background.
func (s *Server) StartAsync(c Config) {
s.addRoutes(c)
threading.GoSafe(func() {
addr := fmt.Sprintf("%s:%d", s.config.Host, s.config.Port)
logx.Infof("Starting dev http server at %s", addr)
if err := http.ListenAndServe(addr, s.server); err != nil {
logx.Error(err)
}
})
}
// StartAgent start inner http server by config.
func StartAgent(c Config) {
if !c.Enabled {
return
}
once.Do(func() {
s := NewServer(c)
s.StartAsync(c)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/trace/trace.go | internal/trace/trace.go | package trace
import (
"context"
"go.opentelemetry.io/otel/trace"
)
func SpanIDFromContext(ctx context.Context) string {
spanCtx := trace.SpanContextFromContext(ctx)
if spanCtx.HasSpanID() {
return spanCtx.SpanID().String()
}
return ""
}
func TraceIDFromContext(ctx context.Context) string {
spanCtx := trace.SpanContextFromContext(ctx)
if spanCtx.HasTraceID() {
return spanCtx.TraceID().String()
}
return ""
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/trace/trace_test.go | internal/trace/trace_test.go | package trace
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
oteltrace "go.opentelemetry.io/otel/trace"
)
func TestSpanIDFromContext(t *testing.T) {
tracer := sdktrace.NewTracerProvider().Tracer("test")
ctx, span := tracer.Start(
context.Background(),
"foo",
oteltrace.WithSpanKind(oteltrace.SpanKindClient),
oteltrace.WithAttributes(semconv.HTTPClientAttributesFromHTTPRequest(httptest.NewRequest(http.MethodGet, "/", nil))...),
)
defer span.End()
assert.NotEmpty(t, TraceIDFromContext(ctx))
assert.NotEmpty(t, SpanIDFromContext(ctx))
}
func TestSpanIDFromContextEmpty(t *testing.T) {
assert.Empty(t, TraceIDFromContext(context.Background()))
assert.Empty(t, SpanIDFromContext(context.Background()))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/profiling/profiling_test.go | internal/profiling/profiling_test.go | package profiling
import (
"sync"
"testing"
"time"
"github.com/grafana/pyroscope-go"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/syncx"
)
func TestStart(t *testing.T) {
t.Run("profiling", func(t *testing.T) {
var c Config
assert.NoError(t, conf.FillDefault(&c))
c.Name = "test"
p := newProfiler(c)
assert.NotNil(t, p)
assert.NoError(t, p.Start())
assert.NoError(t, p.Stop())
})
t.Run("invalid config", func(t *testing.T) {
mp := &mockProfiler{}
newProfiler = func(c Config) profiler {
return mp
}
Start(Config{})
Start(Config{
ServerAddr: "localhost:4040",
})
})
t.Run("test start profiler", func(t *testing.T) {
mp := &mockProfiler{}
newProfiler = func(c Config) profiler {
return mp
}
c := Config{
Name: "test",
ServerAddr: "localhost:4040",
CheckInterval: time.Millisecond,
ProfilingDuration: time.Millisecond * 10,
CpuThreshold: 0,
}
var done = make(chan struct{})
go startPyroscope(c, done)
time.Sleep(time.Millisecond * 50)
close(done)
assert.True(t, mp.started.True())
assert.True(t, mp.stopped.True())
})
t.Run("test start profiler with cpu overloaded", func(t *testing.T) {
mp := &mockProfiler{}
newProfiler = func(c Config) profiler {
return mp
}
c := Config{
Name: "test",
ServerAddr: "localhost:4040",
CheckInterval: time.Millisecond,
ProfilingDuration: time.Millisecond * 10,
CpuThreshold: 900,
}
var done = make(chan struct{})
go startPyroscope(c, done)
time.Sleep(time.Millisecond * 50)
close(done)
assert.False(t, mp.started.True())
})
t.Run("start/stop err", func(t *testing.T) {
mp := &mockProfiler{
err: assert.AnError,
}
newProfiler = func(c Config) profiler {
return mp
}
c := Config{
Name: "test",
ServerAddr: "localhost:4040",
CheckInterval: time.Millisecond,
ProfilingDuration: time.Millisecond * 10,
CpuThreshold: 0,
}
var done = make(chan struct{})
go startPyroscope(c, done)
time.Sleep(time.Millisecond * 50)
close(done)
assert.False(t, mp.started.True())
assert.False(t, mp.stopped.True())
})
}
func TestGenPyroscopeConf(t *testing.T) {
c := Config{
Name: "",
ServerAddr: "localhost:4040",
AuthUser: "user",
AuthPassword: "password",
ProfileType: ProfileType{
Logger: true,
CPU: true,
Goroutines: true,
Memory: true,
Mutex: true,
Block: true,
},
}
pyroscopeConf := genPyroscopeConf(c)
assert.Equal(t, c.ServerAddr, pyroscopeConf.ServerAddress)
assert.Equal(t, c.AuthUser, pyroscopeConf.BasicAuthUser)
assert.Equal(t, c.AuthPassword, pyroscopeConf.BasicAuthPassword)
assert.Equal(t, c.Name, pyroscopeConf.ApplicationName)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileCPU)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileGoroutines)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileAllocObjects)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileAllocSpace)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileInuseObjects)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileInuseSpace)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileMutexCount)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileMutexDuration)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileBlockCount)
assert.Contains(t, pyroscopeConf.ProfileTypes, pyroscope.ProfileBlockDuration)
setFraction(c)
resetFraction(c)
newPyroscopeProfiler(c)
}
func TestNewPyroscopeProfiler(t *testing.T) {
p := newPyroscopeProfiler(Config{})
assert.Error(t, p.Start())
assert.NoError(t, p.Stop())
}
type mockProfiler struct {
mutex sync.Mutex
started syncx.AtomicBool
stopped syncx.AtomicBool
err error
}
func (m *mockProfiler) Start() error {
m.mutex.Lock()
if m.err == nil {
m.started.Set(true)
}
m.mutex.Unlock()
return m.err
}
func (m *mockProfiler) Stop() error {
m.mutex.Lock()
if m.err == nil {
m.stopped.Set(true)
}
m.mutex.Unlock()
return m.err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/internal/profiling/profiling.go | internal/profiling/profiling.go | package profiling
import (
"runtime"
"sync"
"time"
"github.com/grafana/pyroscope-go"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/threading"
)
const (
defaultCheckInterval = time.Second * 10
defaultProfilingDuration = time.Minute * 2
defaultUploadRate = time.Second * 15
)
type (
Config struct {
// Name is the name of the application.
Name string `json:",optional,inherit"`
// ServerAddr is the address of the profiling server.
ServerAddr string
// AuthUser is the username for basic authentication.
AuthUser string `json:",optional"`
// AuthPassword is the password for basic authentication.
AuthPassword string `json:",optional"`
// UploadRate is the duration for which profiling data is uploaded.
UploadRate time.Duration `json:",default=15s"`
// CheckInterval is the interval to check if profiling should start.
CheckInterval time.Duration `json:",default=10s"`
// ProfilingDuration is the duration for which profiling data is collected.
ProfilingDuration time.Duration `json:",default=2m"`
// CpuThreshold the collection is allowed only when the current service cpu > CpuThreshold
CpuThreshold int64 `json:",default=700,range=[0:1000)"`
// ProfileType is the type of profiling to be performed.
ProfileType ProfileType
}
ProfileType struct {
// Logger is a flag to enable or disable logging.
Logger bool `json:",default=false"`
// CPU is a flag to disable CPU profiling.
CPU bool `json:",default=true"`
// Goroutines is a flag to disable goroutine profiling.
Goroutines bool `json:",default=true"`
// Memory is a flag to disable memory profiling.
Memory bool `json:",default=true"`
// Mutex is a flag to disable mutex profiling.
Mutex bool `json:",default=false"`
// Block is a flag to disable block profiling.
Block bool `json:",default=false"`
}
profiler interface {
Start() error
Stop() error
}
pyroscopeProfiler struct {
c Config
profiler *pyroscope.Profiler
}
)
var (
once sync.Once
newProfiler = func(c Config) profiler {
return newPyroscopeProfiler(c)
}
)
// Start initializes the pyroscope profiler with the given configuration.
func Start(c Config) {
// check if the profiling is enabled
if len(c.ServerAddr) == 0 {
return
}
// set default values for the configuration
if c.ProfilingDuration <= 0 {
c.ProfilingDuration = defaultProfilingDuration
}
// set default values for the configuration
if c.CheckInterval <= 0 {
c.CheckInterval = defaultCheckInterval
}
if c.UploadRate <= 0 {
c.UploadRate = defaultUploadRate
}
once.Do(func() {
logx.Info("continuous profiling started")
threading.GoSafe(func() {
startPyroscope(c, proc.Done())
})
})
}
// startPyroscope starts the pyroscope profiler with the given configuration.
func startPyroscope(c Config, done <-chan struct{}) {
var (
pr profiler
err error
latestProfilingTime time.Time
intervalTicker = time.NewTicker(c.CheckInterval)
profilingTicker = time.NewTicker(c.ProfilingDuration)
)
defer profilingTicker.Stop()
defer intervalTicker.Stop()
for {
select {
case <-intervalTicker.C:
// Check if the machine is overloaded and if the profiler is not running
if pr == nil && isCpuOverloaded(c) {
pr = newProfiler(c)
if err := pr.Start(); err != nil {
logx.Errorf("failed to start profiler: %v", err)
continue
}
// record the latest profiling time
latestProfilingTime = time.Now()
logx.Infof("pyroscope profiler started.")
}
case <-profilingTicker.C:
// check if the profiling duration has passed
if !time.Now().After(latestProfilingTime.Add(c.ProfilingDuration)) {
continue
}
// check if the profiler is already running, if so, skip
if pr != nil {
if err = pr.Stop(); err != nil {
logx.Errorf("failed to stop profiler: %v", err)
}
logx.Infof("pyroscope profiler stopped.")
pr = nil
}
case <-done:
logx.Infof("continuous profiling stopped.")
return
}
}
}
// genPyroscopeConf generates the pyroscope configuration based on the given config.
func genPyroscopeConf(c Config) pyroscope.Config {
pConf := pyroscope.Config{
UploadRate: c.UploadRate,
ApplicationName: c.Name,
BasicAuthUser: c.AuthUser, // http basic auth user
BasicAuthPassword: c.AuthPassword, // http basic auth password
ServerAddress: c.ServerAddr,
Logger: nil,
HTTPHeaders: map[string]string{},
// you can provide static tags via a map:
Tags: map[string]string{
"name": c.Name,
},
}
if c.ProfileType.Logger {
pConf.Logger = logx.WithCallerSkip(0)
}
if c.ProfileType.CPU {
pConf.ProfileTypes = append(pConf.ProfileTypes, pyroscope.ProfileCPU)
}
if c.ProfileType.Goroutines {
pConf.ProfileTypes = append(pConf.ProfileTypes, pyroscope.ProfileGoroutines)
}
if c.ProfileType.Memory {
pConf.ProfileTypes = append(pConf.ProfileTypes, pyroscope.ProfileAllocObjects, pyroscope.ProfileAllocSpace,
pyroscope.ProfileInuseObjects, pyroscope.ProfileInuseSpace)
}
if c.ProfileType.Mutex {
pConf.ProfileTypes = append(pConf.ProfileTypes, pyroscope.ProfileMutexCount, pyroscope.ProfileMutexDuration)
}
if c.ProfileType.Block {
pConf.ProfileTypes = append(pConf.ProfileTypes, pyroscope.ProfileBlockCount, pyroscope.ProfileBlockDuration)
}
logx.Infof("applicationName: %s", pConf.ApplicationName)
return pConf
}
// isCpuOverloaded checks the machine performance based on the given configuration.
func isCpuOverloaded(c Config) bool {
currentValue := stat.CpuUsage()
if currentValue >= c.CpuThreshold {
logx.Infof("continuous profiling cpu overload, cpu: %d", currentValue)
return true
}
return false
}
func newPyroscopeProfiler(c Config) profiler {
return &pyroscopeProfiler{
c: c,
}
}
func (p *pyroscopeProfiler) Start() error {
pConf := genPyroscopeConf(p.c)
// set mutex and block profile rate
setFraction(p.c)
prof, err := pyroscope.Start(pConf)
if err != nil {
resetFraction(p.c)
return err
}
p.profiler = prof
return nil
}
func (p *pyroscopeProfiler) Stop() error {
if p.profiler == nil {
return nil
}
if err := p.profiler.Stop(); err != nil {
return err
}
resetFraction(p.c)
p.profiler = nil
return nil
}
func setFraction(c Config) {
// These 2 lines are only required if you're using mutex or block profiling
if c.ProfileType.Mutex {
runtime.SetMutexProfileFraction(10) // 10/seconds
}
if c.ProfileType.Block {
runtime.SetBlockProfileRate(1000 * 1000) // 1/millisecond
}
}
func resetFraction(c Config) {
// These 2 lines are only required if you're using mutex or block profiling
if c.ProfileType.Mutex {
runtime.SetMutexProfileFraction(0)
}
if c.ProfileType.Block {
runtime.SetBlockProfileRate(0)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/validation/validator.go | core/validation/validator.go | package validation
// Validator represents a validator.
type Validator interface {
// Validate validates the value.
Validate() error
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/writer_test.go | core/logx/writer_test.go | package logx
import (
"bytes"
"encoding/json"
"errors"
"log"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestNewWriter(t *testing.T) {
const literal = "foo bar"
var buf bytes.Buffer
w := NewWriter(&buf)
w.Info(literal)
assert.Contains(t, buf.String(), literal)
buf.Reset()
w.Debug(literal)
assert.Contains(t, buf.String(), literal)
}
func TestConsoleWriter(t *testing.T) {
var buf bytes.Buffer
w := newConsoleWriter()
lw := newLogWriter(log.New(&buf, "", 0))
w.(*concreteWriter).errorLog = lw
w.Alert("foo bar 1")
var val mockedEntry
if err := json.Unmarshal(buf.Bytes(), &val); err != nil {
t.Fatal(err)
}
assert.Equal(t, levelAlert, val.Level)
assert.Equal(t, "foo bar 1", val.Content)
buf.Reset()
w.(*concreteWriter).errorLog = lw
w.Error("foo bar 2")
if err := json.Unmarshal(buf.Bytes(), &val); err != nil {
t.Fatal(err)
}
assert.Equal(t, levelError, val.Level)
assert.Equal(t, "foo bar 2", val.Content)
buf.Reset()
w.(*concreteWriter).infoLog = lw
w.Info("foo bar 3")
if err := json.Unmarshal(buf.Bytes(), &val); err != nil {
t.Fatal(err)
}
assert.Equal(t, levelInfo, val.Level)
assert.Equal(t, "foo bar 3", val.Content)
buf.Reset()
w.(*concreteWriter).severeLog = lw
w.Severe("foo bar 4")
if err := json.Unmarshal(buf.Bytes(), &val); err != nil {
t.Fatal(err)
}
assert.Equal(t, levelFatal, val.Level)
assert.Equal(t, "foo bar 4", val.Content)
buf.Reset()
w.(*concreteWriter).slowLog = lw
w.Slow("foo bar 5")
if err := json.Unmarshal(buf.Bytes(), &val); err != nil {
t.Fatal(err)
}
assert.Equal(t, levelSlow, val.Level)
assert.Equal(t, "foo bar 5", val.Content)
buf.Reset()
w.(*concreteWriter).statLog = lw
w.Stat("foo bar 6")
if err := json.Unmarshal(buf.Bytes(), &val); err != nil {
t.Fatal(err)
}
assert.Equal(t, levelStat, val.Level)
assert.Equal(t, "foo bar 6", val.Content)
w.(*concreteWriter).infoLog = hardToCloseWriter{}
assert.NotNil(t, w.Close())
w.(*concreteWriter).infoLog = easyToCloseWriter{}
w.(*concreteWriter).errorLog = hardToCloseWriter{}
assert.NotNil(t, w.Close())
w.(*concreteWriter).errorLog = easyToCloseWriter{}
w.(*concreteWriter).severeLog = hardToCloseWriter{}
assert.NotNil(t, w.Close())
w.(*concreteWriter).severeLog = easyToCloseWriter{}
w.(*concreteWriter).slowLog = hardToCloseWriter{}
assert.NotNil(t, w.Close())
w.(*concreteWriter).slowLog = easyToCloseWriter{}
w.(*concreteWriter).statLog = hardToCloseWriter{}
assert.NotNil(t, w.Close())
w.(*concreteWriter).statLog = easyToCloseWriter{}
}
func TestNewFileWriter(t *testing.T) {
t.Run("access", func(t *testing.T) {
_, err := newFileWriter(LogConf{
Path: "/not-exists",
})
assert.Error(t, err)
})
}
func TestNopWriter(t *testing.T) {
assert.NotPanics(t, func() {
var w nopWriter
w.Alert("foo")
w.Debug("foo")
w.Error("foo")
w.Info("foo")
w.Severe("foo")
w.Stack("foo")
w.Stat("foo")
w.Slow("foo")
_ = w.Close()
})
}
func TestWriteJson(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
writeJson(nil, "foo")
assert.Contains(t, buf.String(), "foo")
buf.Reset()
writeJson(hardToWriteWriter{}, "foo")
assert.Contains(t, buf.String(), "write error")
buf.Reset()
writeJson(nil, make(chan int))
assert.Contains(t, buf.String(), "unsupported type")
buf.Reset()
type C struct {
RC func()
}
writeJson(nil, C{
RC: func() {},
})
assert.Contains(t, buf.String(), "runtime/debug.Stack")
}
func TestWritePlainAny(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
writePlainAny(nil, levelInfo, "foo")
assert.Contains(t, buf.String(), "foo")
buf.Reset()
writePlainAny(nil, levelDebug, make(chan int))
assert.Contains(t, buf.String(), "unsupported type")
writePlainAny(nil, levelDebug, 100)
assert.Contains(t, buf.String(), "100")
buf.Reset()
writePlainAny(nil, levelError, make(chan int))
assert.Contains(t, buf.String(), "unsupported type")
writePlainAny(nil, levelSlow, 100)
assert.Contains(t, buf.String(), "100")
buf.Reset()
writePlainAny(hardToWriteWriter{}, levelStat, 100)
assert.Contains(t, buf.String(), "write error")
buf.Reset()
writePlainAny(hardToWriteWriter{}, levelSevere, "foo")
assert.Contains(t, buf.String(), "write error")
buf.Reset()
writePlainAny(hardToWriteWriter{}, levelAlert, "foo")
assert.Contains(t, buf.String(), "write error")
buf.Reset()
writePlainAny(hardToWriteWriter{}, levelFatal, "foo")
assert.Contains(t, buf.String(), "write error")
buf.Reset()
type C struct {
RC func()
}
writePlainAny(nil, levelError, C{
RC: func() {},
})
assert.Contains(t, buf.String(), "runtime/debug.Stack")
}
func TestWritePlainDuplicate(t *testing.T) {
old := atomic.SwapUint32(&encoding, plainEncodingType)
t.Cleanup(func() {
atomic.StoreUint32(&encoding, old)
})
var buf bytes.Buffer
output(&buf, levelInfo, "foo", LogField{
Key: "first",
Value: "a",
}, LogField{
Key: "first",
Value: "b",
})
assert.Contains(t, buf.String(), "foo")
assert.NotContains(t, buf.String(), "first=a")
assert.Contains(t, buf.String(), "first=b")
buf.Reset()
output(&buf, levelInfo, "foo", LogField{
Key: "first",
Value: "a",
}, LogField{
Key: "first",
Value: "b",
}, LogField{
Key: "second",
Value: "c",
})
assert.Contains(t, buf.String(), "foo")
assert.NotContains(t, buf.String(), "first=a")
assert.Contains(t, buf.String(), "first=b")
assert.Contains(t, buf.String(), "second=c")
}
func TestLogWithSensitive(t *testing.T) {
old := atomic.SwapUint32(&encoding, plainEncodingType)
t.Cleanup(func() {
atomic.StoreUint32(&encoding, old)
})
t.Run("sensitive", func(t *testing.T) {
var buf bytes.Buffer
output(&buf, levelInfo, User{
Name: "kevin",
Pass: "123",
}, LogField{
Key: "first",
Value: "a",
}, LogField{
Key: "first",
Value: "b",
})
assert.Contains(t, buf.String(), maskedContent)
assert.NotContains(t, buf.String(), "first=a")
assert.Contains(t, buf.String(), "first=b")
})
t.Run("sensitive fields", func(t *testing.T) {
var buf bytes.Buffer
output(&buf, levelInfo, "foo", LogField{
Key: "first",
Value: User{
Name: "kevin",
Pass: "123",
},
}, LogField{
Key: "second",
Value: "b",
})
assert.Contains(t, buf.String(), "foo")
assert.Contains(t, buf.String(), "first")
assert.Contains(t, buf.String(), maskedContent)
assert.Contains(t, buf.String(), "second=b")
})
}
func TestLogWithLimitContentLength(t *testing.T) {
maxLen := atomic.LoadUint32(&maxContentLength)
atomic.StoreUint32(&maxContentLength, 10)
t.Cleanup(func() {
atomic.StoreUint32(&maxContentLength, maxLen)
})
t.Run("alert", func(t *testing.T) {
var buf bytes.Buffer
w := NewWriter(&buf)
w.Info("1234567890")
var v1 mockedEntry
if err := json.Unmarshal(buf.Bytes(), &v1); err != nil {
t.Fatal(err)
}
assert.Equal(t, "1234567890", v1.Content)
assert.False(t, v1.Truncated)
buf.Reset()
var v2 mockedEntry
w.Info("12345678901")
if err := json.Unmarshal(buf.Bytes(), &v2); err != nil {
t.Fatal(err)
}
assert.Equal(t, "1234567890", v2.Content)
assert.True(t, v2.Truncated)
})
}
func TestComboWriter(t *testing.T) {
var mockWriters []Writer
for i := 0; i < 3; i++ {
mockWriters = append(mockWriters, new(tracedWriter))
}
cw := comboWriter{
writers: mockWriters,
}
t.Run("Alert", func(t *testing.T) {
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Alert", "test alert").Once()
}
cw.Alert("test alert")
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Alert", "test alert")
}
})
t.Run("Close", func(t *testing.T) {
for i := range cw.writers {
if i == 1 {
cw.writers[i].(*tracedWriter).On("Close").Return(errors.New("error")).Once()
} else {
cw.writers[i].(*tracedWriter).On("Close").Return(nil).Once()
}
}
err := cw.Close()
assert.Error(t, err)
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Close")
}
})
t.Run("Debug", func(t *testing.T) {
fields := []LogField{{Key: "key", Value: "value"}}
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Debug", "test debug", fields).Once()
}
cw.Debug("test debug", fields...)
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Debug", "test debug", fields)
}
})
t.Run("Error", func(t *testing.T) {
fields := []LogField{{Key: "key", Value: "value"}}
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Error", "test error", fields).Once()
}
cw.Error("test error", fields...)
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Error", "test error", fields)
}
})
t.Run("Info", func(t *testing.T) {
fields := []LogField{{Key: "key", Value: "value"}}
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Info", "test info", fields).Once()
}
cw.Info("test info", fields...)
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Info", "test info", fields)
}
})
t.Run("Severe", func(t *testing.T) {
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Severe", "test severe").Once()
}
cw.Severe("test severe")
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Severe", "test severe")
}
})
t.Run("Slow", func(t *testing.T) {
fields := []LogField{{Key: "key", Value: "value"}}
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Slow", "test slow", fields).Once()
}
cw.Slow("test slow", fields...)
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Slow", "test slow", fields)
}
})
t.Run("Stack", func(t *testing.T) {
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Stack", "test stack").Once()
}
cw.Stack("test stack")
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Stack", "test stack")
}
})
t.Run("Stat", func(t *testing.T) {
fields := []LogField{{Key: "key", Value: "value"}}
for _, mw := range cw.writers {
mw.(*tracedWriter).On("Stat", "test stat", fields).Once()
}
cw.Stat("test stat", fields...)
for _, mw := range cw.writers {
mw.(*tracedWriter).AssertCalled(t, "Stat", "test stat", fields)
}
})
}
type mockedEntry struct {
Level string `json:"level"`
Content string `json:"content"`
Truncated bool `json:"truncated"`
}
type easyToCloseWriter struct{}
func (h easyToCloseWriter) Write(_ []byte) (_ int, _ error) {
return
}
func (h easyToCloseWriter) Close() error {
return nil
}
type hardToCloseWriter struct{}
func (h hardToCloseWriter) Write(_ []byte) (_ int, _ error) {
return
}
func (h hardToCloseWriter) Close() error {
return errors.New("close error")
}
type hardToWriteWriter struct{}
func (h hardToWriteWriter) Write(_ []byte) (_ int, _ error) {
return 0, errors.New("write error")
}
type tracedWriter struct {
mock.Mock
}
func (w *tracedWriter) Alert(v any) {
w.Called(v)
}
func (w *tracedWriter) Close() error {
args := w.Called()
return args.Error(0)
}
func (w *tracedWriter) Debug(v any, fields ...LogField) {
w.Called(v, fields)
}
func (w *tracedWriter) Error(v any, fields ...LogField) {
w.Called(v, fields)
}
func (w *tracedWriter) Info(v any, fields ...LogField) {
w.Called(v, fields)
}
func (w *tracedWriter) Severe(v any) {
w.Called(v)
}
func (w *tracedWriter) Slow(v any, fields ...LogField) {
w.Called(v, fields)
}
func (w *tracedWriter) Stack(v any) {
w.Called(v)
}
func (w *tracedWriter) Stat(v any, fields ...LogField) {
w.Called(v, fields)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/richlogger.go | core/logx/richlogger.go | package logx
import (
"context"
"fmt"
"time"
"github.com/zeromicro/go-zero/core/timex"
"github.com/zeromicro/go-zero/internal/trace"
)
// WithCallerSkip returns a Logger with given caller skip.
func WithCallerSkip(skip int) Logger {
if skip <= 0 {
return new(richLogger)
}
return &richLogger{
callerSkip: skip,
}
}
// WithContext sets ctx to log, for keeping tracing information.
func WithContext(ctx context.Context) Logger {
return &richLogger{
ctx: ctx,
}
}
// WithDuration returns a Logger with given duration.
func WithDuration(d time.Duration) Logger {
return &richLogger{
fields: []LogField{Field(durationKey, timex.ReprOfDuration(d))},
}
}
type richLogger struct {
ctx context.Context
callerSkip int
fields []LogField
}
func (l *richLogger) Debug(v ...any) {
if shallLog(DebugLevel) {
l.debug(fmt.Sprint(v...))
}
}
func (l *richLogger) Debugf(format string, v ...any) {
if shallLog(DebugLevel) {
l.debug(fmt.Sprintf(format, v...))
}
}
func (l *richLogger) Debugfn(fn func() any) {
if shallLog(DebugLevel) {
l.debug(fn())
}
}
func (l *richLogger) Debugv(v any) {
if shallLog(DebugLevel) {
l.debug(v)
}
}
func (l *richLogger) Debugw(msg string, fields ...LogField) {
if shallLog(DebugLevel) {
l.debug(msg, fields...)
}
}
func (l *richLogger) Error(v ...any) {
if shallLog(ErrorLevel) {
l.err(fmt.Sprint(v...))
}
}
func (l *richLogger) Errorf(format string, v ...any) {
if shallLog(ErrorLevel) {
l.err(fmt.Sprintf(format, v...))
}
}
func (l *richLogger) Errorfn(fn func() any) {
if shallLog(ErrorLevel) {
l.err(fn())
}
}
func (l *richLogger) Errorv(v any) {
if shallLog(ErrorLevel) {
l.err(v)
}
}
func (l *richLogger) Errorw(msg string, fields ...LogField) {
if shallLog(ErrorLevel) {
l.err(msg, fields...)
}
}
func (l *richLogger) Info(v ...any) {
if shallLog(InfoLevel) {
l.info(fmt.Sprint(v...))
}
}
func (l *richLogger) Infof(format string, v ...any) {
if shallLog(InfoLevel) {
l.info(fmt.Sprintf(format, v...))
}
}
func (l *richLogger) Infofn(fn func() any) {
if shallLog(InfoLevel) {
l.info(fn())
}
}
func (l *richLogger) Infov(v any) {
if shallLog(InfoLevel) {
l.info(v)
}
}
func (l *richLogger) Infow(msg string, fields ...LogField) {
if shallLog(InfoLevel) {
l.info(msg, fields...)
}
}
func (l *richLogger) Slow(v ...any) {
if shallLog(ErrorLevel) {
l.slow(fmt.Sprint(v...))
}
}
func (l *richLogger) Slowf(format string, v ...any) {
if shallLog(ErrorLevel) {
l.slow(fmt.Sprintf(format, v...))
}
}
func (l *richLogger) Slowfn(fn func() any) {
if shallLog(ErrorLevel) {
l.slow(fn())
}
}
func (l *richLogger) Slowv(v any) {
if shallLog(ErrorLevel) {
l.slow(v)
}
}
func (l *richLogger) Sloww(msg string, fields ...LogField) {
if shallLog(ErrorLevel) {
l.slow(msg, fields...)
}
}
func (l *richLogger) WithCallerSkip(skip int) Logger {
if skip <= 0 {
return l
}
return &richLogger{
ctx: l.ctx,
callerSkip: skip,
fields: l.fields,
}
}
func (l *richLogger) WithContext(ctx context.Context) Logger {
return &richLogger{
ctx: ctx,
callerSkip: l.callerSkip,
fields: l.fields,
}
}
func (l *richLogger) WithDuration(duration time.Duration) Logger {
fields := append(l.fields, Field(durationKey, timex.ReprOfDuration(duration)))
return &richLogger{
ctx: l.ctx,
callerSkip: l.callerSkip,
fields: fields,
}
}
func (l *richLogger) WithFields(fields ...LogField) Logger {
if len(fields) == 0 {
return l
}
f := append(l.fields, fields...)
return &richLogger{
ctx: l.ctx,
callerSkip: l.callerSkip,
fields: f,
}
}
func (l *richLogger) buildFields(fields ...LogField) []LogField {
fields = append(l.fields, fields...)
// caller field should always appear together with global fields
fields = append(fields, Field(callerKey, getCaller(callerDepth+l.callerSkip)))
fields = mergeGlobalFields(fields)
if l.ctx == nil {
return fields
}
traceID := trace.TraceIDFromContext(l.ctx)
if len(traceID) > 0 {
fields = append(fields, Field(traceKey, traceID))
}
spanID := trace.SpanIDFromContext(l.ctx)
if len(spanID) > 0 {
fields = append(fields, Field(spanKey, spanID))
}
val := l.ctx.Value(fieldsKey{})
if val != nil {
if arr, ok := val.([]LogField); ok {
fields = append(fields, arr...)
}
}
return fields
}
func (l *richLogger) debug(v any, fields ...LogField) {
if shallLog(DebugLevel) {
getWriter().Debug(v, l.buildFields(fields...)...)
}
}
func (l *richLogger) err(v any, fields ...LogField) {
if shallLog(ErrorLevel) {
getWriter().Error(v, l.buildFields(fields...)...)
}
}
func (l *richLogger) info(v any, fields ...LogField) {
if shallLog(InfoLevel) {
getWriter().Info(v, l.buildFields(fields...)...)
}
}
func (l *richLogger) slow(v any, fields ...LogField) {
if shallLog(ErrorLevel) {
getWriter().Slow(v, l.buildFields(fields...)...)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/lesswriter_test.go | core/logx/lesswriter_test.go | package logx
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLessWriter(t *testing.T) {
var builder strings.Builder
w := newLessWriter(&builder, 500)
for i := 0; i < 100; i++ {
_, err := w.Write([]byte("hello"))
assert.Nil(t, err)
}
assert.Equal(t, "hello", builder.String())
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/lesswriter.go | core/logx/lesswriter.go | package logx
import "io"
type lessWriter struct {
*limitedExecutor
writer io.Writer
}
func newLessWriter(writer io.Writer, milliseconds int) *lessWriter {
return &lessWriter{
limitedExecutor: newLimitedExecutor(milliseconds),
writer: writer,
}
}
func (w *lessWriter) Write(p []byte) (n int, err error) {
w.logOrDiscard(func() {
w.writer.Write(p)
})
return len(p), nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/rotatelogger_test.go | core/logx/rotatelogger_test.go | package logx
import (
"errors"
"io"
"os"
"path"
"path/filepath"
"sync/atomic"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
"github.com/zeromicro/go-zero/core/stringx"
)
func TestDailyRotateRuleMarkRotated(t *testing.T) {
t.Run("daily rule", func(t *testing.T) {
var rule DailyRotateRule
rule.MarkRotated()
assert.Equal(t, getNowDate(), rule.rotatedTime)
})
t.Run("daily rule", func(t *testing.T) {
rule := DefaultRotateRule("test", "-", 1, false)
_, ok := rule.(*DailyRotateRule)
assert.True(t, ok)
})
}
func TestDailyRotateRuleOutdatedFiles(t *testing.T) {
t.Run("no files", func(t *testing.T) {
var rule DailyRotateRule
assert.Empty(t, rule.OutdatedFiles())
rule.days = 1
assert.Empty(t, rule.OutdatedFiles())
rule.gzip = true
assert.Empty(t, rule.OutdatedFiles())
})
t.Run("bad files", func(t *testing.T) {
rule := DailyRotateRule{
filename: "[a-z",
}
assert.Empty(t, rule.OutdatedFiles())
rule.days = 1
assert.Empty(t, rule.OutdatedFiles())
rule.gzip = true
assert.Empty(t, rule.OutdatedFiles())
})
t.Run("temp files", func(t *testing.T) {
boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay) * 2).Format(time.DateOnly)
f1, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary)
assert.NoError(t, err)
_ = f1.Close()
f2, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary)
assert.NoError(t, err)
_ = f2.Close()
t.Cleanup(func() {
_ = os.Remove(f1.Name())
_ = os.Remove(f2.Name())
})
rule := DailyRotateRule{
filename: path.Join(os.TempDir(), "go-zero-test-"),
days: 1,
}
assert.NotEmpty(t, rule.OutdatedFiles())
})
}
func TestDailyRotateRuleShallRotate(t *testing.T) {
var rule DailyRotateRule
rule.rotatedTime = time.Now().Add(time.Hour * 24).Format(time.DateOnly)
assert.True(t, rule.ShallRotate(0))
}
func TestSizeLimitRotateRuleMarkRotated(t *testing.T) {
t.Run("size limit rule", func(t *testing.T) {
var rule SizeLimitRotateRule
rule.MarkRotated()
assert.Equal(t, getNowDateInRFC3339Format(), rule.rotatedTime)
})
t.Run("size limit rule", func(t *testing.T) {
rule := NewSizeLimitRotateRule("foo", "-", 1, 1, 1, false)
rule.MarkRotated()
assert.Equal(t, getNowDateInRFC3339Format(), rule.(*SizeLimitRotateRule).rotatedTime)
})
}
func TestSizeLimitRotateRuleOutdatedFiles(t *testing.T) {
t.Run("no files", func(t *testing.T) {
var rule SizeLimitRotateRule
assert.Empty(t, rule.OutdatedFiles())
rule.days = 1
assert.Empty(t, rule.OutdatedFiles())
rule.gzip = true
assert.Empty(t, rule.OutdatedFiles())
rule.maxBackups = 0
assert.Empty(t, rule.OutdatedFiles())
})
t.Run("bad files", func(t *testing.T) {
rule := SizeLimitRotateRule{
DailyRotateRule: DailyRotateRule{
filename: "[a-z",
},
}
assert.Empty(t, rule.OutdatedFiles())
rule.days = 1
assert.Empty(t, rule.OutdatedFiles())
rule.gzip = true
assert.Empty(t, rule.OutdatedFiles())
})
t.Run("temp files", func(t *testing.T) {
boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay) * 2).Format(time.DateOnly)
f1, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary)
assert.NoError(t, err)
f2, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary)
assert.NoError(t, err)
boundary1 := time.Now().Add(time.Hour * time.Duration(hoursPerDay) * 2).Format(time.DateOnly)
f3, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary1)
assert.NoError(t, err)
t.Cleanup(func() {
_ = f1.Close()
_ = os.Remove(f1.Name())
_ = f2.Close()
_ = os.Remove(f2.Name())
_ = f3.Close()
_ = os.Remove(f3.Name())
})
rule := SizeLimitRotateRule{
DailyRotateRule: DailyRotateRule{
filename: path.Join(os.TempDir(), "go-zero-test-"),
days: 1,
},
maxBackups: 3,
}
assert.NotEmpty(t, rule.OutdatedFiles())
})
t.Run("no backups", func(t *testing.T) {
boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay) * 2).Format(time.DateOnly)
f1, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary)
assert.NoError(t, err)
f2, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary)
assert.NoError(t, err)
boundary1 := time.Now().Add(time.Hour * time.Duration(hoursPerDay) * 2).Format(time.DateOnly)
f3, err := os.CreateTemp(os.TempDir(), "go-zero-test-"+boundary1)
assert.NoError(t, err)
t.Cleanup(func() {
_ = f1.Close()
_ = os.Remove(f1.Name())
_ = f2.Close()
_ = os.Remove(f2.Name())
_ = f3.Close()
_ = os.Remove(f3.Name())
})
rule := SizeLimitRotateRule{
DailyRotateRule: DailyRotateRule{
filename: path.Join(os.TempDir(), "go-zero-test-"),
days: 1,
},
}
assert.NotEmpty(t, rule.OutdatedFiles())
logger := new(RotateLogger)
logger.rule = &rule
logger.maybeDeleteOutdatedFiles()
assert.Empty(t, rule.OutdatedFiles())
})
}
func TestSizeLimitRotateRuleShallRotate(t *testing.T) {
var rule SizeLimitRotateRule
rule.rotatedTime = time.Now().Add(time.Hour * 24).Format(fileTimeFormat)
rule.maxSize = 0
assert.False(t, rule.ShallRotate(0))
rule.maxSize = 100
assert.False(t, rule.ShallRotate(0))
assert.True(t, rule.ShallRotate(101*megaBytes))
}
func TestRotateLoggerClose(t *testing.T) {
t.Run("close", func(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(DailyRotateRule), false)
assert.Nil(t, err)
_, err = logger.Write([]byte("foo"))
assert.Nil(t, err)
assert.Nil(t, logger.Close())
})
t.Run("close and write", func(t *testing.T) {
logger := new(RotateLogger)
logger.done = make(chan struct{})
close(logger.done)
_, err := logger.Write([]byte("foo"))
assert.ErrorIs(t, err, ErrLogFileClosed)
})
t.Run("close without losing logs", func(t *testing.T) {
text := "foo"
filename, err := fs.TempFilenameWithText(text)
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(DailyRotateRule), false)
assert.Nil(t, err)
msg := []byte("foo")
n := 100
for i := 0; i < n; i++ {
_, err = logger.Write(msg)
assert.Nil(t, err)
}
assert.Nil(t, logger.Close())
bs, err := os.ReadFile(filename)
assert.Nil(t, err)
assert.Equal(t, len(msg)*n+len(text), len(bs))
})
}
func TestRotateLoggerGetBackupFilename(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(DailyRotateRule), false)
assert.Nil(t, err)
assert.True(t, len(logger.getBackupFilename()) > 0)
logger.backup = ""
assert.True(t, len(logger.getBackupFilename()) > 0)
}
func TestRotateLoggerMayCompressFile(t *testing.T) {
old := os.Stdout
os.Stdout = os.NewFile(0, os.DevNull)
defer func() {
os.Stdout = old
}()
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(DailyRotateRule), false)
assert.Nil(t, err)
logger.maybeCompressFile(filename)
_, err = os.Stat(filename)
assert.Nil(t, err)
}
func TestRotateLoggerMayCompressFileTrue(t *testing.T) {
old := os.Stdout
os.Stdout = os.NewFile(0, os.DevNull)
defer func() {
os.Stdout = old
}()
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
logger, err := NewLogger(filename, new(DailyRotateRule), true)
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filepath.Base(logger.getBackupFilename()) + ".gz")
}
logger.maybeCompressFile(filename)
_, err = os.Stat(filename)
assert.NotNil(t, err)
}
func TestRotateLoggerRotate(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
logger, err := NewLogger(filename, new(DailyRotateRule), true)
assert.Nil(t, err)
if len(filename) > 0 {
defer func() {
os.Remove(logger.getBackupFilename())
os.Remove(filepath.Base(logger.getBackupFilename()) + ".gz")
}()
}
err = logger.rotate()
switch v := err.(type) {
case *os.LinkError:
// avoid rename error on docker container
assert.Equal(t, syscall.EXDEV, v.Err)
case *os.PathError:
// ignore remove error for tests,
// files are cleaned in GitHub actions.
assert.Equal(t, "remove", v.Op)
default:
assert.Nil(t, err)
}
}
func TestRotateLoggerWrite(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
rule := new(DailyRotateRule)
logger, err := NewLogger(filename, rule, true)
assert.Nil(t, err)
if len(filename) > 0 {
defer func() {
os.Remove(logger.getBackupFilename())
os.Remove(filepath.Base(logger.getBackupFilename()) + ".gz")
}()
}
// the following write calls cannot be changed to Write, because of DATA RACE.
logger.write([]byte(`foo`))
rule.rotatedTime = time.Now().Add(-time.Hour * 24).Format(time.DateOnly)
logger.write([]byte(`bar`))
logger.Close()
logger.write([]byte(`baz`))
}
func TestLogWriterClose(t *testing.T) {
assert.Nil(t, newLogWriter(nil).Close())
}
func TestRotateLoggerWithSizeLimitRotateRuleClose(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(SizeLimitRotateRule), false)
assert.Nil(t, err)
_ = logger.Close()
}
func TestRotateLoggerGetBackupWithSizeLimitRotateRuleFilename(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(SizeLimitRotateRule), false)
assert.Nil(t, err)
assert.True(t, len(logger.getBackupFilename()) > 0)
logger.backup = ""
assert.True(t, len(logger.getBackupFilename()) > 0)
}
func TestRotateLoggerWithSizeLimitRotateRuleMayCompressFile(t *testing.T) {
old := os.Stdout
os.Stdout = os.NewFile(0, os.DevNull)
defer func() {
os.Stdout = old
}()
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
logger, err := NewLogger(filename, new(SizeLimitRotateRule), false)
assert.Nil(t, err)
logger.maybeCompressFile(filename)
_, err = os.Stat(filename)
assert.Nil(t, err)
}
func TestRotateLoggerWithSizeLimitRotateRuleMayCompressFileTrue(t *testing.T) {
old := os.Stdout
os.Stdout = os.NewFile(0, os.DevNull)
defer func() {
os.Stdout = old
}()
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
logger, err := NewLogger(filename, new(SizeLimitRotateRule), true)
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filepath.Base(logger.getBackupFilename()) + ".gz")
}
logger.maybeCompressFile(filename)
_, err = os.Stat(filename)
assert.NotNil(t, err)
}
func TestRotateLoggerWithSizeLimitRotateRuleMayCompressFileFailed(t *testing.T) {
old := os.Stdout
os.Stdout = os.NewFile(0, os.DevNull)
defer func() {
os.Stdout = old
}()
filename := stringx.RandId()
logger, err := NewLogger(filename, new(SizeLimitRotateRule), true)
defer os.Remove(filename)
if assert.NoError(t, err) {
assert.NotPanics(t, func() {
logger.maybeCompressFile(stringx.RandId())
})
}
}
func TestRotateLoggerWithSizeLimitRotateRuleRotate(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
logger, err := NewLogger(filename, new(SizeLimitRotateRule), true)
assert.Nil(t, err)
if len(filename) > 0 {
defer func() {
os.Remove(logger.getBackupFilename())
os.Remove(filepath.Base(logger.getBackupFilename()) + ".gz")
}()
}
err = logger.rotate()
switch v := err.(type) {
case *os.LinkError:
// avoid rename error on docker container
assert.Equal(t, syscall.EXDEV, v.Err)
case *os.PathError:
// ignore remove error for tests,
// files are cleaned in GitHub actions.
assert.Equal(t, "remove", v.Op)
default:
assert.Nil(t, err)
}
}
func TestRotateLoggerWithSizeLimitRotateRuleWrite(t *testing.T) {
filename, err := fs.TempFilenameWithText("foo")
assert.Nil(t, err)
rule := new(SizeLimitRotateRule)
logger, err := NewLogger(filename, rule, true)
assert.Nil(t, err)
if len(filename) > 0 {
defer func() {
os.Remove(logger.getBackupFilename())
os.Remove(filepath.Base(logger.getBackupFilename()) + ".gz")
}()
}
// the following write calls cannot be changed to Write, because of DATA RACE.
logger.write([]byte(`foo`))
rule.rotatedTime = time.Now().Add(-time.Hour * 24).Format(time.DateOnly)
logger.write([]byte(`bar`))
logger.Close()
logger.write([]byte(`baz`))
}
func TestGzipFile(t *testing.T) {
err := errors.New("any error")
t.Run("gzip file open failed", func(t *testing.T) {
fsys := &fakeFileSystem{
openFn: func(name string) (*os.File, error) {
return nil, err
},
}
assert.ErrorIs(t, err, gzipFile("any", fsys))
assert.False(t, fsys.Removed())
})
t.Run("gzip file create failed", func(t *testing.T) {
fsys := &fakeFileSystem{
createFn: func(name string) (*os.File, error) {
return nil, err
},
}
assert.ErrorIs(t, err, gzipFile("any", fsys))
assert.False(t, fsys.Removed())
})
t.Run("gzip file copy failed", func(t *testing.T) {
fsys := &fakeFileSystem{
copyFn: func(writer io.Writer, reader io.Reader) (int64, error) {
return 0, err
},
}
assert.ErrorIs(t, err, gzipFile("any", fsys))
assert.False(t, fsys.Removed())
})
t.Run("gzip file last close failed", func(t *testing.T) {
var called int32
fsys := &fakeFileSystem{
closeFn: func(closer io.Closer) error {
if atomic.AddInt32(&called, 1) > 2 {
return err
}
return nil
},
}
assert.NoError(t, gzipFile("any", fsys))
assert.True(t, fsys.Removed())
})
t.Run("gzip file remove failed", func(t *testing.T) {
fsys := &fakeFileSystem{
removeFn: func(name string) error {
return err
},
}
assert.Error(t, err, gzipFile("any", fsys))
assert.True(t, fsys.Removed())
})
t.Run("gzip file everything ok", func(t *testing.T) {
fsys := &fakeFileSystem{}
assert.NoError(t, gzipFile("any", fsys))
assert.True(t, fsys.Removed())
})
}
func TestRotateLogger_WithExistingFile(t *testing.T) {
const body = "foo"
filename, err := fs.TempFilenameWithText(body)
assert.Nil(t, err)
if len(filename) > 0 {
defer os.Remove(filename)
}
rule := NewSizeLimitRotateRule(filename, "-", 1, 100, 3, false)
logger, err := NewLogger(filename, rule, false)
assert.Nil(t, err)
assert.Equal(t, int64(len(body)), logger.currentSize)
assert.Nil(t, logger.Close())
}
func BenchmarkRotateLogger(b *testing.B) {
filename := "./test.log"
filename2 := "./test2.log"
dailyRotateRuleLogger, err1 := NewLogger(
filename,
DefaultRotateRule(
filename,
backupFileDelimiter,
1,
true,
),
true,
)
if err1 != nil {
b.Logf("Failed to new daily rotate rule logger: %v", err1)
b.FailNow()
}
sizeLimitRotateRuleLogger, err2 := NewLogger(
filename2,
NewSizeLimitRotateRule(
filename,
backupFileDelimiter,
1,
100,
10,
true,
),
true,
)
if err2 != nil {
b.Logf("Failed to new size limit rotate rule logger: %v", err1)
b.FailNow()
}
defer func() {
dailyRotateRuleLogger.Close()
sizeLimitRotateRuleLogger.Close()
os.Remove(filename)
os.Remove(filename2)
}()
b.Run("daily rotate rule", func(b *testing.B) {
for i := 0; i < b.N; i++ {
dailyRotateRuleLogger.write([]byte("testing\ntesting\n"))
}
})
b.Run("size limit rotate rule", func(b *testing.B) {
for i := 0; i < b.N; i++ {
sizeLimitRotateRuleLogger.write([]byte("testing\ntesting\n"))
}
})
}
type fakeFileSystem struct {
removed int32
closeFn func(closer io.Closer) error
copyFn func(writer io.Writer, reader io.Reader) (int64, error)
createFn func(name string) (*os.File, error)
openFn func(name string) (*os.File, error)
removeFn func(name string) error
}
func (f *fakeFileSystem) Close(closer io.Closer) error {
if f.closeFn != nil {
return f.closeFn(closer)
}
return nil
}
func (f *fakeFileSystem) Copy(writer io.Writer, reader io.Reader) (int64, error) {
if f.copyFn != nil {
return f.copyFn(writer, reader)
}
return 0, nil
}
func (f *fakeFileSystem) Create(name string) (*os.File, error) {
if f.createFn != nil {
return f.createFn(name)
}
return nil, nil
}
func (f *fakeFileSystem) Open(name string) (*os.File, error) {
if f.openFn != nil {
return f.openFn(name)
}
return nil, nil
}
func (f *fakeFileSystem) Remove(name string) error {
atomic.AddInt32(&f.removed, 1)
if f.removeFn != nil {
return f.removeFn(name)
}
return nil
}
func (f *fakeFileSystem) Removed() bool {
return atomic.LoadInt32(&f.removed) > 0
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/syslog_test.go | core/logx/syslog_test.go | package logx
import (
"encoding/json"
"log"
"strings"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
const testlog = "Stay hungry, stay foolish."
var testobj = map[string]any{"foo": "bar"}
func TestCollectSysLog(t *testing.T) {
CollectSysLog()
content := getContent(captureOutput(func() {
log.Print(testlog)
}))
assert.True(t, strings.Contains(content, testlog))
}
func TestRedirector(t *testing.T) {
var r redirector
content := getContent(captureOutput(func() {
r.Write([]byte(testlog))
}))
assert.Equal(t, testlog, content)
}
func captureOutput(f func()) string {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
prevLevel := atomic.LoadUint32(&logLevel)
SetLevel(InfoLevel)
f()
SetLevel(prevLevel)
return w.String()
}
func getContent(jsonStr string) string {
var entry map[string]any
json.Unmarshal([]byte(jsonStr), &entry)
val, ok := entry[contentKey]
if !ok {
return ""
}
str, ok := val.(string)
if !ok {
return ""
}
return str
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/lesslogger.go | core/logx/lesslogger.go | package logx
// A LessLogger is a logger that controls to log once during the given duration.
type LessLogger struct {
*limitedExecutor
}
// NewLessLogger returns a LessLogger.
func NewLessLogger(milliseconds int) *LessLogger {
return &LessLogger{
limitedExecutor: newLimitedExecutor(milliseconds),
}
}
// Error logs v into error log or discard it if more than once in the given duration.
func (logger *LessLogger) Error(v ...any) {
logger.logOrDiscard(func() {
Error(v...)
})
}
// Errorf logs v with format into error log or discard it if more than once in the given duration.
func (logger *LessLogger) Errorf(format string, v ...any) {
logger.logOrDiscard(func() {
Errorf(format, v...)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/logwriter.go | core/logx/logwriter.go | package logx
import "log"
type logWriter struct {
logger *log.Logger
}
func newLogWriter(logger *log.Logger) logWriter {
return logWriter{
logger: logger,
}
}
func (lw logWriter) Close() error {
return nil
}
func (lw logWriter) Write(data []byte) (int, error) {
lw.logger.Print(string(data))
return len(data), nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/lesslogger_test.go | core/logx/lesslogger_test.go | package logx
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLessLogger_Error(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
l := NewLessLogger(500)
for i := 0; i < 100; i++ {
l.Error("hello")
}
assert.Equal(t, 1, strings.Count(w.String(), "\n"))
}
func TestLessLogger_Errorf(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
l := NewLessLogger(500)
for i := 0; i < 100; i++ {
l.Errorf("hello")
}
assert.Equal(t, 1, strings.Count(w.String(), "\n"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/syslog.go | core/logx/syslog.go | package logx
import "log"
type redirector struct{}
// CollectSysLog redirects system log into logx info
func CollectSysLog() {
log.SetOutput(new(redirector))
}
func (r *redirector) Write(p []byte) (n int, err error) {
Info(string(p))
return len(p), nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/config.go | core/logx/config.go | package logx
type (
// A LogConf is a logging config.
LogConf struct {
// ServiceName represents the service name.
ServiceName string `json:",optional"`
// Mode represents the logging mode, default is `console`.
// console: log to console.
// file: log to file.
// volume: used in k8s, prepend the hostname to the log file name.
Mode string `json:",default=console,options=[console,file,volume]"`
// Encoding represents the encoding type, default is `json`.
// json: json encoding.
// plain: plain text encoding, typically used in development.
Encoding string `json:",default=json,options=[json,plain]"`
// TimeFormat represents the time format, default is `2006-01-02T15:04:05.000Z07:00`.
TimeFormat string `json:",optional"`
// Path represents the log file path, default is `logs`.
Path string `json:",default=logs"`
// Level represents the log level, default is `info`.
Level string `json:",default=info,options=[debug,info,error,severe]"`
// MaxContentLength represents the max content bytes, default is no limit.
MaxContentLength uint32 `json:",optional"`
// Compress represents whether to compress the log file, default is `false`.
Compress bool `json:",optional"`
// Stat represents whether to log statistics, default is `true`.
Stat bool `json:",default=true"`
// KeepDays represents how many days the log files will be kept. Default to keep all files.
// Only take effect when Mode is `file` or `volume`, both work when Rotation is `daily` or `size`.
KeepDays int `json:",optional"`
// StackCooldownMillis represents the cooldown time for stack logging, default is 100ms.
StackCooldownMillis int `json:",default=100"`
// MaxBackups represents how many backup log files will be kept. 0 means all files will be kept forever.
// Only take effect when RotationRuleType is `size`.
// Even though `MaxBackups` sets 0, log files will still be removed
// if the `KeepDays` limitation is reached.
MaxBackups int `json:",default=0"`
// MaxSize represents how much space the writing log file takes up. 0 means no limit. The unit is `MB`.
// Only take effect when RotationRuleType is `size`
MaxSize int `json:",default=0"`
// Rotation represents the type of log rotation rule. Default is `daily`.
// daily: daily rotation.
// size: size limited rotation.
Rotation string `json:",default=daily,options=[daily,size]"`
// FileTimeFormat represents the time format for file name, default is `2006-01-02T15:04:05.000Z07:00`.
FileTimeFormat string `json:",optional"`
// FieldKeys represents the field keys.
FieldKeys fieldKeyConf `json:",optional"`
}
fieldKeyConf struct {
// CallerKey represents the caller key.
CallerKey string `json:",default=caller"`
// ContentKey represents the content key.
ContentKey string `json:",default=content"`
// DurationKey represents the duration key.
DurationKey string `json:",default=duration"`
// LevelKey represents the level key.
LevelKey string `json:",default=level"`
// SpanKey represents the span key.
SpanKey string `json:",default=span"`
// TimestampKey represents the timestamp key.
TimestampKey string `json:",default=@timestamp"`
// TraceKey represents the trace key.
TraceKey string `json:",default=trace"`
// TruncatedKey represents the truncated key.
TruncatedKey string `json:",default=truncated"`
}
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/limitedexecutor_test.go | core/logx/limitedexecutor_test.go | package logx
import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/timex"
)
func TestLimitedExecutor_logOrDiscard(t *testing.T) {
tests := []struct {
name string
threshold time.Duration
lastTime time.Duration
discarded uint32
executed bool
}{
{
name: "nil executor",
executed: true,
},
{
name: "regular",
threshold: time.Hour,
lastTime: timex.Now(),
discarded: 10,
executed: false,
},
{
name: "slow",
threshold: time.Duration(1),
lastTime: -1000,
discarded: 10,
executed: true,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
executor := newLimitedExecutor(0)
executor.threshold = test.threshold
executor.discarded = test.discarded
executor.lastTime.Set(test.lastTime)
var run int32
executor.logOrDiscard(func() {
atomic.AddInt32(&run, 1)
})
if test.executed {
assert.Equal(t, int32(1), atomic.LoadInt32(&run))
} else {
assert.Equal(t, int32(0), atomic.LoadInt32(&run))
assert.Equal(t, test.discarded+1, atomic.LoadUint32(&executor.discarded))
}
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/writer.go | core/logx/writer.go | package logx
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"path"
"runtime/debug"
"sync"
"sync/atomic"
"time"
fatihcolor "github.com/fatih/color"
"github.com/zeromicro/go-zero/core/color"
"github.com/zeromicro/go-zero/core/errorx"
)
type (
// Writer is the interface for writing logs.
// It's designed to let users customize their own log writer,
// such as writing logs to a kafka, a database, or using third-party loggers.
Writer interface {
// Alert sends an alert message, if your writer implemented alerting functionality.
Alert(v any)
// Close closes the writer.
Close() error
// Debug logs a message at debug level.
Debug(v any, fields ...LogField)
// Error logs a message at error level.
Error(v any, fields ...LogField)
// Info logs a message at info level.
Info(v any, fields ...LogField)
// Severe logs a message at severe level.
Severe(v any)
// Slow logs a message at slow level.
Slow(v any, fields ...LogField)
// Stack logs a message at error level.
Stack(v any)
// Stat logs a message at stat level.
Stat(v any, fields ...LogField)
}
atomicWriter struct {
writer Writer
lock sync.RWMutex
}
comboWriter struct {
writers []Writer
}
concreteWriter struct {
infoLog io.WriteCloser
errorLog io.WriteCloser
severeLog io.WriteCloser
slowLog io.WriteCloser
statLog io.WriteCloser
stackLog io.Writer
}
)
// NewWriter creates a new Writer with the given io.Writer.
func NewWriter(w io.Writer) Writer {
lw := newLogWriter(log.New(w, "", flags))
return &concreteWriter{
infoLog: lw,
errorLog: lw,
severeLog: lw,
slowLog: lw,
statLog: lw,
stackLog: lw,
}
}
func (w *atomicWriter) Load() Writer {
w.lock.RLock()
defer w.lock.RUnlock()
return w.writer
}
func (w *atomicWriter) Store(v Writer) {
w.lock.Lock()
defer w.lock.Unlock()
w.writer = v
}
func (w *atomicWriter) StoreIfNil(v Writer) Writer {
w.lock.Lock()
defer w.lock.Unlock()
if w.writer == nil {
w.writer = v
}
return w.writer
}
func (w *atomicWriter) Swap(v Writer) Writer {
w.lock.Lock()
defer w.lock.Unlock()
old := w.writer
w.writer = v
return old
}
func (c comboWriter) Alert(v any) {
for _, w := range c.writers {
w.Alert(v)
}
}
func (c comboWriter) Close() error {
var be errorx.BatchError
for _, w := range c.writers {
be.Add(w.Close())
}
return be.Err()
}
func (c comboWriter) Debug(v any, fields ...LogField) {
for _, w := range c.writers {
w.Debug(v, fields...)
}
}
func (c comboWriter) Error(v any, fields ...LogField) {
for _, w := range c.writers {
w.Error(v, fields...)
}
}
func (c comboWriter) Info(v any, fields ...LogField) {
for _, w := range c.writers {
w.Info(v, fields...)
}
}
func (c comboWriter) Severe(v any) {
for _, w := range c.writers {
w.Severe(v)
}
}
func (c comboWriter) Slow(v any, fields ...LogField) {
for _, w := range c.writers {
w.Slow(v, fields...)
}
}
func (c comboWriter) Stack(v any) {
for _, w := range c.writers {
w.Stack(v)
}
}
func (c comboWriter) Stat(v any, fields ...LogField) {
for _, w := range c.writers {
w.Stat(v, fields...)
}
}
func newConsoleWriter() Writer {
outLog := newLogWriter(log.New(fatihcolor.Output, "", flags))
errLog := newLogWriter(log.New(fatihcolor.Error, "", flags))
return &concreteWriter{
infoLog: outLog,
errorLog: errLog,
severeLog: errLog,
slowLog: errLog,
stackLog: newLessWriter(errLog, options.logStackCooldownMills),
statLog: outLog,
}
}
func newFileWriter(c LogConf) (Writer, error) {
var err error
var opts []LogOption
var infoLog io.WriteCloser
var errorLog io.WriteCloser
var severeLog io.WriteCloser
var slowLog io.WriteCloser
var statLog io.WriteCloser
var stackLog io.Writer
if len(c.Path) == 0 {
return nil, ErrLogPathNotSet
}
opts = append(opts, WithCooldownMillis(c.StackCooldownMillis))
if c.Compress {
opts = append(opts, WithGzip())
}
if c.KeepDays > 0 {
opts = append(opts, WithKeepDays(c.KeepDays))
}
if c.MaxBackups > 0 {
opts = append(opts, WithMaxBackups(c.MaxBackups))
}
if c.MaxSize > 0 {
opts = append(opts, WithMaxSize(c.MaxSize))
}
opts = append(opts, WithRotation(c.Rotation))
accessFile := path.Join(c.Path, accessFilename)
errorFile := path.Join(c.Path, errorFilename)
severeFile := path.Join(c.Path, severeFilename)
slowFile := path.Join(c.Path, slowFilename)
statFile := path.Join(c.Path, statFilename)
handleOptions(opts)
if infoLog, err = createOutput(accessFile); err != nil {
return nil, err
}
if errorLog, err = createOutput(errorFile); err != nil {
return nil, err
}
if severeLog, err = createOutput(severeFile); err != nil {
return nil, err
}
if slowLog, err = createOutput(slowFile); err != nil {
return nil, err
}
if statLog, err = createOutput(statFile); err != nil {
return nil, err
}
stackLog = newLessWriter(errorLog, options.logStackCooldownMills)
return &concreteWriter{
infoLog: infoLog,
errorLog: errorLog,
severeLog: severeLog,
slowLog: slowLog,
statLog: statLog,
stackLog: stackLog,
}, nil
}
func (w *concreteWriter) Alert(v any) {
output(w.errorLog, levelAlert, v)
}
func (w *concreteWriter) Close() error {
if err := w.infoLog.Close(); err != nil {
return err
}
if err := w.errorLog.Close(); err != nil {
return err
}
if err := w.severeLog.Close(); err != nil {
return err
}
if err := w.slowLog.Close(); err != nil {
return err
}
return w.statLog.Close()
}
func (w *concreteWriter) Debug(v any, fields ...LogField) {
output(w.infoLog, levelDebug, v, fields...)
}
func (w *concreteWriter) Error(v any, fields ...LogField) {
output(w.errorLog, levelError, v, fields...)
}
func (w *concreteWriter) Info(v any, fields ...LogField) {
output(w.infoLog, levelInfo, v, fields...)
}
func (w *concreteWriter) Severe(v any) {
output(w.severeLog, levelFatal, v)
}
func (w *concreteWriter) Slow(v any, fields ...LogField) {
output(w.slowLog, levelSlow, v, fields...)
}
func (w *concreteWriter) Stack(v any) {
output(w.stackLog, levelError, v)
}
func (w *concreteWriter) Stat(v any, fields ...LogField) {
output(w.statLog, levelStat, v, fields...)
}
type nopWriter struct{}
func (n nopWriter) Alert(_ any) {
}
func (n nopWriter) Close() error {
return nil
}
func (n nopWriter) Debug(_ any, _ ...LogField) {
}
func (n nopWriter) Error(_ any, _ ...LogField) {
}
func (n nopWriter) Info(_ any, _ ...LogField) {
}
func (n nopWriter) Severe(_ any) {
}
func (n nopWriter) Slow(_ any, _ ...LogField) {
}
func (n nopWriter) Stack(_ any) {
}
func (n nopWriter) Stat(_ any, _ ...LogField) {
}
func buildPlainFields(fields logEntry) []string {
items := make([]string, 0, len(fields))
for k, v := range fields {
items = append(items, fmt.Sprintf("%s=%+v", k, v))
}
return items
}
func marshalJson(t interface{}) ([]byte, error) {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
// go 1.5+ will append a newline to the end of the json string
// https://github.com/golang/go/issues/13520
if l := buf.Len(); l > 0 && buf.Bytes()[l-1] == '\n' {
buf.Truncate(l - 1)
}
return buf.Bytes(), err
}
func mergeGlobalFields(fields []LogField) []LogField {
globals := globalFields.Load()
if globals == nil {
return fields
}
gf := globals.([]LogField)
ret := make([]LogField, 0, len(gf)+len(fields))
ret = append(ret, gf...)
ret = append(ret, fields...)
return ret
}
func output(writer io.Writer, level string, val any, fields ...LogField) {
switch v := val.(type) {
case string:
// only truncate string content, don't know how to truncate the values of other types.
maxLen := atomic.LoadUint32(&maxContentLength)
if maxLen > 0 && len(v) > int(maxLen) {
val = v[:maxLen]
fields = append(fields, truncatedField)
}
case Sensitive:
val = v.MaskSensitive()
}
// +3 for timestamp, level and content
entry := make(logEntry, len(fields)+3)
for _, field := range fields {
// mask sensitive data before processing types,
// in case field.Value is a sensitive type and also implemented fmt.Stringer.
mval := maskSensitive(field.Value)
entry[field.Key] = processFieldValue(mval)
}
switch atomic.LoadUint32(&encoding) {
case plainEncodingType:
plainFields := buildPlainFields(entry)
writePlainAny(writer, level, val, plainFields...)
default:
entry[timestampKey] = getTimestamp()
entry[levelKey] = level
entry[contentKey] = val
writeJson(writer, entry)
}
}
func processFieldValue(value any) any {
switch val := value.(type) {
case error:
return encodeError(val)
case []error:
var errs []string
for _, err := range val {
errs = append(errs, encodeError(err))
}
return errs
case time.Duration:
return fmt.Sprint(val)
case []time.Duration:
var durs []string
for _, dur := range val {
durs = append(durs, fmt.Sprint(dur))
}
return durs
case []time.Time:
var times []string
for _, t := range val {
times = append(times, fmt.Sprint(t))
}
return times
case json.Marshaler:
return val
case fmt.Stringer:
return encodeStringer(val)
case []fmt.Stringer:
var strs []string
for _, str := range val {
strs = append(strs, encodeStringer(str))
}
return strs
default:
return val
}
}
func wrapLevelWithColor(level string) string {
var colour color.Color
switch level {
case levelAlert:
colour = color.FgRed
case levelError:
colour = color.FgRed
case levelSevere:
colour = color.FgRed
case levelFatal:
colour = color.FgRed
case levelInfo:
colour = color.FgBlue
case levelSlow:
colour = color.FgYellow
case levelDebug:
colour = color.FgYellow
case levelStat:
colour = color.FgGreen
}
if colour == color.NoColor {
return level
}
return color.WithColorPadding(level, colour)
}
func writeJson(writer io.Writer, info any) {
if content, err := marshalJson(info); err != nil {
log.Printf("err: %s\n\n%s", err.Error(), debug.Stack())
} else if writer == nil {
log.Println(string(content))
} else {
if _, err := writer.Write(append(content, '\n')); err != nil {
log.Println(err.Error())
}
}
}
func writePlainAny(writer io.Writer, level string, val any, fields ...string) {
level = wrapLevelWithColor(level)
switch v := val.(type) {
case string:
writePlainText(writer, level, v, fields...)
case error:
writePlainText(writer, level, v.Error(), fields...)
case fmt.Stringer:
writePlainText(writer, level, v.String(), fields...)
default:
writePlainValue(writer, level, v, fields...)
}
}
func writePlainText(writer io.Writer, level, msg string, fields ...string) {
var buf bytes.Buffer
buf.WriteString(getTimestamp())
buf.WriteByte(plainEncodingSep)
buf.WriteString(level)
buf.WriteByte(plainEncodingSep)
buf.WriteString(msg)
for _, item := range fields {
buf.WriteByte(plainEncodingSep)
buf.WriteString(item)
}
buf.WriteByte('\n')
if writer == nil {
log.Println(buf.String())
return
}
if _, err := writer.Write(buf.Bytes()); err != nil {
log.Println(err.Error())
}
}
func writePlainValue(writer io.Writer, level string, val any, fields ...string) {
var buf bytes.Buffer
buf.WriteString(getTimestamp())
buf.WriteByte(plainEncodingSep)
buf.WriteString(level)
buf.WriteByte(plainEncodingSep)
if err := json.NewEncoder(&buf).Encode(val); err != nil {
log.Printf("err: %s\n\n%s", err.Error(), debug.Stack())
return
}
for _, item := range fields {
buf.WriteByte(plainEncodingSep)
buf.WriteString(item)
}
buf.WriteByte('\n')
if writer == nil {
log.Println(buf.String())
return
}
if _, err := writer.Write(buf.Bytes()); err != nil {
log.Println(err.Error())
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/color_test.go | core/logx/color_test.go | package logx
import (
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/color"
)
func TestWithColor(t *testing.T) {
old := atomic.SwapUint32(&encoding, plainEncodingType)
defer atomic.StoreUint32(&encoding, old)
output := WithColor("hello", color.BgBlue)
assert.Equal(t, "hello", output)
atomic.StoreUint32(&encoding, jsonEncodingType)
output = WithColor("hello", color.BgBlue)
assert.Equal(t, "hello", output)
}
func TestWithColorPadding(t *testing.T) {
old := atomic.SwapUint32(&encoding, plainEncodingType)
defer atomic.StoreUint32(&encoding, old)
output := WithColorPadding("hello", color.BgBlue)
assert.Equal(t, " hello ", output)
atomic.StoreUint32(&encoding, jsonEncodingType)
output = WithColorPadding("hello", color.BgBlue)
assert.Equal(t, "hello", output)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/util.go | core/logx/util.go | package logx
import (
"fmt"
"runtime"
"strings"
"time"
)
func getCaller(callDepth int) string {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
return ""
}
return prettyCaller(file, line)
}
func getTimestamp() string {
return time.Now().Format(timeFormat)
}
func prettyCaller(file string, line int) string {
idx := strings.LastIndexByte(file, '/')
if idx < 0 {
return fmt.Sprintf("%s:%d", file, line)
}
idx = strings.LastIndexByte(file[:idx], '/')
if idx < 0 {
return fmt.Sprintf("%s:%d", file, line)
}
return fmt.Sprintf("%s:%d", file[idx+1:], line)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/richlogger_test.go | core/logx/richlogger_test.go | package logx
import (
"context"
"encoding/json"
"fmt"
"io"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
func TestTraceLog(t *testing.T) {
SetLevel(InfoLevel)
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
otp := otel.GetTracerProvider()
tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()))
otel.SetTracerProvider(tp)
defer otel.SetTracerProvider(otp)
ctx, span := tp.Tracer("trace-id").Start(context.Background(), "span-id")
defer span.End()
WithContext(ctx).Info(testlog)
validate(t, w.String(), true, true)
}
func TestTraceDebug(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
otp := otel.GetTracerProvider()
tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()))
otel.SetTracerProvider(tp)
defer otel.SetTracerProvider(otp)
ctx, span := tp.Tracer("foo").Start(context.Background(), "bar")
defer span.End()
l := WithContext(ctx)
SetLevel(DebugLevel)
l.WithDuration(time.Second).Debug(testlog)
assert.True(t, strings.Contains(w.String(), traceKey))
assert.True(t, strings.Contains(w.String(), spanKey))
w.Reset()
l.WithDuration(time.Second).Debugf(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Debugfn(func() any {
return testlog
})
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Debugv(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Debugv(testobj)
validateContentType(t, w.String(), map[string]any{}, true, true)
w.Reset()
l.WithDuration(time.Second).Debugw(testlog, Field("foo", "bar"))
validate(t, w.String(), true, true)
assert.True(t, strings.Contains(w.String(), "foo"), w.String())
assert.True(t, strings.Contains(w.String(), "bar"), w.String())
}
func TestTraceError(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
otp := otel.GetTracerProvider()
tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()))
otel.SetTracerProvider(tp)
defer otel.SetTracerProvider(otp)
ctx, span := tp.Tracer("trace-id").Start(context.Background(), "span-id")
defer span.End()
var nilCtx context.Context
l := WithContext(context.Background())
l = l.WithContext(nilCtx)
l = l.WithContext(ctx)
SetLevel(ErrorLevel)
l.WithDuration(time.Second).Error(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Errorf(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Errorfn(func() any {
return testlog
})
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Errorv(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Errorv(testobj)
validateContentType(t, w.String(), map[string]any{}, true, true)
w.Reset()
l.WithDuration(time.Second).Errorw(testlog, Field("basket", "ball"))
validate(t, w.String(), true, true)
assert.True(t, strings.Contains(w.String(), "basket"), w.String())
assert.True(t, strings.Contains(w.String(), "ball"), w.String())
}
func TestTraceInfo(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
otp := otel.GetTracerProvider()
tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()))
otel.SetTracerProvider(tp)
defer otel.SetTracerProvider(otp)
ctx, span := tp.Tracer("trace-id").Start(context.Background(), "span-id")
defer span.End()
SetLevel(InfoLevel)
l := WithContext(ctx)
l.WithDuration(time.Second).Info(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Infof(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Infofn(func() any {
return testlog
})
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Infov(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Infov(testobj)
validateContentType(t, w.String(), map[string]any{}, true, true)
w.Reset()
l.WithDuration(time.Second).Infow(testlog, Field("basket", "ball"))
validate(t, w.String(), true, true)
assert.True(t, strings.Contains(w.String(), "basket"), w.String())
assert.True(t, strings.Contains(w.String(), "ball"), w.String())
}
func TestTraceInfoConsole(t *testing.T) {
old := atomic.SwapUint32(&encoding, jsonEncodingType)
defer atomic.StoreUint32(&encoding, old)
w := new(mockWriter)
o := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(o)
}()
otp := otel.GetTracerProvider()
tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()))
otel.SetTracerProvider(tp)
defer otel.SetTracerProvider(otp)
ctx, span := tp.Tracer("trace-id").Start(context.Background(), "span-id")
defer span.End()
l := WithContext(ctx)
SetLevel(InfoLevel)
l.WithDuration(time.Second).Info(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Infof(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Infov(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Infov(testobj)
validateContentType(t, w.String(), map[string]any{}, true, true)
}
func TestTraceSlow(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
otp := otel.GetTracerProvider()
tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()))
otel.SetTracerProvider(tp)
defer otel.SetTracerProvider(otp)
ctx, span := tp.Tracer("trace-id").Start(context.Background(), "span-id")
defer span.End()
l := WithContext(ctx)
SetLevel(InfoLevel)
l.WithDuration(time.Second).Slow(testlog)
assert.True(t, strings.Contains(w.String(), traceKey))
assert.True(t, strings.Contains(w.String(), spanKey))
w.Reset()
l.WithDuration(time.Second).Slowf(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Slowfn(func() any {
return testlog
})
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Slowv(testlog)
validate(t, w.String(), true, true)
w.Reset()
l.WithDuration(time.Second).Slowv(testobj)
validateContentType(t, w.String(), map[string]any{}, true, true)
w.Reset()
l.WithDuration(time.Second).Sloww(testlog, Field("basket", "ball"))
validate(t, w.String(), true, true)
assert.True(t, strings.Contains(w.String(), "basket"), w.String())
assert.True(t, strings.Contains(w.String(), "ball"), w.String())
}
func TestTraceWithoutContext(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
l := WithContext(context.Background())
SetLevel(InfoLevel)
l.WithDuration(time.Second).Info(testlog)
validate(t, w.String(), false, false)
w.Reset()
l.WithDuration(time.Second).Infof(testlog)
validate(t, w.String(), false, false)
}
func TestLogWithFields(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
ctx := ContextWithFields(context.Background(), Field("foo", "bar"))
l := WithContext(ctx)
SetLevel(InfoLevel)
l.Info(testlog)
var val mockValue
assert.Nil(t, json.Unmarshal([]byte(w.String()), &val))
assert.Equal(t, "bar", val.Foo)
}
func TestLogWithCallerSkip(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
l := WithCallerSkip(1).WithCallerSkip(0)
p := func(v string) {
l.Info(v)
}
file, line := getFileLine()
p(testlog)
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
w.Reset()
l = WithCallerSkip(0).WithCallerSkip(1)
file, line = getFileLine()
p(testlog)
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
}
func TestLogWithCallerSkipCopy(t *testing.T) {
log1 := WithCallerSkip(2)
log2 := log1.WithCallerSkip(3)
log3 := log2.WithCallerSkip(-1)
assert.Equal(t, 2, log1.(*richLogger).callerSkip)
assert.Equal(t, 3, log2.(*richLogger).callerSkip)
assert.Equal(t, 3, log3.(*richLogger).callerSkip)
}
func TestLogWithContextCopy(t *testing.T) {
c1 := context.Background()
c2 := context.WithValue(context.Background(), "foo", "bar")
log1 := WithContext(c1)
log2 := log1.WithContext(c2)
assert.Equal(t, c1, log1.(*richLogger).ctx)
assert.Equal(t, c2, log2.(*richLogger).ctx)
}
func TestLogWithDurationCopy(t *testing.T) {
log1 := WithContext(context.Background())
log2 := log1.WithDuration(time.Second)
assert.Empty(t, log1.(*richLogger).fields)
assert.Equal(t, 1, len(log2.(*richLogger).fields))
var w mockWriter
old := writer.Swap(&w)
defer writer.Store(old)
log2.Info("hello")
assert.Contains(t, w.String(), `"duration":"1000.0ms"`)
}
func TestLogWithFieldsCopy(t *testing.T) {
log1 := WithContext(context.Background())
log2 := log1.WithFields(Field("foo", "bar"))
log3 := log1.WithFields()
assert.Empty(t, log1.(*richLogger).fields)
assert.Equal(t, 1, len(log2.(*richLogger).fields))
assert.Equal(t, log1, log3)
assert.Empty(t, log3.(*richLogger).fields)
var w mockWriter
old := writer.Swap(&w)
defer writer.Store(old)
log2.Info("hello")
assert.Contains(t, w.String(), `"foo":"bar"`)
}
func TestLoggerWithFields(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
l := WithContext(context.Background()).WithFields(Field("foo", "bar"))
l.Info(testlog)
var val mockValue
assert.Nil(t, json.Unmarshal([]byte(w.String()), &val))
assert.Equal(t, "bar", val.Foo)
}
func validate(t *testing.T, body string, expectedTrace, expectedSpan bool) {
var val mockValue
dec := json.NewDecoder(strings.NewReader(body))
for {
var doc mockValue
err := dec.Decode(&doc)
if err == io.EOF {
// all done
break
}
if err != nil {
continue
}
val = doc
}
assert.Equal(t, expectedTrace, len(val.Trace) > 0, body)
assert.Equal(t, expectedSpan, len(val.Span) > 0, body)
}
func validateContentType(t *testing.T, body string, expectedType any, expectedTrace, expectedSpan bool) {
var val mockValue
dec := json.NewDecoder(strings.NewReader(body))
for {
var doc mockValue
err := dec.Decode(&doc)
if err == io.EOF {
// all done
break
}
if err != nil {
continue
}
val = doc
}
assert.IsType(t, expectedType, val.Content, body)
assert.Equal(t, expectedTrace, len(val.Trace) > 0, body)
assert.Equal(t, expectedSpan, len(val.Span) > 0, body)
}
type mockValue struct {
Trace string `json:"trace"`
Span string `json:"span"`
Foo string `json:"foo"`
Content any `json:"content"`
}
type testJson struct {
Name string `json:"name"`
Age int `json:"age"`
Score float64 `json:"score"`
}
func (t testJson) MarshalJSON() ([]byte, error) {
type testJsonImpl testJson
return json.Marshal(testJsonImpl(t))
}
func (t testJson) String() string {
return fmt.Sprintf("%s %d %f", t.Name, t.Age, t.Score)
}
func TestLogWithJson(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()
l := WithContext(context.Background()).WithFields(Field("bar", testJson{
Name: "foo",
Age: 1,
Score: 1.0,
}))
l.Info(testlog)
type mockValue2 struct {
mockValue
Bar testJson `json:"bar"`
}
var val mockValue2
err := json.Unmarshal([]byte(w.String()), &val)
assert.NoError(t, err)
assert.Equal(t, testlog, val.Content)
assert.Equal(t, "foo", val.Bar.Name)
assert.Equal(t, 1, val.Bar.Age)
assert.Equal(t, 1.0, val.Bar.Score)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/color.go | core/logx/color.go | package logx
import (
"sync/atomic"
"github.com/zeromicro/go-zero/core/color"
)
// WithColor is a helper function to add color to a string, only in plain encoding.
func WithColor(text string, colour color.Color) string {
if atomic.LoadUint32(&encoding) == plainEncodingType {
return color.WithColor(text, colour)
}
return text
}
// WithColorPadding is a helper function to add color to a string with leading and trailing spaces,
// only in plain encoding.
func WithColorPadding(text string, colour color.Color) string {
if atomic.LoadUint32(&encoding) == plainEncodingType {
return color.WithColorPadding(text, colour)
}
return text
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/fields_test.go | core/logx/fields_test.go | package logx
import (
"bytes"
"context"
"encoding/json"
"strconv"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAddGlobalFields(t *testing.T) {
var buf bytes.Buffer
writer := NewWriter(&buf)
old := Reset()
SetWriter(writer)
defer SetWriter(old)
Info("hello")
buf.Reset()
AddGlobalFields(Field("a", "1"), Field("b", "2"))
AddGlobalFields(Field("c", "3"))
Info("world")
var m map[string]any
assert.NoError(t, json.Unmarshal(buf.Bytes(), &m))
assert.Equal(t, "1", m["a"])
assert.Equal(t, "2", m["b"])
assert.Equal(t, "3", m["c"])
}
func TestContextWithFields(t *testing.T) {
ctx := ContextWithFields(context.Background(), Field("a", 1), Field("b", 2))
vals := ctx.Value(fieldsKey{})
assert.NotNil(t, vals)
fields, ok := vals.([]LogField)
assert.True(t, ok)
assert.EqualValues(t, []LogField{Field("a", 1), Field("b", 2)}, fields)
}
func TestWithFields(t *testing.T) {
ctx := WithFields(context.Background(), Field("a", 1), Field("b", 2))
vals := ctx.Value(fieldsKey{})
assert.NotNil(t, vals)
fields, ok := vals.([]LogField)
assert.True(t, ok)
assert.EqualValues(t, []LogField{Field("a", 1), Field("b", 2)}, fields)
}
func TestWithFieldsAppend(t *testing.T) {
var dummyKey struct{}
ctx := context.WithValue(context.Background(), dummyKey, "dummy")
ctx = ContextWithFields(ctx, Field("a", 1), Field("b", 2))
ctx = ContextWithFields(ctx, Field("c", 3), Field("d", 4))
vals := ctx.Value(fieldsKey{})
assert.NotNil(t, vals)
fields, ok := vals.([]LogField)
assert.True(t, ok)
assert.Equal(t, "dummy", ctx.Value(dummyKey))
assert.EqualValues(t, []LogField{
Field("a", 1),
Field("b", 2),
Field("c", 3),
Field("d", 4),
}, fields)
}
func TestWithFieldsAppendCopy(t *testing.T) {
const count = 10
ctx := context.Background()
for i := 0; i < count; i++ {
ctx = ContextWithFields(ctx, Field(strconv.Itoa(i), 1))
}
af := Field("foo", 1)
bf := Field("bar", 2)
ctxa := ContextWithFields(ctx, af)
ctxb := ContextWithFields(ctx, bf)
assert.EqualValues(t, af, ctxa.Value(fieldsKey{}).([]LogField)[count])
assert.EqualValues(t, bf, ctxb.Value(fieldsKey{}).([]LogField)[count])
}
func BenchmarkAtomicValue(b *testing.B) {
b.ReportAllocs()
var container atomic.Value
vals := []LogField{
Field("a", "b"),
Field("c", "d"),
Field("e", "f"),
}
container.Store(&vals)
for i := 0; i < b.N; i++ {
val := container.Load()
if val != nil {
_ = *val.(*[]LogField)
}
}
}
func BenchmarkRWMutex(b *testing.B) {
b.ReportAllocs()
var lock sync.RWMutex
vals := []LogField{
Field("a", "b"),
Field("c", "d"),
Field("e", "f"),
}
for i := 0; i < b.N; i++ {
lock.RLock()
_ = vals
lock.RUnlock()
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/rotatelogger.go | core/logx/rotatelogger.go | package logx
import (
"compress/gzip"
"errors"
"fmt"
"log"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/fs"
"github.com/zeromicro/go-zero/core/lang"
)
const (
hoursPerDay = 24
bufferSize = 100
defaultDirMode = 0o755
defaultFileMode = 0o600
gzipExt = ".gz"
megaBytes = 1 << 20
)
var (
// ErrLogFileClosed is an error that indicates the log file is already closed.
ErrLogFileClosed = errors.New("error: log file closed")
fileTimeFormat = time.RFC3339
)
type (
// A RotateRule interface is used to define the log rotating rules.
RotateRule interface {
BackupFileName() string
MarkRotated()
OutdatedFiles() []string
ShallRotate(size int64) bool
}
// A RotateLogger is a Logger that can rotate log files with given rules.
RotateLogger struct {
filename string
backup string
fp *os.File
channel chan []byte
done chan lang.PlaceholderType
rule RotateRule
compress bool
// can't use threading.RoutineGroup because of cycle import
waitGroup sync.WaitGroup
closeOnce sync.Once
currentSize int64
}
// A DailyRotateRule is a rule to daily rotate the log files.
DailyRotateRule struct {
rotatedTime string
filename string
delimiter string
days int
gzip bool
}
// SizeLimitRotateRule a rotation rule that makes the log file rotated based on size
SizeLimitRotateRule struct {
DailyRotateRule
maxSize int64
maxBackups int
}
)
// DefaultRotateRule is a default log rotating rule, currently DailyRotateRule.
func DefaultRotateRule(filename, delimiter string, days int, gzip bool) RotateRule {
return &DailyRotateRule{
rotatedTime: getNowDate(),
filename: filename,
delimiter: delimiter,
days: days,
gzip: gzip,
}
}
// BackupFileName returns the backup filename on rotating.
func (r *DailyRotateRule) BackupFileName() string {
return fmt.Sprintf("%s%s%s", r.filename, r.delimiter, getNowDate())
}
// MarkRotated marks the rotated time of r to be the current time.
func (r *DailyRotateRule) MarkRotated() {
r.rotatedTime = getNowDate()
}
// OutdatedFiles returns the files that exceeded the keeping days.
func (r *DailyRotateRule) OutdatedFiles() []string {
if r.days <= 0 {
return nil
}
var pattern string
if r.gzip {
pattern = fmt.Sprintf("%s%s*%s", r.filename, r.delimiter, gzipExt)
} else {
pattern = fmt.Sprintf("%s%s*", r.filename, r.delimiter)
}
files, err := filepath.Glob(pattern)
if err != nil {
Errorf("failed to delete outdated log files, error: %s", err)
return nil
}
var buf strings.Builder
boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay*r.days)).Format(time.DateOnly)
buf.WriteString(r.filename)
buf.WriteString(r.delimiter)
buf.WriteString(boundary)
if r.gzip {
buf.WriteString(gzipExt)
}
boundaryFile := buf.String()
var outdates []string
for _, file := range files {
if file < boundaryFile {
outdates = append(outdates, file)
}
}
return outdates
}
// ShallRotate checks if the file should be rotated.
func (r *DailyRotateRule) ShallRotate(_ int64) bool {
return len(r.rotatedTime) > 0 && getNowDate() != r.rotatedTime
}
// NewSizeLimitRotateRule returns the rotation rule with size limit
func NewSizeLimitRotateRule(filename, delimiter string, days, maxSize, maxBackups int, gzip bool) RotateRule {
return &SizeLimitRotateRule{
DailyRotateRule: DailyRotateRule{
rotatedTime: getNowDateInRFC3339Format(),
filename: filename,
delimiter: delimiter,
days: days,
gzip: gzip,
},
maxSize: int64(maxSize) * megaBytes,
maxBackups: maxBackups,
}
}
func (r *SizeLimitRotateRule) BackupFileName() string {
dir := filepath.Dir(r.filename)
prefix, ext := r.parseFilename()
timestamp := getNowDateInRFC3339Format()
return filepath.Join(dir, fmt.Sprintf("%s%s%s%s", prefix, r.delimiter, timestamp, ext))
}
func (r *SizeLimitRotateRule) MarkRotated() {
r.rotatedTime = getNowDateInRFC3339Format()
}
func (r *SizeLimitRotateRule) OutdatedFiles() []string {
dir := filepath.Dir(r.filename)
prefix, ext := r.parseFilename()
var pattern string
if r.gzip {
pattern = fmt.Sprintf("%s%s%s%s*%s%s", dir, string(filepath.Separator),
prefix, r.delimiter, ext, gzipExt)
} else {
pattern = fmt.Sprintf("%s%s%s%s*%s", dir, string(filepath.Separator),
prefix, r.delimiter, ext)
}
files, err := filepath.Glob(pattern)
if err != nil {
Errorf("failed to delete outdated log files, error: %s", err)
return nil
}
sort.Strings(files)
outdated := make(map[string]lang.PlaceholderType)
// test if too many backups
if r.maxBackups > 0 && len(files) > r.maxBackups {
for _, f := range files[:len(files)-r.maxBackups] {
outdated[f] = lang.Placeholder
}
files = files[len(files)-r.maxBackups:]
}
// test if any too old backups
if r.days > 0 {
boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay*r.days)).Format(fileTimeFormat)
boundaryFile := filepath.Join(dir, fmt.Sprintf("%s%s%s%s", prefix, r.delimiter, boundary, ext))
if r.gzip {
boundaryFile += gzipExt
}
for _, f := range files {
if f >= boundaryFile {
break
}
outdated[f] = lang.Placeholder
}
}
result := make([]string, 0, len(outdated))
for k := range outdated {
result = append(result, k)
}
return result
}
func (r *SizeLimitRotateRule) ShallRotate(size int64) bool {
return r.maxSize > 0 && r.maxSize < size
}
func (r *SizeLimitRotateRule) parseFilename() (prefix, ext string) {
logName := filepath.Base(r.filename)
ext = filepath.Ext(r.filename)
prefix = logName[:len(logName)-len(ext)]
return
}
// NewLogger returns a RotateLogger with given filename and rule, etc.
func NewLogger(filename string, rule RotateRule, compress bool) (*RotateLogger, error) {
l := &RotateLogger{
filename: filename,
channel: make(chan []byte, bufferSize),
done: make(chan lang.PlaceholderType),
rule: rule,
compress: compress,
}
if err := l.initialize(); err != nil {
return nil, err
}
l.startWorker()
return l, nil
}
// Close closes l.
func (l *RotateLogger) Close() error {
var err error
l.closeOnce.Do(func() {
close(l.done)
l.waitGroup.Wait()
if err = l.fp.Sync(); err != nil {
return
}
err = l.fp.Close()
})
return err
}
func (l *RotateLogger) Write(data []byte) (int, error) {
select {
case l.channel <- data:
return len(data), nil
case <-l.done:
log.Println(string(data))
return 0, ErrLogFileClosed
}
}
func (l *RotateLogger) getBackupFilename() string {
if len(l.backup) == 0 {
return l.rule.BackupFileName()
}
return l.backup
}
func (l *RotateLogger) initialize() error {
l.backup = l.rule.BackupFileName()
if fileInfo, err := os.Stat(l.filename); err != nil {
basePath := path.Dir(l.filename)
if _, err = os.Stat(basePath); err != nil {
if err = os.MkdirAll(basePath, defaultDirMode); err != nil {
return err
}
}
if l.fp, err = os.Create(l.filename); err != nil {
return err
}
} else {
if l.fp, err = os.OpenFile(l.filename, os.O_APPEND|os.O_WRONLY, defaultFileMode); err != nil {
return err
}
l.currentSize = fileInfo.Size()
}
fs.CloseOnExec(l.fp)
return nil
}
func (l *RotateLogger) maybeCompressFile(file string) {
if !l.compress {
return
}
defer func() {
if r := recover(); r != nil {
ErrorStack(r)
}
}()
if _, err := os.Stat(file); err != nil {
// file doesn't exist or another error, ignore compression
return
}
compressLogFile(file)
}
func (l *RotateLogger) maybeDeleteOutdatedFiles() {
files := l.rule.OutdatedFiles()
for _, file := range files {
if err := os.Remove(file); err != nil {
Errorf("failed to remove outdated file: %s", file)
}
}
}
func (l *RotateLogger) postRotate(file string) {
go func() {
// we cannot use threading.GoSafe here, because of import cycle.
l.maybeCompressFile(file)
l.maybeDeleteOutdatedFiles()
}()
}
func (l *RotateLogger) rotate() error {
if l.fp != nil {
err := l.fp.Close()
l.fp = nil
if err != nil {
return err
}
}
_, err := os.Stat(l.filename)
if err == nil && len(l.backup) > 0 {
backupFilename := l.getBackupFilename()
err = os.Rename(l.filename, backupFilename)
if err != nil {
return err
}
l.postRotate(backupFilename)
}
l.backup = l.rule.BackupFileName()
if l.fp, err = os.Create(l.filename); err == nil {
fs.CloseOnExec(l.fp)
}
return err
}
func (l *RotateLogger) startWorker() {
l.waitGroup.Add(1)
go func() {
defer l.waitGroup.Done()
for {
select {
case event := <-l.channel:
l.write(event)
case <-l.done:
// avoid losing logs before closing.
for {
select {
case event := <-l.channel:
l.write(event)
default:
return
}
}
}
}
}()
}
func (l *RotateLogger) write(v []byte) {
if l.rule.ShallRotate(l.currentSize + int64(len(v))) {
if err := l.rotate(); err != nil {
log.Println(err)
} else {
l.rule.MarkRotated()
l.currentSize = 0
}
}
if l.fp != nil {
l.fp.Write(v)
l.currentSize += int64(len(v))
}
}
func compressLogFile(file string) {
start := time.Now()
Infof("compressing log file: %s", file)
if err := gzipFile(file, fileSys); err != nil {
Errorf("compress error: %s", err)
} else {
Infof("compressed log file: %s, took %s", file, time.Since(start))
}
}
func getNowDate() string {
return time.Now().Format(time.DateOnly)
}
func getNowDateInRFC3339Format() string {
return time.Now().Format(fileTimeFormat)
}
func gzipFile(file string, fsys fileSystem) (err error) {
in, err := fsys.Open(file)
if err != nil {
return err
}
defer func() {
if e := fsys.Close(in); e != nil {
Errorf("failed to close file: %s, error: %v", file, e)
}
if err == nil {
// only remove the original file when compression is successful
err = fsys.Remove(file)
}
}()
out, err := fsys.Create(fmt.Sprintf("%s%s", file, gzipExt))
if err != nil {
return err
}
defer func() {
e := fsys.Close(out)
if err == nil {
err = e
}
}()
w := gzip.NewWriter(out)
if _, err = fsys.Copy(w, in); err != nil {
// failed to copy, no need to close w
return err
}
return fsys.Close(w)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/logs_test.go | core/logx/logs_test.go | package logx
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"reflect"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/sdk/trace"
)
var (
s = []byte("Sending #11 notification (id: 1451875113812010473) in #1 connection")
pool = make(chan []byte, 1)
_ Writer = (*mockWriter)(nil)
)
func init() {
ExitOnFatal.Set(false)
}
type mockWriter struct {
lock sync.Mutex
builder strings.Builder
}
func (mw *mockWriter) Alert(v any) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelAlert, v)
}
func (mw *mockWriter) Debug(v any, fields ...LogField) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelDebug, v, fields...)
}
func (mw *mockWriter) Error(v any, fields ...LogField) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelError, v, fields...)
}
func (mw *mockWriter) Info(v any, fields ...LogField) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelInfo, v, fields...)
}
func (mw *mockWriter) Severe(v any) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelSevere, v)
}
func (mw *mockWriter) Slow(v any, fields ...LogField) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelSlow, v, fields...)
}
func (mw *mockWriter) Stack(v any) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelError, v)
}
func (mw *mockWriter) Stat(v any, fields ...LogField) {
mw.lock.Lock()
defer mw.lock.Unlock()
output(&mw.builder, levelStat, v, fields...)
}
func (mw *mockWriter) Close() error {
return nil
}
func (mw *mockWriter) Contains(text string) bool {
mw.lock.Lock()
defer mw.lock.Unlock()
return strings.Contains(mw.builder.String(), text)
}
func (mw *mockWriter) Reset() {
mw.lock.Lock()
defer mw.lock.Unlock()
mw.builder.Reset()
}
func (mw *mockWriter) String() string {
mw.lock.Lock()
defer mw.lock.Unlock()
return mw.builder.String()
}
func TestField(t *testing.T) {
tests := []struct {
name string
f LogField
want map[string]any
}{
{
name: "error",
f: Field("foo", errors.New("bar")),
want: map[string]any{
"foo": "bar",
},
},
{
name: "errors",
f: Field("foo", []error{errors.New("bar"), errors.New("baz")}),
want: map[string]any{
"foo": []any{"bar", "baz"},
},
},
{
name: "strings",
f: Field("foo", []string{"bar", "baz"}),
want: map[string]any{
"foo": []any{"bar", "baz"},
},
},
{
name: "duration",
f: Field("foo", time.Second),
want: map[string]any{
"foo": "1s",
},
},
{
name: "durations",
f: Field("foo", []time.Duration{time.Second, 2 * time.Second}),
want: map[string]any{
"foo": []any{"1s", "2s"},
},
},
{
name: "times",
f: Field("foo", []time.Time{
time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC),
time.Date(2020, time.January, 2, 0, 0, 0, 0, time.UTC),
}),
want: map[string]any{
"foo": []any{"2020-01-01 00:00:00 +0000 UTC", "2020-01-02 00:00:00 +0000 UTC"},
},
},
{
name: "stringer",
f: Field("foo", ValStringer{val: "bar"}),
want: map[string]any{
"foo": "bar",
},
},
{
name: "stringers",
f: Field("foo", []fmt.Stringer{ValStringer{val: "bar"}, ValStringer{val: "baz"}}),
want: map[string]any{
"foo": []any{"bar", "baz"},
},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
Infow("foo", test.f)
validateFields(t, w.String(), test.want)
})
}
}
func TestFileLineFileMode(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
file, line := getFileLine()
Error("anything")
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
file, line = getFileLine()
Errorf("anything %s", "format")
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
}
func TestFileLineConsoleMode(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
file, line := getFileLine()
Error("anything")
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
w.Reset()
file, line = getFileLine()
Errorf("anything %s", "format")
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
}
func TestMust(t *testing.T) {
assert.Panics(t, func() {
Must(errors.New("foo"))
})
}
func TestStructedLogAlert(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelAlert, w, func(v ...any) {
Alert(fmt.Sprint(v...))
})
}
func TestStructedLogDebug(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelDebug, w, func(v ...any) {
Debug(v...)
})
}
func TestStructedLogDebugf(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelDebug, w, func(v ...any) {
Debugf(fmt.Sprint(v...))
})
}
func TestStructedLogDebugfn(t *testing.T) {
t.Run("debugfn with output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelDebug, w, func(v ...any) {
Debugfn(func() any {
return fmt.Sprint(v...)
})
})
})
t.Run("debugfn without output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogEmpty(t, w, InfoLevel, func(v ...any) {
Debugfn(func() any {
return fmt.Sprint(v...)
})
})
})
}
func TestStructedLogDebugv(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelDebug, w, func(v ...any) {
Debugv(fmt.Sprint(v...))
})
}
func TestStructedLogDebugw(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelDebug, w, func(v ...any) {
Debugw(fmt.Sprint(v...), Field("foo", time.Second))
})
}
func TestStructedLogError(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelError, w, func(v ...any) {
Error(v...)
})
}
func TestStructedLogErrorf(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelError, w, func(v ...any) {
Errorf("%s", fmt.Sprint(v...))
})
}
func TestStructedLogErrorfn(t *testing.T) {
t.Run("errorfn with output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelError, w, func(v ...any) {
Errorfn(func() any {
return fmt.Sprint(v...)
})
})
})
t.Run("errorfn without output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogEmpty(t, w, SevereLevel, func(v ...any) {
Errorfn(func() any {
return fmt.Sprint(v...)
})
})
})
}
func TestStructedLogErrorv(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelError, w, func(v ...any) {
Errorv(fmt.Sprint(v...))
})
}
func TestStructedLogErrorw(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelError, w, func(v ...any) {
Errorw(fmt.Sprint(v...), Field("foo", "bar"))
})
}
func TestStructedLogInfo(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelInfo, w, func(v ...any) {
Info(v...)
})
}
func TestStructedLogInfof(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelInfo, w, func(v ...any) {
Infof("%s", fmt.Sprint(v...))
})
}
func TestStructedInfofn(t *testing.T) {
t.Run("infofn with output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelInfo, w, func(v ...any) {
Infofn(func() any {
return fmt.Sprint(v...)
})
})
})
t.Run("infofn without output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogEmpty(t, w, ErrorLevel, func(v ...any) {
Infofn(func() any {
return fmt.Sprint(v...)
})
})
})
}
func TestStructedLogInfov(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelInfo, w, func(v ...any) {
Infov(fmt.Sprint(v...))
})
}
func TestStructedLogInfow(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelInfo, w, func(v ...any) {
Infow(fmt.Sprint(v...), Field("foo", "bar"))
})
}
func TestStructedLogFieldNil(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
assert.NotPanics(t, func() {
var s *string
Infow("test", Field("bb", s))
var d *nilStringer
Infow("test", Field("bb", d))
var e *nilError
Errorw("test", Field("bb", e))
})
assert.NotPanics(t, func() {
var p panicStringer
Infow("test", Field("bb", p))
var ps innerPanicStringer
Infow("test", Field("bb", ps))
})
}
func TestStructedLogInfoConsoleAny(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogConsole(t, w, func(v ...any) {
old := atomic.LoadUint32(&encoding)
atomic.StoreUint32(&encoding, plainEncodingType)
defer func() {
atomic.StoreUint32(&encoding, old)
}()
Infov(v)
})
}
func TestStructedLogInfoConsoleAnyString(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogConsole(t, w, func(v ...any) {
old := atomic.LoadUint32(&encoding)
atomic.StoreUint32(&encoding, plainEncodingType)
defer func() {
atomic.StoreUint32(&encoding, old)
}()
Infov(fmt.Sprint(v...))
})
}
func TestStructedLogInfoConsoleAnyError(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogConsole(t, w, func(v ...any) {
old := atomic.LoadUint32(&encoding)
atomic.StoreUint32(&encoding, plainEncodingType)
defer func() {
atomic.StoreUint32(&encoding, old)
}()
Infov(errors.New(fmt.Sprint(v...)))
})
}
func TestStructedLogInfoConsoleAnyStringer(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogConsole(t, w, func(v ...any) {
old := atomic.LoadUint32(&encoding)
atomic.StoreUint32(&encoding, plainEncodingType)
defer func() {
atomic.StoreUint32(&encoding, old)
}()
Infov(ValStringer{
val: fmt.Sprint(v...),
})
})
}
func TestStructedLogInfoConsoleText(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogConsole(t, w, func(v ...any) {
old := atomic.LoadUint32(&encoding)
atomic.StoreUint32(&encoding, plainEncodingType)
defer func() {
atomic.StoreUint32(&encoding, old)
}()
Info(fmt.Sprint(v...))
})
}
func TestInfofnWithErrorLevel(t *testing.T) {
called := false
SetLevel(ErrorLevel)
defer SetLevel(DebugLevel)
Infofn(func() any {
called = true
return "info log"
})
assert.False(t, called)
}
func TestStructedLogSlow(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSlow, w, func(v ...any) {
Slow(v...)
})
}
func TestStructedLogSlowf(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSlow, w, func(v ...any) {
Slowf(fmt.Sprint(v...))
})
}
func TestStructedLogSlowfn(t *testing.T) {
t.Run("slowfn with output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSlow, w, func(v ...any) {
Slowfn(func() any {
return fmt.Sprint(v...)
})
})
})
t.Run("slowfn without output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLogEmpty(t, w, SevereLevel, func(v ...any) {
Slowfn(func() any {
return fmt.Sprint(v...)
})
})
})
}
func TestStructedLogSlowv(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSlow, w, func(v ...any) {
Slowv(fmt.Sprint(v...))
})
}
func TestStructedLogSloww(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSlow, w, func(v ...any) {
Sloww(fmt.Sprint(v...), Field("foo", time.Second))
})
}
func TestStructedLogStat(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelStat, w, func(v ...any) {
Stat(v...)
})
}
func TestStructedLogStatf(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelStat, w, func(v ...any) {
Statf(fmt.Sprint(v...))
})
}
func TestStructedLogSevere(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSevere, w, func(v ...any) {
Severe(v...)
})
}
func TestStructedLogSeveref(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSevere, w, func(v ...any) {
Severef(fmt.Sprint(v...))
})
}
func TestStructedLogWithDuration(t *testing.T) {
const message = "hello there"
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
WithDuration(time.Second).Info(message)
var entry map[string]any
if err := json.Unmarshal([]byte(w.String()), &entry); err != nil {
t.Error(err)
}
assert.Equal(t, levelInfo, entry[levelKey])
assert.Equal(t, message, entry[contentKey])
assert.Equal(t, "1000.0ms", entry[durationKey])
}
func TestSetLevel(t *testing.T) {
SetLevel(ErrorLevel)
const message = "hello there"
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
Info(message)
assert.Equal(t, 0, w.builder.Len())
}
func TestSetLevelTwiceWithMode(t *testing.T) {
testModes := []string{
"console",
"volumn",
"mode",
}
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
for _, mode := range testModes {
testSetLevelTwiceWithMode(t, mode, w)
}
}
func TestSetLevelWithDuration(t *testing.T) {
SetLevel(ErrorLevel)
const message = "hello there"
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
WithDuration(time.Second).Info(message)
assert.Equal(t, 0, w.builder.Len())
}
func TestErrorfWithWrappedError(t *testing.T) {
SetLevel(ErrorLevel)
const message = "there"
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
Errorf("hello %s", errors.New(message))
assert.True(t, strings.Contains(w.String(), "hello there"))
}
func TestMustNil(t *testing.T) {
Must(nil)
}
func TestSetup(t *testing.T) {
defer func() {
SetLevel(InfoLevel)
atomic.StoreUint32(&encoding, jsonEncodingType)
}()
setupOnce = sync.Once{}
MustSetup(LogConf{
ServiceName: "any",
Mode: "console",
Encoding: "json",
TimeFormat: timeFormat,
})
setupOnce = sync.Once{}
MustSetup(LogConf{
ServiceName: "any",
Mode: "console",
TimeFormat: timeFormat,
})
setupOnce = sync.Once{}
MustSetup(LogConf{
ServiceName: "any",
Mode: "file",
Path: os.TempDir(),
})
setupOnce = sync.Once{}
MustSetup(LogConf{
ServiceName: "any",
Mode: "volume",
Path: os.TempDir(),
})
setupOnce = sync.Once{}
MustSetup(LogConf{
ServiceName: "any",
Mode: "console",
TimeFormat: timeFormat,
})
setupOnce = sync.Once{}
MustSetup(LogConf{
ServiceName: "any",
Mode: "console",
Encoding: plainEncoding,
})
defer os.RemoveAll("CD01CB7D-2705-4F3F-889E-86219BF56F10")
assert.NotNil(t, setupWithVolume(LogConf{}))
assert.Nil(t, setupWithVolume(LogConf{
ServiceName: "CD01CB7D-2705-4F3F-889E-86219BF56F10",
}))
assert.Nil(t, setupWithVolume(LogConf{
ServiceName: "CD01CB7D-2705-4F3F-889E-86219BF56F10",
Rotation: sizeRotationRule,
}))
assert.NotNil(t, setupWithFiles(LogConf{}))
assert.Nil(t, setupWithFiles(LogConf{
ServiceName: "any",
Path: os.TempDir(),
Compress: true,
KeepDays: 1,
MaxBackups: 3,
MaxSize: 1024 * 1024,
}))
setupLogLevel(levelInfo)
setupLogLevel(levelError)
setupLogLevel(levelSevere)
_, err := createOutput("")
assert.NotNil(t, err)
Disable()
SetLevel(InfoLevel)
atomic.StoreUint32(&encoding, jsonEncodingType)
}
func TestDisable(t *testing.T) {
Disable()
defer func() {
SetLevel(InfoLevel)
atomic.StoreUint32(&encoding, jsonEncodingType)
}()
var opt logOptions
WithKeepDays(1)(&opt)
WithGzip()(&opt)
WithMaxBackups(1)(&opt)
WithMaxSize(1024)(&opt)
assert.Nil(t, Close())
assert.Nil(t, Close())
assert.Equal(t, uint32(disableLevel), atomic.LoadUint32(&logLevel))
}
func TestDisableStat(t *testing.T) {
DisableStat()
const message = "hello there"
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
Stat(message)
assert.Equal(t, 0, w.builder.Len())
}
func TestAddWriter(t *testing.T) {
const message = "hello there"
w := new(mockWriter)
AddWriter(w)
w1 := new(mockWriter)
AddWriter(w1)
Error(message)
assert.Contains(t, w.String(), message)
assert.Contains(t, w1.String(), message)
}
func TestSetWriter(t *testing.T) {
atomic.StoreUint32(&logLevel, 0)
Reset()
SetWriter(nopWriter{})
assert.NotNil(t, writer.Load())
assert.True(t, writer.Load() == nopWriter{})
mocked := new(mockWriter)
SetWriter(mocked)
assert.Equal(t, mocked, writer.Load())
}
func TestWithGzip(t *testing.T) {
fn := WithGzip()
var opt logOptions
fn(&opt)
assert.True(t, opt.gzipEnabled)
}
func TestWithKeepDays(t *testing.T) {
fn := WithKeepDays(1)
var opt logOptions
fn(&opt)
assert.Equal(t, 1, opt.keepDays)
}
func TestWithField_LogLevel(t *testing.T) {
tests := []struct {
name string
level uint32
fn func(string, ...LogField)
count int32
}{
{
name: "debug/info",
level: DebugLevel,
fn: Infow,
count: 1,
},
{
name: "info/error",
level: InfoLevel,
fn: Errorw,
count: 1,
},
{
name: "info/info",
level: InfoLevel,
fn: Infow,
count: 1,
},
{
name: "info/severe",
level: InfoLevel,
fn: Errorw,
count: 1,
},
{
name: "error/info",
level: ErrorLevel,
fn: Infow,
count: 0,
},
{
name: "error/debug",
level: ErrorLevel,
fn: Debugw,
count: 0,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
olevel := atomic.LoadUint32(&logLevel)
SetLevel(tt.level)
defer SetLevel(olevel)
var val countingStringer
tt.fn("hello there", Field("foo", &val))
assert.Equal(t, tt.count, val.Count())
})
}
}
func TestWithField_LogLevelWithContext(t *testing.T) {
t.Run("context more than once with info/info", func(t *testing.T) {
olevel := atomic.LoadUint32(&logLevel)
SetLevel(InfoLevel)
defer SetLevel(olevel)
var val countingStringer
ctx := ContextWithFields(context.Background(), Field("foo", &val))
logger := WithContext(ctx)
logger.Info("hello there")
logger.Info("hello there")
logger.Info("hello there")
assert.True(t, val.Count() > 0)
})
t.Run("context more than once with error/info", func(t *testing.T) {
olevel := atomic.LoadUint32(&logLevel)
SetLevel(ErrorLevel)
defer SetLevel(olevel)
var val countingStringer
ctx := ContextWithFields(context.Background(), Field("foo", &val))
logger := WithContext(ctx)
logger.Info("hello there")
logger.Info("hello there")
logger.Info("hello there")
assert.Equal(t, int32(0), val.Count())
})
}
func BenchmarkCopyByteSliceAppend(b *testing.B) {
for i := 0; i < b.N; i++ {
var buf []byte
buf = append(buf, getTimestamp()...)
buf = append(buf, ' ')
buf = append(buf, s...)
_ = buf
}
}
func BenchmarkCopyByteSliceAllocExactly(b *testing.B) {
for i := 0; i < b.N; i++ {
now := []byte(getTimestamp())
buf := make([]byte, len(now)+1+len(s))
n := copy(buf, now)
buf[n] = ' '
copy(buf[n+1:], s)
}
}
func BenchmarkCopyByteSlice(b *testing.B) {
var buf []byte
for i := 0; i < b.N; i++ {
buf = make([]byte, len(s))
copy(buf, s)
}
fmt.Fprint(io.Discard, buf)
}
func BenchmarkCopyOnWriteByteSlice(b *testing.B) {
var buf []byte
for i := 0; i < b.N; i++ {
size := len(s)
buf = s[:size:size]
}
fmt.Fprint(io.Discard, buf)
}
func BenchmarkCacheByteSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
dup := fetch()
copy(dup, s)
put(dup)
}
}
func BenchmarkLogs(b *testing.B) {
b.ReportAllocs()
log.SetOutput(io.Discard)
for i := 0; i < b.N; i++ {
Info(i)
}
}
func fetch() []byte {
select {
case b := <-pool:
return b
default:
}
return make([]byte, 4096)
}
func getFileLine() (string, int) {
_, file, line, _ := runtime.Caller(1)
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
return short, line
}
func put(b []byte) {
select {
case pool <- b:
default:
}
}
func doTestStructedLog(t *testing.T, level string, w *mockWriter, write func(...any)) {
const message = "hello there"
write(message)
var entry map[string]any
if err := json.Unmarshal([]byte(w.String()), &entry); err != nil {
t.Error(err)
}
assert.Equal(t, level, entry[levelKey])
val, ok := entry[contentKey]
assert.True(t, ok)
assert.True(t, strings.Contains(val.(string), message))
}
func doTestStructedLogConsole(t *testing.T, w *mockWriter, write func(...any)) {
const message = "hello there"
write(message)
assert.True(t, strings.Contains(w.String(), message))
}
func doTestStructedLogEmpty(t *testing.T, w *mockWriter, level uint32, write func(...any)) {
olevel := atomic.LoadUint32(&logLevel)
SetLevel(level)
defer SetLevel(olevel)
const message = "hello there"
write(message)
assert.Empty(t, w.String())
}
func testSetLevelTwiceWithMode(t *testing.T, mode string, w *mockWriter) {
writer.Store(nil)
SetUp(LogConf{
Mode: mode,
Level: "debug",
Path: "/dev/null",
Encoding: plainEncoding,
Stat: false,
TimeFormat: time.RFC3339,
FileTimeFormat: time.DateTime,
})
SetUp(LogConf{
Mode: mode,
Level: "info",
Path: "/dev/null",
})
const message = "hello there"
Info(message)
assert.Equal(t, 0, w.builder.Len())
Infof(message)
assert.Equal(t, 0, w.builder.Len())
ErrorStack(message)
assert.Equal(t, 0, w.builder.Len())
ErrorStackf(message)
assert.Equal(t, 0, w.builder.Len())
}
type ValStringer struct {
val string
}
func (v ValStringer) String() string {
return v.val
}
func validateFields(t *testing.T, content string, fields map[string]any) {
var m map[string]any
if err := json.Unmarshal([]byte(content), &m); err != nil {
t.Error(err)
}
for k, v := range fields {
if reflect.TypeOf(v).Kind() == reflect.Slice {
assert.EqualValues(t, v, m[k])
} else {
assert.Equal(t, v, m[k], content)
}
}
}
type nilError struct {
Name string
}
func (e *nilError) Error() string {
return e.Name
}
type nilStringer struct {
Name string
}
func (s *nilStringer) String() string {
return s.Name
}
type innerPanicStringer struct {
Inner *struct {
Name string
}
}
func (s innerPanicStringer) String() string {
return s.Inner.Name
}
type panicStringer struct {
}
func (s panicStringer) String() string {
panic("panic")
}
type countingStringer struct {
count int32
}
func (s *countingStringer) Count() int32 {
return atomic.LoadInt32(&s.count)
}
func (s *countingStringer) String() string {
atomic.AddInt32(&s.count, 1)
return "countingStringer"
}
func TestLogKey(t *testing.T) {
setupOnce = sync.Once{}
MustSetup(LogConf{
ServiceName: "any",
Mode: "console",
Encoding: "json",
TimeFormat: timeFormat,
FieldKeys: fieldKeyConf{
CallerKey: "_caller",
ContentKey: "_content",
DurationKey: "_duration",
LevelKey: "_level",
SpanKey: "_span",
TimestampKey: "_timestamp",
TraceKey: "_trace",
TruncatedKey: "_truncated",
},
})
t.Cleanup(func() {
setupFieldKeys(fieldKeyConf{
CallerKey: defaultCallerKey,
ContentKey: defaultContentKey,
DurationKey: defaultDurationKey,
LevelKey: defaultLevelKey,
SpanKey: defaultSpanKey,
TimestampKey: defaultTimestampKey,
TraceKey: defaultTraceKey,
TruncatedKey: defaultTruncatedKey,
})
})
const message = "hello there"
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
otp := otel.GetTracerProvider()
tp := trace.NewTracerProvider(trace.WithSampler(trace.AlwaysSample()))
otel.SetTracerProvider(tp)
defer otel.SetTracerProvider(otp)
ctx, span := tp.Tracer("trace-id").Start(context.Background(), "span-id")
defer span.End()
WithContext(ctx).WithDuration(time.Second).Info(message)
now := time.Now()
var m map[string]string
if err := json.Unmarshal([]byte(w.String()), &m); err != nil {
t.Error(err)
}
assert.Equal(t, "info", m["_level"])
assert.Equal(t, message, m["_content"])
assert.Equal(t, "1000.0ms", m["_duration"])
assert.Regexp(t, `logx/logs_test.go:\d+`, m["_caller"])
assert.NotEmpty(t, m["_trace"])
assert.NotEmpty(t, m["_span"])
parsedTime, err := time.Parse(timeFormat, m["_timestamp"])
assert.True(t, err == nil)
assert.Equal(t, now.Minute(), parsedTime.Minute())
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/sensitive.go | core/logx/sensitive.go | package logx
// Sensitive is an interface that defines a method for masking sensitive information in logs.
// It is typically implemented by types that contain sensitive data,
// such as passwords or personal information.
// Infov, Errorv, Debugv, and Slowv methods will call this method to mask sensitive data.
// The values in LogField will also be masked if they implement the Sensitive interface.
type Sensitive interface {
// MaskSensitive masks sensitive information in the log.
MaskSensitive() any
}
// maskSensitive returns the value returned by MaskSensitive method,
// if the value implements Sensitive interface.
func maskSensitive(v any) any {
if s, ok := v.(Sensitive); ok {
return s.MaskSensitive()
}
return v
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/logs.go | core/logx/logs.go | package logx
import (
"fmt"
"io"
"log"
"os"
"path"
"reflect"
"runtime/debug"
"sync"
"sync/atomic"
"github.com/zeromicro/go-zero/core/sysx"
)
const callerDepth = 4
var (
timeFormat = "2006-01-02T15:04:05.000Z07:00"
encoding uint32 = jsonEncodingType
// maxContentLength is used to truncate the log content, 0 for not truncating.
maxContentLength uint32
// use uint32 for atomic operations
disableStat uint32
logLevel uint32
options logOptions
writer = new(atomicWriter)
setupOnce sync.Once
)
type (
// LogField is a key-value pair that will be added to the log entry.
LogField struct {
Key string
Value any
}
// LogOption defines the method to customize the logging.
LogOption func(options *logOptions)
logEntry map[string]any
logOptions struct {
gzipEnabled bool
logStackCooldownMills int
keepDays int
maxBackups int
maxSize int
rotationRule string
}
)
// AddWriter adds a new writer.
// If there is already a writer, the new writer will be added to the writer chain.
// For example, to write logs to both file and console, if there is already a file writer,
// ```go
// logx.AddWriter(logx.NewWriter(os.Stdout))
// ```
func AddWriter(w Writer) {
ow := Reset()
if ow == nil {
SetWriter(w)
} else {
// no need to check if the existing writer is a comboWriter,
// because it is not common to add more than one writer.
// even more than one writer, the behavior is the same.
SetWriter(comboWriter{
writers: []Writer{ow, w},
})
}
}
// Alert alerts v in alert level, and the message is written to error log.
func Alert(v string) {
getWriter().Alert(v)
}
// Close closes the logging.
func Close() error {
if w := writer.Swap(nil); w != nil {
return w.(io.Closer).Close()
}
return nil
}
// Debug writes v into access log.
func Debug(v ...any) {
if shallLog(DebugLevel) {
writeDebug(fmt.Sprint(v...))
}
}
// Debugf writes v with format into access log.
func Debugf(format string, v ...any) {
if shallLog(DebugLevel) {
writeDebug(fmt.Sprintf(format, v...))
}
}
// Debugfn writes function result into access log if debug level enabled.
// This is useful when the function is expensive to call and debug level disabled.
func Debugfn(fn func() any) {
if shallLog(DebugLevel) {
writeDebug(fn())
}
}
// Debugv writes v into access log with json content.
func Debugv(v any) {
if shallLog(DebugLevel) {
writeDebug(v)
}
}
// Debugw writes msg along with fields into the access log.
func Debugw(msg string, fields ...LogField) {
if shallLog(DebugLevel) {
writeDebug(msg, fields...)
}
}
// Disable disables the logging.
func Disable() {
atomic.StoreUint32(&logLevel, disableLevel)
writer.Store(nopWriter{})
}
// DisableStat disables the stat logs.
func DisableStat() {
atomic.StoreUint32(&disableStat, 1)
}
// Error writes v into error log.
func Error(v ...any) {
if shallLog(ErrorLevel) {
writeError(fmt.Sprint(v...))
}
}
// Errorf writes v with format into error log.
func Errorf(format string, v ...any) {
if shallLog(ErrorLevel) {
writeError(fmt.Errorf(format, v...).Error())
}
}
// Errorfn writes function result into error log.
func Errorfn(fn func() any) {
if shallLog(ErrorLevel) {
writeError(fn())
}
}
// ErrorStack writes v along with call stack into error log.
func ErrorStack(v ...any) {
if shallLog(ErrorLevel) {
// there is newline in stack string
writeStack(fmt.Sprint(v...))
}
}
// ErrorStackf writes v along with call stack in format into error log.
func ErrorStackf(format string, v ...any) {
if shallLog(ErrorLevel) {
// there is newline in stack string
writeStack(fmt.Sprintf(format, v...))
}
}
// Errorv writes v into error log with json content.
// No call stack attached, because not elegant to pack the messages.
func Errorv(v any) {
if shallLog(ErrorLevel) {
writeError(v)
}
}
// Errorw writes msg along with fields into the error log.
func Errorw(msg string, fields ...LogField) {
if shallLog(ErrorLevel) {
writeError(msg, fields...)
}
}
// Field returns a LogField for the given key and value.
func Field(key string, value any) LogField {
return LogField{
Key: key,
Value: value,
}
}
// Info writes v into access log.
func Info(v ...any) {
if shallLog(InfoLevel) {
writeInfo(fmt.Sprint(v...))
}
}
// Infof writes v with format into access log.
func Infof(format string, v ...any) {
if shallLog(InfoLevel) {
writeInfo(fmt.Sprintf(format, v...))
}
}
// Infofn writes function result into access log.
// This is useful when the function is expensive to call and info level disabled.
func Infofn(fn func() any) {
if shallLog(InfoLevel) {
writeInfo(fn())
}
}
// Infov writes v into access log with json content.
func Infov(v any) {
if shallLog(InfoLevel) {
writeInfo(v)
}
}
// Infow writes msg along with fields into the access log.
func Infow(msg string, fields ...LogField) {
if shallLog(InfoLevel) {
writeInfo(msg, fields...)
}
}
// Must checks if err is nil, otherwise logs the error and exits.
func Must(err error) {
if err == nil {
return
}
msg := fmt.Sprintf("%+v\n\n%s", err.Error(), debug.Stack())
log.Print(msg)
getWriter().Severe(msg)
if ExitOnFatal.True() {
os.Exit(1)
} else {
panic(msg)
}
}
// MustSetup sets up logging with given config c. It exits on error.
func MustSetup(c LogConf) {
Must(SetUp(c))
}
// Reset clears the writer and resets the log level.
func Reset() Writer {
return writer.Swap(nil)
}
// SetLevel sets the logging level. It can be used to suppress some logs.
func SetLevel(level uint32) {
atomic.StoreUint32(&logLevel, level)
}
// SetWriter sets the logging writer. It can be used to customize the logging.
func SetWriter(w Writer) {
if atomic.LoadUint32(&logLevel) != disableLevel {
writer.Store(w)
}
}
// SetUp sets up the logx.
// If already set up, return nil.
// We allow SetUp to be called multiple times, because, for example,
// we need to allow different service frameworks to initialize logx respectively.
func SetUp(c LogConf) (err error) {
// Ignore the later SetUp calls.
// Because multiple services in one process might call SetUp respectively.
// Need to wait for the first caller to complete the execution.
setupOnce.Do(func() {
setupLogLevel(c.Level)
setupFieldKeys(c.FieldKeys)
if !c.Stat {
DisableStat()
}
if len(c.TimeFormat) > 0 {
timeFormat = c.TimeFormat
}
if len(c.FileTimeFormat) > 0 {
fileTimeFormat = c.FileTimeFormat
}
atomic.StoreUint32(&maxContentLength, c.MaxContentLength)
switch c.Encoding {
case plainEncoding:
atomic.StoreUint32(&encoding, plainEncodingType)
default:
atomic.StoreUint32(&encoding, jsonEncodingType)
}
switch c.Mode {
case fileMode:
err = setupWithFiles(c)
case volumeMode:
err = setupWithVolume(c)
default:
setupWithConsole()
}
})
return
}
// Severe writes v into severe log.
func Severe(v ...any) {
if shallLog(SevereLevel) {
writeSevere(fmt.Sprint(v...))
}
}
// Severef writes v with format into severe log.
func Severef(format string, v ...any) {
if shallLog(SevereLevel) {
writeSevere(fmt.Sprintf(format, v...))
}
}
// Slow writes v into slow log.
func Slow(v ...any) {
if shallLog(ErrorLevel) {
writeSlow(fmt.Sprint(v...))
}
}
// Slowf writes v with format into slow log.
func Slowf(format string, v ...any) {
if shallLog(ErrorLevel) {
writeSlow(fmt.Sprintf(format, v...))
}
}
// Slowfn writes function result into slow log.
// This is useful when the function is expensive to call and slow level disabled.
func Slowfn(fn func() any) {
if shallLog(ErrorLevel) {
writeSlow(fn())
}
}
// Slowv writes v into slow log with json content.
func Slowv(v any) {
if shallLog(ErrorLevel) {
writeSlow(v)
}
}
// Sloww writes msg along with fields into slow log.
func Sloww(msg string, fields ...LogField) {
if shallLog(ErrorLevel) {
writeSlow(msg, fields...)
}
}
// Stat writes v into stat log.
func Stat(v ...any) {
if shallLogStat() && shallLog(InfoLevel) {
writeStat(fmt.Sprint(v...))
}
}
// Statf writes v with format into stat log.
func Statf(format string, v ...any) {
if shallLogStat() && shallLog(InfoLevel) {
writeStat(fmt.Sprintf(format, v...))
}
}
// WithCooldownMillis customizes logging on writing call stack interval.
func WithCooldownMillis(millis int) LogOption {
return func(opts *logOptions) {
opts.logStackCooldownMills = millis
}
}
// WithKeepDays customizes logging to keep logs with days.
func WithKeepDays(days int) LogOption {
return func(opts *logOptions) {
opts.keepDays = days
}
}
// WithGzip customizes logging to automatically gzip the log files.
func WithGzip() LogOption {
return func(opts *logOptions) {
opts.gzipEnabled = true
}
}
// WithMaxBackups customizes how many log files backups will be kept.
func WithMaxBackups(count int) LogOption {
return func(opts *logOptions) {
opts.maxBackups = count
}
}
// WithMaxSize customizes how much space the writing log file can take up.
func WithMaxSize(size int) LogOption {
return func(opts *logOptions) {
opts.maxSize = size
}
}
// WithRotation customizes which log rotation rule to use.
func WithRotation(r string) LogOption {
return func(opts *logOptions) {
opts.rotationRule = r
}
}
func addCaller(fields ...LogField) []LogField {
return append(fields, Field(callerKey, getCaller(callerDepth)))
}
func createOutput(path string) (io.WriteCloser, error) {
if len(path) == 0 {
return nil, ErrLogPathNotSet
}
var rule RotateRule
switch options.rotationRule {
case sizeRotationRule:
rule = NewSizeLimitRotateRule(path, backupFileDelimiter, options.keepDays, options.maxSize,
options.maxBackups, options.gzipEnabled)
default:
rule = DefaultRotateRule(path, backupFileDelimiter, options.keepDays, options.gzipEnabled)
}
return NewLogger(path, rule, options.gzipEnabled)
}
func encodeError(err error) (ret string) {
return encodeWithRecover(err, func() string {
return err.Error()
})
}
func encodeStringer(v fmt.Stringer) (ret string) {
return encodeWithRecover(v, func() string {
return v.String()
})
}
func encodeWithRecover(arg any, fn func() string) (ret string) {
defer func() {
if err := recover(); err != nil {
if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() {
ret = nilAngleString
} else {
ret = fmt.Sprintf("panic: %v", err)
}
}
}()
return fn()
}
func getWriter() Writer {
w := writer.Load()
if w == nil {
w = writer.StoreIfNil(newConsoleWriter())
}
return w
}
func handleOptions(opts []LogOption) {
for _, opt := range opts {
opt(&options)
}
}
func setupFieldKeys(c fieldKeyConf) {
if len(c.CallerKey) > 0 {
callerKey = c.CallerKey
}
if len(c.ContentKey) > 0 {
contentKey = c.ContentKey
}
if len(c.DurationKey) > 0 {
durationKey = c.DurationKey
}
if len(c.LevelKey) > 0 {
levelKey = c.LevelKey
}
if len(c.SpanKey) > 0 {
spanKey = c.SpanKey
}
if len(c.TimestampKey) > 0 {
timestampKey = c.TimestampKey
}
if len(c.TraceKey) > 0 {
traceKey = c.TraceKey
}
if len(c.TruncatedKey) > 0 {
truncatedKey = c.TruncatedKey
}
}
func setupLogLevel(level string) {
switch level {
case levelDebug:
SetLevel(DebugLevel)
case levelInfo:
SetLevel(InfoLevel)
case levelError:
SetLevel(ErrorLevel)
case levelSevere:
SetLevel(SevereLevel)
}
}
func setupWithConsole() {
SetWriter(newConsoleWriter())
}
func setupWithFiles(c LogConf) error {
w, err := newFileWriter(c)
if err != nil {
return err
}
SetWriter(w)
return nil
}
func setupWithVolume(c LogConf) error {
if len(c.ServiceName) == 0 {
return ErrLogServiceNameNotSet
}
c.Path = path.Join(c.Path, c.ServiceName, sysx.Hostname())
return setupWithFiles(c)
}
func shallLog(level uint32) bool {
return atomic.LoadUint32(&logLevel) <= level
}
func shallLogStat() bool {
return atomic.LoadUint32(&disableStat) == 0
}
// writeDebug writes v into debug log.
// Not checking shallLog here is for performance consideration.
// If we check shallLog here, the fmt.Sprint might be called even if the log level is not enabled.
// The caller should check shallLog before calling this function.
func writeDebug(val any, fields ...LogField) {
getWriter().Debug(val, mergeGlobalFields(addCaller(fields...))...)
}
// writeError writes v into the error log.
// Not checking shallLog here is for performance consideration.
// If we check shallLog here, the fmt.Sprint might be called even if the log level is not enabled.
// The caller should check shallLog before calling this function.
func writeError(val any, fields ...LogField) {
getWriter().Error(val, mergeGlobalFields(addCaller(fields...))...)
}
// writeInfo writes v into info log.
// Not checking shallLog here is for performance consideration.
// If we check shallLog here, the fmt.Sprint might be called even if the log level is not enabled.
// The caller should check shallLog before calling this function.
func writeInfo(val any, fields ...LogField) {
getWriter().Info(val, mergeGlobalFields(addCaller(fields...))...)
}
// writeSevere writes v into severe log.
// Not checking shallLog here is for performance consideration.
// If we check shallLog here, the fmt.Sprint might be called even if the log level is not enabled.
// The caller should check shallLog before calling this function.
func writeSevere(msg string) {
getWriter().Severe(fmt.Sprintf("%s\n%s", msg, string(debug.Stack())))
}
// writeSlow writes v into slow log.
// Not checking shallLog here is for performance consideration.
// If we check shallLog here, the fmt.Sprint might be called even if the log level is not enabled.
// The caller should check shallLog before calling this function.
func writeSlow(val any, fields ...LogField) {
getWriter().Slow(val, mergeGlobalFields(addCaller(fields...))...)
}
// writeStack writes v into stack log.
// Not checking shallLog here is for performance consideration.
// If we check shallLog here, the fmt.Sprint might be called even if the log level is not enabled.
// The caller should check shallLog before calling this function.
func writeStack(msg string) {
getWriter().Stack(fmt.Sprintf("%s\n%s", msg, string(debug.Stack())))
}
// writeStat writes v into the stat log.
// Not checking shallLog here is for performance consideration.
// If we check shallLog here, the fmt.Sprint might be called even if the log level is not enabled.
// The caller should check shallLog before calling this function.
func writeStat(msg string) {
getWriter().Stat(msg, mergeGlobalFields(addCaller())...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/vars.go | core/logx/vars.go | package logx
import (
"errors"
"github.com/zeromicro/go-zero/core/syncx"
)
const (
// DebugLevel logs everything
DebugLevel uint32 = iota
// InfoLevel does not include debugs
InfoLevel
// ErrorLevel includes errors, slows, stacks
ErrorLevel
// SevereLevel only log severe messages
SevereLevel
// disableLevel doesn't log any messages
disableLevel = 0xff
)
const (
jsonEncodingType = iota
plainEncodingType
)
const (
plainEncoding = "plain"
plainEncodingSep = '\t'
sizeRotationRule = "size"
accessFilename = "access.log"
errorFilename = "error.log"
severeFilename = "severe.log"
slowFilename = "slow.log"
statFilename = "stat.log"
fileMode = "file"
volumeMode = "volume"
levelAlert = "alert"
levelInfo = "info"
levelError = "error"
levelSevere = "severe"
levelFatal = "fatal"
levelSlow = "slow"
levelStat = "stat"
levelDebug = "debug"
backupFileDelimiter = "-"
nilAngleString = "<nil>"
flags = 0x0
)
const (
defaultCallerKey = "caller"
defaultContentKey = "content"
defaultDurationKey = "duration"
defaultLevelKey = "level"
defaultSpanKey = "span"
defaultTimestampKey = "@timestamp"
defaultTraceKey = "trace"
defaultTruncatedKey = "truncated"
)
var (
// ErrLogPathNotSet is an error that indicates the log path is not set.
ErrLogPathNotSet = errors.New("log path must be set")
// ErrLogServiceNameNotSet is an error that indicates that the service name is not set.
ErrLogServiceNameNotSet = errors.New("log service name must be set")
// ExitOnFatal defines whether to exit on fatal errors, defined here to make it easier to test.
ExitOnFatal = syncx.ForAtomicBool(true)
truncatedField = Field(truncatedKey, true)
)
var (
callerKey = defaultCallerKey
contentKey = defaultContentKey
durationKey = defaultDurationKey
levelKey = defaultLevelKey
spanKey = defaultSpanKey
timestampKey = defaultTimestampKey
traceKey = defaultTraceKey
truncatedKey = defaultTruncatedKey
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/logger.go | core/logx/logger.go | package logx
import (
"context"
"time"
)
// A Logger represents a logger.
type Logger interface {
// Debug logs a message at debug level.
Debug(...any)
// Debugf logs a message at debug level.
Debugf(string, ...any)
// Debugfn logs a message at debug level.
Debugfn(func() any)
// Debugv logs a message at debug level.
Debugv(any)
// Debugw logs a message at debug level.
Debugw(string, ...LogField)
// Error logs a message at error level.
Error(...any)
// Errorf logs a message at error level.
Errorf(string, ...any)
// Errorfn logs a message at error level.
Errorfn(func() any)
// Errorv logs a message at error level.
Errorv(any)
// Errorw logs a message at error level.
Errorw(string, ...LogField)
// Info logs a message at info level.
Info(...any)
// Infof logs a message at info level.
Infof(string, ...any)
// Infofn logs a message at info level.
Infofn(func() any)
// Infov logs a message at info level.
Infov(any)
// Infow logs a message at info level.
Infow(string, ...LogField)
// Slow logs a message at slow level.
Slow(...any)
// Slowf logs a message at slow level.
Slowf(string, ...any)
// Slowfn logs a message at slow level.
Slowfn(func() any)
// Slowv logs a message at slow level.
Slowv(any)
// Sloww logs a message at slow level.
Sloww(string, ...LogField)
// WithCallerSkip returns a new logger with the given caller skip.
WithCallerSkip(skip int) Logger
// WithContext returns a new logger with the given context.
WithContext(ctx context.Context) Logger
// WithDuration returns a new logger with the given duration.
WithDuration(d time.Duration) Logger
// WithFields returns a new logger with the given fields.
WithFields(fields ...LogField) Logger
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/fs.go | core/logx/fs.go | package logx
import (
"io"
"os"
)
var fileSys realFileSystem
type (
fileSystem interface {
Close(closer io.Closer) error
Copy(writer io.Writer, reader io.Reader) (int64, error)
Create(name string) (*os.File, error)
Open(name string) (*os.File, error)
Remove(name string) error
}
realFileSystem struct{}
)
func (fs realFileSystem) Close(closer io.Closer) error {
return closer.Close()
}
func (fs realFileSystem) Copy(writer io.Writer, reader io.Reader) (int64, error) {
return io.Copy(writer, reader)
}
func (fs realFileSystem) Create(name string) (*os.File, error) {
return os.Create(name)
}
func (fs realFileSystem) Open(name string) (*os.File, error) {
return os.Open(name)
}
func (fs realFileSystem) Remove(name string) error {
return os.Remove(name)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/limitedexecutor.go | core/logx/limitedexecutor.go | package logx
import (
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/timex"
)
type limitedExecutor struct {
threshold time.Duration
lastTime *syncx.AtomicDuration
discarded uint32
}
func newLimitedExecutor(milliseconds int) *limitedExecutor {
return &limitedExecutor{
threshold: time.Duration(milliseconds) * time.Millisecond,
lastTime: syncx.NewAtomicDuration(),
}
}
func (le *limitedExecutor) logOrDiscard(execute func()) {
if le == nil || le.threshold <= 0 {
execute()
return
}
now := timex.Now()
if now-le.lastTime.Load() <= le.threshold {
atomic.AddUint32(&le.discarded, 1)
} else {
le.lastTime.Set(now)
discarded := atomic.SwapUint32(&le.discarded, 0)
if discarded > 0 {
Errorf("Discarded %d error messages", discarded)
}
execute()
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/sensitive_test.go | core/logx/sensitive_test.go | package logx
import (
"testing"
"github.com/stretchr/testify/assert"
)
const maskedContent = "******"
type User struct {
Name string
Pass string
}
func (u User) MaskSensitive() any {
return User{
Name: u.Name,
Pass: maskedContent,
}
}
type NonSensitiveUser struct {
Name string
Pass string
}
func TestMaskSensitive(t *testing.T) {
t.Run("sensitive", func(t *testing.T) {
user := User{
Name: "kevin",
Pass: "123",
}
mu := maskSensitive(user)
assert.Equal(t, user.Name, mu.(User).Name)
assert.Equal(t, maskedContent, mu.(User).Pass)
})
t.Run("non-sensitive", func(t *testing.T) {
user := NonSensitiveUser{
Name: "kevin",
Pass: "123",
}
mu := maskSensitive(user)
assert.Equal(t, user.Name, mu.(NonSensitiveUser).Name)
assert.Equal(t, user.Pass, mu.(NonSensitiveUser).Pass)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/util_test.go | core/logx/util_test.go | package logx
import (
"path/filepath"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestGetCaller(t *testing.T) {
_, file, _, _ := runtime.Caller(0)
assert.Contains(t, getCaller(1), filepath.Base(file))
assert.True(t, len(getCaller(1<<10)) == 0)
}
func TestGetTimestamp(t *testing.T) {
ts := getTimestamp()
tm, err := time.Parse(timeFormat, ts)
assert.Nil(t, err)
assert.True(t, time.Since(tm) < time.Minute)
}
func TestPrettyCaller(t *testing.T) {
tests := []struct {
name string
file string
line int
want string
}{
{
name: "regular",
file: "logx_test.go",
line: 123,
want: "logx_test.go:123",
},
{
name: "relative",
file: "adhoc/logx_test.go",
line: 123,
want: "adhoc/logx_test.go:123",
},
{
name: "long path",
file: "github.com/zeromicro/go-zero/core/logx/util_test.go",
line: 12,
want: "logx/util_test.go:12",
},
{
name: "local path",
file: "/Users/kevin/go-zero/core/logx/util_test.go",
line: 1234,
want: "logx/util_test.go:1234",
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, prettyCaller(test.file, test.line))
})
}
}
func BenchmarkGetCaller(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
getCaller(1)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/fields.go | core/logx/fields.go | package logx
import (
"context"
"sync"
"sync/atomic"
)
var (
globalFields atomic.Value
globalFieldsLock sync.Mutex
)
type fieldsKey struct{}
// AddGlobalFields adds global fields.
func AddGlobalFields(fields ...LogField) {
globalFieldsLock.Lock()
defer globalFieldsLock.Unlock()
old := globalFields.Load()
if old == nil {
globalFields.Store(append([]LogField(nil), fields...))
} else {
globalFields.Store(append(old.([]LogField), fields...))
}
}
// ContextWithFields returns a new context with the given fields.
func ContextWithFields(ctx context.Context, fields ...LogField) context.Context {
if val := ctx.Value(fieldsKey{}); val != nil {
if arr, ok := val.([]LogField); ok {
allFields := make([]LogField, 0, len(arr)+len(fields))
allFields = append(allFields, arr...)
allFields = append(allFields, fields...)
return context.WithValue(ctx, fieldsKey{}, allFields)
}
}
return context.WithValue(ctx, fieldsKey{}, fields)
}
// WithFields returns a new logger with the given fields.
// deprecated: use ContextWithFields instead.
func WithFields(ctx context.Context, fields ...LogField) context.Context {
return ContextWithFields(ctx, fields...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/logtest/logtest.go | core/logx/logtest/logtest.go | package logtest
import (
"bytes"
"encoding/json"
"io"
"testing"
"github.com/zeromicro/go-zero/core/logx"
)
type Buffer struct {
buf *bytes.Buffer
t *testing.T
}
func Discard(t *testing.T) {
prev := logx.Reset()
logx.SetWriter(logx.NewWriter(io.Discard))
t.Cleanup(func() {
logx.SetWriter(prev)
})
}
func NewCollector(t *testing.T) *Buffer {
var buf bytes.Buffer
writer := logx.NewWriter(&buf)
prev := logx.Reset()
logx.SetWriter(writer)
t.Cleanup(func() {
logx.SetWriter(prev)
})
return &Buffer{
buf: &buf,
t: t,
}
}
func (b *Buffer) Bytes() []byte {
return b.buf.Bytes()
}
func (b *Buffer) Content() string {
var m map[string]interface{}
if err := json.Unmarshal(b.buf.Bytes(), &m); err != nil {
return ""
}
content, ok := m["content"]
if !ok {
return ""
}
switch val := content.(type) {
case string:
return val
default:
// err is impossible to be not nil, unmarshaled from b.buf.Bytes()
bs, _ := json.Marshal(content)
return string(bs)
}
}
func (b *Buffer) Reset() {
b.buf.Reset()
}
func (b *Buffer) String() string {
return b.buf.String()
}
func PanicOnFatal(t *testing.T) {
ok := logx.ExitOnFatal.CompareAndSwap(true, false)
if !ok {
return
}
t.Cleanup(func() {
logx.ExitOnFatal.CompareAndSwap(false, true)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logx/logtest/logtest_test.go | core/logx/logtest/logtest_test.go | package logtest
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
)
func TestCollector(t *testing.T) {
const input = "hello"
c := NewCollector(t)
logx.Info(input)
assert.Equal(t, input, c.Content())
assert.Contains(t, c.String(), input)
c.Reset()
assert.Empty(t, c.Bytes())
}
func TestPanicOnFatal(t *testing.T) {
const input = "hello"
Discard(t)
logx.Info(input)
PanicOnFatal(t)
PanicOnFatal(t)
assert.Panics(t, func() {
logx.Must(errors.New("foo"))
})
}
func TestCollectorContent(t *testing.T) {
const input = "hello"
c := NewCollector(t)
c.buf.WriteString(input)
assert.Empty(t, c.Content())
c.Reset()
c.buf.WriteString(`{}`)
assert.Empty(t, c.Content())
c.Reset()
c.buf.WriteString(`{"content":1}`)
assert.Equal(t, "1", c.Content())
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/cmdline/input_test.go | core/cmdline/input_test.go | package cmdline
import (
"fmt"
"os"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/lang"
)
func TestEnterToContinue(t *testing.T) {
restore, err := iox.RedirectInOut()
assert.Nil(t, err)
defer restore()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println()
}()
go func() {
defer wg.Done()
EnterToContinue()
}()
wait := make(chan lang.PlaceholderType)
go func() {
wg.Wait()
close(wait)
}()
select {
case <-time.After(time.Second):
t.Error("timeout")
case <-wait:
}
}
func TestReadLine(t *testing.T) {
r, w, err := os.Pipe()
assert.Nil(t, err)
ow := os.Stdout
os.Stdout = w
or := os.Stdin
os.Stdin = r
defer func() {
os.Stdin = or
os.Stdout = ow
}()
const message = "hello"
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println(message)
}()
go func() {
defer wg.Done()
input := ReadLine("")
assert.Equal(t, message, input)
}()
wait := make(chan lang.PlaceholderType)
go func() {
wg.Wait()
close(wait)
}()
select {
case <-time.After(time.Second):
t.Error("timeout")
case <-wait:
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/cmdline/input.go | core/cmdline/input.go | package cmdline
import (
"bufio"
"fmt"
"os"
"strings"
)
// EnterToContinue let stdin waiting for an enter key to continue.
func EnterToContinue() {
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
// ReadLine shows prompt to stdout and read a line from stdin.
func ReadLine(prompt string) string {
fmt.Print(prompt)
input, _ := bufio.NewReader(os.Stdin).ReadString('\n')
return strings.TrimSpace(input)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/gzip_test.go | core/codec/gzip_test.go | package codec
import (
"bytes"
"compress/gzip"
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGzip(t *testing.T) {
var buf bytes.Buffer
for i := 0; i < 10000; i++ {
fmt.Fprint(&buf, i)
}
bs := Gzip(buf.Bytes())
actual, err := Gunzip(bs)
assert.Nil(t, err)
assert.True(t, len(bs) < buf.Len())
assert.Equal(t, buf.Bytes(), actual)
}
func TestGunzip(t *testing.T) {
tests := []struct {
name string
input []byte
expected []byte
expectedErr error
}{
{
name: "valid input",
input: func() []byte {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
gz.Write([]byte("hello"))
gz.Close()
return buf.Bytes()
}(),
expected: []byte("hello"),
expectedErr: nil,
},
{
name: "invalid input",
input: []byte("invalid input"),
expected: nil,
expectedErr: gzip.ErrHeader,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result, err := Gunzip(test.input)
if !bytes.Equal(result, test.expected) {
t.Errorf("unexpected result: %v", result)
}
if !errors.Is(err, test.expectedErr) {
t.Errorf("unexpected error: %v", err)
}
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/gzip.go | core/codec/gzip.go | package codec
import (
"bytes"
"compress/gzip"
"io"
)
const unzipLimit = 100 * 1024 * 1024 // 100MB
// Gzip compresses bs.
func Gzip(bs []byte) []byte {
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(bs)
w.Close()
return b.Bytes()
}
// Gunzip uncompresses bs.
func Gunzip(bs []byte) ([]byte, error) {
r, err := gzip.NewReader(bytes.NewBuffer(bs))
if err != nil {
return nil, err
}
defer r.Close()
var c bytes.Buffer
if _, err = io.Copy(&c, io.LimitReader(r, unzipLimit)); err != nil {
return nil, err
}
return c.Bytes(), nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/dh.go | core/codec/dh.go | package codec
import (
"crypto/rand"
"errors"
"math/big"
)
// see https://www.zhihu.com/question/29383090/answer/70435297
// see https://www.ietf.org/rfc/rfc3526.txt
// 2048-bit MODP Group
var (
// ErrInvalidPriKey indicates the invalid private key.
ErrInvalidPriKey = errors.New("invalid private key")
// ErrInvalidPubKey indicates the invalid public key.
ErrInvalidPubKey = errors.New("invalid public key")
// ErrPubKeyOutOfBound indicates the public key is out of bound.
ErrPubKeyOutOfBound = errors.New("public key out of bound")
p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
g, _ = new(big.Int).SetString("2", 16)
zero = big.NewInt(0)
)
// DhKey defines the Diffie-Hellman key.
type DhKey struct {
PriKey *big.Int
PubKey *big.Int
}
// ComputeKey returns a key from public key and private key.
func ComputeKey(pubKey, priKey *big.Int) (*big.Int, error) {
if pubKey == nil {
return nil, ErrInvalidPubKey
}
if pubKey.Sign() <= 0 && p.Cmp(pubKey) <= 0 {
return nil, ErrPubKeyOutOfBound
}
if priKey == nil {
return nil, ErrInvalidPriKey
}
return new(big.Int).Exp(pubKey, priKey, p), nil
}
// GenerateKey returns a Diffie-Hellman key.
func GenerateKey() (*DhKey, error) {
var err error
var x *big.Int
for {
x, err = rand.Int(rand.Reader, p)
if err != nil {
return nil, err
}
if zero.Cmp(x) < 0 {
break
}
}
key := new(DhKey)
key.PriKey = x
key.PubKey = new(big.Int).Exp(g, x, p)
return key, nil
}
// NewPublicKey returns a public key from the given bytes.
func NewPublicKey(bs []byte) *big.Int {
return new(big.Int).SetBytes(bs)
}
// Bytes returns public key bytes.
func (k *DhKey) Bytes() []byte {
if k.PubKey == nil {
return nil
}
byteLen := (p.BitLen() + 7) >> 3
ret := make([]byte, byteLen)
copyWithLeftPad(ret, k.PubKey.Bytes())
return ret
}
func copyWithLeftPad(dst, src []byte) {
padBytes := len(dst) - len(src)
for i := 0; i < padBytes; i++ {
dst[i] = 0
}
copy(dst[padBytes:], src)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/aesecb.go | core/codec/aesecb.go | package codec
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"github.com/zeromicro/go-zero/core/logx"
)
// ErrPaddingSize indicates bad padding size.
var ErrPaddingSize = errors.New("padding size error")
type ecb struct {
b cipher.Block
blockSize int
}
func newECB(b cipher.Block) *ecb {
return &ecb{
b: b,
blockSize: b.BlockSize(),
}
}
type ecbEncrypter ecb
// NewECBEncrypter returns an ECB encrypter.
func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
return (*ecbEncrypter)(newECB(b))
}
// BlockSize returns the mode's block size.
func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
// CryptBlocks encrypts a number of blocks. The length of src must be a multiple of
// the block size. Dst and src must overlap entirely or not at all.
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
logx.Error("crypto/cipher: input not full blocks")
return
}
if len(dst) < len(src) {
logx.Error("crypto/cipher: output smaller than input")
return
}
for len(src) > 0 {
x.b.Encrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}
type ecbDecrypter ecb
// NewECBDecrypter returns an ECB decrypter.
func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
return (*ecbDecrypter)(newECB(b))
}
// BlockSize returns the mode's block size.
func (x *ecbDecrypter) BlockSize() int {
return x.blockSize
}
// CryptBlocks decrypts a number of blocks. The length of src must be a multiple of
// the block size. Dst and src must overlap entirely or not at all.
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
logx.Error("crypto/cipher: input not full blocks")
return
}
if len(dst) < len(src) {
logx.Error("crypto/cipher: output smaller than input")
return
}
for len(src) > 0 {
x.b.Decrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}
// EcbDecrypt decrypts src with the given key.
func EcbDecrypt(key, src []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
logx.Errorf("Decrypt key error: % x", key)
return nil, err
}
decrypter := NewECBDecrypter(block)
decrypted := make([]byte, len(src))
decrypter.CryptBlocks(decrypted, src)
return pkcs5Unpadding(decrypted, decrypter.BlockSize())
}
// EcbDecryptBase64 decrypts base64 encoded src with the given base64 encoded key.
// The returned string is also base64 encoded.
func EcbDecryptBase64(key, src string) (string, error) {
keyBytes, err := getKeyBytes(key)
if err != nil {
return "", err
}
encryptedBytes, err := base64.StdEncoding.DecodeString(src)
if err != nil {
return "", err
}
decryptedBytes, err := EcbDecrypt(keyBytes, encryptedBytes)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(decryptedBytes), nil
}
// EcbEncrypt encrypts src with the given key.
func EcbEncrypt(key, src []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
logx.Errorf("Encrypt key error: % x", key)
return nil, err
}
padded := pkcs5Padding(src, block.BlockSize())
crypted := make([]byte, len(padded))
encrypter := NewECBEncrypter(block)
encrypter.CryptBlocks(crypted, padded)
return crypted, nil
}
// EcbEncryptBase64 encrypts base64 encoded src with the given base64 encoded key.
// The returned string is also base64 encoded.
func EcbEncryptBase64(key, src string) (string, error) {
keyBytes, err := getKeyBytes(key)
if err != nil {
return "", err
}
srcBytes, err := base64.StdEncoding.DecodeString(src)
if err != nil {
return "", err
}
encryptedBytes, err := EcbEncrypt(keyBytes, srcBytes)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(encryptedBytes), nil
}
func getKeyBytes(key string) ([]byte, error) {
if len(key) <= 32 {
return []byte(key), nil
}
keyBytes, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return nil, err
}
return keyBytes, nil
}
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func pkcs5Unpadding(src []byte, blockSize int) ([]byte, error) {
length := len(src)
unpadding := int(src[length-1])
if unpadding >= length || unpadding > blockSize {
return nil, ErrPaddingSize
}
return src[:length-unpadding], nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/hmac_test.go | core/codec/hmac_test.go | package codec
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestHmac(t *testing.T) {
ret := Hmac([]byte("foo"), "bar")
assert.Equal(t, "f9320baf0249169e73850cd6156ded0106e2bb6ad8cab01b7bbbebe6d1065317",
fmt.Sprintf("%x", ret))
}
func TestHmacBase64(t *testing.T) {
ret := HmacBase64([]byte("foo"), "bar")
assert.Equal(t, "+TILrwJJFp5zhQzWFW3tAQbiu2rYyrAbe7vr5tEGUxc=", ret)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/rsa_test.go | core/codec/rsa_test.go | package codec
import (
"encoding/base64"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
)
const (
priKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC4TJk3onpqb2RYE3wwt23J9SHLFstHGSkUYFLe+nl1dEKHbD+/
Zt95L757J3xGTrwoTc7KCTxbrgn+stn0w52BNjj/kIE2ko4lbh/v8Fl14AyVR9ms
fKtKOnhe5FCT72mdtApr+qvzcC3q9hfXwkyQU32pv7q5UimZ205iKSBmgQIDAQAB
AoGAM5mWqGIAXj5z3MkP01/4CDxuyrrGDVD5FHBno3CDgyQa4Gmpa4B0/ywj671B
aTnwKmSmiiCN2qleuQYASixes2zY5fgTzt+7KNkl9JHsy7i606eH2eCKzsUa/s6u
WD8V3w/hGCQ9zYI18ihwyXlGHIgcRz/eeRh+nWcWVJzGOPUCQQD5nr6It/1yHb1p
C6l4fC4xXF19l4KxJjGu1xv/sOpSx0pOqBDEX3Mh//FU954392rUWDXV1/I65BPt
TLphdsu3AkEAvQJ2Qay/lffFj9FaUrvXuftJZ/Ypn0FpaSiUh3Ak3obBT6UvSZS0
bcYdCJCNHDtBOsWHnIN1x+BcWAPrdU7PhwJBAIQ0dUlH2S3VXnoCOTGc44I1Hzbj
Rc65IdsuBqA3fQN2lX5vOOIog3vgaFrOArg1jBkG1wx5IMvb/EnUN2pjVqUCQCza
KLXtCInOAlPemlCHwumfeAvznmzsWNdbieOZ+SXVVIpR6KbNYwOpv7oIk3Pfm9sW
hNffWlPUKhW42Gc+DIECQQDmk20YgBXwXWRM5DRPbhisIV088N5Z58K9DtFWkZsd
OBDT3dFcgZONtlmR1MqZO0pTh30lA4qovYj3Bx7A8i36
-----END RSA PRIVATE KEY-----`
pubKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4TJk3onpqb2RYE3wwt23J9SHL
FstHGSkUYFLe+nl1dEKHbD+/Zt95L757J3xGTrwoTc7KCTxbrgn+stn0w52BNjj/
kIE2ko4lbh/v8Fl14AyVR9msfKtKOnhe5FCT72mdtApr+qvzcC3q9hfXwkyQU32p
v7q5UimZ205iKSBmgQIDAQAB
-----END PUBLIC KEY-----`
testBody = `this is the content`
)
func TestCryption(t *testing.T) {
enc, err := NewRsaEncrypter([]byte(pubKey))
assert.Nil(t, err)
ret, err := enc.Encrypt([]byte(testBody))
assert.Nil(t, err)
file, err := fs.TempFilenameWithText(priKey)
assert.Nil(t, err)
defer os.Remove(file)
dec, err := NewRsaDecrypter(file)
assert.Nil(t, err)
actual, err := dec.Decrypt(ret)
assert.Nil(t, err)
assert.Equal(t, testBody, string(actual))
actual, err = dec.DecryptBase64(base64.StdEncoding.EncodeToString(ret))
assert.Nil(t, err)
assert.Equal(t, testBody, string(actual))
}
func TestBadPubKey(t *testing.T) {
_, err := NewRsaEncrypter([]byte("foo"))
assert.Equal(t, ErrPublicKey, err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/dh_test.go | core/codec/dh_test.go | package codec
import (
"math/big"
"testing"
"github.com/stretchr/testify/assert"
)
func TestDiffieHellman(t *testing.T) {
key1, err := GenerateKey()
assert.Nil(t, err)
key2, err := GenerateKey()
assert.Nil(t, err)
pubKey1, err := ComputeKey(key1.PubKey, key2.PriKey)
assert.Nil(t, err)
pubKey2, err := ComputeKey(key2.PubKey, key1.PriKey)
assert.Nil(t, err)
assert.Equal(t, pubKey1, pubKey2)
}
func TestDiffieHellman1024(t *testing.T) {
old := p
p, _ = new(big.Int).SetString("F488FD584E49DBCD20B49DE49107366B336C380D451D0F7C88B31C7C5B2D8EF6F3C923C043F0A55B188D8EBB558CB85D38D334FD7C175743A31D186CDE33212CB52AFF3CE1B1294018118D7C84A70A72D686C40319C807297ACA950CD9969FABD00A509B0246D3083D66A45D419F9C7CBD894B221926BAABA25EC355E92F78C7", 16)
defer func() {
p = old
}()
key1, err := GenerateKey()
assert.Nil(t, err)
key2, err := GenerateKey()
assert.Nil(t, err)
pubKey1, err := ComputeKey(key1.PubKey, key2.PriKey)
assert.Nil(t, err)
pubKey2, err := ComputeKey(key2.PubKey, key1.PriKey)
assert.Nil(t, err)
assert.Equal(t, pubKey1, pubKey2)
}
func TestDiffieHellmanMiddleManAttack(t *testing.T) {
key1, err := GenerateKey()
assert.Nil(t, err)
keyMiddle, err := GenerateKey()
assert.Nil(t, err)
key2, err := GenerateKey()
assert.Nil(t, err)
const aesByteLen = 32
pubKey1, err := ComputeKey(keyMiddle.PubKey, key1.PriKey)
assert.Nil(t, err)
src := []byte(`hello, world!`)
encryptedSrc, err := EcbEncrypt(pubKey1.Bytes()[:aesByteLen], src)
assert.Nil(t, err)
pubKeyMiddle, err := ComputeKey(key1.PubKey, keyMiddle.PriKey)
assert.Nil(t, err)
decryptedSrc, err := EcbDecrypt(pubKeyMiddle.Bytes()[:aesByteLen], encryptedSrc)
assert.Nil(t, err)
assert.Equal(t, string(src), string(decryptedSrc))
pubKeyMiddle, err = ComputeKey(key2.PubKey, keyMiddle.PriKey)
assert.Nil(t, err)
encryptedSrc, err = EcbEncrypt(pubKeyMiddle.Bytes()[:aesByteLen], decryptedSrc)
assert.Nil(t, err)
pubKey2, err := ComputeKey(keyMiddle.PubKey, key2.PriKey)
assert.Nil(t, err)
decryptedSrc, err = EcbDecrypt(pubKey2.Bytes()[:aesByteLen], encryptedSrc)
assert.Nil(t, err)
assert.Equal(t, string(src), string(decryptedSrc))
}
func TestKeyBytes(t *testing.T) {
var empty DhKey
assert.Equal(t, 0, len(empty.Bytes()))
key, err := GenerateKey()
assert.Nil(t, err)
assert.True(t, len(key.Bytes()) > 0)
}
func TestDHOnErrors(t *testing.T) {
key, err := GenerateKey()
assert.Nil(t, err)
assert.NotEmpty(t, key.Bytes())
_, err = ComputeKey(key.PubKey, key.PriKey)
assert.NoError(t, err)
_, err = ComputeKey(nil, key.PriKey)
assert.Error(t, err)
_, err = ComputeKey(key.PubKey, nil)
assert.Error(t, err)
assert.NotNil(t, NewPublicKey([]byte("")))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/aesecb_test.go | core/codec/aesecb_test.go | package codec
import (
"crypto/aes"
"encoding/base64"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAesEcb(t *testing.T) {
var (
key = []byte("q4t7w!z%C*F-JaNdRgUjXn2r5u8x/A?D")
val = []byte("helloworld")
valLong = []byte("helloworldlong..")
badKey1 = []byte("aaaaaaaaa")
// more than 32 chars
badKey2 = []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
)
_, err := EcbEncrypt(badKey1, val)
assert.NotNil(t, err)
_, err = EcbEncrypt(badKey2, val)
assert.NotNil(t, err)
dst, err := EcbEncrypt(key, val)
assert.Nil(t, err)
_, err = EcbDecrypt(badKey1, dst)
assert.NotNil(t, err)
_, err = EcbDecrypt(badKey2, dst)
assert.NotNil(t, err)
_, err = EcbDecrypt(key, val)
// not enough block, just nil
assert.Nil(t, err)
src, err := EcbDecrypt(key, dst)
assert.Nil(t, err)
assert.Equal(t, val, src)
block, err := aes.NewCipher(key)
assert.NoError(t, err)
encrypter := NewECBEncrypter(block)
assert.Equal(t, 16, encrypter.BlockSize())
decrypter := NewECBDecrypter(block)
assert.Equal(t, 16, decrypter.BlockSize())
dst = make([]byte, 8)
encrypter.CryptBlocks(dst, val)
for _, b := range dst {
assert.Equal(t, byte(0), b)
}
dst = make([]byte, 8)
encrypter.CryptBlocks(dst, valLong)
for _, b := range dst {
assert.Equal(t, byte(0), b)
}
dst = make([]byte, 8)
decrypter.CryptBlocks(dst, val)
for _, b := range dst {
assert.Equal(t, byte(0), b)
}
dst = make([]byte, 8)
decrypter.CryptBlocks(dst, valLong)
for _, b := range dst {
assert.Equal(t, byte(0), b)
}
_, err = EcbEncryptBase64("cTR0N3dDKkYtSmFOZFJnVWpYbjJyNXU4eC9BP0QK", "aGVsbG93b3JsZGxvbmcuLgo=")
assert.Error(t, err)
}
func TestAesEcbBase64(t *testing.T) {
const (
val = "hello"
badKey1 = "aaaaaaaaa"
// more than 32 chars
badKey2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
)
key := []byte("q4t7w!z%C*F-JaNdRgUjXn2r5u8x/A?D")
b64Key := base64.StdEncoding.EncodeToString(key)
b64Val := base64.StdEncoding.EncodeToString([]byte(val))
_, err := EcbEncryptBase64(badKey1, val)
assert.NotNil(t, err)
_, err = EcbEncryptBase64(badKey2, val)
assert.NotNil(t, err)
_, err = EcbEncryptBase64(b64Key, val)
assert.NotNil(t, err)
dst, err := EcbEncryptBase64(b64Key, b64Val)
assert.Nil(t, err)
_, err = EcbDecryptBase64(badKey1, dst)
assert.NotNil(t, err)
_, err = EcbDecryptBase64(badKey2, dst)
assert.NotNil(t, err)
_, err = EcbDecryptBase64(b64Key, val)
assert.NotNil(t, err)
src, err := EcbDecryptBase64(b64Key, dst)
assert.Nil(t, err)
b, err := base64.StdEncoding.DecodeString(src)
assert.Nil(t, err)
assert.Equal(t, val, string(b))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/hmac.go | core/codec/hmac.go | package codec
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"io"
)
// Hmac returns HMAC bytes for body with the given key.
func Hmac(key []byte, body string) []byte {
h := hmac.New(sha256.New, key)
io.WriteString(h, body)
return h.Sum(nil)
}
// HmacBase64 returns the base64 encoded string of HMAC for body with the given key.
func HmacBase64(key []byte, body string) string {
return base64.StdEncoding.EncodeToString(Hmac(key, body))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/codec/rsa.go | core/codec/rsa.go | package codec
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"os"
)
var (
// ErrPrivateKey indicates the invalid private key.
ErrPrivateKey = errors.New("private key error")
// ErrPublicKey indicates the invalid public key.
ErrPublicKey = errors.New("failed to parse PEM block containing the public key")
// ErrNotRsaKey indicates the invalid RSA key.
ErrNotRsaKey = errors.New("key type is not RSA")
)
type (
// RsaDecrypter represents a RSA decrypter.
RsaDecrypter interface {
Decrypt(input []byte) ([]byte, error)
DecryptBase64(input string) ([]byte, error)
}
// RsaEncrypter represents a RSA encrypter.
RsaEncrypter interface {
Encrypt(input []byte) ([]byte, error)
}
rsaBase struct {
bytesLimit int
}
rsaDecrypter struct {
rsaBase
privateKey *rsa.PrivateKey
}
rsaEncrypter struct {
rsaBase
publicKey *rsa.PublicKey
}
)
// NewRsaDecrypter returns a RsaDecrypter with the given file.
func NewRsaDecrypter(file string) (RsaDecrypter, error) {
content, err := os.ReadFile(file)
if err != nil {
return nil, err
}
block, _ := pem.Decode(content)
if block == nil {
return nil, ErrPrivateKey
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return &rsaDecrypter{
rsaBase: rsaBase{
bytesLimit: privateKey.N.BitLen() >> 3,
},
privateKey: privateKey,
}, nil
}
func (r *rsaDecrypter) Decrypt(input []byte) ([]byte, error) {
return r.crypt(input, func(block []byte) ([]byte, error) {
return rsaDecryptBlock(r.privateKey, block)
})
}
func (r *rsaDecrypter) DecryptBase64(input string) ([]byte, error) {
if len(input) == 0 {
return nil, nil
}
base64Decoded, err := base64.StdEncoding.DecodeString(input)
if err != nil {
return nil, err
}
return r.Decrypt(base64Decoded)
}
// NewRsaEncrypter returns a RsaEncrypter with the given key.
func NewRsaEncrypter(key []byte) (RsaEncrypter, error) {
block, _ := pem.Decode(key)
if block == nil {
return nil, ErrPublicKey
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
switch pubKey := pub.(type) {
case *rsa.PublicKey:
return &rsaEncrypter{
rsaBase: rsaBase{
// https://www.ietf.org/rfc/rfc2313.txt
// The length of the data D shall not be more than k-11 octets, which is
// positive since the length k of the modulus is at least 12 octets.
bytesLimit: (pubKey.N.BitLen() >> 3) - 11,
},
publicKey: pubKey,
}, nil
default:
return nil, ErrNotRsaKey
}
}
func (r *rsaEncrypter) Encrypt(input []byte) ([]byte, error) {
return r.crypt(input, func(block []byte) ([]byte, error) {
return rsaEncryptBlock(r.publicKey, block)
})
}
func (r *rsaBase) crypt(input []byte, cryptFn func([]byte) ([]byte, error)) ([]byte, error) {
var result []byte
inputLen := len(input)
for i := 0; i*r.bytesLimit < inputLen; i++ {
start := r.bytesLimit * i
var stop int
if r.bytesLimit*(i+1) > inputLen {
stop = inputLen
} else {
stop = r.bytesLimit * (i + 1)
}
bs, err := cryptFn(input[start:stop])
if err != nil {
return nil, err
}
result = append(result, bs...)
}
return result, nil
}
func rsaDecryptBlock(privateKey *rsa.PrivateKey, block []byte) ([]byte, error) {
return rsa.DecryptPKCS1v15(rand.Reader, privateKey, block)
}
func rsaEncryptBlock(publicKey *rsa.PublicKey, msg []byte) ([]byte, error) {
return rsa.EncryptPKCS1v15(rand.Reader, publicKey, msg)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/fieldoptions.go | core/mapping/fieldoptions.go | package mapping
import "fmt"
const notSymbol = '!'
type (
// use context and OptionalDep option to determine the value of Optional
// nothing to do with context.Context
fieldOptionsWithContext struct {
Inherit bool
FromString bool
Optional bool
Options []string
Default string
EnvVar string
Range *numberRange
}
fieldOptions struct {
fieldOptionsWithContext
OptionalDep string
}
numberRange struct {
left float64
leftInclude bool
right float64
rightInclude bool
}
)
func (o *fieldOptionsWithContext) fromString() bool {
return o != nil && o.FromString
}
func (o *fieldOptionsWithContext) getDefault() (string, bool) {
if o == nil {
return "", false
}
return o.Default, len(o.Default) > 0
}
func (o *fieldOptionsWithContext) inherit() bool {
return o != nil && o.Inherit
}
func (o *fieldOptionsWithContext) optional() bool {
return o != nil && o.Optional
}
func (o *fieldOptionsWithContext) options() []string {
if o == nil {
return nil
}
return o.Options
}
func (o *fieldOptions) optionalDep() string {
if o == nil {
return ""
}
return o.OptionalDep
}
func (o *fieldOptions) toOptionsWithContext(key string, m Valuer, fullName string) (
*fieldOptionsWithContext, error) {
var optional bool
if o.optional() {
dep := o.optionalDep()
if len(dep) == 0 {
optional = true
} else if dep[0] == notSymbol {
dep = dep[1:]
if len(dep) == 0 {
return nil, fmt.Errorf("wrong optional value for %q in %q", key, fullName)
}
_, baseOn := m.Value(dep)
_, selfOn := m.Value(key)
if baseOn == selfOn {
return nil, fmt.Errorf("set value for either %q or %q in %q", dep, key, fullName)
}
optional = baseOn
} else {
_, baseOn := m.Value(dep)
_, selfOn := m.Value(key)
if baseOn != selfOn {
return nil, fmt.Errorf("values for %q and %q should be both provided or both not in %q",
dep, key, fullName)
}
optional = !baseOn
}
}
if o.fieldOptionsWithContext.Optional == optional {
return &o.fieldOptionsWithContext, nil
}
return &fieldOptionsWithContext{
FromString: o.FromString,
Optional: optional,
Options: o.Options,
Default: o.Default,
EnvVar: o.EnvVar,
}, nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/marshaler.go | core/mapping/marshaler.go | package mapping
import (
"fmt"
"reflect"
"slices"
"strings"
)
const (
emptyTag = ""
tagKVSeparator = ":"
)
// Marshal marshals the given val and returns the map that contains the fields.
// optional=another is not implemented, and it's hard to implement and not commonly used.
// support anonymous field, e.g.:
//
// type Foo struct {
// Token string `header:"token"`
// }
// type FooB struct {
// Foo
// Bar string `json:"bar"`
// }
func Marshal(val any) (map[string]map[string]any, error) {
ret := make(map[string]map[string]any)
tp := reflect.TypeOf(val)
if tp.Kind() == reflect.Ptr {
tp = tp.Elem()
}
rv := reflect.ValueOf(val)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
for i := 0; i < tp.NumField(); i++ {
field := tp.Field(i)
value := rv.Field(i)
if err := processMember(field, value, ret); err != nil {
return nil, err
}
}
return ret, nil
}
func getTag(field reflect.StructField) (string, bool) {
tag := string(field.Tag)
if i := strings.Index(tag, tagKVSeparator); i >= 0 {
return strings.TrimSpace(tag[:i]), true
}
return strings.TrimSpace(tag), false
}
func insertValue(collector map[string]map[string]any, tag string, key string, val any) {
if m, ok := collector[tag]; ok {
m[key] = val
} else {
collector[tag] = map[string]any{
key: val,
}
}
}
func processMember(field reflect.StructField, value reflect.Value,
collector map[string]map[string]any) error {
var key string
var opt *fieldOptions
var err error
tag, ok := getTag(field)
if !ok {
tag = emptyTag
key = field.Name
} else {
key, opt, err = parseKeyAndOptions(tag, field)
if err != nil {
return err
}
if err = validate(field, value, opt); err != nil {
return err
}
}
val := value.Interface()
if opt != nil && opt.FromString {
val = fmt.Sprint(val)
}
if field.Anonymous {
anonCollector, err := Marshal(val)
if err != nil {
return err
}
for anonTag, anonMap := range anonCollector {
for anonKey, anonVal := range anonMap {
insertValue(collector, anonTag, anonKey, anonVal)
}
}
} else {
insertValue(collector, tag, key, val)
}
return nil
}
func validate(field reflect.StructField, value reflect.Value, opt *fieldOptions) error {
if opt == nil || !opt.Optional {
if err := validateOptional(field, value); err != nil {
return err
}
}
if opt == nil {
return nil
}
if opt.Optional && value.IsZero() {
return nil
}
if len(opt.Options) > 0 {
if err := validateOptions(value, opt); err != nil {
return err
}
}
if opt.Range != nil {
if err := validateRange(value, opt); err != nil {
return err
}
}
return nil
}
func validateOptional(field reflect.StructField, value reflect.Value) error {
switch field.Type.Kind() {
case reflect.Ptr:
if value.IsNil() {
return fmt.Errorf("field %q is nil", field.Name)
}
case reflect.Slice, reflect.Map:
if value.IsNil() || value.Len() == 0 {
return fmt.Errorf("field %q is empty", field.Name)
}
}
return nil
}
func validateOptions(value reflect.Value, opt *fieldOptions) error {
val := fmt.Sprint(value.Interface())
if !slices.Contains(opt.Options, val) {
return fmt.Errorf("field %q not in options", val)
}
return nil
}
func validateRange(value reflect.Value, opt *fieldOptions) error {
var val float64
switch v := value.Interface().(type) {
case int:
val = float64(v)
case int8:
val = float64(v)
case int16:
val = float64(v)
case int32:
val = float64(v)
case int64:
val = float64(v)
case uint:
val = float64(v)
case uint8:
val = float64(v)
case uint16:
val = float64(v)
case uint32:
val = float64(v)
case uint64:
val = float64(v)
case float32:
val = float64(v)
case float64:
val = v
default:
return fmt.Errorf("unknown support type for range %q", value.Type().String())
}
// validates [left, right], [left, right), (left, right], (left, right)
if val < opt.Range.left ||
(!opt.Range.leftInclude && val == opt.Range.left) ||
val > opt.Range.right ||
(!opt.Range.rightInclude && val == opt.Range.right) {
return fmt.Errorf("%v out of range", value.Interface())
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/valuer_test.go | core/mapping/valuer_test.go | package mapping
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMapValuerWithInherit_Value(t *testing.T) {
input := map[string]any{
"discovery": map[string]any{
"host": "localhost",
"port": 8080,
},
"component": map[string]any{
"name": "test",
},
}
valuer := recursiveValuer{
current: mapValuer(input["component"].(map[string]any)),
parent: simpleValuer{
current: mapValuer(input),
},
}
val, ok := valuer.Value("discovery")
assert.True(t, ok)
m, ok := val.(map[string]any)
assert.True(t, ok)
assert.Equal(t, "localhost", m["host"])
assert.Equal(t, 8080, m["port"])
}
func TestRecursiveValuer_Value(t *testing.T) {
input := map[string]any{
"component": map[string]any{
"name": "test",
"foo": map[string]any{
"bar": "baz",
},
},
"foo": "value",
}
valuer := recursiveValuer{
current: mapValuer(input["component"].(map[string]any)),
parent: simpleValuer{
current: mapValuer(input),
},
}
val, ok := valuer.Value("foo")
assert.True(t, ok)
assert.EqualValues(t, map[string]any{
"bar": "baz",
}, val)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/yamlunmarshaler_test.go | core/mapping/yamlunmarshaler_test.go | package mapping
import (
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/utils/io"
)
func TestUnmarshalYamlBytes(t *testing.T) {
var c struct {
Name string
}
content := []byte(`Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Name)
}
func TestUnmarshalYamlBytesErrorInput(t *testing.T) {
var c struct {
Name string
}
content := []byte(`liao`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesEmptyInput(t *testing.T) {
var c struct {
Name string
}
content := []byte(``)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesOptional(t *testing.T) {
var c struct {
Name string
Age int `json:",optional"`
}
content := []byte(`Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Name)
}
func TestUnmarshalYamlBytesOptionalDefault(t *testing.T) {
var c struct {
Name string
Age int `json:",optional,default=1"`
}
content := []byte(`Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Name)
assert.Equal(t, 1, c.Age)
}
func TestUnmarshalYamlBytesDefaultOptional(t *testing.T) {
var c struct {
Name string
Age int `json:",default=1,optional"`
}
content := []byte(`Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Name)
assert.Equal(t, 1, c.Age)
}
func TestUnmarshalYamlBytesDefault(t *testing.T) {
var c struct {
Name string `json:",default=liao"`
}
content := []byte(`{}`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Name)
}
func TestUnmarshalYamlBytesBool(t *testing.T) {
var c struct {
Great bool
}
content := []byte(`Great: true`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.True(t, c.Great)
}
func TestUnmarshalYamlBytesInt(t *testing.T) {
var c struct {
Age int
}
content := []byte(`Age: 1`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, c.Age)
}
func TestUnmarshalYamlBytesUint(t *testing.T) {
var c struct {
Age uint
}
content := []byte(`Age: 1`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, uint(1), c.Age)
}
func TestUnmarshalYamlBytesFloat(t *testing.T) {
var c struct {
Age float32
}
content := []byte(`Age: 1.5`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, float32(1.5), c.Age)
}
func TestUnmarshalYamlBytesMustInOptional(t *testing.T) {
var c struct {
Inner struct {
There string
Must string
Optional string `json:",optional"`
} `json:",optional"`
}
content := []byte(`{}`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesMustInOptionalMissedPart(t *testing.T) {
var c struct {
Inner struct {
There string
Must string
Optional string `json:",optional"`
} `json:",optional"`
}
content := []byte(`Inner:
There: sure`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesMustInOptionalOnlyOptionalFilled(t *testing.T) {
var c struct {
Inner struct {
There string
Must string
Optional string `json:",optional"`
} `json:",optional"`
}
content := []byte(`Inner:
Optional: sure`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesPartial(t *testing.T) {
var c struct {
Name string
Age float32
}
content := []byte(`Age: 1.5`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesStruct(t *testing.T) {
var c struct {
Inner struct {
Name string
}
}
content := []byte(`Inner:
Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
}
func TestUnmarshalYamlBytesStructOptional(t *testing.T) {
var c struct {
Inner struct {
Name string
Age int `json:",optional"`
}
}
content := []byte(`Inner:
Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
}
func TestUnmarshalYamlBytesStructPtr(t *testing.T) {
var c struct {
Inner *struct {
Name string
}
}
content := []byte(`Inner:
Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
}
func TestUnmarshalYamlBytesStructPtrOptional(t *testing.T) {
var c struct {
Inner *struct {
Name string
Age int `json:",optional"`
}
}
content := []byte(`Inner:
Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesStructPtrDefault(t *testing.T) {
var c struct {
Inner *struct {
Name string
Age int `json:",default=4"`
}
}
content := []byte(`Inner:
Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
assert.Equal(t, 4, c.Inner.Age)
}
func TestUnmarshalYamlBytesSliceString(t *testing.T) {
var c struct {
Names []string
}
content := []byte(`Names:
- liao
- chaoxin`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
want := []string{"liao", "chaoxin"}
if !reflect.DeepEqual(c.Names, want) {
t.Fatalf("want %q, got %q", c.Names, want)
}
}
func TestUnmarshalYamlBytesSliceStringOptional(t *testing.T) {
var c struct {
Names []string
Age []int `json:",optional"`
}
content := []byte(`Names:
- liao
- chaoxin`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
want := []string{"liao", "chaoxin"}
if !reflect.DeepEqual(c.Names, want) {
t.Fatalf("want %q, got %q", c.Names, want)
}
}
func TestUnmarshalYamlBytesSliceStruct(t *testing.T) {
var c struct {
People []struct {
Name string
Age int
}
}
content := []byte(`People:
- Name: liao
Age: 1
- Name: chaoxin
Age: 2`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
want := []struct {
Name string
Age int
}{
{"liao", 1},
{"chaoxin", 2},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %q, got %q", c.People, want)
}
}
func TestUnmarshalYamlBytesSliceStructOptional(t *testing.T) {
var c struct {
People []struct {
Name string
Age int
Emails []string `json:",optional"`
}
}
content := []byte(`People:
- Name: liao
Age: 1
- Name: chaoxin
Age: 2`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
want := []struct {
Name string
Age int
Emails []string `json:",optional"`
}{
{"liao", 1, nil},
{"chaoxin", 2, nil},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %q, got %q", c.People, want)
}
}
func TestUnmarshalYamlBytesSliceStructPtr(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
}
}
content := []byte(`People:
- Name: liao
Age: 1
- Name: chaoxin
Age: 2`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
want := []*struct {
Name string
Age int
}{
{"liao", 1},
{"chaoxin", 2},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %v, got %v", c.People, want)
}
}
func TestUnmarshalYamlBytesSliceStructPtrOptional(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
Emails []string `json:",optional"`
}
}
content := []byte(`People:
- Name: liao
Age: 1
- Name: chaoxin
Age: 2`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
want := []*struct {
Name string
Age int
Emails []string `json:",optional"`
}{
{"liao", 1, nil},
{"chaoxin", 2, nil},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %v, got %v", c.People, want)
}
}
func TestUnmarshalYamlBytesSliceStructPtrPartial(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
Email string
}
}
content := []byte(`People:
- Name: liao
Age: 1
- Name: chaoxin
Age: 2`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesSliceStructPtrDefault(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
Email string `json:",default=chaoxin@liao.com"`
}
}
content := []byte(`People:
- Name: liao
Age: 1
- Name: chaoxin
Age: 2`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
want := []*struct {
Name string
Age int
Email string
}{
{"liao", 1, "chaoxin@liao.com"},
{"chaoxin", 2, "chaoxin@liao.com"},
}
for i := range c.People {
actual := c.People[i]
expect := want[i]
assert.Equal(t, expect.Age, actual.Age)
assert.Equal(t, expect.Email, actual.Email)
assert.Equal(t, expect.Name, actual.Name)
}
}
func TestUnmarshalYamlBytesSliceStringPartial(t *testing.T) {
var c struct {
Names []string
Age int
}
content := []byte(`Age: 1`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesSliceStructPartial(t *testing.T) {
var c struct {
Group string
People []struct {
Name string
Age int
}
}
content := []byte(`Group: chaoxin`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesInnerAnonymousPartial(t *testing.T) {
type (
Deep struct {
A string
B string `json:",optional"`
}
Inner struct {
Deep
InnerV string `json:",optional"`
}
)
var c struct {
Value Inner `json:",optional"`
}
content := []byte(`Value:
InnerV: chaoxin`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesStructPartial(t *testing.T) {
var c struct {
Group string
Person struct {
Name string
Age int
}
}
content := []byte(`Group: chaoxin`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesEmptyMap(t *testing.T) {
var c struct {
Persons map[string]int `json:",optional"`
}
content := []byte(`{}`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Empty(t, c.Persons)
}
func TestUnmarshalYamlBytesMap(t *testing.T) {
var c struct {
Persons map[string]int
}
content := []byte(`Persons:
first: 1
second: 2`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 2, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"])
assert.Equal(t, 2, c.Persons["second"])
}
func TestUnmarshalYamlBytesMapStruct(t *testing.T) {
var c struct {
Persons map[string]struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first:
ID: 1
name: kevin`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"].ID)
assert.Equal(t, "kevin", c.Persons["first"].Name)
}
func TestUnmarshalYamlBytesMapStructPtr(t *testing.T) {
var c struct {
Persons map[string]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first:
ID: 1
name: kevin`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"].ID)
assert.Equal(t, "kevin", c.Persons["first"].Name)
}
func TestUnmarshalYamlBytesMapStructMissingPartial(t *testing.T) {
var c struct {
Persons map[string]*struct {
ID int
Name string
}
}
content := []byte(`Persons:
first:
ID: 1`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesMapStructOptional(t *testing.T) {
var c struct {
Persons map[string]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first:
ID: 1`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"].ID)
}
func TestUnmarshalYamlBytesMapStructSlice(t *testing.T) {
var c struct {
Persons map[string][]struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first:
- ID: 1
name: kevin`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"][0].ID)
assert.Equal(t, "kevin", c.Persons["first"][0].Name)
}
func TestUnmarshalYamlBytesMapEmptyStructSlice(t *testing.T) {
var c struct {
Persons map[string][]struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first: []`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Empty(t, c.Persons["first"])
}
func TestUnmarshalYamlBytesMapStructPtrSlice(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first:
- ID: 1
name: kevin`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"][0].ID)
assert.Equal(t, "kevin", c.Persons["first"][0].Name)
}
func TestUnmarshalYamlBytesMapEmptyStructPtrSlice(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first: []`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Empty(t, c.Persons["first"])
}
func TestUnmarshalYamlBytesMapStructPtrSliceMissingPartial(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string
}
}
content := []byte(`Persons:
first:
- ID: 1`)
assert.NotNil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlBytesMapStructPtrSliceOptional(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`Persons:
first:
- ID: 1`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"][0].ID)
}
func TestUnmarshalYamlStructOptional(t *testing.T) {
var c struct {
Name string
Etcd struct {
Hosts []string
Key string
} `json:",optional"`
}
content := []byte(`Name: kevin`)
err := UnmarshalYamlBytes(content, &c)
assert.Nil(t, err)
assert.Equal(t, "kevin", c.Name)
}
func TestUnmarshalYamlStructLowerCase(t *testing.T) {
var c struct {
Name string
Etcd struct {
Key string
} `json:"etcd"`
}
content := []byte(`Name: kevin
etcd:
Key: the key`)
err := UnmarshalYamlBytes(content, &c)
assert.Nil(t, err)
assert.Equal(t, "kevin", c.Name)
assert.Equal(t, "the key", c.Etcd.Key)
}
func TestUnmarshalYamlWithStructAllOptionalWithEmpty(t *testing.T) {
var c struct {
Inner struct {
Optional string `json:",optional"`
}
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlWithStructAllOptionalPtr(t *testing.T) {
var c struct {
Inner *struct {
Optional string `json:",optional"`
}
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlWithStructOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
In Inner `json:",optional"`
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "", c.In.Must)
}
func TestUnmarshalYamlWithStructPtrOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
In *Inner `json:",optional"`
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Nil(t, c.In)
}
func TestUnmarshalYamlWithStructAllOptionalAnonymous(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
Inner
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlWithStructAllOptionalAnonymousPtr(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
*Inner
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
}
func TestUnmarshalYamlWithStructAllOptionalProvoidedAnonymous(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
Inner
Else string
}
content := []byte(`Else: sure
Optional: optional`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "optional", c.Optional)
}
func TestUnmarshalYamlWithStructAllOptionalProvoidedAnonymousPtr(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
*Inner
Else string
}
content := []byte(`Else: sure
Optional: optional`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "optional", c.Optional)
}
func TestUnmarshalYamlWithStructAnonymous(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
Inner
Else string
}
content := []byte(`Else: sure
Must: must`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "must", c.Must)
}
func TestUnmarshalYamlWithStructAnonymousPtr(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
*Inner
Else string
}
content := []byte(`Else: sure
Must: must`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "must", c.Must)
}
func TestUnmarshalYamlWithStructAnonymousOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
Inner `json:",optional"`
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "", c.Must)
}
func TestUnmarshalYamlWithStructPtrAnonymousOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
*Inner `json:",optional"`
Else string
}
content := []byte(`Else: sure`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Nil(t, c.Inner)
}
func TestUnmarshalYamlWithZeroValues(t *testing.T) {
type inner struct {
False bool `json:"negative"`
Int int `json:"int"`
String string `json:"string"`
}
content := []byte(`negative: false
int: 0
string: ""`)
var in inner
ast := assert.New(t)
ast.Nil(UnmarshalYamlBytes(content, &in))
ast.False(in.False)
ast.Equal(0, in.Int)
ast.Equal("", in.String)
}
func TestUnmarshalYamlBytesError(t *testing.T) {
payload := `abcd:
- cdef`
var v struct {
Any []string `json:"abcd"`
}
err := UnmarshalYamlBytes([]byte(payload), &v)
assert.Nil(t, err)
assert.Equal(t, 1, len(v.Any))
assert.Equal(t, "cdef", v.Any[0])
}
func TestUnmarshalYamlReaderError(t *testing.T) {
var v struct {
Any string
}
reader := strings.NewReader(`abcd: cdef`)
err := UnmarshalYamlReader(reader, &v)
assert.NotNil(t, err)
reader = strings.NewReader("foo")
assert.Error(t, UnmarshalYamlReader(reader, &v))
}
func TestUnmarshalYamlBadReader(t *testing.T) {
var v struct {
Any string
}
err := UnmarshalYamlReader(new(badReader), &v)
assert.NotNil(t, err)
}
func TestUnmarshalYamlMapBool(t *testing.T) {
text := `machine:
node1: true
node2: true
node3: true
`
var v struct {
Machine map[string]bool `json:"machine,optional"`
}
reader := strings.NewReader(text)
assert.Nil(t, UnmarshalYamlReader(reader, &v))
assert.True(t, v.Machine["node1"])
assert.True(t, v.Machine["node2"])
assert.True(t, v.Machine["node3"])
}
func TestUnmarshalYamlMapInt(t *testing.T) {
text := `machine:
node1: 1
node2: 2
node3: 3
`
var v struct {
Machine map[string]int `json:"machine,optional"`
}
reader := strings.NewReader(text)
assert.Nil(t, UnmarshalYamlReader(reader, &v))
assert.Equal(t, 1, v.Machine["node1"])
assert.Equal(t, 2, v.Machine["node2"])
assert.Equal(t, 3, v.Machine["node3"])
}
func TestUnmarshalYamlMapByte(t *testing.T) {
text := `machine:
node1: 1
node2: 2
node3: 3
`
var v struct {
Machine map[string]byte `json:"machine,optional"`
}
reader := strings.NewReader(text)
assert.Nil(t, UnmarshalYamlReader(reader, &v))
assert.Equal(t, byte(1), v.Machine["node1"])
assert.Equal(t, byte(2), v.Machine["node2"])
assert.Equal(t, byte(3), v.Machine["node3"])
}
func TestUnmarshalYamlMapRune(t *testing.T) {
text := `machine:
node1: 1
node2: 2
node3: 3
`
var v struct {
Machine map[string]rune `json:"machine,optional"`
}
reader := strings.NewReader(text)
assert.Nil(t, UnmarshalYamlReader(reader, &v))
assert.Equal(t, rune(1), v.Machine["node1"])
assert.Equal(t, rune(2), v.Machine["node2"])
assert.Equal(t, rune(3), v.Machine["node3"])
}
func TestUnmarshalYamlStringOfInt(t *testing.T) {
text := `password: 123456`
var v struct {
Password string `json:"password"`
}
reader := strings.NewReader(text)
assert.Error(t, UnmarshalYamlReader(reader, &v))
}
func TestUnmarshalYamlBadInput(t *testing.T) {
var v struct {
Any string
}
assert.Error(t, UnmarshalYamlBytes([]byte("':foo"), &v))
}
type badReader struct{}
func (b *badReader) Read(_ []byte) (n int, err error) {
return 0, io.ErrLimitReached
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/fieldoptions_test.go | core/mapping/fieldoptions_test.go | package mapping
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
type Bar struct {
Val string `json:"val"`
}
func TestFieldOptionOptionalDep(t *testing.T) {
var bar Bar
rt := reflect.TypeOf(bar)
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
val, opt, err := parseKeyAndOptions(jsonTagKey, field)
assert.Equal(t, "val", val)
assert.Nil(t, opt)
assert.Nil(t, err)
}
// check nil working
var o *fieldOptions
check := func(o *fieldOptions) {
assert.Equal(t, 0, len(o.optionalDep()))
}
check(o)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/utils.go | core/mapping/utils.go | package mapping
import (
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/stringx"
)
const (
defaultOption = "default"
envOption = "env"
inheritOption = "inherit"
stringOption = "string"
optionalOption = "optional"
optionsOption = "options"
rangeOption = "range"
optionSeparator = "|"
equalToken = "="
escapeChar = '\\'
leftBracket = '('
rightBracket = ')'
leftSquareBracket = '['
rightSquareBracket = ']'
segmentSeparator = ','
intSize = 32 << (^uint(0) >> 63) // 32 or 64
)
var (
errUnsupportedType = errors.New("unsupported type on setting field value")
errNumberRange = errors.New("wrong number range setting")
errNilSliceElement = errors.New("null element for slice")
optionsCache = make(map[string]optionsCacheValue)
cacheLock sync.RWMutex
structRequiredCache = make(map[reflect.Type]requiredCacheValue)
structCacheLock sync.RWMutex
)
type (
optionsCacheValue struct {
key string
options *fieldOptions
err error
}
requiredCacheValue struct {
required bool
err error
}
)
// Deref dereferences a type, if pointer type, returns its element type.
func Deref(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
// Repr returns the string representation of v.
func Repr(v any) string {
return lang.Repr(v)
}
// SetValue sets target to value, pointers are processed automatically.
func SetValue(tp reflect.Type, value, target reflect.Value) {
value.Set(convertTypeOfPtr(tp, target))
}
// SetMapIndexValue sets target to value at key position, pointers are processed automatically.
func SetMapIndexValue(tp reflect.Type, value, key, target reflect.Value) {
value.SetMapIndex(key, convertTypeOfPtr(tp, target))
}
// ValidatePtr validates v if it's a valid pointer.
func ValidatePtr(v reflect.Value) error {
// sequence is very important, IsNil must be called after checking Kind() with reflect.Ptr,
// panic otherwise
if !v.IsValid() || v.Kind() != reflect.Ptr || v.IsNil() {
return fmt.Errorf("not a valid pointer: %v", v)
}
return nil
}
func convertToString(val any, fullName string) (string, error) {
v, ok := val.(string)
if !ok {
return "", fmt.Errorf("expect string for field %s, but got type %T", fullName, val)
}
return v, nil
}
func convertTypeFromString(kind reflect.Kind, str string) (any, error) {
switch kind {
case reflect.Bool:
if str == "1" || strings.EqualFold(str, "true") {
return true, nil
}
if str == "0" || strings.EqualFold(str, "false") {
return false, nil
}
return false, errTypeMismatch
case reflect.Int:
return strconv.ParseInt(str, 10, intSize)
case reflect.Int8:
return strconv.ParseInt(str, 10, 8)
case reflect.Int16:
return strconv.ParseInt(str, 10, 16)
case reflect.Int32:
return strconv.ParseInt(str, 10, 32)
case reflect.Int64:
return strconv.ParseInt(str, 10, 64)
case reflect.Uint:
return strconv.ParseUint(str, 10, intSize)
case reflect.Uint8:
return strconv.ParseUint(str, 10, 8)
case reflect.Uint16:
return strconv.ParseUint(str, 10, 16)
case reflect.Uint32:
return strconv.ParseUint(str, 10, 32)
case reflect.Uint64:
return strconv.ParseUint(str, 10, 64)
case reflect.Float32:
return strconv.ParseFloat(str, 32)
case reflect.Float64:
return strconv.ParseFloat(str, 64)
case reflect.String:
return str, nil
default:
return nil, errUnsupportedType
}
}
func convertTypeOfPtr(tp reflect.Type, target reflect.Value) reflect.Value {
// keep the original value is a pointer
if tp.Kind() == reflect.Ptr && target.CanAddr() {
tp = tp.Elem()
target = target.Addr()
}
for tp.Kind() == reflect.Ptr {
p := reflect.New(target.Type())
p.Elem().Set(target)
target = p
tp = tp.Elem()
}
return target
}
func doParseKeyAndOptions(field reflect.StructField, value string) (string, *fieldOptions, error) {
segments := parseSegments(value)
key := strings.TrimSpace(segments[0])
options := segments[1:]
if len(options) == 0 {
return key, nil, nil
}
var fieldOpts fieldOptions
for _, segment := range options {
option := strings.TrimSpace(segment)
if err := parseOption(&fieldOpts, field.Name, option); err != nil {
return "", nil, err
}
}
return key, &fieldOpts, nil
}
// ensureValue ensures nested members not to be nil.
// If pointer value is nil, set to a new value.
func ensureValue(v reflect.Value) reflect.Value {
for {
if v.Kind() != reflect.Ptr {
break
}
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
return v
}
func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) {
numFields := tp.NumField()
for i := 0; i < numFields; i++ {
childField := tp.Field(i)
if usingDifferentKeys(tag, childField) {
return true, nil
}
_, opts, err := parseKeyAndOptions(tag, childField)
if err != nil {
return false, err
}
if opts == nil {
if childField.Type.Kind() != reflect.Struct {
return true, nil
}
if required, err := implicitValueRequiredStruct(tag, childField.Type); err != nil {
return false, err
} else if required {
return true, nil
}
} else if !opts.Optional && len(opts.Default) == 0 {
return true, nil
} else if len(opts.OptionalDep) > 0 && opts.OptionalDep[0] == notSymbol {
return true, nil
}
}
return false, nil
}
func isLeftInclude(b byte) (bool, error) {
switch b {
case '[':
return true, nil
case '(':
return false, nil
default:
return false, errNumberRange
}
}
func isRightInclude(b byte) (bool, error) {
switch b {
case ']':
return true, nil
case ')':
return false, nil
default:
return false, errNumberRange
}
}
func maybeNewValue(fieldType reflect.Type, value reflect.Value) {
if fieldType.Kind() == reflect.Ptr && value.IsNil() {
value.Set(reflect.New(value.Type().Elem()))
}
}
func parseGroupedSegments(val string) []string {
val = strings.TrimLeftFunc(val, func(r rune) bool {
return r == leftBracket || r == leftSquareBracket
})
val = strings.TrimRightFunc(val, func(r rune) bool {
return r == rightBracket || r == rightSquareBracket
})
return parseSegments(val)
}
// don't modify returned fieldOptions, it's cached and shared among different calls.
func parseKeyAndOptions(tagName string, field reflect.StructField) (string, *fieldOptions, error) {
value := strings.TrimSpace(field.Tag.Get(tagName))
if len(value) == 0 {
return field.Name, nil, nil
}
cacheLock.RLock()
cache, ok := optionsCache[value]
cacheLock.RUnlock()
if ok {
return stringx.TakeOne(cache.key, field.Name), cache.options, cache.err
}
key, options, err := doParseKeyAndOptions(field, value)
cacheLock.Lock()
optionsCache[value] = optionsCacheValue{
key: key,
options: options,
err: err,
}
cacheLock.Unlock()
return stringx.TakeOne(key, field.Name), options, err
}
// support below notations:
// [:5] (:5] [:5) (:5)
// [1:] [1:) (1:] (1:)
// [1:5] [1:5) (1:5] (1:5)
func parseNumberRange(str string) (*numberRange, error) {
if len(str) == 0 {
return nil, errNumberRange
}
leftInclude, err := isLeftInclude(str[0])
if err != nil {
return nil, err
}
str = str[1:]
if len(str) == 0 {
return nil, errNumberRange
}
rightInclude, err := isRightInclude(str[len(str)-1])
if err != nil {
return nil, err
}
str = str[:len(str)-1]
fields := strings.Split(str, ":")
if len(fields) != 2 {
return nil, errNumberRange
}
if len(fields[0]) == 0 && len(fields[1]) == 0 {
return nil, errNumberRange
}
var left float64
if len(fields[0]) > 0 {
var err error
if left, err = strconv.ParseFloat(fields[0], 64); err != nil {
return nil, err
}
} else {
left = -math.MaxFloat64
}
var right float64
if len(fields[1]) > 0 {
var err error
if right, err = strconv.ParseFloat(fields[1], 64); err != nil {
return nil, err
}
} else {
right = math.MaxFloat64
}
if left > right {
return nil, errNumberRange
}
// [2:2] valid
// [2:2) invalid
// (2:2] invalid
// (2:2) invalid
if left == right {
if !leftInclude || !rightInclude {
return nil, errNumberRange
}
}
return &numberRange{
left: left,
leftInclude: leftInclude,
right: right,
rightInclude: rightInclude,
}, nil
}
func parseOption(fieldOpts *fieldOptions, fieldName, option string) error {
switch {
case option == inheritOption:
fieldOpts.Inherit = true
case option == stringOption:
fieldOpts.FromString = true
case strings.HasPrefix(option, optionalOption):
segs := strings.Split(option, equalToken)
switch len(segs) {
case 1:
fieldOpts.Optional = true
case 2:
fieldOpts.Optional = true
fieldOpts.OptionalDep = segs[1]
default:
return fmt.Errorf("field %q has wrong optional", fieldName)
}
case strings.HasPrefix(option, optionsOption):
val, err := parseProperty(fieldName, optionsOption, option)
if err != nil {
return err
}
fieldOpts.Options = parseOptions(val)
case strings.HasPrefix(option, defaultOption):
val, err := parseProperty(fieldName, defaultOption, option)
if err != nil {
return err
}
fieldOpts.Default = val
case strings.HasPrefix(option, envOption):
val, err := parseProperty(fieldName, envOption, option)
if err != nil {
return err
}
fieldOpts.EnvVar = val
case strings.HasPrefix(option, rangeOption):
val, err := parseProperty(fieldName, rangeOption, option)
if err != nil {
return err
}
nr, err := parseNumberRange(val)
if err != nil {
return err
}
fieldOpts.Range = nr
}
return nil
}
// parseOptions parses the given options in tag.
// for example, `json:"name,options=foo|bar"` or `json:"name,options=[foo,bar]"`
func parseOptions(val string) []string {
if len(val) == 0 {
return nil
}
if val[0] == leftSquareBracket {
return parseGroupedSegments(val)
}
return strings.Split(val, optionSeparator)
}
func parseProperty(field, tag, val string) (string, error) {
segs := strings.Split(val, equalToken)
if len(segs) != 2 {
return "", fmt.Errorf("field %q has wrong tag value %q", field, tag)
}
return strings.TrimSpace(segs[1]), nil
}
func parseSegments(val string) []string {
var segments []string
var escaped, grouped bool
var buf strings.Builder
for _, ch := range val {
if escaped {
buf.WriteRune(ch)
escaped = false
continue
}
switch ch {
case segmentSeparator:
if grouped {
buf.WriteRune(ch)
} else {
// need to trim spaces, but we cannot ignore empty string,
// because the first segment stands for the key might be empty.
// if ignored, the later tag will be used as the key.
segments = append(segments, strings.TrimSpace(buf.String()))
buf.Reset()
}
case escapeChar:
if grouped {
buf.WriteRune(ch)
} else {
escaped = true
}
case leftBracket, leftSquareBracket:
buf.WriteRune(ch)
grouped = true
case rightBracket, rightSquareBracket:
buf.WriteRune(ch)
grouped = false
default:
buf.WriteRune(ch)
}
}
last := strings.TrimSpace(buf.String())
// ignore last empty string
if len(last) > 0 {
segments = append(segments, last)
}
return segments
}
func setMatchedPrimitiveValue(kind reflect.Kind, value reflect.Value, v any) error {
switch kind {
case reflect.Bool:
value.SetBool(v.(bool))
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
value.SetInt(v.(int64))
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
value.SetUint(v.(uint64))
return nil
case reflect.Float32, reflect.Float64:
value.SetFloat(v.(float64))
return nil
case reflect.String:
value.SetString(v.(string))
return nil
default:
return errUnsupportedType
}
}
func setValueFromString(kind reflect.Kind, value reflect.Value, str string) error {
if !value.CanSet() {
return errValueNotSettable
}
value = ensureValue(value)
v, err := convertTypeFromString(kind, str)
if err != nil {
return err
}
return setMatchedPrimitiveValue(kind, value, v)
}
func structValueRequired(tag string, tp reflect.Type) (bool, error) {
structCacheLock.RLock()
val, ok := structRequiredCache[tp]
structCacheLock.RUnlock()
if ok {
return val.required, val.err
}
required, err := implicitValueRequiredStruct(tag, tp)
structCacheLock.Lock()
structRequiredCache[tp] = requiredCacheValue{
required: required,
err: err,
}
structCacheLock.Unlock()
return required, err
}
func toFloat64(v any) (float64, bool) {
switch val := v.(type) {
case int:
return float64(val), true
case int8:
return float64(val), true
case int16:
return float64(val), true
case int32:
return float64(val), true
case int64:
return float64(val), true
case uint:
return float64(val), true
case uint8:
return float64(val), true
case uint16:
return float64(val), true
case uint32:
return float64(val), true
case uint64:
return float64(val), true
case float32:
return float64(val), true
case float64:
return val, true
default:
return 0, false
}
}
func toReflectValue(tp reflect.Type, v any) reflect.Value {
return reflect.ValueOf(v).Convert(Deref(tp))
}
func usingDifferentKeys(key string, field reflect.StructField) bool {
if len(field.Tag) > 0 {
if _, ok := field.Tag.Lookup(key); !ok {
return true
}
}
return false
}
func validateAndSetValue(kind reflect.Kind, value reflect.Value, str string,
opts *fieldOptionsWithContext) error {
if !value.CanSet() {
return errValueNotSettable
}
v, err := convertTypeFromString(kind, str)
if err != nil {
return err
}
if err := validateValueRange(v, opts); err != nil {
return err
}
return setMatchedPrimitiveValue(kind, value, v)
}
func validateJsonNumberRange(v json.Number, opts *fieldOptionsWithContext) error {
if opts == nil || opts.Range == nil {
return nil
}
fv, err := v.Float64()
if err != nil {
return err
}
return validateNumberRange(fv, opts.Range)
}
func validateNumberRange(fv float64, nr *numberRange) error {
if nr == nil {
return nil
}
if (nr.leftInclude && fv < nr.left) || (!nr.leftInclude && fv <= nr.left) {
return errNumberRange
}
if (nr.rightInclude && fv > nr.right) || (!nr.rightInclude && fv >= nr.right) {
return errNumberRange
}
return nil
}
func validateValueInOptions(val any, options []string) error {
if len(options) > 0 {
switch v := val.(type) {
case string:
if !slices.Contains(options, v) {
return fmt.Errorf(`error: value %q is not defined in options "%v"`, v, options)
}
default:
if !slices.Contains(options, Repr(v)) {
return fmt.Errorf(`error: value "%v" is not defined in options "%v"`, val, options)
}
}
}
return nil
}
func validateValueRange(mapValue any, opts *fieldOptionsWithContext) error {
if opts == nil || opts.Range == nil {
return nil
}
fv, ok := toFloat64(mapValue)
if !ok {
return errNumberRange
}
return validateNumberRange(fv, opts.Range)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/tomlunmarshaler_test.go | core/mapping/tomlunmarshaler_test.go | package mapping
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUnmarshalToml(t *testing.T) {
const input = `a = "foo"
b = 1
c = "${FOO}"
d = "abcd!@#$112"
`
var val struct {
A string `json:"a"`
B int `json:"b"`
C string `json:"c"`
D string `json:"d"`
}
assert.NoError(t, UnmarshalTomlReader(strings.NewReader(input), &val))
assert.Equal(t, "foo", val.A)
assert.Equal(t, 1, val.B)
assert.Equal(t, "${FOO}", val.C)
assert.Equal(t, "abcd!@#$112", val.D)
}
func TestUnmarshalTomlErrorToml(t *testing.T) {
const input = `foo"
b = 1
c = "${FOO}"
d = "abcd!@#$112"
`
var val struct {
A string `json:"a"`
B int `json:"b"`
C string `json:"c"`
D string `json:"d"`
}
assert.Error(t, UnmarshalTomlReader(strings.NewReader(input), &val))
}
func TestUnmarshalTomlBadReader(t *testing.T) {
var val struct {
A string `json:"a"`
}
assert.Error(t, UnmarshalTomlReader(new(badReader), &val))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/jsonunmarshaler.go | core/mapping/jsonunmarshaler.go | package mapping
import (
"io"
"github.com/zeromicro/go-zero/core/jsonx"
)
const jsonTagKey = "json"
var jsonUnmarshaler = NewUnmarshaler(jsonTagKey)
// UnmarshalJsonBytes unmarshals content into v.
func UnmarshalJsonBytes(content []byte, v any, opts ...UnmarshalOption) error {
return unmarshalJsonBytes(content, v, getJsonUnmarshaler(opts...))
}
// UnmarshalJsonMap unmarshals content from m into v.
func UnmarshalJsonMap(m map[string]any, v any, opts ...UnmarshalOption) error {
return getJsonUnmarshaler(opts...).Unmarshal(m, v)
}
// UnmarshalJsonReader unmarshals content from reader into v.
func UnmarshalJsonReader(reader io.Reader, v any, opts ...UnmarshalOption) error {
return unmarshalJsonReader(reader, v, getJsonUnmarshaler(opts...))
}
func getJsonUnmarshaler(opts ...UnmarshalOption) *Unmarshaler {
if len(opts) > 0 {
return NewUnmarshaler(jsonTagKey, opts...)
}
return jsonUnmarshaler
}
func unmarshalJsonBytes(content []byte, v any, unmarshaler *Unmarshaler) error {
var m any
if err := jsonx.Unmarshal(content, &m); err != nil {
return err
}
return unmarshaler.Unmarshal(m, v)
}
func unmarshalJsonReader(reader io.Reader, v any, unmarshaler *Unmarshaler) error {
var m any
if err := jsonx.UnmarshalFromReader(reader, &m); err != nil {
return err
}
return unmarshaler.Unmarshal(m, v)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/marshaler_test.go | core/mapping/marshaler_test.go | package mapping
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMarshal(t *testing.T) {
v := struct {
Name string `path:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
Anonymous bool
}{
Name: "kevin",
Address: "shanghai",
Age: 20,
Anonymous: true,
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, "kevin", m["path"]["name"])
assert.Equal(t, "shanghai", m["json"]["address"])
assert.Equal(t, 20, m["json"]["age"].(int))
assert.True(t, m[emptyTag]["Anonymous"].(bool))
}
func TestMarshal_Anonymous(t *testing.T) {
t.Run("anonymous", func(t *testing.T) {
type BaseHeader struct {
Token string `header:"token"`
}
v := struct {
Name string `json:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
BaseHeader
}{
Name: "kevin",
Address: "shanghai",
Age: 20,
BaseHeader: BaseHeader{
Token: "token_xxx",
},
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, "kevin", m["json"]["name"])
assert.Equal(t, "shanghai", m["json"]["address"])
assert.Equal(t, 20, m["json"]["age"].(int))
assert.Equal(t, "token_xxx", m["header"]["token"])
v1 := struct {
Name string `json:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
BaseHeader
}{
Name: "kevin",
Address: "shanghai",
Age: 20,
}
m1, err1 := Marshal(v1)
assert.Nil(t, err1)
assert.Equal(t, "kevin", m1["json"]["name"])
assert.Equal(t, "shanghai", m1["json"]["address"])
assert.Equal(t, 20, m1["json"]["age"].(int))
type AnotherHeader struct {
Version string `header:"version"`
}
v2 := struct {
Name string `json:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
BaseHeader
AnotherHeader
}{
Name: "kevin",
Address: "shanghai",
Age: 20,
BaseHeader: BaseHeader{
Token: "token_xxx",
},
AnotherHeader: AnotherHeader{
Version: "v1.0",
},
}
m2, err2 := Marshal(v2)
assert.Nil(t, err2)
assert.Equal(t, "kevin", m2["json"]["name"])
assert.Equal(t, "shanghai", m2["json"]["address"])
assert.Equal(t, 20, m2["json"]["age"].(int))
assert.Equal(t, "token_xxx", m2["header"]["token"])
assert.Equal(t, "v1.0", m2["header"]["version"])
type PointerHeader struct {
Ref *string `header:"ref"`
}
ref := "reference"
v3 := struct {
Name string `json:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
PointerHeader
}{
Name: "kevin",
Address: "shanghai",
Age: 20,
PointerHeader: PointerHeader{
Ref: &ref,
},
}
m3, err3 := Marshal(v3)
assert.Nil(t, err3)
assert.Equal(t, "kevin", m3["json"]["name"])
assert.Equal(t, "shanghai", m3["json"]["address"])
assert.Equal(t, 20, m3["json"]["age"].(int))
assert.Equal(t, "reference", *m3["header"]["ref"].(*string))
})
t.Run("bad anonymous", func(t *testing.T) {
type BaseHeader struct {
Token string `json:"token,options=[a,b]"`
}
v := struct {
Name string `json:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
BaseHeader
}{
Name: "kevin",
Address: "shanghai",
Age: 20,
BaseHeader: BaseHeader{
Token: "c",
},
}
_, err := Marshal(v)
assert.NotNil(t, err)
})
}
func TestMarshal_Ptr(t *testing.T) {
v := &struct {
Name string `path:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
Anonymous bool
}{
Name: "kevin",
Address: "shanghai",
Age: 20,
Anonymous: true,
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, "kevin", m["path"]["name"])
assert.Equal(t, "shanghai", m["json"]["address"])
assert.Equal(t, 20, m["json"]["age"].(int))
assert.True(t, m[emptyTag]["Anonymous"].(bool))
}
func TestMarshal_OptionalPtr(t *testing.T) {
var val = 1
v := struct {
Age *int `json:"age"`
}{
Age: &val,
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, 1, *m["json"]["age"].(*int))
}
func TestMarshal_OptionalPtrNil(t *testing.T) {
v := struct {
Age *int `json:"age"`
}{}
_, err := Marshal(v)
assert.NotNil(t, err)
}
func TestMarshal_BadOptions(t *testing.T) {
v := struct {
Name string `json:"name,options"`
}{
Name: "kevin",
}
_, err := Marshal(v)
assert.NotNil(t, err)
}
func TestMarshal_NotInOptions(t *testing.T) {
v := struct {
Name string `json:"name,options=[a,b]"`
}{
Name: "kevin",
}
_, err := Marshal(v)
assert.NotNil(t, err)
}
func TestMarshal_NotInOptionsOptional(t *testing.T) {
v := struct {
Name string `json:"name,options=[a,b],optional"`
}{}
_, err := Marshal(v)
assert.Nil(t, err)
}
func TestMarshal_NotInOptionsOptionalWrongValue(t *testing.T) {
v := struct {
Name string `json:"name,options=[a,b],optional"`
}{
Name: "kevin",
}
_, err := Marshal(v)
assert.NotNil(t, err)
}
func TestMarshal_Nested(t *testing.T) {
type address struct {
Country string `json:"country"`
City string `json:"city"`
}
v := struct {
Name string `json:"name,options=[kevin,wan]"`
Address address `json:"address"`
}{
Name: "kevin",
Address: address{
Country: "China",
City: "Shanghai",
},
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, "kevin", m["json"]["name"])
assert.Equal(t, "China", m["json"]["address"].(address).Country)
assert.Equal(t, "Shanghai", m["json"]["address"].(address).City)
}
func TestMarshal_NestedPtr(t *testing.T) {
type address struct {
Country string `json:"country"`
City string `json:"city"`
}
v := struct {
Name string `json:"name,options=[kevin,wan]"`
Address *address `json:"address"`
}{
Name: "kevin",
Address: &address{
Country: "China",
City: "Shanghai",
},
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, "kevin", m["json"]["name"])
assert.Equal(t, "China", m["json"]["address"].(*address).Country)
assert.Equal(t, "Shanghai", m["json"]["address"].(*address).City)
}
func TestMarshal_Slice(t *testing.T) {
v := struct {
Name []string `json:"name"`
}{
Name: []string{"kevin", "wan"},
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.ElementsMatch(t, []string{"kevin", "wan"}, m["json"]["name"].([]string))
}
func TestMarshal_SliceNil(t *testing.T) {
v := struct {
Name []string `json:"name"`
}{
Name: nil,
}
_, err := Marshal(v)
assert.NotNil(t, err)
}
func TestMarshal_Range(t *testing.T) {
v := struct {
Int int `json:"int,range=[1:3]"`
Int8 int8 `json:"int8,range=[1:3)"`
Int16 int16 `json:"int16,range=(1:3]"`
Int32 int32 `json:"int32,range=(1:3)"`
Int64 int64 `json:"int64,range=(1:3)"`
Uint uint `json:"uint,range=[1:3]"`
Uint8 uint8 `json:"uint8,range=[1:3)"`
Uint16 uint16 `json:"uint16,range=(1:3]"`
Uint32 uint32 `json:"uint32,range=(1:3)"`
Uint64 uint64 `json:"uint64,range=(1:3)"`
Float32 float32 `json:"float32,range=(1:3)"`
Float64 float64 `json:"float64,range=(1:3)"`
}{
Int: 1,
Int8: 1,
Int16: 2,
Int32: 2,
Int64: 2,
Uint: 1,
Uint8: 1,
Uint16: 2,
Uint32: 2,
Uint64: 2,
Float32: 2,
Float64: 2,
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, 1, m["json"]["int"].(int))
assert.Equal(t, int8(1), m["json"]["int8"].(int8))
assert.Equal(t, int16(2), m["json"]["int16"].(int16))
assert.Equal(t, int32(2), m["json"]["int32"].(int32))
assert.Equal(t, int64(2), m["json"]["int64"].(int64))
assert.Equal(t, uint(1), m["json"]["uint"].(uint))
assert.Equal(t, uint8(1), m["json"]["uint8"].(uint8))
assert.Equal(t, uint16(2), m["json"]["uint16"].(uint16))
assert.Equal(t, uint32(2), m["json"]["uint32"].(uint32))
assert.Equal(t, uint64(2), m["json"]["uint64"].(uint64))
assert.Equal(t, float32(2), m["json"]["float32"].(float32))
assert.Equal(t, float64(2), m["json"]["float64"].(float64))
}
func TestMarshal_RangeOut(t *testing.T) {
tests := []any{
struct {
Int int `json:"int,range=[1:3]"`
}{
Int: 4,
},
struct {
Int int `json:"int,range=(1:3]"`
}{
Int: 1,
},
struct {
Int int `json:"int,range=[1:3)"`
}{
Int: 3,
},
struct {
Int int `json:"int,range=(1:3)"`
}{
Int: 3,
},
struct {
Bool bool `json:"bool,range=(1:3)"`
}{
Bool: true,
},
}
for _, test := range tests {
_, err := Marshal(test)
assert.NotNil(t, err)
}
}
func TestMarshal_RangeIllegal(t *testing.T) {
tests := []any{
struct {
Int int `json:"int,range=[3:1]"`
}{
Int: 2,
},
struct {
Int int `json:"int,range=(3:1]"`
}{
Int: 2,
},
}
for _, test := range tests {
_, err := Marshal(test)
assert.Equal(t, err, errNumberRange)
}
}
func TestMarshal_RangeLeftEqualsToRight(t *testing.T) {
tests := []struct {
name string
value any
err error
}{
{
name: "left inclusive, right inclusive",
value: struct {
Int int `json:"int,range=[2:2]"`
}{
Int: 2,
},
},
{
name: "left inclusive, right exclusive",
value: struct {
Int int `json:"int,range=[2:2)"`
}{
Int: 2,
},
err: errNumberRange,
},
{
name: "left exclusive, right inclusive",
value: struct {
Int int `json:"int,range=(2:2]"`
}{
Int: 2,
},
err: errNumberRange,
},
{
name: "left exclusive, right exclusive",
value: struct {
Int int `json:"int,range=(2:2)"`
}{
Int: 2,
},
err: errNumberRange,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
_, err := Marshal(test.value)
assert.Equal(t, test.err, err)
})
}
}
func TestMarshal_FromString(t *testing.T) {
v := struct {
Age int `json:"age,string"`
}{
Age: 10,
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, "10", m["json"]["age"].(string))
}
func TestMarshal_Array(t *testing.T) {
v := struct {
H [1]int `json:"h,string"`
}{
H: [1]int{1},
}
m, err := Marshal(v)
assert.Nil(t, err)
assert.Equal(t, "[1]", m["json"]["h"].(string))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/yamlunmarshaler.go | core/mapping/yamlunmarshaler.go | package mapping
import (
"io"
"github.com/zeromicro/go-zero/internal/encoding"
)
// UnmarshalYamlBytes unmarshals content into v.
func UnmarshalYamlBytes(content []byte, v any, opts ...UnmarshalOption) error {
b, err := encoding.YamlToJson(content)
if err != nil {
return err
}
return UnmarshalJsonBytes(b, v, opts...)
}
// UnmarshalYamlReader unmarshals content from reader into v.
func UnmarshalYamlReader(reader io.Reader, v any, opts ...UnmarshalOption) error {
b, err := io.ReadAll(reader)
if err != nil {
return err
}
return UnmarshalYamlBytes(b, v, opts...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/tomlunmarshaler.go | core/mapping/tomlunmarshaler.go | package mapping
import (
"io"
"github.com/zeromicro/go-zero/internal/encoding"
)
// UnmarshalTomlBytes unmarshals TOML bytes into the given v.
func UnmarshalTomlBytes(content []byte, v any, opts ...UnmarshalOption) error {
b, err := encoding.TomlToJson(content)
if err != nil {
return err
}
return UnmarshalJsonBytes(b, v, opts...)
}
// UnmarshalTomlReader unmarshals TOML from the given io.Reader into the given v.
func UnmarshalTomlReader(r io.Reader, v any, opts ...UnmarshalOption) error {
b, err := io.ReadAll(r)
if err != nil {
return err
}
return UnmarshalTomlBytes(b, v, opts...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/utils_test.go | core/mapping/utils_test.go | package mapping
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
const testTagName = "key"
type Foo struct {
Str string
StrWithTag string `key:"stringwithtag"`
StrWithTagAndOption string `key:"stringwithtag,string"`
}
func TestDerefInt(t *testing.T) {
i := 1
s := "hello"
number := struct {
f float64
}{
f: 6.4,
}
cases := []struct {
t reflect.Type
expect reflect.Kind
}{
{
t: reflect.TypeOf(i),
expect: reflect.Int,
},
{
t: reflect.TypeOf(&i),
expect: reflect.Int,
},
{
t: reflect.TypeOf(s),
expect: reflect.String,
},
{
t: reflect.TypeOf(&s),
expect: reflect.String,
},
{
t: reflect.TypeOf(number.f),
expect: reflect.Float64,
},
{
t: reflect.TypeOf(&number.f),
expect: reflect.Float64,
},
}
for _, each := range cases {
t.Run(each.t.String(), func(t *testing.T) {
assert.Equal(t, each.expect, Deref(each.t).Kind())
})
}
}
func TestDerefValInt(t *testing.T) {
i := 1
s := "hello"
number := struct {
f float64
}{
f: 6.4,
}
cases := []struct {
t reflect.Value
expect reflect.Kind
}{
{
t: reflect.ValueOf(i),
expect: reflect.Int,
},
{
t: reflect.ValueOf(&i),
expect: reflect.Int,
},
{
t: reflect.ValueOf(s),
expect: reflect.String,
},
{
t: reflect.ValueOf(&s),
expect: reflect.String,
},
{
t: reflect.ValueOf(number.f),
expect: reflect.Float64,
},
{
t: reflect.ValueOf(&number.f),
expect: reflect.Float64,
},
}
for _, each := range cases {
t.Run(each.t.String(), func(t *testing.T) {
assert.Equal(t, each.expect, ensureValue(each.t).Kind())
})
}
}
func TestParseKeyAndOptionWithoutTag(t *testing.T) {
var foo Foo
rte := reflect.TypeOf(&foo).Elem()
field, _ := rte.FieldByName("Str")
key, options, err := parseKeyAndOptions(testTagName, field)
assert.Nil(t, err)
assert.Equal(t, "Str", key)
assert.Nil(t, options)
}
func TestParseKeyAndOptionWithTagWithoutOption(t *testing.T) {
var foo Foo
rte := reflect.TypeOf(&foo).Elem()
field, _ := rte.FieldByName("StrWithTag")
key, options, err := parseKeyAndOptions(testTagName, field)
assert.Nil(t, err)
assert.Equal(t, "stringwithtag", key)
assert.Nil(t, options)
}
func TestParseKeyAndOptionWithTagAndOption(t *testing.T) {
var foo Foo
rte := reflect.TypeOf(&foo).Elem()
field, _ := rte.FieldByName("StrWithTagAndOption")
key, options, err := parseKeyAndOptions(testTagName, field)
assert.Nil(t, err)
assert.Equal(t, "stringwithtag", key)
assert.True(t, options.FromString)
}
func TestParseSegments(t *testing.T) {
tests := []struct {
input string
expect []string
}{
{
input: "",
expect: []string{},
},
{
input: " ",
expect: []string{},
},
{
input: ",",
expect: []string{""},
},
{
input: "foo,",
expect: []string{"foo"},
},
{
input: ",foo",
// the first empty string cannot be ignored, it's the key.
expect: []string{"", "foo"},
},
{
input: "foo",
expect: []string{"foo"},
},
{
input: "foo,bar",
expect: []string{"foo", "bar"},
},
{
input: "foo,bar,baz",
expect: []string{"foo", "bar", "baz"},
},
{
input: "foo,options=a|b",
expect: []string{"foo", "options=a|b"},
},
{
input: "foo,bar,default=[baz,qux]",
expect: []string{"foo", "bar", "default=[baz,qux]"},
},
{
input: "foo,bar,options=[baz,qux]",
expect: []string{"foo", "bar", "options=[baz,qux]"},
},
{
input: `foo\,bar,options=[baz,qux]`,
expect: []string{`foo,bar`, "options=[baz,qux]"},
},
{
input: `foo,bar,options=\[baz,qux]`,
expect: []string{"foo", "bar", "options=[baz", "qux]"},
},
{
input: `foo,bar,options=[baz\,qux]`,
expect: []string{"foo", "bar", `options=[baz\,qux]`},
},
{
input: `foo\,bar,options=[baz,qux],default=baz`,
expect: []string{`foo,bar`, "options=[baz,qux]", "default=baz"},
},
{
input: `foo\,bar,options=[baz,qux, quux],default=[qux, baz]`,
expect: []string{`foo,bar`, "options=[baz,qux, quux]", "default=[qux, baz]"},
},
}
for _, test := range tests {
test := test
t.Run(test.input, func(t *testing.T) {
assert.ElementsMatch(t, test.expect, parseSegments(test.input))
})
}
}
func TestValidatePtrWithNonPtr(t *testing.T) {
var foo string
rve := reflect.ValueOf(foo)
assert.NotNil(t, ValidatePtr(rve))
}
func TestValidatePtrWithPtr(t *testing.T) {
var foo string
rve := reflect.ValueOf(&foo)
assert.Nil(t, ValidatePtr(rve))
}
func TestValidatePtrWithNilPtr(t *testing.T) {
var foo *string
rve := reflect.ValueOf(foo)
assert.NotNil(t, ValidatePtr(rve))
}
func TestValidatePtrWithZeroValue(t *testing.T) {
var s string
e := reflect.Zero(reflect.TypeOf(s))
assert.NotNil(t, ValidatePtr(e))
}
func TestSetValueNotSettable(t *testing.T) {
var i int
assert.Error(t, setValueFromString(reflect.Int, reflect.ValueOf(i), "1"))
assert.Error(t, validateAndSetValue(reflect.Int, reflect.ValueOf(i), "1", nil))
}
func TestParseKeyAndOptionsErrors(t *testing.T) {
type Bar struct {
OptionsValue string `key:",options=a=b"`
DefaultValue string `key:",default=a=b"`
}
var bar Bar
_, _, err := parseKeyAndOptions("key", reflect.TypeOf(&bar).Elem().Field(0))
assert.NotNil(t, err)
_, _, err = parseKeyAndOptions("key", reflect.TypeOf(&bar).Elem().Field(1))
assert.NotNil(t, err)
}
func TestSetValueFormatErrors(t *testing.T) {
type Bar struct {
IntValue int
UintValue uint
FloatValue float32
MapValue map[string]any
}
var bar Bar
tests := []struct {
kind reflect.Kind
target reflect.Value
value string
}{
{
kind: reflect.Int,
target: reflect.ValueOf(&bar.IntValue).Elem(),
value: "a",
},
{
kind: reflect.Uint,
target: reflect.ValueOf(&bar.UintValue).Elem(),
value: "a",
},
{
kind: reflect.Float32,
target: reflect.ValueOf(&bar.FloatValue).Elem(),
value: "a",
},
{
kind: reflect.Map,
target: reflect.ValueOf(&bar.MapValue).Elem(),
},
}
for _, test := range tests {
t.Run(test.kind.String(), func(t *testing.T) {
err := setValueFromString(test.kind, test.target, test.value)
assert.NotEqual(t, errValueNotSettable, err)
assert.NotNil(t, err)
})
}
}
func TestValidateValueRange(t *testing.T) {
t.Run("float", func(t *testing.T) {
assert.NoError(t, validateValueRange(1.2, nil))
})
t.Run("float number range", func(t *testing.T) {
assert.NoError(t, validateNumberRange(1.2, nil))
})
t.Run("bad float", func(t *testing.T) {
assert.Error(t, validateValueRange("a", &fieldOptionsWithContext{
Range: &numberRange{},
}))
})
t.Run("bad float validate", func(t *testing.T) {
var v struct {
Foo float32
}
assert.Error(t, validateAndSetValue(reflect.Int, reflect.ValueOf(&v).Elem().Field(0),
"1", &fieldOptionsWithContext{
Range: &numberRange{
left: 2,
right: 3,
},
}))
})
}
func TestSetMatchedPrimitiveValue(t *testing.T) {
assert.Error(t, setMatchedPrimitiveValue(reflect.Func, reflect.ValueOf(2), "1"))
}
func TestConvertTypeFromString_Bool(t *testing.T) {
tests := []struct {
name string
input string
want bool
wantErr bool
}{
// true cases
{name: "1", input: "1", want: true, wantErr: false},
{name: "true lowercase", input: "true", want: true, wantErr: false},
{name: "True mixed", input: "True", want: true, wantErr: false},
{name: "TRUE uppercase", input: "TRUE", want: true, wantErr: false},
{name: "TrUe mixed", input: "TrUe", want: true, wantErr: false},
// false cases
{name: "0", input: "0", want: false, wantErr: false},
{name: "false lowercase", input: "false", want: false, wantErr: false},
{name: "False mixed", input: "False", want: false, wantErr: false},
{name: "FALSE uppercase", input: "FALSE", want: false, wantErr: false},
{name: "FaLsE mixed", input: "FaLsE", want: false, wantErr: false},
// error cases
{name: "invalid yes", input: "yes", want: false, wantErr: true},
{name: "invalid no", input: "no", want: false, wantErr: true},
{name: "invalid empty", input: "", want: false, wantErr: true},
{name: "invalid 2", input: "2", want: false, wantErr: true},
{name: "invalid truee", input: "truee", want: false, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := convertTypeFromString(reflect.Bool, tt.input)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
}
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/unmarshaler_test.go | core/mapping/unmarshaler_test.go | package mapping
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
"time"
"unicode"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/jsonx"
"github.com/zeromicro/go-zero/core/stringx"
)
// because json.Number doesn't support strconv.ParseUint(...),
// so we only can test to 62 bits.
const maxUintBitsToTest = 62
func TestUnmarshalWithFullNameNotStruct(t *testing.T) {
var s map[string]any
content := []byte(`{"name":"xiaoming"}`)
err := UnmarshalJsonBytes(content, &s)
assert.Equal(t, errTypeMismatch, err)
}
func TestUnmarshalValueNotSettable(t *testing.T) {
var s map[string]any
content := []byte(`{"name":"xiaoming"}`)
err := UnmarshalJsonBytes(content, s)
assert.Equal(t, errValueNotSettable, err)
}
func TestUnmarshalWithoutTagName(t *testing.T) {
type inner struct {
Optional bool `key:",optional"`
OptionalP *bool `key:",optional"`
OptionalPP **bool `key:",optional"`
}
m := map[string]any{
"Optional": true,
"OptionalP": true,
"OptionalPP": true,
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.True(t, in.Optional)
assert.True(t, *in.OptionalP)
assert.True(t, **in.OptionalPP)
}
}
func TestUnmarshalWithLowerField(t *testing.T) {
type (
Lower struct {
value int `key:"lower"`
}
inner struct {
Lower
Optional bool `key:",optional"`
}
)
m := map[string]any{
"Optional": true,
"lower": 1,
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.True(t, in.Optional)
assert.Equal(t, 0, in.value)
}
}
func TestUnmarshalWithLowerAnonymousStruct(t *testing.T) {
type (
lower struct {
Value int `key:"lower"`
}
inner struct {
lower
Optional bool `key:",optional"`
}
)
m := map[string]any{
"Optional": true,
"lower": 1,
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.True(t, in.Optional)
assert.Equal(t, 1, in.Value)
}
}
func TestUnmarshalWithoutTagNameWithCanonicalKey(t *testing.T) {
type inner struct {
Name string `key:"name"`
}
m := map[string]any{
"Name": "go-zero",
}
var in inner
unmarshaler := NewUnmarshaler(defaultKeyName, WithCanonicalKeyFunc(func(s string) string {
first := true
return strings.Map(func(r rune) rune {
if first {
first = false
return unicode.ToTitle(r)
}
return r
}, s)
}))
if assert.NoError(t, unmarshaler.Unmarshal(m, &in)) {
assert.Equal(t, "go-zero", in.Name)
}
}
func TestUnmarshalWithoutTagNameWithCanonicalKeyOptionalDep(t *testing.T) {
type inner struct {
FirstName string `key:",optional"`
LastName string `key:",optional=FirstName"`
}
m := map[string]any{
"firstname": "go",
"lastname": "zero",
}
var in inner
unmarshaler := NewUnmarshaler(defaultKeyName, WithCanonicalKeyFunc(func(s string) string {
return strings.ToLower(s)
}))
if assert.NoError(t, unmarshaler.Unmarshal(m, &in)) {
assert.Equal(t, "go", in.FirstName)
assert.Equal(t, "zero", in.LastName)
}
}
func TestUnmarshalBool(t *testing.T) {
type inner struct {
True bool `key:"yes"`
False bool `key:"no"`
TrueFromOne bool `key:"yesone,string"`
FalseFromZero bool `key:"nozero,string"`
TrueFromTrue bool `key:"yestrue,string"`
FalseFromFalse bool `key:"nofalse,string"`
DefaultTrue bool `key:"defaulttrue,default=1"`
Optional bool `key:"optional,optional"`
}
m := map[string]any{
"yes": true,
"no": false,
"yesone": "1",
"nozero": "0",
"yestrue": "true",
"nofalse": "false",
}
var in inner
ast := assert.New(t)
if ast.NoError(UnmarshalKey(m, &in)) {
ast.True(in.True)
ast.False(in.False)
ast.True(in.TrueFromOne)
ast.False(in.FalseFromZero)
ast.True(in.TrueFromTrue)
ast.False(in.FalseFromFalse)
ast.True(in.DefaultTrue)
}
}
func TestUnmarshalDuration(t *testing.T) {
type inner struct {
Duration time.Duration `key:"duration"`
LessDuration time.Duration `key:"less"`
MoreDuration time.Duration `key:"more"`
PtrDuration *time.Duration `key:"ptr"`
PtrPtrDuration **time.Duration `key:"ptrptr"`
}
m := map[string]any{
"duration": "5s",
"less": "100ms",
"more": "24h",
"ptr": "1h",
"ptrptr": "2h",
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, time.Second*5, in.Duration)
assert.Equal(t, time.Millisecond*100, in.LessDuration)
assert.Equal(t, time.Hour*24, in.MoreDuration)
assert.Equal(t, time.Hour, *in.PtrDuration)
assert.Equal(t, time.Hour*2, **in.PtrPtrDuration)
}
}
func TestUnmarshalDurationUnexpectedError(t *testing.T) {
type inner struct {
Duration time.Duration `key:"duration"`
}
content := "{\"duration\": 1}"
var m = map[string]any{}
err := jsonx.Unmarshal([]byte(content), &m)
assert.NoError(t, err)
var in inner
err = UnmarshalKey(m, &in)
assert.Error(t, err)
assert.Contains(t, err.Error(), "expect string")
}
func TestUnmarshalDurationDefault(t *testing.T) {
type inner struct {
Int int `key:"int"`
Duration time.Duration `key:"duration,default=5s"`
}
m := map[string]any{
"int": 5,
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, 5, in.Int)
assert.Equal(t, time.Second*5, in.Duration)
}
}
func TestUnmarshalDurationPtr(t *testing.T) {
type inner struct {
Duration *time.Duration `key:"duration"`
}
m := map[string]any{
"duration": "5s",
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, time.Second*5, *in.Duration)
}
}
func TestUnmarshalDurationPtrDefault(t *testing.T) {
type inner struct {
Int int `key:"int"`
Value *int `key:",default=5"`
Duration *time.Duration `key:"duration,default=5s"`
}
m := map[string]any{
"int": 5,
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, 5, in.Int)
assert.Equal(t, 5, *in.Value)
assert.Equal(t, time.Second*5, *in.Duration)
}
}
func TestUnmarshalInt(t *testing.T) {
type inner struct {
Int int `key:"int"`
IntFromStr int `key:"intstr,string"`
Int8 int8 `key:"int8"`
Int8FromStr int8 `key:"int8str,string"`
Int16 int16 `key:"int16"`
Int16FromStr int16 `key:"int16str,string"`
Int32 int32 `key:"int32"`
Int32FromStr int32 `key:"int32str,string"`
Int64 int64 `key:"int64"`
Int64FromStr int64 `key:"int64str,string"`
DefaultInt int64 `key:"defaultint,default=11"`
Optional int `key:"optional,optional"`
IntOptDef int `key:"intopt,optional,default=6"`
}
m := map[string]any{
"int": 1,
"intstr": "2",
"int8": int8(3),
"int8str": "4",
"int16": int16(5),
"int16str": "6",
"int32": int32(7),
"int32str": "8",
"int64": int64(9),
"int64str": "10",
}
var in inner
ast := assert.New(t)
if ast.NoError(UnmarshalKey(m, &in)) {
ast.Equal(1, in.Int)
ast.Equal(2, in.IntFromStr)
ast.Equal(int8(3), in.Int8)
ast.Equal(int8(4), in.Int8FromStr)
ast.Equal(int16(5), in.Int16)
ast.Equal(int16(6), in.Int16FromStr)
ast.Equal(int32(7), in.Int32)
ast.Equal(int32(8), in.Int32FromStr)
ast.Equal(int64(9), in.Int64)
ast.Equal(int64(10), in.Int64FromStr)
ast.Equal(int64(11), in.DefaultInt)
ast.Equal(6, in.IntOptDef)
}
}
func TestUnmarshalIntPtr(t *testing.T) {
type inner struct {
Int *int `key:"int"`
}
m := map[string]any{
"int": 1,
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.NotNil(t, in.Int)
assert.Equal(t, 1, *in.Int)
}
}
func TestUnmarshalIntSliceOfPtr(t *testing.T) {
t.Run("int slice", func(t *testing.T) {
type inner struct {
Ints []*int `key:"ints"`
Intps []**int `key:"intps"`
}
m := map[string]any{
"ints": []int{1, 2, 3},
"intps": []int{1, 2, 3, 4},
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.NotEmpty(t, in.Ints)
var ints []int
for _, i := range in.Ints {
ints = append(ints, *i)
}
assert.EqualValues(t, []int{1, 2, 3}, ints)
var intps []int
for _, i := range in.Intps {
intps = append(intps, **i)
}
assert.EqualValues(t, []int{1, 2, 3, 4}, intps)
}
})
t.Run("int slice with error", func(t *testing.T) {
type inner struct {
Ints []*int `key:"ints"`
Intps []**int `key:"intps"`
}
m := map[string]any{
"ints": []any{1, 2, "a"},
"intps": []int{1, 2, 3, 4},
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int slice with nil element", func(t *testing.T) {
type inner struct {
Ints []int `key:"ints"`
}
m := map[string]any{
"ints": []any{nil},
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Empty(t, in.Ints)
}
})
t.Run("int slice with nil", func(t *testing.T) {
type inner struct {
Ints []int `key:"ints"`
}
m := map[string]any{
"ints": []any(nil),
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Empty(t, in.Ints)
}
})
}
func TestUnmarshalIntWithDefault(t *testing.T) {
type inner struct {
Int int `key:"int,default=5"`
Intp *int `key:"intp,default=5"`
Intpp **int `key:"intpp,default=5"`
}
m := map[string]any{
"int": 1,
"intp": 2,
"intpp": 3,
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, 1, in.Int)
assert.Equal(t, 2, *in.Intp)
assert.Equal(t, 3, **in.Intpp)
}
}
func TestUnmarshalIntWithString(t *testing.T) {
t.Run("int without options", func(t *testing.T) {
type inner struct {
Int int64 `key:"int,string"`
Intp *int64 `key:"intp,string"`
Intpp **int64 `key:"intpp,string"`
}
m := map[string]any{
"int": json.Number("1"),
"intp": json.Number("2"),
"intpp": json.Number("3"),
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, int64(1), in.Int)
assert.Equal(t, int64(2), *in.Intp)
assert.Equal(t, int64(3), **in.Intpp)
}
})
t.Run("int wrong range", func(t *testing.T) {
type inner struct {
Int int64 `key:"int,string,range=[2:3]"`
Intp *int64 `key:"intp,range=[2:3]"`
Intpp **int64 `key:"intpp,range=[2:3]"`
}
m := map[string]any{
"int": json.Number("1"),
"intp": json.Number("2"),
"intpp": json.Number("3"),
}
var in inner
assert.ErrorIs(t, UnmarshalKey(m, &in), errNumberRange)
})
t.Run("int with wrong type", func(t *testing.T) {
type (
myString string
inner struct {
Int int64 `key:"int,string"`
Intp *int64 `key:"intp,string"`
Intpp **int64 `key:"intpp,string"`
}
)
m := map[string]any{
"int": myString("1"),
"intp": myString("2"),
"intpp": myString("3"),
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int with ptr", func(t *testing.T) {
type inner struct {
Int *int64 `key:"int"`
}
m := map[string]any{
"int": json.Number("1"),
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, int64(1), *in.Int)
}
})
t.Run("int with invalid value", func(t *testing.T) {
type inner struct {
Int int64 `key:"int"`
}
m := map[string]any{
"int": json.Number("a"),
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint with invalid value", func(t *testing.T) {
type inner struct {
Int uint64 `key:"int"`
}
m := map[string]any{
"int": json.Number("a"),
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float with invalid value", func(t *testing.T) {
type inner struct {
Value float64 `key:"float"`
}
m := map[string]any{
"float": json.Number("a"),
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float with invalid value", func(t *testing.T) {
type inner struct {
Value string `key:"value"`
}
m := map[string]any{
"value": json.Number("a"),
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int with ptr of ptr", func(t *testing.T) {
type inner struct {
Int **int64 `key:"int"`
}
m := map[string]any{
"int": json.Number("1"),
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, int64(1), **in.Int)
}
})
t.Run("int with options", func(t *testing.T) {
type inner struct {
Int int64 `key:"int,string,options=[0,1]"`
}
m := map[string]any{
"int": json.Number("1"),
}
var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.Equal(t, int64(1), in.Int)
}
})
t.Run("int with options", func(t *testing.T) {
type inner struct {
Int int64 `key:"int,string,options=[0,1]"`
}
m := map[string]any{
"int": nil,
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int with options", func(t *testing.T) {
type (
StrType string
inner struct {
Int int64 `key:"int,string,options=[0,1]"`
}
)
m := map[string]any{
"int": StrType("1"),
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("invalid options", func(t *testing.T) {
type Value struct {
Name string `key:"name,options="`
}
var v Value
assert.Error(t, UnmarshalKey(emptyMap, &v))
})
}
func TestUnmarshalInt8WithOverflow(t *testing.T) {
t.Run("int8 from string", func(t *testing.T) {
type inner struct {
Value int8 `key:"int,string"`
}
m := map[string]any{
"int": "8589934592", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int8 from json.Number", func(t *testing.T) {
type inner struct {
Value int8 `key:"int"`
}
m := map[string]any{
"int": json.Number("8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int8 from json.Number", func(t *testing.T) {
type inner struct {
Value int8 `key:"int"`
}
m := map[string]any{
"int": json.Number("-8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int8 from int64", func(t *testing.T) {
type inner struct {
Value int8 `key:"int"`
}
m := map[string]any{
"int": int64(1) << 36, // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalInt16WithOverflow(t *testing.T) {
t.Run("int16 from string", func(t *testing.T) {
type inner struct {
Value int16 `key:"int,string"`
}
m := map[string]any{
"int": "8589934592", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int16 from json.Number", func(t *testing.T) {
type inner struct {
Value int16 `key:"int"`
}
m := map[string]any{
"int": json.Number("8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int16 from json.Number", func(t *testing.T) {
type inner struct {
Value int16 `key:"int"`
}
m := map[string]any{
"int": json.Number("-8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int16 from int64", func(t *testing.T) {
type inner struct {
Value int16 `key:"int"`
}
m := map[string]any{
"int": int64(1) << 36, // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalInt32WithOverflow(t *testing.T) {
t.Run("int32 from string", func(t *testing.T) {
type inner struct {
Value int32 `key:"int,string"`
}
m := map[string]any{
"int": "8589934592", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int32 from json.Number", func(t *testing.T) {
type inner struct {
Value int32 `key:"int"`
}
m := map[string]any{
"int": json.Number("8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int32 from json.Number", func(t *testing.T) {
type inner struct {
Value int32 `key:"int"`
}
m := map[string]any{
"int": json.Number("-8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int32 from int64", func(t *testing.T) {
type inner struct {
Value int32 `key:"int"`
}
m := map[string]any{
"int": int64(1) << 36, // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalInt64WithOverflow(t *testing.T) {
t.Run("int64 from string", func(t *testing.T) {
type inner struct {
Value int64 `key:"int,string"`
}
m := map[string]any{
"int": "18446744073709551616", // overflow, 1 << 64
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("int64 from json.Number", func(t *testing.T) {
type inner struct {
Value int64 `key:"int,string"`
}
m := map[string]any{
"int": json.Number("18446744073709551616"), // overflow, 1 << 64
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalUint8WithOverflow(t *testing.T) {
t.Run("uint8 from string", func(t *testing.T) {
type inner struct {
Value uint8 `key:"int,string"`
}
m := map[string]any{
"int": "8589934592", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint8 from json.Number", func(t *testing.T) {
type inner struct {
Value uint8 `key:"int"`
}
m := map[string]any{
"int": json.Number("8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint8 from json.Number with negative", func(t *testing.T) {
type inner struct {
Value uint8 `key:"int"`
}
m := map[string]any{
"int": json.Number("-1"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint8 from int64", func(t *testing.T) {
type inner struct {
Value uint8 `key:"int"`
}
m := map[string]any{
"int": int64(1) << 36, // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalUint16WithOverflow(t *testing.T) {
t.Run("uint16 from string", func(t *testing.T) {
type inner struct {
Value uint16 `key:"int,string"`
}
m := map[string]any{
"int": "8589934592", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint16 from json.Number", func(t *testing.T) {
type inner struct {
Value uint16 `key:"int"`
}
m := map[string]any{
"int": json.Number("8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint16 from json.Number with negative", func(t *testing.T) {
type inner struct {
Value uint16 `key:"int"`
}
m := map[string]any{
"int": json.Number("-1"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint16 from int64", func(t *testing.T) {
type inner struct {
Value uint16 `key:"int"`
}
m := map[string]any{
"int": int64(1) << 36, // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalUint32WithOverflow(t *testing.T) {
t.Run("uint32 from string", func(t *testing.T) {
type inner struct {
Value uint32 `key:"int,string"`
}
m := map[string]any{
"int": "8589934592", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint32 from json.Number", func(t *testing.T) {
type inner struct {
Value uint32 `key:"int"`
}
m := map[string]any{
"int": json.Number("8589934592"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint32 from json.Number with negative", func(t *testing.T) {
type inner struct {
Value uint32 `key:"int"`
}
m := map[string]any{
"int": json.Number("-1"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint32 from int64", func(t *testing.T) {
type inner struct {
Value uint32 `key:"int"`
}
m := map[string]any{
"int": int64(1) << 36, // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalUint64WithOverflow(t *testing.T) {
t.Run("uint64 from string", func(t *testing.T) {
type inner struct {
Value uint64 `key:"int,string"`
}
m := map[string]any{
"int": "18446744073709551616", // overflow, 1 << 64
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("uint64 from json.Number", func(t *testing.T) {
type inner struct {
Value uint64 `key:"int,string"`
}
m := map[string]any{
"int": json.Number("18446744073709551616"), // overflow, 1 << 64
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalFloat32WithOverflow(t *testing.T) {
t.Run("float32 from string greater than float64", func(t *testing.T) {
type inner struct {
Value float32 `key:"float,string"`
}
m := map[string]any{
"float": "1.79769313486231570814527423731704356798070e+309", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float32 from string greater than float32", func(t *testing.T) {
type inner struct {
Value float32 `key:"float,string"`
}
m := map[string]any{
"float": "1.79769313486231570814527423731704356798070e+300", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float32 from string less than float32", func(t *testing.T) {
type inner struct {
Value float32 `key:"float, string"`
}
m := map[string]any{
"float": "-1.79769313486231570814527423731704356798070e+300", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float32 from json.Number greater than float64", func(t *testing.T) {
type inner struct {
Value float32 `key:"float"`
}
m := map[string]any{
"float": json.Number("1.79769313486231570814527423731704356798070e+309"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float32 from json.Number greater than float32", func(t *testing.T) {
type inner struct {
Value float32 `key:"float"`
}
m := map[string]any{
"float": json.Number("1.79769313486231570814527423731704356798070e+300"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float32 from json number less than float32", func(t *testing.T) {
type inner struct {
Value float32 `key:"float"`
}
m := map[string]any{
"float": json.Number("-1.79769313486231570814527423731704356798070e+300"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalFloat64WithOverflow(t *testing.T) {
t.Run("float64 from string greater than float64", func(t *testing.T) {
type inner struct {
Value float64 `key:"float,string"`
}
m := map[string]any{
"float": "1.79769313486231570814527423731704356798070e+309", // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
t.Run("float32 from json.Number greater than float64", func(t *testing.T) {
type inner struct {
Value float64 `key:"float"`
}
m := map[string]any{
"float": json.Number("1.79769313486231570814527423731704356798070e+309"), // overflow
}
var in inner
assert.Error(t, UnmarshalKey(m, &in))
})
}
func TestUnmarshalBoolSliceRequired(t *testing.T) {
type inner struct {
Bools []bool `key:"bools"`
}
var in inner
assert.NotNil(t, UnmarshalKey(map[string]any{}, &in))
}
func TestUnmarshalBoolSliceNil(t *testing.T) {
type inner struct {
Bools []bool `key:"bools,optional"`
}
var in inner
if assert.NoError(t, UnmarshalKey(map[string]any{}, &in)) {
assert.Nil(t, in.Bools)
}
}
func TestUnmarshalBoolSliceNilExplicit(t *testing.T) {
type inner struct {
Bools []bool `key:"bools,optional"`
}
var in inner
if assert.NoError(t, UnmarshalKey(map[string]any{
"bools": nil,
}, &in)) {
assert.Nil(t, in.Bools)
}
}
func TestUnmarshalBoolSliceEmpty(t *testing.T) {
type inner struct {
Bools []bool `key:"bools,optional"`
}
var in inner
if assert.NoError(t, UnmarshalKey(map[string]any{
"bools": []bool{},
}, &in)) {
assert.Empty(t, in.Bools)
}
}
func TestUnmarshalBoolSliceWithDefault(t *testing.T) {
t.Run("slice with default", func(t *testing.T) {
type inner struct {
Bools []bool `key:"bools,default=[true,false]"`
}
var in inner
if assert.NoError(t, UnmarshalKey(nil, &in)) {
assert.ElementsMatch(t, []bool{true, false}, in.Bools)
}
})
t.Run("slice with default error", func(t *testing.T) {
type inner struct {
Bools []bool `key:"bools,default=[true,fal]"`
}
var in inner
assert.Error(t, UnmarshalKey(nil, &in))
})
}
func TestUnmarshalIntSliceWithDefault(t *testing.T) {
type inner struct {
Ints []int `key:"ints,default=[1,2,3]"`
}
var in inner
if assert.NoError(t, UnmarshalKey(nil, &in)) {
assert.ElementsMatch(t, []int{1, 2, 3}, in.Ints)
}
}
func TestUnmarshalIntSliceWithDefaultHasSpaces(t *testing.T) {
type inner struct {
Ints []int `key:"ints,default=[1, 2, 3]"`
Intps []*int `key:"intps,default=[1, 2, 3, 4]"`
Intpps []**int `key:"intpps,default=[1, 2, 3, 4, 5]"`
}
var in inner
if assert.NoError(t, UnmarshalKey(nil, &in)) {
assert.ElementsMatch(t, []int{1, 2, 3}, in.Ints)
var intps []int
for _, i := range in.Intps {
intps = append(intps, *i)
}
assert.ElementsMatch(t, []int{1, 2, 3, 4}, intps)
var intpps []int
for _, i := range in.Intpps {
intpps = append(intpps, **i)
}
assert.ElementsMatch(t, []int{1, 2, 3, 4, 5}, intpps)
}
}
func TestUnmarshalFloatSliceWithDefault(t *testing.T) {
type inner struct {
Floats []float32 `key:"floats,default=[1.1,2.2,3.3]"`
}
var in inner
if assert.NoError(t, UnmarshalKey(nil, &in)) {
assert.ElementsMatch(t, []float32{1.1, 2.2, 3.3}, in.Floats)
}
}
func TestUnmarshalStringSliceWithDefault(t *testing.T) {
t.Run("slice with default", func(t *testing.T) {
type inner struct {
Strs []string `key:"strs,default=[foo,bar,woo]"`
Strps []*string `key:"strs,default=[foo,bar,woo]"`
Strpps []**string `key:"strs,default=[foo,bar,woo]"`
}
var in inner
if assert.NoError(t, UnmarshalKey(nil, &in)) {
assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, in.Strs)
var ss []string
for _, s := range in.Strps {
ss = append(ss, *s)
}
assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, ss)
var sss []string
for _, s := range in.Strpps {
sss = append(sss, **s)
}
assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, sss)
}
})
t.Run("slice with default on errors", func(t *testing.T) {
type (
holder struct {
Chan []chan int
}
inner struct {
Strs []holder `key:"strs,default=[foo,bar,woo]"`
}
)
var in inner
assert.Error(t, UnmarshalKey(nil, &in))
})
t.Run("slice with default on errors", func(t *testing.T) {
type inner struct {
Strs []complex64 `key:"strs,default=[foo,bar,woo]"`
}
var in inner
assert.Error(t, UnmarshalKey(nil, &in))
})
}
func TestUnmarshalStringSliceWithDefaultHasSpaces(t *testing.T) {
type inner struct {
Strs []string `key:"strs,default=[foo, bar, woo]"`
}
var in inner
if assert.NoError(t, UnmarshalKey(nil, &in)) {
assert.ElementsMatch(t, []string{"foo", "bar", "woo"}, in.Strs)
}
}
func TestUnmarshalUint(t *testing.T) {
type inner struct {
Uint uint `key:"uint"`
UintFromStr uint `key:"uintstr,string"`
Uint8 uint8 `key:"uint8"`
Uint8FromStr uint8 `key:"uint8str,string"`
Uint16 uint16 `key:"uint16"`
Uint16FromStr uint16 `key:"uint16str,string"`
Uint32 uint32 `key:"uint32"`
Uint32FromStr uint32 `key:"uint32str,string"`
Uint64 uint64 `key:"uint64"`
Uint64FromStr uint64 `key:"uint64str,string"`
DefaultUint uint `key:"defaultuint,default=11"`
Optional uint `key:"optional,optional"`
}
m := map[string]any{
"uint": uint(1),
"uintstr": "2",
"uint8": uint8(3),
"uint8str": "4",
"uint16": uint16(5),
"uint16str": "6",
"uint32": uint32(7),
"uint32str": "8",
"uint64": uint64(9),
"uint64str": "10",
}
var in inner
ast := assert.New(t)
if ast.NoError(UnmarshalKey(m, &in)) {
ast.Equal(uint(1), in.Uint)
ast.Equal(uint(2), in.UintFromStr)
ast.Equal(uint8(3), in.Uint8)
ast.Equal(uint8(4), in.Uint8FromStr)
ast.Equal(uint16(5), in.Uint16)
ast.Equal(uint16(6), in.Uint16FromStr)
ast.Equal(uint32(7), in.Uint32)
ast.Equal(uint32(8), in.Uint32FromStr)
ast.Equal(uint64(9), in.Uint64)
ast.Equal(uint64(10), in.Uint64FromStr)
ast.Equal(uint(11), in.DefaultUint)
}
}
func TestUnmarshalFloat(t *testing.T) {
type inner struct {
Float32 float32 `key:"float32"`
Float32Str float32 `key:"float32str,string"`
Float32Num float32 `key:"float32num"`
Float64 float64 `key:"float64"`
Float64Str float64 `key:"float64str,string"`
Float64Num float64 `key:"float64num"`
DefaultFloat float32 `key:"defaultfloat,default=5.5"`
Optional float32 `key:",optional"`
}
m := map[string]any{
"float32": float32(1.5),
"float32str": "2.5",
"float32num": json.Number("2.6"),
"float64": 3.5,
"float64str": "4.5",
"float64num": json.Number("4.6"),
}
var in inner
ast := assert.New(t)
if ast.NoError(UnmarshalKey(m, &in)) {
ast.Equal(float32(1.5), in.Float32)
ast.Equal(float32(2.5), in.Float32Str)
ast.Equal(float32(2.6), in.Float32Num)
ast.Equal(3.5, in.Float64)
ast.Equal(4.5, in.Float64Str)
ast.Equal(4.6, in.Float64Num)
ast.Equal(float32(5.5), in.DefaultFloat)
}
}
func TestUnmarshalInt64Slice(t *testing.T) {
var v struct {
Ages []int64 `key:"ages"`
Slice []int64 `key:"slice"`
}
m := map[string]any{
"ages": []int64{1, 2},
"slice": []any{},
}
ast := assert.New(t)
if ast.NoError(UnmarshalKey(m, &v)) {
ast.ElementsMatch([]int64{1, 2}, v.Ages)
ast.Equal([]int64{}, v.Slice)
}
}
func TestUnmarshalNullableSlice(t *testing.T) {
var v struct {
Ages []int64 `key:"ages"`
Slice []int8 `key:"slice"`
}
m := map[string]any{
"ages": []int64{1, 2},
"slice": `[null,2]`,
}
assert.New(t).Equal(UnmarshalKey(m, &v), errNilSliceElement)
}
func TestUnmarshalWithFloatPtr(t *testing.T) {
t.Run("*float32", func(t *testing.T) {
var v struct {
WeightFloat32 *float32 `key:"weightFloat32,optional"`
}
m := map[string]any{
"weightFloat32": json.Number("3.2"),
}
if assert.NoError(t, UnmarshalKey(m, &v)) {
assert.Equal(t, float32(3.2), *v.WeightFloat32)
}
})
t.Run("**float32", func(t *testing.T) {
var v struct {
WeightFloat32 **float32 `key:"weightFloat32,optional"`
}
m := map[string]any{
"weightFloat32": json.Number("3.2"),
}
if assert.NoError(t, UnmarshalKey(m, &v)) {
assert.Equal(t, float32(3.2), **v.WeightFloat32)
}
})
}
func TestUnmarshalIntSlice(t *testing.T) {
t.Run("int slice from int", func(t *testing.T) {
var v struct {
Ages []int `key:"ages"`
Slice []int `key:"slice"`
}
m := map[string]any{
"ages": []int{1, 2},
"slice": []any{},
}
ast := assert.New(t)
if ast.NoError(UnmarshalKey(m, &v)) {
ast.ElementsMatch([]int{1, 2}, v.Ages)
ast.Equal([]int{}, v.Slice)
}
})
t.Run("int slice from one int", func(t *testing.T) {
var v struct {
Ages []int `key:"ages"`
}
m := map[string]any{
"ages": []int{2},
}
ast := assert.New(t)
unmarshaler := NewUnmarshaler(defaultKeyName, WithFromArray())
if ast.NoError(unmarshaler.Unmarshal(m, &v)) {
ast.ElementsMatch([]int{2}, v.Ages)
}
})
t.Run("int slice from one int string", func(t *testing.T) {
var v struct {
Ages []int `key:"ages"`
}
m := map[string]any{
"ages": []string{"2"},
}
ast := assert.New(t)
unmarshaler := NewUnmarshaler(defaultKeyName, WithFromArray())
if ast.NoError(unmarshaler.Unmarshal(m, &v)) {
ast.ElementsMatch([]int{2}, v.Ages)
}
})
t.Run("int slice from one json.Number", func(t *testing.T) {
var v struct {
Ages []int `key:"ages"`
}
m := map[string]any{
"ages": []json.Number{"2"},
}
ast := assert.New(t)
unmarshaler := NewUnmarshaler(defaultKeyName, WithFromArray())
if ast.NoError(unmarshaler.Unmarshal(m, &v)) {
ast.ElementsMatch([]int{2}, v.Ages)
}
})
t.Run("int slice from one int strings", func(t *testing.T) {
var v struct {
Ages []int `key:"ages"`
}
m := map[string]any{
"ages": []string{"1,2"},
}
ast := assert.New(t)
unmarshaler := NewUnmarshaler(defaultKeyName, WithFromArray())
ast.Error(unmarshaler.Unmarshal(m, &v))
})
}
func TestUnmarshalString(t *testing.T) {
type inner struct {
Name string `key:"name"`
NameStr string `key:"namestr,string"`
NotPresent string `key:",optional"`
NotPresentWithTag string `key:"notpresent,optional"`
DefaultString string `key:"defaultstring,default=hello"`
Optional string `key:",optional"`
}
m := map[string]any{
"name": "kevin",
"namestr": "namewithstring",
}
var in inner
ast := assert.New(t)
if ast.NoError(UnmarshalKey(m, &in)) {
ast.Equal("kevin", in.Name)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | true |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/jsonunmarshaler_test.go | core/mapping/jsonunmarshaler_test.go | package mapping
import (
"bytes"
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUnmarshalBytes(t *testing.T) {
var c struct {
Name string
}
content := []byte(`{"Name": "liao"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Name)
}
func TestUnmarshalBytesOptional(t *testing.T) {
var c struct {
Name string
Age int `json:",optional"`
}
content := []byte(`{"Name": "liao"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Name)
}
func TestUnmarshalBytesOptionalDefault(t *testing.T) {
var c struct {
Name string
Age int `json:",optional,default=1"`
}
content := []byte(`{"Name": "liao"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Name)
assert.Equal(t, 1, c.Age)
}
func TestUnmarshalBytesDefaultOptional(t *testing.T) {
var c struct {
Name string
Age int `json:",default=1,optional"`
}
content := []byte(`{"Name": "liao"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Name)
assert.Equal(t, 1, c.Age)
}
func TestUnmarshalBytesDefault(t *testing.T) {
var c struct {
Name string `json:",default=liao"`
}
content := []byte(`{}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Name)
}
func TestUnmarshalBytesBool(t *testing.T) {
var c struct {
Great bool
}
content := []byte(`{"Great": true}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.True(t, c.Great)
}
func TestUnmarshalBytesInt(t *testing.T) {
var c struct {
Age int
}
content := []byte(`{"Age": 1}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, c.Age)
}
func TestUnmarshalBytesUint(t *testing.T) {
var c struct {
Age uint
}
content := []byte(`{"Age": 1}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, uint(1), c.Age)
}
func TestUnmarshalBytesFloat(t *testing.T) {
var c struct {
Age float32
}
content := []byte(`{"Age": 1.5}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, float32(1.5), c.Age)
}
func TestUnmarshalBytesMustInOptional(t *testing.T) {
var c struct {
Inner struct {
There string
Must string
Optional string `json:",optional"`
} `json:",optional"`
}
content := []byte(`{}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesMustInOptionalMissedPart(t *testing.T) {
var c struct {
Inner struct {
There string
Must string
Optional string `json:",optional"`
} `json:",optional"`
}
content := []byte(`{"Inner": {"There": "sure"}}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesMustInOptionalOnlyOptionalFilled(t *testing.T) {
var c struct {
Inner struct {
There string
Must string
Optional string `json:",optional"`
} `json:",optional"`
}
content := []byte(`{"Inner": {"Optional": "sure"}}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesNil(t *testing.T) {
var c struct {
Int int64 `json:"int,optional"`
}
content := []byte(`{"int":null}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, int64(0), c.Int)
}
func TestUnmarshalBytesNilSlice(t *testing.T) {
var c struct {
Ints []int64 `json:"ints"`
}
content := []byte(`{"ints":[null]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 0, len(c.Ints))
}
func TestUnmarshalBytesPartial(t *testing.T) {
var c struct {
Name string
Age float32
}
content := []byte(`{"Age": 1.5}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesStruct(t *testing.T) {
var c struct {
Inner struct {
Name string
}
}
content := []byte(`{"Inner": {"Name": "liao"}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
}
func TestUnmarshalBytesStructOptional(t *testing.T) {
var c struct {
Inner struct {
Name string
Age int `json:",optional"`
}
}
content := []byte(`{"Inner": {"Name": "liao"}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
}
func TestUnmarshalBytesStructPtr(t *testing.T) {
var c struct {
Inner *struct {
Name string
}
}
content := []byte(`{"Inner": {"Name": "liao"}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
}
func TestUnmarshalBytesStructPtrOptional(t *testing.T) {
var c struct {
Inner *struct {
Name string
Age int `json:",optional"`
}
}
content := []byte(`{"Inner": {"Name": "liao"}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesStructPtrDefault(t *testing.T) {
var c struct {
Inner *struct {
Name string
Age int `json:",default=4"`
}
}
content := []byte(`{"Inner": {"Name": "liao"}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Inner.Name)
assert.Equal(t, 4, c.Inner.Age)
}
func TestUnmarshalBytesSliceString(t *testing.T) {
var c struct {
Names []string
}
content := []byte(`{"Names": ["liao", "chaoxin"]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
want := []string{"liao", "chaoxin"}
if !reflect.DeepEqual(c.Names, want) {
t.Fatalf("want %q, got %q", c.Names, want)
}
}
func TestUnmarshalBytesSliceStringOptional(t *testing.T) {
var c struct {
Names []string
Age []int `json:",optional"`
}
content := []byte(`{"Names": ["liao", "chaoxin"]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
want := []string{"liao", "chaoxin"}
if !reflect.DeepEqual(c.Names, want) {
t.Fatalf("want %q, got %q", c.Names, want)
}
}
func TestUnmarshalBytesSliceStruct(t *testing.T) {
var c struct {
People []struct {
Name string
Age int
}
}
content := []byte(`{"People": [{"Name": "liao", "Age": 1}, {"Name": "chaoxin", "Age": 2}]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
want := []struct {
Name string
Age int
}{
{"liao", 1},
{"chaoxin", 2},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %q, got %q", c.People, want)
}
}
func TestUnmarshalBytesSliceStructOptional(t *testing.T) {
var c struct {
People []struct {
Name string
Age int
Emails []string `json:",optional"`
}
}
content := []byte(`{"People": [{"Name": "liao", "Age": 1}, {"Name": "chaoxin", "Age": 2}]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
want := []struct {
Name string
Age int
Emails []string `json:",optional"`
}{
{"liao", 1, nil},
{"chaoxin", 2, nil},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %q, got %q", c.People, want)
}
}
func TestUnmarshalBytesSliceStructPtr(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
}
}
content := []byte(`{"People": [{"Name": "liao", "Age": 1}, {"Name": "chaoxin", "Age": 2}]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
want := []*struct {
Name string
Age int
}{
{"liao", 1},
{"chaoxin", 2},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %v, got %v", c.People, want)
}
}
func TestUnmarshalBytesSliceStructPtrOptional(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
Emails []string `json:",optional"`
}
}
content := []byte(`{"People": [{"Name": "liao", "Age": 1}, {"Name": "chaoxin", "Age": 2}]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
want := []*struct {
Name string
Age int
Emails []string `json:",optional"`
}{
{"liao", 1, nil},
{"chaoxin", 2, nil},
}
if !reflect.DeepEqual(c.People, want) {
t.Fatalf("want %v, got %v", c.People, want)
}
}
func TestUnmarshalBytesSliceStructPtrPartial(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
Email string
}
}
content := []byte(`{"People": [{"Name": "liao", "Age": 1}, {"Name": "chaoxin", "Age": 2}]}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesSliceStructPtrDefault(t *testing.T) {
var c struct {
People []*struct {
Name string
Age int
Email string `json:",default=chaoxin@liao.com"`
}
}
content := []byte(`{"People": [{"Name": "liao", "Age": 1}, {"Name": "chaoxin", "Age": 2}]}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
want := []*struct {
Name string
Age int
Email string
}{
{"liao", 1, "chaoxin@liao.com"},
{"chaoxin", 2, "chaoxin@liao.com"},
}
for i := range c.People {
actual := c.People[i]
expect := want[i]
assert.Equal(t, expect.Age, actual.Age)
assert.Equal(t, expect.Email, actual.Email)
assert.Equal(t, expect.Name, actual.Name)
}
}
func TestUnmarshalBytesSliceStringPartial(t *testing.T) {
var c struct {
Names []string
Age int
}
content := []byte(`{"Age": 1}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesSliceStructPartial(t *testing.T) {
var c struct {
Group string
People []struct {
Name string
Age int
}
}
content := []byte(`{"Group": "chaoxin"}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesInnerAnonymousPartial(t *testing.T) {
type (
Deep struct {
A string
B string `json:",optional"`
}
Inner struct {
Deep
InnerV string `json:",optional"`
}
)
var c struct {
Value Inner `json:",optional"`
}
content := []byte(`{"Value": {"InnerV": "chaoxin"}}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesStructPartial(t *testing.T) {
var c struct {
Group string
Person struct {
Name string
Age int
}
}
content := []byte(`{"Group": "chaoxin"}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesEmptyMap(t *testing.T) {
var c struct {
Persons map[string]int `json:",optional"`
}
content := []byte(`{"Persons": {}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Empty(t, c.Persons)
}
func TestUnmarshalBytesMap(t *testing.T) {
var c struct {
Persons map[string]int
}
content := []byte(`{"Persons": {"first": 1, "second": 2}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 2, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"])
assert.Equal(t, 2, c.Persons["second"])
}
func TestUnmarshalBytesMapStruct(t *testing.T) {
var c struct {
Persons map[string]struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": {"ID": 1, "name": "kevin"}}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"].ID)
assert.Equal(t, "kevin", c.Persons["first"].Name)
}
func TestUnmarshalBytesMapStructPtr(t *testing.T) {
var c struct {
Persons map[string]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": {"ID": 1, "name": "kevin"}}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"].ID)
assert.Equal(t, "kevin", c.Persons["first"].Name)
}
func TestUnmarshalBytesMapStructMissingPartial(t *testing.T) {
var c struct {
Persons map[string]*struct {
ID int
Name string
}
}
content := []byte(`{"Persons": {"first": {"ID": 1}}}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesMapStructOptional(t *testing.T) {
var c struct {
Persons map[string]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": {"ID": 1}}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"].ID)
}
func TestUnmarshalBytesMapEmptyStructSlice(t *testing.T) {
var c struct {
Persons map[string][]struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": []}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Empty(t, c.Persons["first"])
}
func TestUnmarshalBytesMapStructSlice(t *testing.T) {
var c struct {
Persons map[string][]struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": [{"ID": 1, "name": "kevin"}]}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"][0].ID)
assert.Equal(t, "kevin", c.Persons["first"][0].Name)
}
func TestUnmarshalBytesMapEmptyStructPtrSlice(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": []}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Empty(t, c.Persons["first"])
}
func TestUnmarshalBytesMapStructPtrSlice(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": [{"ID": 1, "name": "kevin"}]}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"][0].ID)
assert.Equal(t, "kevin", c.Persons["first"][0].Name)
}
func TestUnmarshalBytesMapStructPtrSliceMissingPartial(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string
}
}
content := []byte(`{"Persons": {"first": [{"ID": 1}]}}`)
assert.NotNil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalBytesMapStructPtrSliceOptional(t *testing.T) {
var c struct {
Persons map[string][]*struct {
ID int
Name string `json:"name,optional"`
}
}
content := []byte(`{"Persons": {"first": [{"ID": 1}]}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, 1, len(c.Persons))
assert.Equal(t, 1, c.Persons["first"][0].ID)
}
func TestUnmarshalStructOptional(t *testing.T) {
var c struct {
Name string
Etcd struct {
Hosts []string
Key string
} `json:",optional"`
}
content := []byte(`{"Name": "kevin"}`)
err := UnmarshalJsonBytes(content, &c)
assert.Nil(t, err)
assert.Equal(t, "kevin", c.Name)
}
func TestUnmarshalStructLowerCase(t *testing.T) {
var c struct {
Name string
Etcd struct {
Key string
} `json:"etcd"`
}
content := []byte(`{"Name": "kevin", "etcd": {"Key": "the key"}}`)
err := UnmarshalJsonBytes(content, &c)
assert.Nil(t, err)
assert.Equal(t, "kevin", c.Name)
assert.Equal(t, "the key", c.Etcd.Key)
}
func TestUnmarshalWithStructAllOptionalWithEmpty(t *testing.T) {
var c struct {
Inner struct {
Optional string `json:",optional"`
}
Else string
}
content := []byte(`{"Else": "sure", "Inner": {}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalWithStructAllOptionalPtr(t *testing.T) {
var c struct {
Inner *struct {
Optional string `json:",optional"`
}
Else string
}
content := []byte(`{"Else": "sure", "Inner": {}}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalWithStructOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
In Inner `json:",optional"`
Else string
}
content := []byte(`{"Else": "sure"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "", c.In.Must)
}
func TestUnmarshalWithStructPtrOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
In *Inner `json:",optional"`
Else string
}
content := []byte(`{"Else": "sure"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Nil(t, c.In)
}
func TestUnmarshalWithStructAllOptionalAnonymous(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
Inner
Else string
}
content := []byte(`{"Else": "sure"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalWithStructAllOptionalAnonymousPtr(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
*Inner
Else string
}
content := []byte(`{"Else": "sure"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
}
func TestUnmarshalWithStructAllOptionalProvoidedAnonymous(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
Inner
Else string
}
content := []byte(`{"Else": "sure", "Optional": "optional"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "optional", c.Optional)
}
func TestUnmarshalWithStructAllOptionalProvoidedAnonymousPtr(t *testing.T) {
type Inner struct {
Optional string `json:",optional"`
}
var c struct {
*Inner
Else string
}
content := []byte(`{"Else": "sure", "Optional": "optional"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "optional", c.Optional)
}
func TestUnmarshalWithStructAnonymous(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
Inner
Else string
}
content := []byte(`{"Else": "sure", "Must": "must"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "must", c.Must)
}
func TestUnmarshalWithStructAnonymousPtr(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
*Inner
Else string
}
content := []byte(`{"Else": "sure", "Must": "must"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "must", c.Must)
}
func TestUnmarshalWithStructAnonymousOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
Inner `json:",optional"`
Else string
}
content := []byte(`{"Else": "sure"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Equal(t, "", c.Must)
}
func TestUnmarshalWithStructPtrAnonymousOptional(t *testing.T) {
type Inner struct {
Must string
}
var c struct {
*Inner `json:",optional"`
Else string
}
content := []byte(`{"Else": "sure"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "sure", c.Else)
assert.Nil(t, c.Inner)
}
func TestUnmarshalWithZeroValues(t *testing.T) {
type inner struct {
False bool `json:"no"`
Int int `json:"int"`
String string `json:"string"`
}
content := []byte(`{"no": false, "int": 0, "string": ""}`)
reader := bytes.NewReader(content)
var in inner
ast := assert.New(t)
ast.Nil(UnmarshalJsonReader(reader, &in))
ast.False(in.False)
ast.Equal(0, in.Int)
ast.Equal("", in.String)
}
func TestUnmarshalBytesError(t *testing.T) {
payload := `[{"abcd": "cdef"}]`
var v struct {
Any string
}
err := UnmarshalJsonBytes([]byte(payload), &v)
assert.Equal(t, errTypeMismatch, err)
}
func TestUnmarshalReaderError(t *testing.T) {
payload := `[{"abcd": "cdef"}]`
reader := strings.NewReader(payload)
var v struct {
Any string
}
assert.Equal(t, errTypeMismatch, UnmarshalJsonReader(reader, &v))
}
func TestUnmarshalMap(t *testing.T) {
t.Run("nil map and valid", func(t *testing.T) {
var m map[string]any
var v struct {
Any string `json:",optional"`
}
err := UnmarshalJsonMap(m, &v)
assert.Nil(t, err)
assert.True(t, len(v.Any) == 0)
})
t.Run("empty map but not valid", func(t *testing.T) {
m := map[string]any{}
var v struct {
Any string
}
err := UnmarshalJsonMap(m, &v)
assert.NotNil(t, err)
})
t.Run("empty map and valid", func(t *testing.T) {
m := map[string]any{}
var v struct {
Any string `json:",optional"`
}
err := UnmarshalJsonMap(m, &v, WithCanonicalKeyFunc(func(s string) string {
return s
}))
assert.Nil(t, err)
assert.True(t, len(v.Any) == 0)
})
t.Run("valid map", func(t *testing.T) {
m := map[string]any{
"Any": "foo",
}
var v struct {
Any string
}
err := UnmarshalJsonMap(m, &v)
assert.Nil(t, err)
assert.Equal(t, "foo", v.Any)
})
}
func TestUnmarshalJsonArray(t *testing.T) {
var v []struct {
Name string `json:"name"`
Age int `json:"age"`
}
body := `[{"name":"kevin", "age": 18}]`
assert.NoError(t, UnmarshalJsonBytes([]byte(body), &v))
assert.Equal(t, 1, len(v))
assert.Equal(t, "kevin", v[0].Name)
assert.Equal(t, 18, v[0].Age)
}
func TestUnmarshalJsonBytesError(t *testing.T) {
var v []struct {
Name string `json:"name"`
Age int `json:"age"`
}
assert.Error(t, UnmarshalJsonBytes([]byte((``)), &v))
assert.Error(t, UnmarshalJsonReader(strings.NewReader(``), &v))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/unmarshaler.go | core/mapping/unmarshaler.go | package mapping
import (
"encoding"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/jsonx"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/proc"
)
const (
defaultKeyName = "key"
delimiter = '.'
ignoreKey = "-"
numberTypeString = "number"
)
var (
errTypeMismatch = errors.New("type mismatch")
errValueNotSettable = errors.New("value is not settable")
errValueNotStruct = errors.New("value type is not struct")
keyUnmarshaler = NewUnmarshaler(defaultKeyName)
durationType = reflect.TypeOf(time.Duration(0))
cacheKeys = make(map[string][]string)
cacheKeysLock sync.Mutex
defaultCache = make(map[string]any)
defaultCacheLock sync.Mutex
emptyMap = map[string]any{}
emptyValue = reflect.ValueOf(lang.Placeholder)
)
type (
// Unmarshaler is used to unmarshal with the given tag key.
Unmarshaler struct {
key string
opts unmarshalOptions
}
// UnmarshalOption defines the method to customize an Unmarshaler.
UnmarshalOption func(*unmarshalOptions)
unmarshalOptions struct {
fillDefault bool
fromArray bool
fromString bool
opaqueKeys bool
canonicalKey func(key string) string
}
)
// NewUnmarshaler returns an Unmarshaler.
func NewUnmarshaler(key string, opts ...UnmarshalOption) *Unmarshaler {
unmarshaler := Unmarshaler{
key: key,
}
for _, opt := range opts {
opt(&unmarshaler.opts)
}
return &unmarshaler
}
// UnmarshalKey unmarshals m into v with the tag key.
func UnmarshalKey(m map[string]any, v any) error {
return keyUnmarshaler.Unmarshal(m, v)
}
// Unmarshal unmarshals m into v.
func (u *Unmarshaler) Unmarshal(i, v any) error {
return u.unmarshal(i, v, "")
}
// UnmarshalValuer unmarshals m into v.
func (u *Unmarshaler) UnmarshalValuer(m Valuer, v any) error {
return u.unmarshalValuer(simpleValuer{current: m}, v, "")
}
func (u *Unmarshaler) fillMap(fieldType reflect.Type, value reflect.Value,
mapValue any, fullName string) error {
if !value.CanSet() {
return errValueNotSettable
}
fieldKeyType := fieldType.Key()
fieldElemType := fieldType.Elem()
targetValue, err := u.generateMap(fieldKeyType, fieldElemType, mapValue, fullName)
if err != nil {
return err
}
if !targetValue.Type().AssignableTo(value.Type()) {
return errTypeMismatch
}
value.Set(targetValue)
return nil
}
func (u *Unmarshaler) fillMapFromString(value reflect.Value, mapValue any) error {
if !value.CanSet() {
return errValueNotSettable
}
switch v := mapValue.(type) {
case fmt.Stringer:
if err := jsonx.UnmarshalFromString(v.String(), value.Addr().Interface()); err != nil {
return err
}
case string:
if err := jsonx.UnmarshalFromString(v, value.Addr().Interface()); err != nil {
return err
}
default:
return errUnsupportedType
}
return nil
}
func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value,
mapValue any, fullName string) error {
if !value.CanSet() {
return errValueNotSettable
}
refValue := reflect.ValueOf(mapValue)
if refValue.Kind() != reflect.Slice {
return newTypeMismatchErrorWithHint(fullName, reflect.Slice.String(), refValue.Type().String())
}
if refValue.IsNil() {
return nil
}
baseType := fieldType.Elem()
dereffedBaseType := Deref(baseType)
dereffedBaseKind := dereffedBaseType.Kind()
if refValue.Len() == 0 {
value.Set(reflect.MakeSlice(reflect.SliceOf(baseType), 0, 0))
return nil
}
var valid bool
conv := reflect.MakeSlice(reflect.SliceOf(baseType), refValue.Len(), refValue.Cap())
for i := 0; i < refValue.Len(); i++ {
ithValue := refValue.Index(i).Interface()
if ithValue == nil {
continue
}
valid = true
sliceFullName := fmt.Sprintf("%s[%d]", fullName, i)
switch dereffedBaseKind {
case reflect.Struct:
if err := u.fillStructElement(baseType, conv.Index(i), ithValue, sliceFullName); err != nil {
return err
}
case reflect.Slice:
if err := u.fillSlice(dereffedBaseType, conv.Index(i), ithValue, sliceFullName); err != nil {
return err
}
default:
if err := u.fillSliceValue(conv, i, dereffedBaseKind, ithValue, sliceFullName); err != nil {
return err
}
}
}
if valid {
value.Set(conv)
}
return nil
}
func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value,
mapValue any, fullName string) error {
var slice []any
switch v := mapValue.(type) {
case fmt.Stringer:
if err := jsonx.UnmarshalFromString(v.String(), &slice); err != nil {
return fmt.Errorf("fullName: `%s`, error: `%w`", fullName, err)
}
case string:
if err := jsonx.UnmarshalFromString(v, &slice); err != nil {
return fmt.Errorf("fullName: `%s`, error: `%w`", fullName, err)
}
default:
return errUnsupportedType
}
baseFieldType := fieldType.Elem()
baseFieldKind := baseFieldType.Kind()
conv := reflect.MakeSlice(reflect.SliceOf(baseFieldType), len(slice), cap(slice))
for i := 0; i < len(slice); i++ {
if err := u.fillSliceValue(conv, i, baseFieldKind, slice[i], fullName); err != nil {
return err
}
}
value.Set(conv)
return nil
}
func (u *Unmarshaler) fillSliceValue(slice reflect.Value, index int,
baseKind reflect.Kind, value any, fullName string) error {
if value == nil {
return errNilSliceElement
}
ithVal := slice.Index(index)
ithValType := ithVal.Type()
switch v := value.(type) {
case fmt.Stringer:
return setValueFromString(baseKind, ithVal, v.String())
case string:
return setValueFromString(baseKind, ithVal, v)
case map[string]any:
// deref to handle both pointer and non-pointer types.
switch Deref(ithValType).Kind() {
case reflect.Struct:
return u.fillStructElement(ithValType, ithVal, v, fullName)
case reflect.Map:
return u.fillMap(ithValType, ithVal, value, fullName)
default:
return errTypeMismatch
}
default:
// don't need to consider the difference between int, int8, int16, int32, int64,
// uint, uint8, uint16, uint32, uint64, because they're handled as json.Number.
if ithVal.Kind() == reflect.Ptr {
baseType := Deref(ithValType)
if !reflect.TypeOf(value).AssignableTo(baseType) {
return errTypeMismatch
}
target := reflect.New(baseType).Elem()
target.Set(reflect.ValueOf(value))
SetValue(ithValType, ithVal, target)
return nil
}
if !reflect.TypeOf(value).AssignableTo(ithValType) {
return errTypeMismatch
}
ithVal.Set(reflect.ValueOf(value))
return nil
}
}
func (u *Unmarshaler) fillSliceWithDefault(derefedType reflect.Type, value reflect.Value,
defaultValue, fullName string) error {
baseFieldType := Deref(derefedType.Elem())
baseFieldKind := baseFieldType.Kind()
defaultCacheLock.Lock()
slice, ok := defaultCache[defaultValue]
defaultCacheLock.Unlock()
if !ok {
if baseFieldKind == reflect.String {
slice = parseGroupedSegments(defaultValue)
} else if err := jsonx.UnmarshalFromString(defaultValue, &slice); err != nil {
return err
}
defaultCacheLock.Lock()
defaultCache[defaultValue] = slice
defaultCacheLock.Unlock()
}
return u.fillSlice(derefedType, value, slice, fullName)
}
func (u *Unmarshaler) fillStructElement(baseType reflect.Type, target reflect.Value,
value any, fullName string) error {
val, ok := value.(map[string]any)
if !ok {
return errTypeMismatch
}
// use Deref(baseType) to get the base type in case the type is a pointer type.
ptr := reflect.New(Deref(baseType))
if err := u.unmarshal(val, ptr.Interface(), fullName); err != nil {
return err
}
SetValue(baseType, target, ptr.Elem())
return nil
}
func (u *Unmarshaler) fillUnmarshalerStruct(fieldType reflect.Type,
value reflect.Value, targetValue string) error {
if !value.CanSet() {
return errValueNotSettable
}
baseType := Deref(fieldType)
target := reflect.New(baseType)
switch u.key {
case jsonTagKey:
unmarshaler, ok := target.Interface().(json.Unmarshaler)
if !ok {
return errUnsupportedType
}
if err := unmarshaler.UnmarshalJSON([]byte(targetValue)); err != nil {
return err
}
default:
return errUnsupportedType
}
value.Set(target)
return nil
}
func (u *Unmarshaler) generateMap(keyType, elemType reflect.Type, mapValue any,
fullName string) (reflect.Value, error) {
mapType := reflect.MapOf(keyType, elemType)
valueType := reflect.TypeOf(mapValue)
if mapType == valueType {
return reflect.ValueOf(mapValue), nil
}
if keyType != valueType.Key() {
return emptyValue, errTypeMismatch
}
refValue := reflect.ValueOf(mapValue)
targetValue := reflect.MakeMapWithSize(mapType, refValue.Len())
dereffedElemType := Deref(elemType)
dereffedElemKind := dereffedElemType.Kind()
for _, key := range refValue.MapKeys() {
keythValue := refValue.MapIndex(key)
keythData := keythValue.Interface()
mapFullName := fmt.Sprintf("%s[%s]", fullName, key.String())
switch dereffedElemKind {
case reflect.Slice:
target := reflect.New(dereffedElemType)
if err := u.fillSlice(elemType, target.Elem(), keythData, mapFullName); err != nil {
return emptyValue, err
}
targetValue.SetMapIndex(key, target.Elem())
case reflect.Struct:
keythMap, ok := keythData.(map[string]any)
if !ok {
return emptyValue, errTypeMismatch
}
target := reflect.New(dereffedElemType)
if err := u.unmarshal(keythMap, target.Interface(), mapFullName); err != nil {
return emptyValue, err
}
SetMapIndexValue(elemType, targetValue, key, target.Elem())
case reflect.Map:
keythMap, ok := keythData.(map[string]any)
if !ok {
return emptyValue, errTypeMismatch
}
innerValue, err := u.generateMap(elemType.Key(), elemType.Elem(), keythMap, mapFullName)
if err != nil {
return emptyValue, err
}
targetValue.SetMapIndex(key, innerValue)
default:
switch v := keythData.(type) {
case bool:
if dereffedElemKind != reflect.Bool {
return emptyValue, errTypeMismatch
}
targetValue.SetMapIndex(key, reflect.ValueOf(v))
case string:
if dereffedElemKind != reflect.String {
return emptyValue, errTypeMismatch
}
val := reflect.ValueOf(v)
if !val.Type().AssignableTo(dereffedElemType) {
return emptyValue, errTypeMismatch
}
targetValue.SetMapIndex(key, val)
case json.Number:
target := reflect.New(dereffedElemType)
if err := setValueFromString(dereffedElemKind, target.Elem(), v.String()); err != nil {
return emptyValue, err
}
targetValue.SetMapIndex(key, target.Elem())
default:
if dereffedElemKind != keythValue.Kind() {
return emptyValue, errTypeMismatch
}
targetValue.SetMapIndex(key, keythValue)
}
}
}
return targetValue, nil
}
func (u *Unmarshaler) implementsUnmarshaler(t reflect.Type) bool {
switch u.key {
case jsonTagKey:
return t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem())
default:
return false
}
}
func (u *Unmarshaler) parseOptionsWithContext(field reflect.StructField, m Valuer, fullName string) (
string, *fieldOptionsWithContext, error) {
key, options, err := parseKeyAndOptions(u.key, field)
if err != nil {
return "", nil, err
} else if options == nil {
return key, nil, nil
}
if u.opts.canonicalKey != nil {
key = u.opts.canonicalKey(key)
if len(options.OptionalDep) > 0 {
// need to create a new fieldOption, because the original one is shared through cache.
options = &fieldOptions{
fieldOptionsWithContext: fieldOptionsWithContext{
Inherit: options.Inherit,
FromString: options.FromString,
Optional: options.Optional,
Options: options.Options,
Default: options.Default,
EnvVar: options.EnvVar,
Range: options.Range,
},
OptionalDep: u.opts.canonicalKey(options.OptionalDep),
}
}
}
if u.opts.fillDefault {
return key, &options.fieldOptionsWithContext, nil
}
optsWithContext, err := options.toOptionsWithContext(key, m, fullName)
if err != nil {
return "", nil, err
}
return key, optsWithContext, nil
}
func (u *Unmarshaler) processAnonymousField(field reflect.StructField, value reflect.Value,
m valuerWithParent, fullName string) error {
key, options, err := u.parseOptionsWithContext(field, m, fullName)
if err != nil {
return err
}
if key == ignoreKey {
return nil
}
if options.optional() {
return u.processAnonymousFieldOptional(field, value, key, m, fullName)
}
return u.processAnonymousFieldRequired(field, value, m, fullName)
}
func (u *Unmarshaler) processAnonymousFieldOptional(field reflect.StructField, value reflect.Value,
key string, m valuerWithParent, fullName string) error {
derefedFieldType := Deref(field.Type)
switch derefedFieldType.Kind() {
case reflect.Struct:
return u.processAnonymousStructFieldOptional(field.Type, value, key, m, fullName)
default:
return u.processNamedField(field, value, m, fullName)
}
}
func (u *Unmarshaler) processAnonymousFieldRequired(field reflect.StructField, value reflect.Value,
m valuerWithParent, fullName string) error {
fieldType := field.Type
maybeNewValue(fieldType, value)
derefedFieldType := Deref(fieldType)
indirectValue := reflect.Indirect(value)
switch derefedFieldType.Kind() {
case reflect.Struct:
for i := 0; i < derefedFieldType.NumField(); i++ {
if err := u.processField(derefedFieldType.Field(i), indirectValue.Field(i),
m, fullName); err != nil {
return err
}
}
default:
if err := u.processNamedField(field, indirectValue, m, fullName); err != nil {
return err
}
}
return nil
}
func (u *Unmarshaler) processAnonymousStructFieldOptional(fieldType reflect.Type,
value reflect.Value, key string, m valuerWithParent, fullName string) error {
var filled bool
var required int
var requiredFilled int
var indirectValue reflect.Value
derefedFieldType := Deref(fieldType)
for i := 0; i < derefedFieldType.NumField(); i++ {
subField := derefedFieldType.Field(i)
fieldKey, fieldOpts, err := u.parseOptionsWithContext(subField, m, fullName)
if err != nil {
return err
}
_, hasValue := getValue(m, fieldKey, u.opts.opaqueKeys)
if hasValue {
if !filled {
filled = true
maybeNewValue(fieldType, value)
indirectValue = reflect.Indirect(value)
}
if err = u.processField(subField, indirectValue.Field(i), m, fullName); err != nil {
return err
}
}
if !fieldOpts.optional() {
required++
if hasValue {
requiredFilled++
}
}
}
if filled && required != requiredFilled {
return fmt.Errorf("%q is not fully set", key)
}
return nil
}
func (u *Unmarshaler) processField(field reflect.StructField, value reflect.Value,
m valuerWithParent, fullName string) error {
if usingDifferentKeys(u.key, field) {
return nil
}
if field.Anonymous {
return u.processAnonymousField(field, value, m, fullName)
}
return u.processNamedField(field, value, m, fullName)
}
func (u *Unmarshaler) processFieldNotFromString(fieldType reflect.Type, value reflect.Value,
vp valueWithParent, opts *fieldOptionsWithContext, fullName string) error {
derefedFieldType := Deref(fieldType)
typeKind := derefedFieldType.Kind()
mapValue := vp.value
valueKind := reflect.TypeOf(mapValue).Kind()
switch {
case valueKind == reflect.Map && typeKind == reflect.Struct:
mv, ok := mapValue.(map[string]any)
if !ok {
return errTypeMismatch
}
return u.processFieldStruct(fieldType, value, &simpleValuer{
current: mapValuer(mv),
parent: vp.parent,
}, fullName)
case typeKind == reflect.Slice && valueKind == reflect.Slice:
return u.fillSlice(fieldType, value, mapValue, fullName)
case valueKind == reflect.Map && typeKind == reflect.Map:
return u.fillMap(fieldType, value, mapValue, fullName)
case valueKind == reflect.String && typeKind == reflect.Map:
return u.fillMapFromString(value, mapValue)
case valueKind == reflect.String && typeKind == reflect.Slice:
// try to find out if it's a byte slice,
// more details https://pkg.go.dev/encoding/json#Marshal
// array and slice values encode as JSON arrays,
// except that []byte encodes as a base64-encoded string,
// and a nil slice encoded as the null JSON value.
// https://stackoverflow.com/questions/34089750/marshal-byte-to-json-giving-a-strange-string
if fieldType.Elem().Kind() == reflect.Uint8 {
// check whether string type, because the kind of some other types can be string
if strVal, ok := mapValue.(string); ok {
if decodedBytes, err := base64.StdEncoding.DecodeString(strVal); err == nil {
value.Set(reflect.ValueOf(decodedBytes))
return nil
}
}
}
return u.fillSliceFromString(fieldType, value, mapValue, fullName)
case valueKind == reflect.String && derefedFieldType == durationType:
v, err := convertToString(mapValue, fullName)
if err != nil {
return err
}
return fillDurationValue(fieldType, value, v)
case valueKind == reflect.String && typeKind == reflect.Struct && u.implementsUnmarshaler(fieldType):
v, err := convertToString(mapValue, fullName)
if err != nil {
return err
}
return u.fillUnmarshalerStruct(fieldType, value, v)
default:
return u.processFieldPrimitive(fieldType, value, mapValue, opts, fullName)
}
}
func (u *Unmarshaler) processFieldPrimitive(fieldType reflect.Type, value reflect.Value,
mapValue any, opts *fieldOptionsWithContext, fullName string) error {
typeKind := Deref(fieldType).Kind()
valueKind := reflect.TypeOf(mapValue).Kind()
switch v := mapValue.(type) {
case json.Number:
return u.processFieldPrimitiveWithJSONNumber(fieldType, value, v, opts, fullName)
default:
if typeKind == valueKind {
if err := validateValueInOptions(mapValue, opts.options()); err != nil {
return err
}
return fillWithSameType(fieldType, value, mapValue, opts)
}
}
return newTypeMismatchError(fullName)
}
func (u *Unmarshaler) processFieldPrimitiveWithJSONNumber(fieldType reflect.Type, value reflect.Value,
v json.Number, opts *fieldOptionsWithContext, fullName string) error {
baseType := Deref(fieldType)
typeKind := baseType.Kind()
if err := validateJsonNumberRange(v, opts); err != nil {
return err
}
if err := validateValueInOptions(v, opts.options()); err != nil {
return err
}
target := reflect.New(Deref(fieldType)).Elem()
switch typeKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if err := setValueFromString(typeKind, target, v.String()); err != nil {
return err
}
case reflect.Float32:
fValue, err := v.Float64()
if err != nil {
return err
}
// if the value is a pointer, we need to check overflow with the pointer's value.
derefedValue := value
for derefedValue.Type().Kind() == reflect.Ptr {
derefedValue = derefedValue.Elem()
}
if derefedValue.CanFloat() && derefedValue.OverflowFloat(fValue) {
return fmt.Errorf("parsing %q as float32: value out of range", v.String())
}
target.SetFloat(fValue)
case reflect.Float64:
fValue, err := v.Float64()
if err != nil {
return err
}
target.SetFloat(fValue)
default:
return newTypeMismatchErrorWithHint(fullName, typeKind.String(), numberTypeString)
}
SetValue(fieldType, value, target)
return nil
}
func (u *Unmarshaler) processFieldStruct(fieldType reflect.Type, value reflect.Value,
m valuerWithParent, fullName string) error {
if fieldType.Kind() == reflect.Ptr {
baseType := Deref(fieldType)
target := reflect.New(baseType).Elem()
if err := u.unmarshalWithFullName(m, target.Addr().Interface(), fullName); err != nil {
return err
}
SetValue(fieldType, value, target)
} else if err := u.unmarshalWithFullName(m, value.Addr().Interface(), fullName); err != nil {
return err
}
return nil
}
func (u *Unmarshaler) processFieldTextUnmarshaler(fieldType reflect.Type, value reflect.Value,
mapValue any) (bool, error) {
var tval encoding.TextUnmarshaler
var ok bool
if fieldType.Kind() == reflect.Ptr {
if value.Elem().Kind() == reflect.Ptr {
target := reflect.New(Deref(fieldType))
SetValue(fieldType.Elem(), value, target)
tval, ok = target.Interface().(encoding.TextUnmarshaler)
} else {
tval, ok = value.Interface().(encoding.TextUnmarshaler)
}
} else {
tval, ok = value.Addr().Interface().(encoding.TextUnmarshaler)
}
if ok {
switch mv := mapValue.(type) {
case string:
return true, tval.UnmarshalText([]byte(mv))
case []byte:
return true, tval.UnmarshalText(mv)
}
}
return false, nil
}
func (u *Unmarshaler) processFieldWithEnvValue(fieldType reflect.Type, value reflect.Value,
envVal string, opts *fieldOptionsWithContext, fullName string) error {
if err := validateValueInOptions(envVal, opts.options()); err != nil {
return err
}
derefType := Deref(fieldType)
derefKind := derefType.Kind()
switch {
case derefKind == reflect.String:
SetValue(fieldType, value, toReflectValue(derefType, envVal))
return nil
case derefKind == reflect.Bool:
val, err := strconv.ParseBool(envVal)
if err != nil {
return fmt.Errorf("unmarshal field %q with environment variable, %w", fullName, err)
}
SetValue(fieldType, value, toReflectValue(derefType, val))
return nil
case derefType == durationType:
// time.Duration is a special case, its derefKind is reflect.Int64.
if err := fillDurationValue(fieldType, value, envVal); err != nil {
return fmt.Errorf("unmarshal field %q with environment variable, %w", fullName, err)
}
return nil
default:
return u.processFieldPrimitiveWithJSONNumber(fieldType, value, json.Number(envVal), opts, fullName)
}
}
func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect.Value,
m valuerWithParent, fullName string) error {
if !field.IsExported() {
return nil
}
key, opts, err := u.parseOptionsWithContext(field, m, fullName)
if err != nil {
return err
}
if key == ignoreKey {
return nil
}
fullName = join(fullName, key)
if opts != nil && len(opts.EnvVar) > 0 {
envVal := proc.Env(opts.EnvVar)
if len(envVal) > 0 {
return u.processFieldWithEnvValue(field.Type, value, envVal, opts, fullName)
}
}
canonicalKey := key
if u.opts.canonicalKey != nil {
canonicalKey = u.opts.canonicalKey(key)
}
valuer := createValuer(m, opts)
mapValue, hasValue := getValue(valuer, canonicalKey, u.opts.opaqueKeys)
// When fillDefault is used, m is a null value, hasValue must be false, all priority judgments fillDefault.
if u.opts.fillDefault {
if !value.IsZero() {
return fmt.Errorf("set the default value, %q must be zero", fullName)
}
return u.processNamedFieldWithoutValue(field.Type, value, opts, fullName)
} else if !hasValue {
return u.processNamedFieldWithoutValue(field.Type, value, opts, fullName)
}
if u.opts.fromArray {
fieldKind := field.Type.Kind()
if fieldKind != reflect.Slice && fieldKind != reflect.Array {
valueKind := reflect.TypeOf(mapValue).Kind()
if valueKind == reflect.Slice || valueKind == reflect.Array {
val := reflect.ValueOf(mapValue)
if val.Len() > 0 {
mapValue = val.Index(0).Interface()
}
}
}
}
return u.processNamedFieldWithValue(field.Type, value, valueWithParent{
value: mapValue,
parent: valuer,
}, key, opts, fullName)
}
func (u *Unmarshaler) processNamedFieldWithValue(fieldType reflect.Type, value reflect.Value,
vp valueWithParent, key string, opts *fieldOptionsWithContext, fullName string) error {
mapValue := vp.value
if mapValue == nil {
if opts.optional() {
return nil
}
return fmt.Errorf("field %q mustn't be nil", key)
}
if !value.CanSet() {
return fmt.Errorf("field %q is not settable", key)
}
maybeNewValue(fieldType, value)
if yes, err := u.processFieldTextUnmarshaler(fieldType, value, mapValue); yes {
return err
}
fieldKind := Deref(fieldType).Kind()
switch fieldKind {
case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct:
return u.processFieldNotFromString(fieldType, value, vp, opts, fullName)
default:
if u.opts.fromString || opts.fromString() {
return u.processNamedFieldWithValueFromString(fieldType, value, mapValue,
key, opts, fullName)
}
return u.processFieldNotFromString(fieldType, value, vp, opts, fullName)
}
}
func (u *Unmarshaler) processNamedFieldWithValueFromString(fieldType reflect.Type, value reflect.Value,
mapValue any, key string, opts *fieldOptionsWithContext, fullName string) error {
valueKind := reflect.TypeOf(mapValue).Kind()
if valueKind != reflect.String {
return fmt.Errorf("the value in map is not string, but %s", valueKind)
}
options := opts.options()
if len(options) > 0 {
var checkValue string
switch mt := mapValue.(type) {
case string:
checkValue = mt
case fmt.Stringer:
checkValue = mt.String()
default:
return fmt.Errorf("the value in map is not string or json.Number, but %s",
valueKind.String())
}
if !slices.Contains(options, checkValue) {
return fmt.Errorf(`value "%s" for field %q is not defined in options "%v"`,
mapValue, key, options)
}
}
return fillPrimitive(fieldType, value, mapValue, opts, fullName)
}
func (u *Unmarshaler) processNamedFieldWithoutValue(fieldType reflect.Type, value reflect.Value,
opts *fieldOptionsWithContext, fullName string) error {
derefedType := Deref(fieldType)
fieldKind := derefedType.Kind()
if defaultValue, ok := opts.getDefault(); ok {
if derefedType == durationType {
return fillDurationValue(fieldType, value, defaultValue)
}
switch fieldKind {
case reflect.Array, reflect.Slice:
return u.fillSliceWithDefault(derefedType, value, defaultValue, fullName)
default:
return setValueFromString(fieldKind, value, defaultValue)
}
}
if u.opts.fillDefault {
if fieldType.Kind() != reflect.Ptr && fieldKind == reflect.Struct {
return u.processFieldNotFromString(fieldType, value, valueWithParent{
value: emptyMap,
}, opts, fullName)
}
return nil
}
switch fieldKind {
case reflect.Array, reflect.Map, reflect.Slice:
if !opts.optional() {
return u.processFieldNotFromString(fieldType, value, valueWithParent{
value: emptyMap,
}, opts, fullName)
}
case reflect.Struct:
if !opts.optional() {
required, err := structValueRequired(u.key, derefedType)
if err != nil {
return err
}
if required {
return fmt.Errorf("%q is not set", fullName)
}
return u.processFieldNotFromString(fieldType, value, valueWithParent{
value: emptyMap,
}, opts, fullName)
}
default:
if !opts.optional() {
return newInitError(fullName)
}
}
return nil
}
func (u *Unmarshaler) unmarshal(i, v any, fullName string) error {
valueType := reflect.TypeOf(v)
if valueType.Kind() != reflect.Ptr {
return errValueNotSettable
}
elemType := Deref(valueType)
switch iv := i.(type) {
case map[string]any:
if elemType.Kind() != reflect.Struct {
return errTypeMismatch
}
return u.unmarshalValuer(mapValuer(iv), v, fullName)
case []any:
if elemType.Kind() != reflect.Slice {
return errTypeMismatch
}
return u.fillSlice(elemType, reflect.ValueOf(v).Elem(), iv, fullName)
default:
return errUnsupportedType
}
}
func (u *Unmarshaler) unmarshalValuer(m Valuer, v any, fullName string) error {
return u.unmarshalWithFullName(simpleValuer{current: m}, v, fullName)
}
func (u *Unmarshaler) unmarshalWithFullName(m valuerWithParent, v any, fullName string) error {
rv := reflect.ValueOf(v)
if err := ValidatePtr(rv); err != nil {
return err
}
valueType := reflect.TypeOf(v)
baseType := Deref(valueType)
if baseType.Kind() != reflect.Struct {
return errValueNotStruct
}
valElem := rv.Elem()
if valElem.Kind() == reflect.Ptr {
target := reflect.New(baseType).Elem()
SetValue(valueType.Elem(), valElem, target)
valElem = target
}
numFields := baseType.NumField()
for i := 0; i < numFields; i++ {
typeField := baseType.Field(i)
valueField := valElem.Field(i)
if err := u.processField(typeField, valueField, m, fullName); err != nil {
return err
}
}
return nil
}
// WithStringValues customizes an Unmarshaler with number values from strings.
func WithStringValues() UnmarshalOption {
return func(opt *unmarshalOptions) {
opt.fromString = true
}
}
// WithCanonicalKeyFunc customizes an Unmarshaler with Canonical Key func.
func WithCanonicalKeyFunc(f func(string) string) UnmarshalOption {
return func(opt *unmarshalOptions) {
opt.canonicalKey = f
}
}
// WithDefault customizes an Unmarshaler with fill default values.
func WithDefault() UnmarshalOption {
return func(opt *unmarshalOptions) {
opt.fillDefault = true
}
}
// WithFromArray customizes an Unmarshaler with converting array values to non-array types.
// For example, if the field type is []string, and the value is [hello],
// the field type can be `string`, instead of `[]string`.
// Typically, this option is used for unmarshaling from form values.
func WithFromArray() UnmarshalOption {
return func(opt *unmarshalOptions) {
opt.fromArray = true
}
}
// WithOpaqueKeys customizes an Unmarshaler with opaque keys.
// Opaque keys are keys that are not processed by the unmarshaler.
func WithOpaqueKeys() UnmarshalOption {
return func(opt *unmarshalOptions) {
opt.opaqueKeys = true
}
}
func createValuer(v valuerWithParent, opts *fieldOptionsWithContext) valuerWithParent {
if opts.inherit() {
return recursiveValuer{
current: v,
parent: v.Parent(),
}
}
return simpleValuer{
current: v,
parent: v.Parent(),
}
}
func fillDurationValue(fieldType reflect.Type, value reflect.Value, dur string) error {
d, err := time.ParseDuration(dur)
if err != nil {
return err
}
SetValue(fieldType, value, reflect.ValueOf(d))
return nil
}
func fillPrimitive(fieldType reflect.Type, value reflect.Value, mapValue any,
opts *fieldOptionsWithContext, fullName string) error {
if !value.CanSet() {
return errValueNotSettable
}
baseType := Deref(fieldType)
if fieldType.Kind() == reflect.Ptr {
target := reflect.New(baseType).Elem()
switch mapValue.(type) {
case string, json.Number:
SetValue(fieldType, value, target)
value = target
}
}
switch v := mapValue.(type) {
case string:
return validateAndSetValue(baseType.Kind(), value, v, opts)
case json.Number:
if err := validateJsonNumberRange(v, opts); err != nil {
return err
}
return setValueFromString(baseType.Kind(), value, v.String())
default:
return newTypeMismatchError(fullName)
}
}
func fillWithSameType(fieldType reflect.Type, value reflect.Value, mapValue any,
opts *fieldOptionsWithContext) error {
if !value.CanSet() {
return errValueNotSettable
}
if err := validateValueRange(mapValue, opts); err != nil {
return err
}
if fieldType.Kind() == reflect.Ptr {
baseType := Deref(fieldType)
target := reflect.New(baseType).Elem()
setSameKindValue(baseType, target, mapValue)
SetValue(fieldType, value, target)
} else {
setSameKindValue(fieldType, value, mapValue)
}
return nil
}
// getValue gets the value for the specific key, the key can be in the format of parentKey.childKey
func getValue(m valuerWithParent, key string, opaque bool) (any, bool) {
keys := readKeys(key, opaque)
return getValueWithChainedKeys(m, keys)
}
func getValueWithChainedKeys(m valuerWithParent, keys []string) (any, bool) {
switch len(keys) {
case 0:
return nil, false
case 1:
v, ok := m.Value(keys[0])
return v, ok
default:
if v, ok := m.Value(keys[0]); ok {
if nextm, ok := v.(map[string]any); ok {
return getValueWithChainedKeys(recursiveValuer{
current: mapValuer(nextm),
parent: m,
}, keys[1:])
}
}
return nil, false
}
}
func join(elem ...string) string {
var builder strings.Builder
var fillSep bool
for _, e := range elem {
if len(e) == 0 {
continue
}
if fillSep {
builder.WriteByte(delimiter)
} else {
fillSep = true
}
builder.WriteString(e)
}
return builder.String()
}
func newInitError(name string) error {
return fmt.Errorf("field %q is not set", name)
}
func newTypeMismatchError(name string) error {
return fmt.Errorf("type mismatch for field %q", name)
}
func newTypeMismatchErrorWithHint(name, expectType, actualType string) error {
return fmt.Errorf("type mismatch for field %q, expect %q, actual %q",
name, expectType, actualType)
}
func readKeys(key string, opaque bool) []string {
if opaque {
return []string{key}
}
cacheKeysLock.Lock()
keys, ok := cacheKeys[key]
cacheKeysLock.Unlock()
if ok {
return keys
}
keys = strings.FieldsFunc(key, func(c rune) bool {
return c == delimiter
})
cacheKeysLock.Lock()
cacheKeys[key] = keys
cacheKeysLock.Unlock()
return keys
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | true |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mapping/valuer.go | core/mapping/valuer.go | package mapping
type (
// A Valuer interface defines the way to get values from the underlying object with keys.
Valuer interface {
// Value gets the value associated with the given key.
Value(key string) (any, bool)
}
// A valuerWithParent defines a node that has a parent node.
valuerWithParent interface {
Valuer
// Parent get the parent valuer for current node.
Parent() valuerWithParent
}
// A node is a map that can use Value method to get values with given keys.
node struct {
current Valuer
parent valuerWithParent
}
// A valueWithParent is used to wrap the value with its parent.
valueWithParent struct {
value any
parent valuerWithParent
}
// mapValuer is a type for the map to meet the Valuer interface.
mapValuer map[string]any
// simpleValuer is a type to get value from the current node.
simpleValuer node
// recursiveValuer is a type to get the value recursively from current and parent nodes.
recursiveValuer node
)
// Value gets the value associated with the given key from mv.
func (mv mapValuer) Value(key string) (any, bool) {
v, ok := mv[key]
return v, ok
}
// Value gets the value associated with the given key from sv.
func (sv simpleValuer) Value(key string) (any, bool) {
v, ok := sv.current.Value(key)
return v, ok
}
// Parent get the parent valuer from sv.
func (sv simpleValuer) Parent() valuerWithParent {
if sv.parent == nil {
return nil
}
return recursiveValuer{
current: sv.parent,
parent: sv.parent.Parent(),
}
}
// Value gets the value associated with the given key from rv,
// and it will inherit the value from parent nodes.
func (rv recursiveValuer) Value(key string) (any, bool) {
val, ok := rv.current.Value(key)
if !ok {
if parent := rv.Parent(); parent != nil {
return parent.Value(key)
}
return nil, false
}
vm, ok := val.(map[string]any)
if !ok {
return val, true
}
parent := rv.Parent()
if parent == nil {
return val, true
}
pv, ok := parent.Value(key)
if !ok {
return val, true
}
pm, ok := pv.(map[string]any)
if !ok {
return val, true
}
for k, v := range pm {
if _, ok := vm[k]; !ok {
vm[k] = v
}
}
return vm, true
}
// Parent get the parent valuer from rv.
func (rv recursiveValuer) Parent() valuerWithParent {
if rv.parent == nil {
return nil
}
return recursiveValuer{
current: rv.parent,
parent: rv.parent.Parent(),
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logc/logs_test.go | core/logc/logs_test.go | package logc
import (
"context"
"encoding/json"
"fmt"
"runtime"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func TestAddGlobalFields(t *testing.T) {
buf := logtest.NewCollector(t)
Info(context.Background(), "hello")
buf.Reset()
AddGlobalFields(Field("a", "1"), Field("b", "2"))
AddGlobalFields(Field("c", "3"))
Info(context.Background(), "world")
var m map[string]any
assert.NoError(t, json.Unmarshal(buf.Bytes(), &m))
assert.Equal(t, "1", m["a"])
assert.Equal(t, "2", m["b"])
assert.Equal(t, "3", m["c"])
}
func TestAlert(t *testing.T) {
buf := logtest.NewCollector(t)
Alert(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), "foo"), buf.String())
}
func TestError(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Error(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestErrorf(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Errorf(context.Background(), "foo %s", "bar")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestErrorfn(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Errorfn(context.Background(), func() any {
return fmt.Sprintf("foo %s", "bar")
})
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestErrorv(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Errorv(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestErrorw(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Errorw(context.Background(), "foo", Field("a", "b"))
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestInfo(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Info(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestInfof(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Infof(context.Background(), "foo %s", "bar")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestInfofn(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Infofn(context.Background(), func() any {
return fmt.Sprintf("foo %s", "bar")
})
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestInfov(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Infov(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestInfow(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Infow(context.Background(), "foo", Field("a", "b"))
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestDebug(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Debug(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestDebugf(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Debugf(context.Background(), "foo %s", "bar")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestDebugfn(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Debugfn(context.Background(), func() any {
return fmt.Sprintf("foo %s", "bar")
})
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestDebugv(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Debugv(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestDebugw(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Debugw(context.Background(), "foo", Field("a", "b"))
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestMust(t *testing.T) {
assert.NotPanics(t, func() {
Must(nil)
})
assert.NotPanics(t, func() {
MustSetup(LogConf{})
})
}
func TestMisc(t *testing.T) {
SetLevel(logx.DebugLevel)
assert.NoError(t, SetUp(LogConf{}))
assert.NoError(t, Close())
}
func TestSlow(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Slow(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)), buf.String())
}
func TestSlowf(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Slowf(context.Background(), "foo %s", "bar")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)), buf.String())
}
func TestSlowfn(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Slowfn(context.Background(), func() any {
return fmt.Sprintf("foo %s", "bar")
})
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)), buf.String())
}
func TestSlowv(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Slowv(context.Background(), "foo")
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)), buf.String())
}
func TestSloww(t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Sloww(context.Background(), "foo", Field("a", "b"))
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)), buf.String())
}
func getFileLine() (string, int) {
_, file, line, _ := runtime.Caller(1)
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
return short, line
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/logc/logs.go | core/logc/logs.go | package logc
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
)
type (
LogConf = logx.LogConf
LogField = logx.LogField
)
// AddGlobalFields adds global fields.
func AddGlobalFields(fields ...LogField) {
logx.AddGlobalFields(fields...)
}
// Alert alerts v in alert level, and the message is written to error log.
func Alert(_ context.Context, v string) {
logx.Alert(v)
}
// Close closes the logging.
func Close() error {
return logx.Close()
}
// Debug writes v into access log.
func Debug(ctx context.Context, v ...interface{}) {
getLogger(ctx).Debug(v...)
}
// Debugf writes v with format into access log.
func Debugf(ctx context.Context, format string, v ...interface{}) {
getLogger(ctx).Debugf(format, v...)
}
// Debugfn writes fn result into access log.
// This is useful when the function is expensive to compute,
// and we want to log it only when necessary.
func Debugfn(ctx context.Context, fn func() any) {
getLogger(ctx).Debugfn(fn)
}
// Debugv writes v into access log with json content.
func Debugv(ctx context.Context, v interface{}) {
getLogger(ctx).Debugv(v)
}
// Debugw writes msg along with fields into the access log.
func Debugw(ctx context.Context, msg string, fields ...LogField) {
getLogger(ctx).Debugw(msg, fields...)
}
// Error writes v into error log.
func Error(ctx context.Context, v ...any) {
getLogger(ctx).Error(v...)
}
// Errorf writes v with format into error log.
func Errorf(ctx context.Context, format string, v ...any) {
getLogger(ctx).Errorf(fmt.Errorf(format, v...).Error())
}
// Errorfn writes fn result into error log.
// This is useful when the function is expensive to compute,
// and we want to log it only when necessary.
func Errorfn(ctx context.Context, fn func() any) {
getLogger(ctx).Errorfn(fn)
}
// Errorv writes v into error log with json content.
// No call stack attached, because not elegant to pack the messages.
func Errorv(ctx context.Context, v any) {
getLogger(ctx).Errorv(v)
}
// Errorw writes msg along with fields into the error log.
func Errorw(ctx context.Context, msg string, fields ...LogField) {
getLogger(ctx).Errorw(msg, fields...)
}
// Field returns a LogField for the given key and value.
func Field(key string, value any) LogField {
return logx.Field(key, value)
}
// Info writes v into access log.
func Info(ctx context.Context, v ...any) {
getLogger(ctx).Info(v...)
}
// Infof writes v with format into access log.
func Infof(ctx context.Context, format string, v ...any) {
getLogger(ctx).Infof(format, v...)
}
// Infofn writes fn result into access log.
// This is useful when the function is expensive to compute,
// and we want to log it only when necessary.
func Infofn(ctx context.Context, fn func() any) {
getLogger(ctx).Infofn(fn)
}
// Infov writes v into access log with json content.
func Infov(ctx context.Context, v any) {
getLogger(ctx).Infov(v)
}
// Infow writes msg along with fields into the access log.
func Infow(ctx context.Context, msg string, fields ...LogField) {
getLogger(ctx).Infow(msg, fields...)
}
// Must checks if err is nil, otherwise logs the error and exits.
func Must(err error) {
logx.Must(err)
}
// MustSetup sets up logging with given config c. It exits on error.
func MustSetup(c logx.LogConf) {
logx.MustSetup(c)
}
// SetLevel sets the logging level. It can be used to suppress some logs.
func SetLevel(level uint32) {
logx.SetLevel(level)
}
// SetUp sets up the logx.
// If already set up, return nil.
// We allow SetUp to be called multiple times, because, for example,
// we need to allow different service frameworks to initialize logx respectively.
// The same logic for SetUp
func SetUp(c LogConf) error {
return logx.SetUp(c)
}
// Slow writes v into slow log.
func Slow(ctx context.Context, v ...any) {
getLogger(ctx).Slow(v...)
}
// Slowf writes v with format into slow log.
func Slowf(ctx context.Context, format string, v ...any) {
getLogger(ctx).Slowf(format, v...)
}
// Slowfn writes fn result into slow log.
// This is useful when the function is expensive to compute,
// and we want to log it only when necessary.
func Slowfn(ctx context.Context, fn func() any) {
getLogger(ctx).Slowfn(fn)
}
// Slowv writes v into slow log with json content.
func Slowv(ctx context.Context, v any) {
getLogger(ctx).Slowv(v)
}
// Sloww writes msg along with fields into slow log.
func Sloww(ctx context.Context, msg string, fields ...LogField) {
getLogger(ctx).Sloww(msg, fields...)
}
// getLogger returns the logx.Logger with the given ctx and correct caller.
func getLogger(ctx context.Context) logx.Logger {
return logx.WithContext(ctx).WithCallerSkip(1)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.