如何为 Go 服务器应用程序设置 Let's Encrypt [英] How to set up Let's Encrypt for a Go server application

查看:19
本文介绍了如何为 Go 服务器应用程序设置 Let's Encrypt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have my own domain with web services written in Go. I am using the inbuilt Go web server, without Nginx or Apache in front.

I would like to start serving over HTTPS and I realized Let's Encrypt is just about to become THE WAY for doing that.

Can anyone share the whole setup procedure for configuring a Go app running on a Linux server?

解决方案

This is the minimal automatic setup of an HTTPS server using Go and Let's Encrypt certificates I have found:

package main

import (
    "crypto/tls"
    "log"
    "net/http"

    "golang.org/x/crypto/acme/autocert"
)

func main() {
    certManager := autocert.Manager{
        Prompt:     autocert.AcceptTOS,
        HostPolicy: autocert.HostWhitelist("example.com"), //Your domain here
        Cache:      autocert.DirCache("certs"),            //Folder for storing certificates
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello world"))
    })

    server := &http.Server{
        Addr: ":https",
        TLSConfig: &tls.Config{
            GetCertificate: certManager.GetCertificate,
        },
    }

    go http.ListenAndServe(":http", certManager.HTTPHandler(nil))

    log.Fatal(server.ListenAndServeTLS("", "")) //Key and cert are coming from Let's Encrypt
}

More information on the autocert package: link

EDIT: Needed to make http available because of letsencrypt security issue, read more here. As a bonus of this fix we now have http-->https redirect. The old example will continue to work if you have already received certificates on it, but it will break for new sites.

这篇关于如何为 Go 服务器应用程序设置 Let's Encrypt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆