Chapter 5. Generated Go Main File (main.go)

Go code is normally generated from within the golang subdirectory in an ASN1C installation. At the main level, main.go and go.mod files are generated. The main.go file is a template file for using the files in the asn1gen package. The asn1gen package source is generated into an asn1gen subdirectory beneath the top-level directory. The main.go file contains a sample writer section to encode a data record of the chosen Protocol Data Unit (PDU) type and to a file. The reader section reads decodes from the file and prints the results. Each is invoked by running the main program with an argument of 'writer' or 'reader', respectively.

By default, the main.go writer section contains a TODO comment to remind the user that a data variable of the PDU type needs to be populated prior to encoding. If the -test command-line option is specified, code will be added to populate the PDU variable with random test data. If the - test-json command-line option is specified, a JSON file containing random test data is generated and code will be added to unmarshal this data into the PDU data variable.

The procedure to generate and build Go source code is rather straightforward:

  1. Invoke the asn1c compiler on your ASN.1 source file(s) to generate Go source code. For example: asn1c test.asn -go -per

  2. Invoke 'go build' to run the Go compiler to build the generated package.

That is it. If successful, an executable file should have been created which can be run with the writer or reader option.

Note that it is possible to use the - make command-line option to generate a makefile for future compilations. The user should also be careful to use the -no-go-main option on future compilations so as to not regenerate the main.go file in the event it was edited by the user.