Finding bugs from source code: 3 examples

go-zero config file uses validate tag, reading fails

// etc/user-api.yaml

Session:
  ExpirationInMinutes: 30
  RefreshThresholdInMinutes: 5

package config
type Config struct {
	Session struct {
		ExpirationInMinutes       int `validate:"gt=0"`
		RefreshThresholdInMinutes int `validate:"ltefield=ExpirationInMinutes"`
	}
}

package main

import (
	...
)

var configFile = flag.String("f", "etc/user-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	...
}

MustLoad finished without error, but the read field values were 0. Then I tried adding a yaml tag before the validate tag, still no luck.

1) Open the MustLoad source to check:

2) Then open the Load function:

The Load function returned a loader function, and the loader function came from a map called loaders

3) Inspect loaders

The config file is written in yaml, so open the LoadFromYamlBytes function

4) Inspect the LoadFromYamlBytes function

It turns out it first converts yaml to json, then parses. Changing the yaml tag to a json tag indeed fixed the problem

gomock redis

Error: redis: unexpected type=int for Int,

res and err are both returned from c.cmd.Eval().Int(), open it:

It was either int64 or string, change mockCmd.SetVal(0) to mockCmd.SetVal(int64(0))

http library panics with nil pointer when creating request

Business code:

According to the http spec, the body of a POST request may be null

Open it:

Open it

The nil pointer panic occurs on this line

Indicates v is nil; calling Len() caused the nil pointer panic

The body in the business code is nil

Solution:

Last updated