Remove source path from Go’s panic stack trace

I would like to share the Golang’s build flag to remove the source path (GOPATH) from panic stack trace output. In production environments or commercial projects it is sometimes not ideal to display the source path because of privacy, security or other reasons.

Below is an example of a stack trace output that reveals the GOPATH location which is located inside the developer’s home directory. In this case /home/johnpili/go/

panic: Aw, snap
 goroutine 1 [running]:
 main.main()
         /home/johnpili/go/src/company.com/event-document-pusher/main.go:42 +0x3e

Build using flags with trimpath

The solution I found is to use build flags with -trimpath.

go build -gcflags=-trimpath=$GOPATH -asmflags=-trimpath=$GOPATH

After posting this blog a reddit user commented that as of Go 1.13 -trimpath can be directly used. I tested and it worked flawlessly.

go build -trimpath

Stack trace output with trimmed-out source path

Using the said build flags the stack trace output looks like this:

panic: Aw, snap
 goroutine 1 [running]:
 main.main()
         src/company.com/event-document-pusher/main.go:42 +0x3e

I hope this post can help other fellow developer with similar requirement or situation. I recommend to further read Go compile packages and dependencies

References

https://github.com/golang/go/issues/13809

https://golang.org/cmd/go/#hdr-Compile_packages_and_dependencies

Leave a Reply