mirror of
https://github.com/rwxrob/bonzai
synced 2024-11-14 18:12:59 +00:00
Add util.NeedsUpdate to check for updates
This commit is contained in:
parent
ef432c34e2
commit
1a54bfb454
25
util/update.go
Normal file
25
util/update.go
Normal file
@ -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
|
||||
}
|
44
util/update_test.go
Normal file
44
util/update_test.go
Normal file
@ -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…
Reference in New Issue
Block a user