Skip to content

Commit 72f4546

Browse files
committed
Add support POST all weight data
1 parent e593daa commit 72f4546

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

internal/weights.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ func SetWeights(config string, src []*core.Weight) error {
9191

9292
switch fields[0] {
9393
case "csv", "json":
94+
if strings.Contains(fields[1], "://") {
95+
return postFile(config, src)
96+
}
97+
9498
// important read file before os.Create
9599
dst := appendFile(config, src)
96100

@@ -234,6 +238,38 @@ func appendGarmin(config string, src []*core.Weight) error {
234238
return nil
235239
}
236240

241+
func postFile(config string, src []*core.Weight) (err error) {
242+
// skip zero weights
243+
dst := make([]*core.Weight, 0, len(src))
244+
for _, weight := range src {
245+
if weight.Weight != 0 {
246+
dst = append(dst, weight)
247+
}
248+
}
249+
250+
// sort weights (latest last)
251+
slices.SortFunc(dst, func(a, b *core.Weight) int {
252+
return a.Date.Compare(b.Date)
253+
})
254+
255+
body := bytes.NewBuffer(nil)
256+
257+
switch fields := strings.Fields(config); fields[0] {
258+
case "csv":
259+
if err = csv.Write(body, dst); err != nil {
260+
return err
261+
}
262+
_, err = http.Post(fields[1], "text/csv", body)
263+
case "json":
264+
if err = json.NewEncoder(body).Encode(dst); err != nil {
265+
return err
266+
}
267+
_, err = http.Post(fields[1], "application/json", body)
268+
}
269+
270+
return
271+
}
272+
237273
func postLatest(config string, src []*core.Weight) error {
238274
slices.SortFunc(src, func(a, b *core.Weight) int {
239275
return b.Date.Compare(a.Date) // latest first

0 commit comments

Comments
 (0)