From 8e15d802865ed57db0018c15ea5559c8bd44c01f Mon Sep 17 00:00:00 2001 From: Keuin Date: Wed, 7 Sep 2022 02:48:46 +0800 Subject: First working version. Just a POC. --- common/orelse.go | 20 ++++++++++++++++++++ common/retry.go | 35 +++++++++++++++++++++++++++++++++++ common/types.go | 3 +++ common/urlparse.go | 21 +++++++++++++++++++++ 4 files changed, 79 insertions(+) create mode 100644 common/orelse.go create mode 100644 common/retry.go create mode 100644 common/types.go create mode 100644 common/urlparse.go (limited to 'common') diff --git a/common/orelse.go b/common/orelse.go new file mode 100644 index 0000000..a96bde7 --- /dev/null +++ b/common/orelse.go @@ -0,0 +1,20 @@ +package common + +type Opt[T any] struct { + thing T + err error +} + +func Optional[T any](thing T, err error) Opt[T] { + return Opt[T]{ + thing: thing, + err: err, + } +} + +func (o Opt[T]) OrElse(thing T) T { + if o.err != nil { + return thing + } + return o.thing +} diff --git a/common/retry.go b/common/retry.go new file mode 100644 index 0000000..6b97ff3 --- /dev/null +++ b/common/retry.go @@ -0,0 +1,35 @@ +package common + +import ( + "log" + "time" +) + +// AutoRetry retries the supplier automatically, with given time limit and interval. +// If maximum retry time limit is reached and the supplier still fails, +// the last error will be returned. +// If logger is not nil, retry information will be printed to it. +func AutoRetry[T any]( + supplier func() (T, error), + maxRetryTimes int, + retryInterval time.Duration, + logger *log.Logger) (T, error) { + var err error + for i := 0; i < maxRetryTimes; i++ { + ret, err := supplier() + if err != nil { + if logger != nil { + logger.Printf("Try %v/%v (sleep %vs): %v\n", + i, maxRetryTimes, retryInterval, err) + } + time.Sleep(retryInterval) + continue + } + // success + return ret, nil + } + if logger != nil { + logger.Printf("Max retry times reached, but it still fails. Last error: %v", err) + } + return *new(T), err +} diff --git a/common/types.go b/common/types.go new file mode 100644 index 0000000..81456b4 --- /dev/null +++ b/common/types.go @@ -0,0 +1,3 @@ +package common + +type RoomId uint64 diff --git a/common/urlparse.go b/common/urlparse.go new file mode 100644 index 0000000..dc72cee --- /dev/null +++ b/common/urlparse.go @@ -0,0 +1,21 @@ +package common + +import ( + "errors" + "net/url" + "strings" +) + +// GetFileExtensionFromUrl +// copied from https://elisegev.medium.com/get-a-file-extension-from-a-url-in-golang-5061d4a298a +func GetFileExtensionFromUrl(rawUrl string) (string, error) { + u, err := url.Parse(rawUrl) + if err != nil { + return "", err + } + pos := strings.LastIndex(u.Path, ".") + if pos == -1 { + return "", errors.New("couldn't find a period to indicate a file extension") + } + return u.Path[pos+1 : len(u.Path)], nil +} -- cgit v1.2.3