Add util.NeedsUpdate to check for updates

pull/53/head v0.0.17
rwxrob 2 years ago
parent ef432c34e2
commit 1a54bfb454
No known key found for this signature in database
GPG Key ID: 2B9111F33082AE77

@ -0,0 +1,25 @@
package util
import (
"log"
"github.com/rwxrob/json"
)
// NeedsUpdate compares the current isosec integer (second at GMT) to
// that retrieved from the URL (usually pointing to a file called
// UPDATED) which must return nothing but a single isosec integer (which
// is unmarshaled as a JSON number). Returns 1 if needed, 0 if not
// needed, and -1 if unable to determine (and will log any error
// encountered).
func NeedsUpdate(current int, url string) int {
var remote int
if err := json.Req(`GET`, url, nil, nil, &remote); err != nil {
log.Print(err)
return -1
}
if remote > current {
return 1
}
return 0
}

@ -0,0 +1,44 @@
package util_test
import (
"fmt"
"net/http"
ht "net/http/httptest"
"github.com/rwxrob/bonzai/util"
)
func ExampleCheckUpdated() {
handler := http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `20220322080540`)
})
older := ht.NewServer(handler)
defer older.Close()
handler = http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `20220322080546`)
})
newer := ht.NewServer(handler)
defer newer.Close()
handler = http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `20220322080542`)
})
same := ht.NewServer(handler)
defer same.Close()
fmt.Println(util.NeedsUpdate(20220322080542, older.URL))
fmt.Println(util.NeedsUpdate(20220322080542, newer.URL))
fmt.Println(util.NeedsUpdate(20220322080542, same.URL))
fmt.Println(util.NeedsUpdate(20220322080542, "foobar"))
// Output:
// 0
// 1
// 0
// -1
}
Loading…
Cancel
Save