/
http.go
71 lines (59 loc) · 1.53 KB
/
http.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
package internal
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/chyroc/mkcert"
"github.com/gin-gonic/gin"
)
func Listen(handler *gin.Engine, isHttps bool) error {
listener, port, err := CreateLocalListener()
if err != nil {
return err
}
hosts, err := getEnableHttpsHost()
if err != nil {
return err
}
if isHttps {
certFile, keyFile, err := createCACert(hosts)
if err != nil {
return err
}
printListener(isHttps, hosts, port)
return http.ServeTLS(listener, handler, workDirCert+"/"+certFile, workDirCert+"/"+keyFile)
}
printListener(isHttps, hosts, port)
return handler.RunListener(listener)
}
func createCACert(hosts []string) (string, string, error) {
cache := newCache(workDirCert + "/cache.json")
key := strings.Join(hosts, "-")
item := cache.Get(key)
if item != nil {
return item.Cert, item.Key, nil
}
fmt.Printf("https=tre, should create local CA and create certificate.\n")
if _, err := mkcert.Install(); err != nil {
return "", "", err
}
info, err := mkcert.CreateCertificate(hosts)
if err != nil {
return "", "", err
}
os.Rename(info.CertFile, workDirCert+"/"+info.CertFile)
os.Rename(info.KeyFile, workDirCert+"/"+info.KeyFile)
cache.Set(key, &cert{Cert: info.CertFile, Key: info.KeyFile}, info.Expiration)
return info.CertFile, info.KeyFile, nil
}
func printListener(isHttps bool, hosts []string, port int) {
scheme := "http"
if isHttps {
scheme = "https"
}
fmt.Printf("Serve Listening at:\n")
for _, v := range hosts {
fmt.Printf("\t%s://%s:%d\n", scheme, v, port)
}
}