From d12d3aa9ee95aef1b0b91f45565640f59870c865 Mon Sep 17 00:00:00 2001 From: Toby Date: Wed, 28 Apr 2021 16:22:37 -0700 Subject: [PATCH] Update checker --- cmd/main.go | 13 ++++++++++--- cmd/update.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 cmd/update.go diff --git a/cmd/main.go b/cmd/main.go index fcf4298..6f65f09 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -19,8 +19,9 @@ var ( ) var ( - configPath = flag.String("config", "config.json", "Config file") - showVersion = flag.Bool("version", false, "Show version") + configPath = flag.String("config", "config.json", "Config file") + showVersion = flag.Bool("version", false, "Show version") + disableUpdateCheck = flag.Bool("no-check", false, "Disable update check") ) func init() { @@ -47,7 +48,10 @@ func init() { } else { logrus.SetFormatter(&nested.Formatter{ FieldsOrder: []string{ - "config", "file", "mode", "addr", "src", "dst", "session", "action", "error", + "version", "url", + "config", "file", "mode", + "addr", "src", "dst", "session", "action", + "error", }, TimestampFormat: tsFormat, }) @@ -64,6 +68,9 @@ func main() { fmt.Printf("%-10s%s\n", "Date:", appDate) return } + if !*disableUpdateCheck { + go checkUpdate() + } cb, err := ioutil.ReadFile(*configPath) if err != nil { logrus.WithFields(logrus.Fields{ diff --git a/cmd/update.go b/cmd/update.go new file mode 100644 index 0000000..ba3b7bb --- /dev/null +++ b/cmd/update.go @@ -0,0 +1,50 @@ +package main + +import ( + "encoding/json" + "github.com/sirupsen/logrus" + "io/ioutil" + "net/http" + "time" +) + +const githubAPIURL = "https://api.github.com/repos/HyNetwork/hysteria/releases/latest" + +type releaseInfo struct { + URL string `json:"html_url"` + TagName string `json:"tag_name"` + CreatedAt string `json:"created_at"` + PublishedAt string `json:"published_at"` +} + +func checkUpdate() { + info, err := fetchLatestRelease() + if err != nil { + logrus.WithFields(logrus.Fields{ + "error": err, + }).Warn("Failed to check for updates") + } else if info.TagName != appVersion { + logrus.WithFields(logrus.Fields{ + "version": info.TagName, + "url": info.URL, + }).Info("New version available") + } +} + +func fetchLatestRelease() (*releaseInfo, error) { + hc := &http.Client{ + Timeout: time.Second * 20, + } + resp, err := hc.Get(githubAPIURL) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + var info releaseInfo + err = json.Unmarshal(body, &info) + return &info, err +}