Cloud Native programming with Golang
上QQ阅读APP看书,第一时间看更新

generate_cert.go

In the world of the Go language, there is another approach besides OpenSSL to generate self-signed certificates to utilize in our testing. If you go to the GOROOT folder, which is where the Go language is installed and then head to the /src/crypto/tls folder, you will find a file called generate_cert.go. This file is nothing but a simple tool that can easily and efficiently generate certificates for our testing pleasure. In my computer, the GOROOT folder is located at C:\Go. The following is a screenshot of the generate_cert.go file on my machine:

generate_cert.go file

The generate_cert.go is a self-contained Go program that can run simply via the go run command. Once you run it, it will create a certificate and private key files for you and place them in your current folder. The tool supports a number of arguments, but typically the most commonly used argument is --host, which indicates the name of the web server that we would like to generate the certificate and the key for. The following is how we would run the tool via the go run command:

go run %GOROOT%/src/crypto/tls/generate_cert.go --host=localhost

The preceding command was executed on the Windows operating system, which is why it represents the GOROOT environmental path variable as %GOROOT%. How the environmental variable is represented differs from one operating system to another. In the case of Linux, for example, the environmental variable would be represented as $GOROOT.

We will now instruct the command to build a certificate and a private key for a server called localhost. The command will generate the certificate and the key for us, then place them in the current folder, as mentioned earlier. Here is a screenshot showing a successful execution of the command:

generate_cert.go command

The generate_cert tool supports other options besides --host. It is worth it to cover some of them:

  • --start-date: This option indicates the start validation date of the certificate. The argument to this option needs to be formatted as Jan 1 15:04:05 2011, for example.
  • --duration: This option indicates the duration that the certificate is valid for in hours. The default value is a year.
  • --rsa-bits: This option indicates the number of bits to be utilized in the rsa encryption of the keys. The default value is 2,048.
  • --help: This provides a list of supported options with their descriptions.

Once the certificate and key files are generated, we can obtain and use them in our web server application in order to support HTTPS. We'll see how to do just that in the next section.