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

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

问题描述

我拥有自己的域,并使用Go编写的Web服务。我正在使用内置Go Web服务器,前面没有Nginx或Apache。



我想通过HTTPS开始服务,我意识到Let's Encrypt即将成为这样做。



任何人都可以共享整个设置过程来配置在Linux服务器上运行的Go应用程序吗?

解决方案

这是使用Go和Let's Encrypt证书对HTTPS服务器的最小自动设置,我发现:

 包主
$ b导入(
加密/ tls
记录
净/ http

golang.org/x/crypto/acme/autocert


func main(){
certManager:= autocert.Manager {
提示: autocert.AcceptTOS,
HostPolicy:autocert.HostWhitelist(example.com),//您的域在这里
缓存:autocert.DirCache(certs),//用于存储证书的文件夹
}

http.HandleFu nc(/,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和Cert来自Let's Encrypt
}

更多关于autocert包:链接



编辑:需要使http可用,因为 letsencrypt安全问题,阅读更多此处。作为此修补程序的奖励,我们现在有http - > https重定向。如果您已经收到证书,那么旧示例将继续工作,但会在新网站中破解。

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服务器应用程序加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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