-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
79 lines (63 loc) · 1.68 KB
/
app.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
package main
import (
"context"
"fmt"
"io"
"log"
"strconv"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
const name = "go-fibonacci"
// App is a Fibonacci computation application.
type App struct {
r io.Reader
l *log.Logger
}
// NewApp returns a new App.
func NewApp(r io.Reader, l *log.Logger) *App {
return &App{r: r, l: l}
}
// Run starts polling users for Fibonacci numbers and writes results.
func (a *App) Run(ctx context.Context) error {
for {
// Each execution of the run loop, we should get a new "root" span and context
newCtx, span := otel.Tracer(name).Start(ctx, "Run")
n, err := a.Poll(newCtx)
if err != nil {
span.End()
return err
}
a.Write(ctx, n)
span.End()
}
}
// Poll asks a user for input and returns the request.
func (a *App) Poll(ctx context.Context) (uint, error) {
_, span := otel.Tracer(name).Start(ctx, "Poll")
defer span.End()
a.l.Print("What Fibonacci number would you like to know: ")
var n uint
_, err := fmt.Fscanf(a.r, "%d\n", &n)
// Store n as a string to not overflow an int64
nStr := strconv.FormatUint(uint64(n), 10)
span.SetAttributes((attribute.String("request.n", nStr)))
return n, err
}
// Write writes the nth Fibonacci number back to the user.
func (a *App) Write(ctx context.Context, n uint) {
var span trace.Span
ctx, span = otel.Tracer(name).Start(ctx, "Write")
defer span.End()
f, err := func(ctx context.Context) (uint64, error) {
_, span := otel.Tracer(name).Start(ctx, "Fibonacci")
defer span.End()
return Fibonacci(n)
}(ctx)
if err != nil {
a.l.Printf("Fibonacci(%d): %v\n", n, err)
} else {
a.l.Printf("Fibonacci(%d) = %d\n", n, f)
}
}