Skip to content

Using the Code Generator

leonklingele edited this page Dec 7, 2022 · 7 revisions

Intro

The msgp code generator takes Go code as input and spits out more Go code as output. More specifically, the msgp command takes the type definitions in a particular Go source file and outputs a number of methods for that type in order to serialize it to/from MessagePack.

Generated Methods

By default, the generator generates implementations for all of the following interfaces:

  • msgp.Marshaler
  • msgp.Unmarshaler
  • msgp.Sizer
  • msgp.Decodable
  • msgp.Encodable

Additionally, the generator will generate tests and benchmarks for the implemented methods. You can turn the generation of particular method sets and tests on and off with flags passed to the generator.

Options

The following flags are supported:

  • -o - output file name (default is {input}_gen.go)
  • -file - input file name (default is $GOFILE, which are set by the go generate command)
  • -io - satisfy the msgp.Decodable and msgp.Encodable interfaces (default is true)
  • -marshal - satisfy the msgp.Marshaler and msgp.Unmarshaler interfaces (default is true)
  • -tests - generate tests and benchmarks (default is true)
  • -unexported - also process unexported types (default is false)
  • -v - verbose diagnostics (default is false)

Using the Generator with go generate

If you want to run the generator with the default options, all you need to include in your source file is one commented line:

//go:generate msgp

Provided that you have msgp and the go generate tool installed, all you should have to do is run go generate in the same directory as your source file to invoke the generator.

If, for example, you wanted the output file to be called stuff.go and you didn't want to generate tests, you would instead use:

//go:generate msgp -o=stuff.go -tests=false

Ignoring specific types

To prevent code to be generated for some of your types, you can use a directive like so:

//msgp:ignore typename

Invoking the Generator Manually

If you want to run the generator without using go generate, the -file flag becomes non-optional. If you wanted to run the generator on my_types.go, then you would run, in the source directory (assuming msgp was installed and $GOBIN is in your $PATH):

msgp -file=my_types.go

which would generate my_types_gen.go and my_types_gen_test.go.