From 0cb2a3c4524eca7d73339c4d266e2a2a93a13620 Mon Sep 17 00:00:00 2001 From: c9s Date: Thu, 4 Feb 2021 16:59:00 +0800 Subject: [PATCH] split files to make routes smaller --- pkg/server/envvars.go | 37 +++++++++++ pkg/server/ping.go | 45 ++++++++++++++ pkg/server/pkger.go | 23 +++++++ pkg/server/routes.go | 139 ------------------------------------------ pkg/server/utils.go | 65 ++++++++++++++++++++ 5 files changed, 170 insertions(+), 139 deletions(-) create mode 100644 pkg/server/envvars.go create mode 100644 pkg/server/ping.go create mode 100644 pkg/server/pkger.go create mode 100644 pkg/server/utils.go diff --git a/pkg/server/envvars.go b/pkg/server/envvars.go new file mode 100644 index 000000000..82f4fbbf9 --- /dev/null +++ b/pkg/server/envvars.go @@ -0,0 +1,37 @@ +package server + +import ( + "fmt" + "strings" + + "github.com/c9s/bbgo/pkg/bbgo" +) + +func collectSessionEnvVars(sessions map[string]*bbgo.ExchangeSession) (envVars map[string]string, err error) { + envVars = make(map[string]string) + + for _, session := range sessions { + if len(session.Key) == 0 && len(session.Secret) == 0 { + err = fmt.Errorf("session %s key & secret is not empty", session.Name) + return + } + + if len(session.EnvVarPrefix) > 0 { + envVars[session.EnvVarPrefix+"_API_KEY"] = session.Key + envVars[session.EnvVarPrefix+"_API_SECRET"] = session.Secret + } else if len(session.Name) > 0 { + sn := strings.ToUpper(session.Name) + envVars[sn+"_API_KEY"] = session.Key + envVars[sn+"_API_SECRET"] = session.Secret + } else { + err = fmt.Errorf("session %s name or env var prefix is not defined", session.Name) + return + } + + // reset key and secret so that we won't marshal them to the config file + session.Key = "" + session.Secret = "" + } + + return +} diff --git a/pkg/server/ping.go b/pkg/server/ping.go new file mode 100644 index 000000000..5aa30d248 --- /dev/null +++ b/pkg/server/ping.go @@ -0,0 +1,45 @@ +package server + +import ( + "context" + "time" + + "github.com/sirupsen/logrus" +) + +func pingUntil(ctx context.Context, baseURL string, callback func()) { + pingURL := baseURL + "/api/ping" + timeout := time.NewTimer(time.Minute) + + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + + for { + select { + + case <-timeout.C: + logrus.Warnf("ping hits 1 minute timeout") + return + + case <-ctx.Done(): + return + + case <-ticker.C: + var response map[string]interface{} + var err = getJSON(pingURL, &response) + if err == nil { + go callback() + return + } + } + } +} + +func pingAndOpenURL(ctx context.Context, baseURL string) { + setupURL := baseURL + "/setup" + go pingUntil(ctx, baseURL, func() { + if err := openURL(setupURL); err != nil { + logrus.WithError(err).Errorf("can not call open command to open the web page") + } + }) +} diff --git a/pkg/server/pkger.go b/pkg/server/pkger.go new file mode 100644 index 000000000..1913018cd --- /dev/null +++ b/pkg/server/pkger.go @@ -0,0 +1,23 @@ +package server + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/markbates/pkger" +) + +func (s *Server) pkgerHandler(c *gin.Context) { + fs := pkger.Dir("/frontend/out") + + // redirect to .html page if the page exists + if pageRoutePattern.MatchString(c.Request.URL.Path) { + + _, err := pkger.Stat("/frontend/out/" + c.Request.URL.Path + ".html") + if err == nil { + c.Request.URL.Path += ".html" + } + } + + http.FileServer(fs).ServeHTTP(c.Writer, c.Request) +} diff --git a/pkg/server/routes.go b/pkg/server/routes.go index 2ff169868..0ce454ee8 100644 --- a/pkg/server/routes.go +++ b/pkg/server/routes.go @@ -2,23 +2,18 @@ package server import ( "context" - "encoding/json" "fmt" "io/ioutil" "net" "net/http" "os" - "os/exec" "regexp" - "runtime" "strconv" - "strings" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/joho/godotenv" - "github.com/markbates/pkger" "github.com/sirupsen/logrus" "github.com/c9s/bbgo/pkg/bbgo" @@ -466,21 +461,6 @@ func (s *Server) setupSaveConfig(c *gin.Context) { var pageRoutePattern = regexp.MustCompile("/[a-z]+$") -func (s *Server) pkgerHandler(c *gin.Context) { - fs := pkger.Dir("/frontend/out") - - // redirect to .html page if the page exists - if pageRoutePattern.MatchString(c.Request.URL.Path) { - - _, err := pkger.Stat("/frontend/out/" + c.Request.URL.Path + ".html") - if err == nil { - c.Request.URL.Path += ".html" - } - } - - http.FileServer(fs).ServeHTTP(c.Writer, c.Request) -} - func moveFileToBackup(filename string) error { stat, err := os.Stat(filename) @@ -494,35 +474,6 @@ func moveFileToBackup(filename string) error { return nil } -func collectSessionEnvVars(sessions map[string]*bbgo.ExchangeSession) (envVars map[string]string, err error) { - envVars = make(map[string]string) - - for _, session := range sessions { - if len(session.Key) == 0 && len(session.Secret) == 0 { - err = fmt.Errorf("session %s key & secret is not empty", session.Name) - return - } - - if len(session.EnvVarPrefix) > 0 { - envVars[session.EnvVarPrefix+"_API_KEY"] = session.Key - envVars[session.EnvVarPrefix+"_API_SECRET"] = session.Secret - } else if len(session.Name) > 0 { - sn := strings.ToUpper(session.Name) - envVars[sn+"_API_KEY"] = session.Key - envVars[sn+"_API_SECRET"] = session.Secret - } else { - err = fmt.Errorf("session %s name or env var prefix is not defined", session.Name) - return - } - - // reset key and secret so that we won't marshal them to the config file - session.Key = "" - session.Secret = "" - } - - return -} - func (s *Server) tradingVolume(c *gin.Context) { if s.Environ.TradeService == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "database is not configured"}) @@ -575,96 +526,6 @@ func (s *Server) tradingVolume(c *gin.Context) { return } -func getJSON(url string, data interface{}) error { - var client = &http.Client{Timeout: 500 * time.Millisecond} - r, err := client.Get(url) - if err != nil { - return err - } - - defer r.Body.Close() - - return json.NewDecoder(r.Body).Decode(data) -} - -func openURL(url string) error { - cmd := exec.Command("open", url) - return cmd.Start() -} - -func pingUntil(ctx context.Context, baseURL string, callback func()) { - pingURL := baseURL + "/api/ping" - timeout := time.NewTimer(time.Minute) - - ticker := time.NewTicker(time.Second) - defer ticker.Stop() - - for { - select { - - case <-timeout.C: - logrus.Warnf("ping hits 1 minute timeout") - return - - case <-ctx.Done(): - return - - case <-ticker.C: - var response map[string]interface{} - var err = getJSON(pingURL, &response) - if err == nil { - go callback() - return - } - } - } -} - -func pingAndOpenURL(ctx context.Context, baseURL string) { - setupURL := baseURL + "/setup" - go pingUntil(ctx, baseURL, func() { - if err := openURL(setupURL); err != nil { - logrus.WithError(err).Errorf("can not call open command to open the web page") - } - }) -} - -func filterStrings(slice []string, needle string) (ns []string) { - for _, str := range slice { - if str == needle { - continue - } - - ns = append(ns, str) - } - - return ns -} - -func openBrowser(ctx context.Context, bind string) { - if runtime.GOOS == "darwin" { - baseURL := "http://" + bind - go pingAndOpenURL(ctx, baseURL) - } else { - logrus.Warnf("%s is not supported for opening browser automatically", runtime.GOOS) - } -} - -func resolveBind(a []string) string { - switch len(a) { - case 0: - return DefaultBindAddress - - case 1: - return a[0] - - default: - panic("too many parameters for binding") - } - - return "" -} - func newServer(r http.Handler, bind string) *http.Server { return &http.Server{ Addr: bind, diff --git a/pkg/server/utils.go b/pkg/server/utils.go new file mode 100644 index 000000000..474fed055 --- /dev/null +++ b/pkg/server/utils.go @@ -0,0 +1,65 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "os/exec" + "runtime" + "time" + + "github.com/sirupsen/logrus" +) + +func getJSON(url string, data interface{}) error { + var client = &http.Client{Timeout: 500 * time.Millisecond} + r, err := client.Get(url) + if err != nil { + return err + } + + defer r.Body.Close() + + return json.NewDecoder(r.Body).Decode(data) +} + +func openURL(url string) error { + cmd := exec.Command("open", url) + return cmd.Start() +} + +func filterStrings(slice []string, needle string) (ns []string) { + for _, str := range slice { + if str == needle { + continue + } + + ns = append(ns, str) + } + + return ns +} + +func openBrowser(ctx context.Context, bind string) { + if runtime.GOOS == "darwin" { + baseURL := "http://" + bind + go pingAndOpenURL(ctx, baseURL) + } else { + logrus.Warnf("%s is not supported for opening browser automatically", runtime.GOOS) + } +} + +func resolveBind(a []string) string { + switch len(a) { + case 0: + return DefaultBindAddress + + case 1: + return a[0] + + default: + panic("too many parameters for binding") + } + + return "" +}