-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
- Loading branch information
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package uptime | ||
|
||
import ( | ||
"strconv" | ||
"strings" | ||
"time" | ||
) | ||
|
||
// Clock interface makes it easier to test | ||
type Clock interface { | ||
Now() time.Time | ||
} | ||
|
||
type realClock struct{} | ||
|
||
func (r *realClock) Now() time.Time { | ||
return time.Now() | ||
} | ||
|
||
func parseLinuxUptime(uptime string) (float64, error) { | ||
parts := strings.Split(string(uptime), " ") | ||
secondsStr := strings.TrimSpace(parts[0]) | ||
return strconv.ParseFloat(secondsStr, 64) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package uptime | ||
|
||
import ( | ||
"time" | ||
) | ||
|
||
var start = time.Now() | ||
|
||
func Uptime() (time.Duration, error) { | ||
return time.Since(start), nil | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package uptime | ||
|
||
import "os" | ||
|
||
var ( | ||
rawUptimeImpl UptimeSource = &LinuxUptime{} | ||
clock Clock = &realClock{} | ||
) | ||
|
||
type UptimeSource interface { | ||
RawUptime() (float64, error) | ||
} | ||
|
||
func Uptime() (time.Duration, error) { | ||
Check failure on line 14 in internal/uptime/uptime_linux.go
|
||
seconds, err := rawUptimeImpl.RawUptime() | ||
if err != nil { | ||
return time.Time{}, fmt.Errorf("could not read raw uptime: %w", err) | ||
Check failure on line 17 in internal/uptime/uptime_linux.go
|
||
} | ||
|
||
return time.Second * time.Duration(seconds), nil | ||
Check failure on line 20 in internal/uptime/uptime_linux.go
|
||
} | ||
|
||
type LinuxUptime struct { | ||
} | ||
|
||
func (p *LinuxUptime) RawUptime() (float64, error) { | ||
uptime, err := os.ReadFile("/proc/uptime") | ||
if err != nil { | ||
return math.MaxFloat64, err | ||
Check failure on line 29 in internal/uptime/uptime_linux.go
|
||
} | ||
return parseLinuxUptime(uptime) | ||
Check failure on line 31 in internal/uptime/uptime_linux.go
|
||
} |