-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.go
89 lines (73 loc) · 1.52 KB
/
fetch.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
79
80
81
82
83
84
85
86
87
88
89
package cmd
import (
"errors"
"fmt"
"net/url"
"os"
"strings"
"text/tabwriter"
"github.com/chenzhiwei/certctl/pkg/cert"
"github.com/spf13/cobra"
)
var (
noout bool
file string
fetchCmd = &cobra.Command{
Use: "fetch url",
Short: "Fetch the certificate from url",
Args: cobra.MinimumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
if err := runFetch(args); err != nil {
return err
}
return nil
},
}
)
func init() {
fetchCmd.Flags().BoolVar(&noout, "noout", false, "do not print the certificate info")
fetchCmd.Flags().StringVar(&file, "file", "", "save the certificate to a file")
}
func runFetch(args []string) error {
s := args[0]
if s == "" {
return errors.New("something went wrong")
}
if !strings.Contains(s, "://") {
s = "https://" + s
}
u, err := url.Parse(s)
if err != nil {
return err
}
if u.Scheme == "http" {
return errors.New("can't fetch certificate with http")
}
host := u.Host
if !strings.Contains(host, ":") && u.Scheme == "https" {
host = host + ":443"
}
certBytes, err := cert.FetchCert(host)
if err != nil {
return err
}
if file != "" {
if err := os.WriteFile(file, certBytes, 0644); err != nil {
return err
}
}
if !noout {
result, err := cert.GetCertInfo(certBytes)
if err != nil {
return err
}
writer := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', tabwriter.AlignRight)
for _, info := range result {
for k, v := range info {
fmt.Fprintf(writer, "%s\t%s\n", k, v)
}
}
writer.Flush()
}
return nil
}