From 4bde5943fa9bee99e8ad1e570d05e142cbacade7 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Wed, 3 Jul 2024 11:27:40 +0300 Subject: add safe errors --- internal/easyhttp/easyhttp.go | 20 ++++++++++++++++++-- internal/easyhttp/saferrors.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 internal/easyhttp/saferrors.go diff --git a/internal/easyhttp/easyhttp.go b/internal/easyhttp/easyhttp.go index ca10a8e..bb963ad 100644 --- a/internal/easyhttp/easyhttp.go +++ b/internal/easyhttp/easyhttp.go @@ -1,6 +1,7 @@ package easyhttp import ( + "errors" "fmt" "io" "net/http" @@ -45,6 +46,21 @@ func GetData[T any](uri, apiKey string, data *T) error { } // Submiut structure as JSON to API -func SubmitData[T any](servers []string, uri, apiKey string, data *T) error { - return nil +func PostData[T any](uri, apiKey string, data *T, servers ...string) error { + if len(servers) == 0 { + return fmt.Errorf("no server configured") + } + var errs SafeErrors + + for _, server := range servers { + go func(server string){ + errs.Append(postData[T](fmt.Sprintf("%s/%s"), apiKey, data)) + }(server) + } + + return errs.Join() +} + +func postData[T any](uri, apiKey string, data * T) error { + return fmt.Errorf("not yet implemented to post to: %s", uri) } diff --git a/internal/easyhttp/saferrors.go b/internal/easyhttp/saferrors.go new file mode 100644 index 0000000..32dd77f --- /dev/null +++ b/internal/easyhttp/saferrors.go @@ -0,0 +1,31 @@ +package easyhttp + +import ( + "errors" + "sync" +) + +// Safe errors +type SafErrors struct { + errs []error + mutex sync.Mutex +} + +func (errs *SafErrors) Append(err error) { + if err == nil { + return + } + errs.mutex.Lock() + defer errs.mutex.Unlock() + errs.errs = append(errs.errs, err) +} + +func (errs *SafErrors) Join() error { + errs.mutex.Lock() + defer errs.mutex.Unlock() + return errors.Join(errs.errs...) +} + +func (errs *SafErrors) Error() string { + return errs.Join().Error() +} -- cgit v1.2.3