Deploying HTTPS using go and let's encrypt certificates

Source: Internet
Author: User
Tags call back cloudflare free ssl free ssl certificate ssl certificate
This is a creation in Article, where the information may have evolved or changed.

Why use HTTPS? What are the ways to use HTTPS? How do I use go to deploy HTTPS? Take out your little laptop, and all the dry goods you need are here!

The benefits of HTTPS have improved a lot in previous articles. It encrypts the traffic between the browser and the server, to ensure the security of your password transmission, so that your page load quickly, to help the SEO optimization of the site and the HTTP site of a variety of dislike browser vendors ... These are the reasons for using HTTPS. So the question is, how can we deploy HTTPS quickly and well?

Using HTTPS provided by a third party

For example, CloudFlare, their free solution provides an imitation HTTPS proxy service for your HTTP-only Web site.

To use CloudFlare:

Configure your domain to use the CloudFlare DNS server

In CloudFlare DNS settings, point the domain to your server and set the "status" to "DNS and HTTP proxy server (CDN)"

In CloudFlare encryption settings, set SSL to "flexible" (this option allows the browser to talk to CloudFlare via HTTPS, CloudFlare to the browser via HTTP)

Configure the CloudFlare HTTPS proxy in the Web management interface to provide the IP address of your server.

In addition, enable the "Always use HTTPS" option

The browser communicates with CloudFlare, CloudFlare is responsible for providing the SSL certificate and acting on the communication to your server. Because of the extra traffic, this can slow down the network, or it may be because the CloudFlare server is faster than your server (which is their job faster), causing the network to become faster.

AWS, Google Cloud, and other host service providers also offer free HTTPS services for servers hosted on them.

Another option is to run your server behind a reverse proxy server that supports HTTPS (such as Caddy).

Direct HTTPS support

A long time ago, to want an SSL certificate must spend a lot of money on a domain name every year. And now, let's encrypt changed it all.

This is a nonprofit organization that provides free certificates and provides HTTP APIs to obtain certificates. The API allows automation to handle this process.

Before let's encrypt appears, you may buy a certificate, which is just a bunch of bytes. You will store the certificate in a file and configure your Web server to use it.

With Let's encrypt, you'll be able to use their APIs to get certificates for free, and this process is done automatically after your server starts.

Thankfully, all the hard work of talking to the API is done by others. We just need to install the plugin on it.

There are two go libraries that enable let's encrypt support.

I've been using, which was developed by Go's core developers.

It's been a few months now and it's running all right.

Here's how to start an HTTPS network server that uses the free SSL certificate provided by let ' s encrypt.

For a complete example, see: Free-ssl-certificates/main.go.

Const (

Htmlindex = ' welcome! '

Inproduction = True


Func Handleindex (w http. Responsewriter, R *http. Request) {

Io. WriteString (W, Htmlindex)


Func makehttpserver () *http. Server {

MUX: = &http. servemux{}

Mux. Handlefunc ("/", Handleindex)

Set timeouts so a slow or malicious client doesn ' t

Hold Resources forever

Return &http. server{

Readtimeout:5 * time. Second,

Writetimeout:5 * time. Second,

idletimeout:120 * time. Second,




Func Main () {

var httpssrv *http. Server

When testing locally it doesn ' t do sense to start

HTTPS server, so only does it in production.

In real code, I control this with-production cmd-line flag

If inproduction {

Note:use a sensible value for data directory

This is the where cached certificates is stored

DataDir: = "."

Hostpolicy: = Func (CTX context. Context, host string) error {

Note:change to your real domain

Allowedhost: = ""

If host = = Allowedhost {

return Nil


Return to FMT. Errorf ("Acme/autocert:only%s host is allowed", allowedhost)


Httpssrv = Makehttpserver ()

M: = Autocert. manager{

Prompt:autocert. Accepttos,


Cache:autocert. Dircache (DataDir),



Httpssrv.tlsconfig = &tls. Config{getcertificate:m.getcertificate}

Go func () {

ERR: = Httpssrv.listenandservetls ("", "")

If err! = Nil {

Log. Fatalf ("Httpssrv.listendandservetls () failed with%s", err)




Httpsrv: = Makehttpserver ()


ERR: = Httpsrv.listenandserve ()

If err! = Nil {

Log. Fatalf ("Httpsrv.listenandserve () failed with%s", err)


It is important to note that:

The standard port for HTTPS is 443.

You can run only HTTP, run only HTTPS, or both.

If the server does not have a certificate, it will use the HTTP API to request a certificate from the Let's encrypt server.

These requests are limited to 20 processing per week to avoid overloading the Let ' s encrypt server.

Therefore, it is important to cache the certificate somewhere. In our example, we cache the certificate to disk, using Autocert. Dircache command.

The cache is just an interface, so you can execute what you have stored in a SQL database or Redis.

You must properly install DNS.

To verify that you are indeed the owner of the domain where you are applying for the certificate, let's encrypt server will call back to your server.

In order to work properly, the DNS name must be resolved to the IP address of your server.

This means that HTTPS code-local testing of the path is difficult. I don't usually do this.

If you really want to do this, you can use Ngrok to expose your local port to the Internet, set up DNS to resolve your domain name to the public DNS created by Ngrok, and then wait for the confirmation DNS information to be passed to the computer that let ' s encrypt.

You may wonder: What is this hostpolicy business?

As I mentioned, let's encrypt limits the certificate provisioning, so you need to make sure that the server doesn't ask for a certificate from the domain you don't care about. Autocert's documentation is a good explanation for this.

Our example assumes the most common scenario: a server responds to only one domain. You can easily change this.

When testing locally, we do not run HTTPS.

When doing local testing on your laptop, it makes no sense to run the HTTPS version.

Your computer probably doesn't have a visible public IP address, so let's encrypt server can't reach you there, so you won't get a certificate.

We also cannot bind to HTTPS port 443 (only the root process can bind to ports below 1024).

In this example, I use the INPRODUCTION flag to determine whether the HTTPS server should be started.

In the actual code, I'll add the code to check the-production command line flag and use it.

redirect from http to https

If you can use HTTPS, it makes no sense to provide pure HTTP.

We can redirect all HTTP requests to the same https for better security and search engine optimization effects.

Func Makeserverfrommux (Mux *http. Servemux) *http. Server {

Set timeouts so a slow or malicious client doesn ' t

Hold Resources forever

Return &http. server{

Readtimeout:5 * time. Second,

Writetimeout:5 * time. Second,

idletimeout:120 * time. Second,




Func makehttptohttpsredirectserver () *http. Server {

Handleredirect: = Func (w http. Responsewriter, R *http. Request) {

Newuri: = "https://" + + r.url. String ()

http. Redirect (W, R, Newuri, http. Statusfound)


MUX: = &http. servemux{}

Mux. Handlefunc ("/", Handleredirect)

Return Makeserverfrommux (MUX)


Func Main () {

Httpsrv: = Makehttptohttpsredirectserver ()


Fmt. Printf ("Starting HTTP server on%s\n", HTTPSRV.ADDR)

ERR: = Httpsrv.listenandserve ()

If err! = Nil {

Log. Fatalf ("Httpsrv.listenandserve () failed with%s", err)



The technical section ends here.

Where does the free certificate come from?

There is a view that, due to a design error, the SSL protocol not only encrypts, but also proves the identity of the website to the browser. It bears responsibility so that we can track the owner of the website and see that the site is indeed owned by Google Inc. of the United States, and not by the Moscow hacker Ivan.

We only trust a very small number of companies (certification authorities) to issue certificates that prove the identity of the site owner.

When you apply for a certificate, the certification authority must verify your identity. They do the work by looking at your files.

Verification of documents requires manpower. It also requires manpower to ensure certificate security. It is reasonable for the certification authority to charge for issuing the certificate.

Trust is not proportional. Browsers and operating system vendors can trust 10 companies not to issue invalid certificates, but they cannot trust 1000.

We don't want any company to turn into a cheat certificate authority, and then issue the domain certificate for the hacker Ivan.

It will take a lot of effort to continuously audit thousands of certification authorities in order to get only a few desirable results.

Controlling the market by a handful of companies is likely to lead to monopolies, so prices will remain high due to a lack of competition.

This is exactly what the SSL certificate market is currently doing. You can have a low-end server for only $60 a year, but a certificate is more expensive than that.

This is a problem because the cost of SSL certificates is a significant barrier to all sites adopting encryption technology.

A handful of companies have decided to share their resources to solve the problem, which is more beneficial to the entire Internet. So they financed a certification authority such as Let's encrypt, then compiled some necessary software and operated the server that issued the certificate.

This is the origin of the free certificate.

For more information please see Asia Integrity official Number: Trustasia_ssl

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.