Search code examples
gosslcertificatewebserver

Need help automating TLS Cert Handling in Go


I have a simple Go webserver and I want it to use TLS certificates. I know certbot, the python application, and used it frequently so far, but I would like to pretty much automate everything. That's where I stumbled upon https://github.com/caddyserver/certmagic, which is pretty awesome. However, I cannot seem to wrap my head around using it in conjunction with a custom server struct.

srv := http.Server{
    ReadTimeout: 1 * time.Second,
    WriteTimeout: 2 * time.Second,
    IdleTimeout: 10 * time.Second,
    ReadHeaderTimeout: 2 * time.Second,
    Handler: router,
    Addr: serverAddr,
}

if fileExists(serverCertFile) && fileExists(serverKeyFile) {
    if err := srv.ListenAndServeTLS(serverCertFile, serverKeyFile); err != nil && err != http.ErrServerClosed {
        panic("Couldn't start server with TLS")
    }
} else {
    if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        panic("Couldn't start server")
    }
}

This is the way I approached the problem so far, just using manually requested certificates. Any suggestions?


Solution

  • The docs here suggest to use Listen() instead of HTTPS() to make use of your own http.Server values.

    listener, err := certmagic.Listen([]string{"yourdomain.com"})
    
    srv := http.Server{
        ReadTimeout: 1 * time.Second,
        WriteTimeout: 2 * time.Second,
        IdleTimeout: 10 * time.Second,
        ReadHeaderTimeout: 2 * time.Second,
        Handler: router,
        Addr: serverAddr,
    }
    
    srv.Serve(listener)
    

    Document for Listent()

    Listen manages certificates for domainName and returns a TLS listener. It uses the Default config. Because this convenience function returns only a TLS-enabled listener and does not presume HTTP is also being served, the HTTP challenge will be disabled. The package variable Default is modified so that the HTTP challenge is disabled. Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service.