cmtstringer Today we are going to introduce a new tool to you named cmtstringer (https://github.com/lazada/cmtstringer). This package helps to generate the method that satisfy the fmt.Stringer interface. Given the name of a type T that has constants defined with comment on constant, cmtstringer will create a new Go source code file which implements fmt.Stringer interface. The file is created in the same directory and has the same package as the package that defines T. It also introduces helpful defaults designed for use with go generate.

For example, given this snippet in statuscode.go file:

package http

type StatusCode int

const (
// StatusBadRequest Bad Request
StatusBadRequest StatusCode = 400
// StatusNotFound Not Found
StatusNotFound StatusCode = 404
)

Usually, status code is a number which is not so meaningful for human eyes. In this case, we will define a map to match code with a readable message:

var statusCodeMsg = map[StatusCode]string {
StatusBadRequest: "Bad Request",
StatusNotFound: "Not Found",
}

Or define `String` function on StatusCode type with switch case statement:

func (s StatusCode) String() string {
switch s {
case StatusBadRequest:
return "Bad Request"
case StatusNotFound:
return "Not Found"
default:
return "Unknown"
}
}

When you want to add a new status code, you only have to add its message to the proper place. If you have a long list of status codes, it’s also hard to ensure that all status code has its message.

cmtstringer can help to generate String method on StatusCode by simply running this command:
cmtstringer -type StatusCode .

Then you will get the file statuscode_string_gen.go in the same directory. The message of the constant is extracted from its comment:

package http

// String returns comment of const type StatusCode
func (s StatusCode) String() string {
switch s {
case StatusBadRequest:
return "Bad Request"
case StatusNotFound:
return "Not Found"
default:
return "Unknown"
}
}

You can use cmtstringer with go generate as below:

package http

//go:generate cmtstringer -type StatusCode
type StatusCode int

As for future improvements, later cmtstringer might also accept custom template for the source code of generated file, so user can use cmtstringer to make type T satisfy for example the Error interface.