Skip to content

Commit 3e56ea3

Browse files
committed
Add JSON output support for results (#45)
1 parent ea1a4db commit 3e56ea3

2 files changed

Lines changed: 30 additions & 4 deletions

File tree

keygen/worker.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ type Cruncher struct {
4949

5050
// Pair struct
5151
type Pair struct {
52-
Private string
53-
Public string
52+
Private string `json:"private"`
53+
Public string `json:"public"`
5454
}
5555

5656
// New returns a Cruncher

main.go

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
package main
33

44
import (
5+
"encoding/json"
56
"fmt"
67
"os"
8+
"path/filepath"
79
"regexp"
810
"runtime"
911
"strings"
@@ -50,11 +52,13 @@ func main() {
5052
}
5153

5254
var summary, showVersion, update bool
55+
var jsonFile string
5356
flag.BoolVarP(&summary, "summary", "s", false, "print results when all are found (default false)")
5457
flag.BoolVarP(&options.CaseSensitive, "case-sensitive", "c", false, "case sensitive match (default false)")
5558
flag.IntVarP(&options.Threads, "threads", "t", options.Cores, "threads")
5659
flag.IntVarP(&options.LimitResults, "limit", "l", 1, "limit results to n (exists after)")
5760
flag.StringVarP(&options.Timeout, "timeout", "T", "", "quit after n minutes (allowed suffixes: s/m/h) (default \"\")")
61+
flag.StringVarP(&jsonFile, "json", "j", "", "write results to JSON file")
5862
flag.BoolVarP(&showVersion, "version", "v", false, "show app version")
5963
flag.BoolVarP(&update, "update", "u", false, "update to latest release")
6064

@@ -174,15 +178,37 @@ func main() {
174178
}
175179

176180
fmt.Printf("\nPress Ctrl-c to cancel\n\n")
177-
if !summary {
181+
182+
var results []keygen.Pair
183+
if !summary && jsonFile == "" {
178184
c.Find(func(match keygen.Pair) {
179185
fmt.Printf("private: %s public: %s\n", match.Private, match.Public)
180186
})
181187
} else {
182-
for _, match := range c.CollectToSlice() {
188+
results = c.CollectToSlice()
189+
for _, match := range results {
183190
fmt.Printf("private: %s public: %s\n", match.Private, match.Public)
184191
}
185192
}
193+
194+
if jsonFile != "" {
195+
jsonFile = filepath.Clean(jsonFile)
196+
if results == nil {
197+
results = []keygen.Pair{}
198+
}
199+
data, err := json.MarshalIndent(struct {
200+
Results []keygen.Pair `json:"results"`
201+
}{Results: results}, "", " ")
202+
if err != nil {
203+
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err)
204+
os.Exit(1)
205+
}
206+
if err := os.WriteFile(jsonFile, data, 0644); err != nil {
207+
fmt.Fprintf(os.Stderr, "Error writing JSON file: %v\n", err)
208+
os.Exit(1)
209+
}
210+
fmt.Printf("\nResults written to %s\n", jsonFile)
211+
}
186212
}
187213

188214
// parseTimeout parses the timeout string to a time.Duration. If the input is

0 commit comments

Comments
 (0)