-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps.go
More file actions
39 lines (32 loc) · 1 KB
/
Copy pathhttps.go
File metadata and controls
39 lines (32 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package server
import (
"log"
"net/http"
"golang.org/x/crypto/acme/autocert"
)
func main_secondary() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, HTTPS!"))
})
// Autocert manager handles cert acquisition/renewal
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache("cert-cache"), // persist certs
HostPolicy: autocert.HostWhitelist("example.com", "www.example.com"),
}
// HTTP (port 80) serves ACME http-01 challenges + redirects
go func() {
log.Println(http.ListenAndServe(":80", m.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
target := "https://" + r.Host + r.URL.RequestURI()
http.Redirect(w, r, target, http.StatusMovedPermanently)
}))))
}()
// HTTPS (port 443) with TLS from autocert
srv := &http.Server{
Addr: ":443",
Handler: mux,
TLSConfig: m.TLSConfig(),
}
log.Fatal(srv.ListenAndServeTLS("", "")) // certs come from TLSConfig
}