golint

The goal of the Lint tool is to make sure that the code respects the code style that is put forth in Effective Go and other public good-coding guidelines. This linter is not part of the Go tool suite so one needs to install it from https://github.com/golang/lint. The usage is fairly simple:

$golint -set_exit_status $(go list ./... )

The following are some issues that Go Lint catches. By default, golint only prints things on the console, so a CICD framework cannot easily figure out if there are any issues. The -set_exit_status option enables the golint return status to be non-zero and thus it infers errors in code. Some of the errors that golint flags are explored here:

  • Variable names:
package errors

import fmt

var e = errors.New("error")

func main() {
fmt.Println ("this program will give a golint error")
}

Here, golint would complain about the naming of variable e ("error var e should have name of the form errFoo"):

  • Error returns:
package myapp

func fetchData() (error, string) {
return nil, ""
}
  • Last else in a function: Here, golint would complain that the error should be the last type when returning multiple items:
func IsGreaterThanZero(x int) int {
if x > 0 {
return 1
} else {
return 0
}
}

Here golint would recommend that you have the last return outside of else.

Unit tests verify the functionality of the application. We have already covered how Go unit tests are written and the best practises for them. For each .go file, you need to have an associated _test.go containing the unit tests.

Clang has a detector for uninitialized reads called MemorySanitizer (described at https://clang.llvm.org/docs/MemorySanitizer.html). It can be used along with go test with the -msan flag. The CI framework should run the tests for all the packages with a command along the lines of this:

$go test -msan -short $(go list ./... )

Along with the status of the unit tests (whether there were any failures), a key metric of code reliability is code coverage. This indicates the amount of code that has been exercised by the unit tests. To calculate the code coverage ratio, we can use a script like this one:

$PKGS=$(go list ./... )
$for p in ${PKGS}; do
go test -covermode=count -coverprofile "cov/${package##*/}.cov" "$p" ;
done
$tail -q -n +2 cov/*.cov >> cov/total_coverage.cov
$go tool cover -func=cov/total_coverage.cov
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset