letsencrypt: rsc.io/letsencrypt Index | Files | Directories

package letsencrypt

import "rsc.io/letsencrypt"

Package letsencrypt obtains TLS certificates from LetsEncrypt.org.

LetsEncrypt.org is a service that issues free SSL/TLS certificates to servers that can prove control over the given domain's DNS records or the servers pointed at by those records.


Like any other random code you find on the internet, this package should not be relied upon in important, production systems without thorough testing to ensure that it meets your needs.

In the long term you should be using https://golang.org/x/crypto/acme/autocert instead of this package. Send improvements there, not here.

This is a package that I wrote for my own personal web sites (swtch.com, rsc.io) in a hurry when my paid-for SSL certificate was expiring. It has no tests, has barely been used, and there is some anecdotal evidence that it does not properly renew certificates in a timely fashion, so servers that run for more than 3 months may run into trouble. I don't run this code anymore: to simplify maintenance, I moved the sites off of Ubuntu VMs and onto Google App Engine, configured with inexpensive long-term certificates purchased from cheapsslsecurity.com.

This package was interesting primarily as an example of how simple the API for using LetsEncrypt.org could be made, in contrast to the low-level implementations that existed at the time. In that respect, it helped inform the design of the golang.org/x/crypto/acme/autocert package.

Quick Start

A complete HTTP/HTTPS web server using TLS certificates from LetsEncrypt.org, redirecting all HTTP access to HTTPS, and maintaining TLS certificates in a file letsencrypt.cache across server restarts.

package main

import (

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, TLS!\n")
	var m letsencrypt.Manager
	if err := m.CacheFile("letsencrypt.cache"); err != nil {


The fundamental type in this package is the Manager, which manages obtaining and refreshing a collection of TLS certificates, typically for use by an HTTPS server. The example above shows the most basic use of a Manager. The use can be customized by calling additional methods of the Manager.


A Manager m registers anonymously with LetsEncrypt.org, including agreeing to the letsencrypt.org terms of service, the first time it needs to obtain a certificate. To register with a particular email address and with the option of a prompt for agreement with the terms of service, call m.Register.


The Manager's GetCertificate method returns certificates from the Manager's cache, filling the cache by requesting certificates from LetsEncrypt.org. In this way, a server with a tls.Config.GetCertificate set to m.GetCertificate will demand load a certificate for any host name it serves. To force loading of certificates ahead of time, install m.GetCertificate as before but then call m.Cert for each host name.

A Manager can only obtain a certificate for a given host name if it can prove control of that host name to LetsEncrypt.org. By default it proves control by answering an HTTPS-based challenge: when the LetsEncrypt.org servers connect to the named host on port 443 (HTTPS), the TLS SNI handshake must use m.GetCertificate to obtain a per-host certificate. The most common way to satisfy this requirement is for the host name to resolve to the IP address of a (single) computer running m.ServeHTTPS, or at least running a Go TLS server with tls.Config.GetCertificate set to m.GetCertificate. However, other configurations are possible. For example, a group of machines could use an implementation of tls.Config.GetCertificate that cached certificates but handled cache misses by making RPCs to a Manager m on an elected leader machine.

In typical usage, then, the setting of tls.Config.GetCertificate to m.GetCertificate serves two purposes: it provides certificates to the TLS server for ordinary serving, and it also answers challenges to prove ownership of the domains in order to obtain those certificates.

To force the loading of a certificate for a given host into the Manager's cache, use m.Cert.

Persistent Storage

If a server always starts with a zero Manager m, the server effectively fetches a new certificate for each of its host name from LetsEncrypt.org on each restart. This is unfortunate both because the server cannot start if LetsEncrypt.org is unavailable and because LetsEncrypt.org limits how often it will issue a certificate for a given host name (at time of writing, the limit is 5 per week for a given host name). To save server state proactively to a cache file and to reload the server state from that same file when creating a new manager, call m.CacheFile with the name of the file to use.

For alternate storage uses, m.Marshal returns the current state of the Manager as an opaque string, m.Unmarshal sets the state of the Manager using a string previously returned by m.Marshal (usually a different m), and m.Watch returns a channel that receives notifications about state changes.


To avoid hitting basic rate limits on LetsEncrypt.org, a given Manager limits all its interactions to at most one request every minute, with an initial allowed burst of 20 requests.

By default, if GetCertificate is asked for a certificate it does not have, it will in turn ask LetsEncrypt.org for that certificate. This opens a potential attack where attackers connect to a server by IP address and pretend to be asking for an incorrect host name. Then GetCertificate will attempt to obtain a certificate for that host, incorrectly, eventually hitting LetsEncrypt.org's rate limit for certificate requests and making it impossible to obtain actual certificates. Because servers hold certificates for months at a time, however, an attack would need to be sustained over a time period of at least a month in order to cause real problems.

To mitigate this kind of attack, a given Manager limits itself to an average of one certificate request for a new host every three hours, with an initial allowed burst of up to 20 requests. Long-running servers will therefore stay within the LetsEncrypt.org limit of 300 failed requests per month. Certificate refreshes are not subject to this limit.

To eliminate the attack entirely, call m.SetHosts to enumerate the exact set of hosts that are allowed in certificate requests.

Web Servers

The basic requirement for use of a Manager is that there be an HTTPS server running on port 443 and calling m.GetCertificate to obtain TLS certificates. Using standard primitives, the way to do this is:

srv := &http.Server{
	Addr: ":https",
	TLSConfig: &tls.Config{
		GetCertificate: m.GetCertificate,
srv.ListenAndServeTLS("", "")

However, this pattern of serving HTTPS with demand-loaded TLS certificates comes up enough to wrap into a single method m.ServeHTTPS.

Similarly, many HTTPS servers prefer to redirect HTTP clients to the HTTPS URLs. That functionality is provided by RedirectHTTP.

The combination of serving HTTPS with demand-loaded TLS certificates and serving HTTPS redirects to HTTP clients is provided by m.Serve, as used in the original example above.


Package Files


func RedirectHTTP Uses

func RedirectHTTP(w http.ResponseWriter, r *http.Request)

RedirectHTTP is an HTTP handler (suitable for use with http.HandleFunc) that responds to all requests by redirecting to the same URL served over HTTPS. It should only be invoked for requests received over HTTP.

type Manager Uses

type Manager struct {
    // contains filtered or unexported fields

A Manager m takes care of obtaining and refreshing a collection of TLS certificates obtained by LetsEncrypt.org.

The zero Manager is not yet registered with LetsEncrypt.org and has no TLS certificates

but is nonetheless ready for use. See the package comment for an overview of how to use a Manager.

func (*Manager) CacheFile Uses

func (m *Manager) CacheFile(name string) error

func (*Manager) Cert Uses

func (m *Manager) Cert(host string) (*tls.Certificate, error)

Cert returns the certificate for the given host name, obtaining a new one if necessary.

As noted in the documentation for Manager and for the GetCertificate method, obtaining a certificate requires that m.GetCertificate be associated with host. In most servers, simply starting a TLS server with a configuration referring to m.GetCertificate is sufficient, and Cert need not be called.

The main use of Cert is to force the manager to obtain a certificate for a particular host name ahead of time.

func (*Manager) GetCertificate Uses

func (m *Manager) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate can be placed a tls.Config's GetCertificate field to make the TLS server use Let's Encrypt certificates. Each time a client connects to the TLS server expecting a new host name, the TLS server's call to GetCertificate will trigger an exchange with the Let's Encrypt servers to obtain that certificate, subject to the manager rate limits.

As noted in the Manager's documentation comment, to obtain a certificate for a given host name, that name must resolve to a computer running a TLS server on port 443 that obtains TLS SNI certificates by calling m.GetCertificate. In the standard usage, then, installing m.GetCertificate in the tls.Config both automatically provisions the TLS certificates needed for ordinary HTTPS service and answers the challenges from LetsEncrypt.org.

func (*Manager) Marshal Uses

func (m *Manager) Marshal() string

Marshal returns an encoding of the manager's state, suitable for writing to disk and reloading by calling Unmarshal. The state includes registration status, the configured host list from SetHosts, and all known certificates, including their private cryptographic keys. Consequently, the state should be kept private.

func (*Manager) Register Uses

func (m *Manager) Register(email string, prompt func(string) bool) error

Register registers the manager with letsencrypt.org, using the given email address. Registration may require agreeing to the letsencrypt.org terms of service. If so, Register calls prompt(url) where url is the URL of the terms of service. Prompt should report whether the caller agrees to the terms. A nil prompt func is taken to mean that the user always agrees. The email address is sent to LetsEncrypt.org but otherwise unchecked; it can be omitted by passing the empty string.

Calling Register is only required to make sure registration uses a particular email address or to insert an explicit prompt into the registration sequence. If the manager is not registered, it will automatically register with no email address and automatic agreement to the terms of service at the first call to Cert or GetCertificate.

func (*Manager) Registered Uses

func (m *Manager) Registered() bool

Registered reports whether the manager has registered with letsencrypt.org yet.

func (*Manager) Serve Uses

func (m *Manager) Serve() error

Serve runs an HTTP/HTTPS web server using TLS certificates obtained by the manager. The HTTP server redirects all requests to the HTTPS server. The HTTPS server obtains TLS certificates as needed and responds to requests by invoking http.DefaultServeMux.

Serve does not return unitil the HTTPS server fails to start or else stops. Either way, Serve can only return a non-nil error, never nil.

func (*Manager) ServeHTTPS Uses

func (m *Manager) ServeHTTPS() error

ServeHTTPS runs an HTTPS web server using TLS certificates obtained by the manager. The HTTPS server obtains TLS certificates as needed and responds to requests by invoking http.DefaultServeMux. ServeHTTPS does not return unitil the HTTPS server fails to start or else stops. Either way, ServeHTTPS can only return a non-nil error, never nil.

func (*Manager) SetHosts Uses

func (m *Manager) SetHosts(hosts []string)

SetHosts sets the manager's list of known host names. If the list is non-nil, the manager will only ever attempt to acquire certificates for host names on the list. If the list is nil, the manager does not restrict the hosts it will ask for certificates for.

func (*Manager) Unmarshal Uses

func (m *Manager) Unmarshal(enc string) error

Unmarshal restores the state encoded by a previous call to Marshal (perhaps on a different Manager in a different program).

func (*Manager) Watch Uses

func (m *Manager) Watch() <-chan struct{}

Watch returns the manager's watch channel, which delivers a notification after every time the manager's state (as exposed by Marshal and Unmarshal) changes. All calls to Watch return the same watch channel.

The watch channel includes notifications about changes before the first call to Watch, so that in the pattern below, the range loop executes once immediately, saving the result of setup (along with any background updates that may have raced in quickly).

m := new(letsencrypt.Manager)
go backgroundUpdates(m)
for range m.Watch() {


vendor/github.com/xenolf/lego/acmePackage acme implements the ACME protocol for Let's Encrypt and other conforming providers.

Package letsencrypt imports 20 packages (graph) and is imported by 50 packages. Updated 2019-01-25. Refresh now. Tools for package owners.