kettlebell-tracker/internal/services/api.go

78 lines
1.8 KiB
Go

package services
import (
"bytes"
"encoding/json"
"log"
"net/http"
"time"
"git.patanix.de/git/kettlebell-app/internal/data"
)
type TrainingPayload struct {
Reps int `json:"reps"`
Rest float64 `json:"rest"`
Sets int `json:"sets"`
UUID string `json:"uuid"`
}
type ApiService struct {
client *http.Client
endpoint string
uuid string
}
func NewApiService(appUUID string) *ApiService {
return &ApiService{
client: &http.Client{
Timeout: 5 * time.Second,
},
endpoint: "http://192.168.178.43:8080/trainings/",
uuid: appUUID,
}
}
func (s *ApiService) SendTrainingData(session *data.TrainingSession) {
var rest float64
if session.Sets > 0 {
rest = float64(session.Duration) / float64(session.Sets)
}
payload := TrainingPayload{
Reps: int(session.RepsPerSet),
Rest: rest,
Sets: int(session.Sets),
UUID: s.uuid,
}
jsonData, err := json.Marshal(payload)
if err != nil {
log.Printf("API Fehler: Konnte Payload nicht in JSON umwandeln: %v", err)
return
}
req, err := http.NewRequest("POST", s.endpoint, bytes.NewBuffer(jsonData))
if err != nil {
log.Printf("API Fehler: Konnte Request nicht erstellen: %v", err)
return
}
req.Header.Set("Content-Type", "application/json")
log.Printf("Sende Training an Backend: %s", string(jsonData))
resp, err := s.client.Do(req)
if err != nil {
log.Printf("API Fehler: Fehler beim Senden des Trainings: %v", err)
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated {
log.Println("Training erfolgreich an Backend gesendet.")
} else {
log.Printf("API Fehler: Unerwarteter Statuscode: %s", resp.Status)
// Optional: Den Body der Antwort lesen, um mehr Details zu erhalten.
// body, _ := io.ReadAll(resp.Body)
// log.Printf("Antwort-Body: %s", string(body))
}
}