arlo-go/util.go
2020-05-27 15:35:02 +04:00

78 lines
1.5 KiB
Go

package arlo
import (
"fmt"
"io"
"math"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
func FloatToHex(x float64) string {
var result []byte
quotient := int(x)
fraction := x - float64(quotient)
for quotient > 0 {
quotient = int(x / 16)
remainder := int(x - (float64(quotient) * 16))
if remainder > 9 {
result = append([]byte{byte(remainder + 55)}, result...)
} else {
for _, c := range strconv.Itoa(int(remainder)) {
result = append([]byte{byte(c)}, result...)
}
}
x = float64(quotient)
}
if fraction == 0 {
return string(result)
}
result = append(result, '.')
for fraction > 0 {
fraction = fraction * 16
integer := int(fraction)
fraction = fraction - float64(integer)
if integer > 9 {
result = append(result, byte(integer+55))
} else {
for _, c := range strconv.Itoa(int(integer)) {
result = append(result, byte(c))
}
}
}
return string(result)
}
func genTransId() string {
random := rand.New(rand.NewSource(time.Now().UnixNano()))
e := random.Float64() * math.Pow(2, 32)
ms := time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
return fmt.Sprintf("%s!%s!%s", TransIdPrefix, strings.ToLower(FloatToHex(e)), strconv.Itoa(int(ms)))
}
func (a *Arlo) DownloadFile(url string, w io.Writer) error {
resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("getting %s: %v", url, err)
}
defer resp.Body.Close()
_, err = io.Copy(w, resp.Body)
if err != nil {
return fmt.Errorf("copying body to writer: %v", err)
}
return nil
}