@@ -16,16 +16,42 @@ var (
1616 out io.Writer = os .Stdout // modified during testing
1717)
1818
19- // Export Export the certificates from the target URL into a pem file
20- func Export (targetURL string , certIndexes []int , outputFile string ) error {
21- certs , err := c .FetchCertificates (targetURL )
19+ // ExportTo ExportTo the certificates from the target URL into a pem file
20+ func ExportTo (targetURL string , certIndexes []int , outputFile string ) error {
21+ data , cnt , err := Export (targetURL , certIndexes )
22+
23+ if err != nil {
24+ return err
25+ }
26+ var fileName string
27+ if outputFile != "" {
28+ fileName = outputFile
29+ } else {
30+ u , _ := url .Parse (targetURL )
31+ fileName = u .Host + ".pem"
32+ }
33+ f , err := os .Create (fileName )
34+
2235 if err != nil {
2336 return err
2437 }
25- return exportCerts (certs , targetURL , certIndexes , outputFile )
38+
39+ defer func () { _ = f .Close () }()
40+ _ , _ = f .Write (data )
41+ _ , _ = fmt .Fprintf (out , "pem file %s with %d certificate(s) created.\n " , fileName , cnt )
42+ return nil
2643}
2744
28- func exportCerts (certs []* x509.Certificate , targetURL string , certIndexes []int , outputFile string ) error {
45+ // Export Export the certificates from the target URL
46+ func Export (targetURL string , certIndexes []int ) ([]byte , int , error ) {
47+ certs , err := c .FetchCertificates (targetURL )
48+ if err != nil {
49+ return nil , 0 , err
50+ }
51+ return exportCerts (certs , certIndexes )
52+ }
53+
54+ func exportCerts (certs []* x509.Certificate , certIndexes []int ) ([]byte , int , error ) {
2955
3056 var pemBytes bytes.Buffer
3157 cnt := 0
@@ -34,31 +60,15 @@ func exportCerts(certs []*x509.Certificate, targetURL string, certIndexes []int,
3460 c .PrintAdd (i , cert )
3561 err := toPEM (& pemBytes , cert )
3662 if err != nil {
37- return err
63+ return nil , 0 , err
3864 }
3965 cnt ++
4066 } else {
4167 c .PrintSkip (i , cert )
4268 }
4369 }
4470
45- var fileName string
46- if outputFile != "" {
47- fileName = outputFile
48- } else {
49- u , _ := url .Parse (targetURL )
50- fileName = u .Host + ".pem"
51- }
52- f , err := os .Create (fileName )
53-
54- if err != nil {
55- return err
56- }
57-
58- defer f .Close ()
59- f .Write (pemBytes .Bytes ())
60- fmt .Fprintf (out , "pem file %s with %d certificate(s) created.\n " , fileName , cnt )
61- return nil
71+ return pemBytes .Bytes (), cnt , nil
6272}
6373
6474func toPEM (pemBytes * bytes.Buffer , cert * x509.Certificate ) error {
0 commit comments