-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (74 loc) · 1.82 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
79
80
81
82
83
84
85
86
87
package main
import (
"flag"
"fmt"
"log/slog"
"os"
"path/filepath"
"strconv"
"time"
"github.com/ifooth/projecteuler-go/euler"
)
var (
version string
)
func parseArgs() (int, bool) {
problemId := flag.Int("n", 0, "euler problem num")
showContent := flag.Bool("c", false, "show euler problem content")
flagVersion := flag.Bool("v", false, "print version")
flag.Parse()
if *flagVersion {
fmt.Println("version:", version)
os.Exit(0)
}
if *problemId == 0 {
flag.Usage()
os.Exit(0)
}
return *problemId, *showContent
}
func main() {
problemId, showContent := parseArgs()
eulerProject := euler.NewEuler()
st := time.Now()
var answer int64
var err error
if showContent {
answer, err = euler.GetProblemContent(problemId)
if err != nil {
slog.Info("not login", "duration", time.Since(st))
} else {
slog.Info("show content done", "duration", time.Since(st))
}
}
st = time.Now()
result, err := eulerProject.Calculate(problemId)
if err != nil {
slog.Info("calculate failed", "duration", time.Since(st), "err", err)
os.Exit(0)
}
if err == nil {
slog.Info(fmt.Sprintf("result %d(solve) = %d(euler) is %t", result, answer, result == answer), "duration", time.Since(st))
os.Exit(0)
}
slog.Info("calculate done", "result", result, "duration", time.Since(st))
}
func init() {
textHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
ReplaceAttr: replaceAttrFunc,
})
logger := slog.New(textHandler)
slog.SetDefault(logger)
}
// SourceAttr source 格式化为 dir/file:line 格式
func replaceAttrFunc(groups []string, a slog.Attr) slog.Attr {
if a.Key != slog.SourceKey {
return a
}
if src, ok := a.Value.Any().(*slog.Source); ok {
a.Value = slog.StringValue(filepath.Base(src.File) + ":" + strconv.Itoa(src.Line))
}
return a
}