Update checker

This commit is contained in:
Toby 2021-04-28 16:22:37 -07:00
parent 0c887e0634
commit d12d3aa9ee
2 changed files with 60 additions and 3 deletions

View File

@ -21,6 +21,7 @@ var (
var (
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{

50
cmd/update.go Normal file
View File

@ -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
}