cmtstringer - Comment to String
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:
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:
Or define `String` function on StatusCode type with switch case statement:
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:
You can use cmtstringer with go generate as below:
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.