-
Notifications
You must be signed in to change notification settings - Fork 36
/
main.go
78 lines (63 loc) · 1.48 KB
/
main.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"context"
"crypto/tls"
"encoding/pem"
"fmt"
"log"
"net/http"
"time"
"github.com/dgrr/http2"
"github.com/valyala/fasthttp"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
)
func main() {
hostName := "example.com"
cert, priv, err := configureCert(hostName)
if err != nil {
log.Fatalln(err)
}
s := &fasthttp.Server{
Handler: requestHandler,
Name: "http2 test",
}
http2.ConfigureServer(s)
log.Println("fasthttp", s.ListenAndServeTLSEmbed(":443", cert, priv))
}
func configureCert(hostName string) ([]byte, []byte, error) {
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(hostName),
Cache: autocert.DirCache("./certs"),
}
cfg := &tls.Config{
GetCertificate: m.GetCertificate,
NextProtos: []string{
acme.ALPNProto,
},
}
s := &http.Server{
Addr: ":80",
Handler: m.HTTPHandler(nil),
TLSConfig: cfg,
}
go s.ListenAndServe()
time.Sleep(time.Second * 10)
s.Shutdown(context.Background())
data, err := m.Cache.Get(context.Background(), hostName)
if err != nil {
return nil, nil, err
}
priv, restBytes := pem.Decode(data)
cert, _ := pem.Decode(restBytes)
return pem.EncodeToMemory(cert), pem.EncodeToMemory(priv), nil
}
func requestHandler(ctx *fasthttp.RequestCtx) {
fmt.Printf("%s\n", ctx.Request.Header.Header())
if ctx.Request.Header.IsPost() {
fmt.Fprintf(ctx, "%s\n", ctx.Request.Body())
} else {
fmt.Fprintf(ctx, "Hello 21th century!\n")
}
}