feat: support Automatically install TLS certificates from Let's Encrypt. (#205)

* feat: support Automatically install TLS certificates from Let's Encrypt.

* refactor: update tls server.

* fix: missing tls package.

* fix: drop 1.6.x support

* docs: update readme.

* fix: listen tcp :443: bind: permission denied
This commit is contained in:
Bo-Yi Wu
2017-04-05 12:03:43 +08:00
committed by GitHub
parent 9b793cf80b
commit 97eae1fab4
19 changed files with 2723 additions and 25 deletions

View File

@@ -1,12 +1,14 @@
package gorush
import (
"crypto/tls"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/crypto/acme/autocert"
api "gopkg.in/appleboy/gin-status-api.v1"
)
@@ -70,6 +72,20 @@ func metricsHandler(c *gin.Context) {
promhttp.Handler().ServeHTTP(c.Writer, c.Request)
}
func autoTLSServer() *http.Server {
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(PushConf.Core.AutoTLS.Host),
Cache: autocert.DirCache(PushConf.Core.AutoTLS.Folder),
}
return &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
Handler: routerEngine(),
}
}
func routerEngine() *gin.Engine {
// set server mode
gin.SetMode(PushConf.Core.Mode)

View File

@@ -63,6 +63,17 @@ func TestRunTLSServer(t *testing.T) {
gofight.TestRequest(t, "https://localhost:8087/api/stat/go")
}
func TestRunAutoTLSServer(t *testing.T) {
initTest()
PushConf.Core.AutoTLS.Enabled = true
go func() {
assert.NoError(t, RunHTTPServer())
}()
// have to wait for the goroutine to start and run the server
// otherwise the main thread will complete
time.Sleep(5 * time.Millisecond)
}
func TestLoadTLSCertError(t *testing.T) {
initTest()

View File

@@ -10,10 +10,10 @@ import (
)
// RunHTTPServer provide run http or https protocol.
func RunHTTPServer() error {
var err error
if PushConf.Core.SSL && PushConf.Core.CertPath != "" && PushConf.Core.KeyPath != "" {
func RunHTTPServer() (err error) {
if PushConf.Core.AutoTLS.Enabled {
err = gracehttp.Serve(autoTLSServer())
} else if PushConf.Core.SSL && PushConf.Core.CertPath != "" && PushConf.Core.KeyPath != "" {
config := &tls.Config{
MinVersion: tls.VersionTLS10,
}
@@ -41,5 +41,5 @@ func RunHTTPServer() error {
})
}
return err
return
}

View File

@@ -7,14 +7,15 @@ import (
)
// RunHTTPServer provide run http or https protocol.
func RunHTTPServer() error {
var err error
if PushConf.Core.SSL && PushConf.Core.CertPath != "" && PushConf.Core.KeyPath != "" {
func RunHTTPServer() (err error) {
if PushConf.Core.AutoTLS.Enabled {
s := autoTLSServer()
err = s.ListenAndServeTLS("", "")
} else if PushConf.Core.SSL && PushConf.Core.CertPath != "" && PushConf.Core.KeyPath != "" {
err = http.ListenAndServeTLS(":"+PushConf.Core.Port, PushConf.Core.CertPath, PushConf.Core.KeyPath, routerEngine())
} else {
err = http.ListenAndServe(":"+PushConf.Core.Port, routerEngine())
}
return err
return
}