main amadaluzia/webfetch / internal / uptime.go
 1package internal
 2
 3import (
 4	"bytes"
 5	"fmt"
 6	"math"
 7	"strconv"
 8)
 9
10// Uptime of the system
11type Uptime struct {
12	Days    int
13	Hours   int
14	Minutes int
15	Seconds int
16}
17
18func (up *Uptime) UnmarshalText(text []byte) error {
19	times := bytes.Split(text, []byte{' '})
20	if len(times) < 2 {
21		return fmt.Errorf("there must be more than one time")
22	}
23	upSeconds, err := strconv.ParseFloat(string(times[0]), 32)
24	if err != nil {
25		return fmt.Errorf("failed to parse seconds to float: %v", err)
26	}
27	up.Days = int(math.Floor(upSeconds)) / 86400
28	up.Hours = int(math.Floor(upSeconds)) / 3600 % 24
29	up.Minutes = int(math.Floor(upSeconds)) / 60 % 60
30	up.Seconds = int(math.Floor(upSeconds)) % 60
31	return nil
32}
33
34func (up Uptime) String() string {
35	return fmt.Sprintf("%d days, %d hours, %d minutes and %d seconds", up.Days, up.Hours, up.Minutes, up.Seconds)
36}