Skip to content
This repository has been archived by the owner on Feb 1, 2024. It is now read-only.

Commit

Permalink
Bundle React.js into Kelp with 3 modes of running with 'serve' command (
Browse files Browse the repository at this point in the history
#158)

- [x] deployment mode embeds JS assets into binary (when building with `./scripts/build.sh -d`)
- [x] local mode running from static files in filesystem (when building with `./scripts/build.sh` and running with `./bin/kelp server`)
- [x] dev mode with hot-reloading of JS code from filesystem (when building with `./scripts/build.sh` and running with `./bin/kelp server --dev`)

first commit for GUI Dashboard issue: #67
  • Loading branch information
nikhilsaraf authored Apr 16, 2019
1 parent 278b0a9 commit 857214c
Show file tree
Hide file tree
Showing 24 changed files with 9,424 additions and 8 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ vendor/
build/
bin/
.idea
gui/filesystem_vfsdata_release.go
kelp.prefs
7 changes: 6 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ import (

// build flags
var version string
var buildDate string
var gitBranch string
var gitHash string
var buildDate string
var env string

const envRelease = "release"
const envDev = "dev"

const rootShort = "Kelp is a free and open-source trading bot for the Stellar universal marketplace."
const rootLong = `Kelp is a free and open-source trading bot for the Stellar universal marketplace (https://stellar.org).
Expand Down Expand Up @@ -48,6 +52,7 @@ func init() {
validateBuild()

RootCmd.AddCommand(tradeCmd)
RootCmd.AddCommand(serverCmd)
RootCmd.AddCommand(strategiesCmd)
RootCmd.AddCommand(exchanagesCmd)
RootCmd.AddCommand(terminateCmd)
Expand Down
135 changes: 135 additions & 0 deletions cmd/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package cmd

import (
"bufio"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"strings"
"time"

"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/spf13/cobra"
"github.com/stellar/kelp/gui"
)

var serverCmd = &cobra.Command{
Use: "server",
Short: "Serves the Kelp GUI",
}

type serverInputs struct {
port *uint16
dev *bool
}

func init() {
options := serverInputs{}
options.port = serverCmd.Flags().Uint16P("port", "p", 8000, "port on which to serve")
options.dev = serverCmd.Flags().Bool("dev", false, "run in dev mode for hot-reloading of JS code")

serverCmd.Run = func(ccmd *cobra.Command, args []string) {
if env == envDev && *options.dev {
checkHomeDir()
runWithYarn(options)
return
}

if env == envDev {
checkHomeDir()
generateStaticFiles()
}

r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(60 * time.Second))
// gui.FS is automatically compiled based on whether this is a local or deployment build
fileServer(r, "/", gui.FS)

portString := fmt.Sprintf(":%d", *options.port)
log.Printf("Serving on HTTP port: %d\n", *options.port)
e := http.ListenAndServe(portString, r)
log.Fatal(e)
}
}

func checkHomeDir() {
op, e := exec.Command("pwd").Output()
if e != nil {
panic(e)
}
result := strings.TrimSpace(string(op))

if !strings.HasSuffix(result, "/kelp") {
log.Fatalf("need to invoke the '%s' command while in the root 'kelp' directory\n", serverCmd.Use)
}
}

func runWithYarn(options serverInputs) {
// yarn requires the PORT variable to be set when serving
os.Setenv("PORT", fmt.Sprintf("%d", *options.port))

e := runCommandStreamOutput(exec.Command("yarn", "--cwd", "gui/web", "start"))
if e != nil {
panic(e)
}
}

func generateStaticFiles() {
log.Printf("generating contents of gui/web/build ...\n")

e := runCommandStreamOutput(exec.Command("yarn", "--cwd", "gui/web", "build"))
if e != nil {
panic(e)
}

log.Printf("... finished generating contents of gui/web/build\n")
log.Println()
}

func runCommandStreamOutput(command *exec.Cmd) error {
stdout, e := command.StdoutPipe()
if e != nil {
return fmt.Errorf("error while creating Stdout pipe: %s", e)
}
command.Start()

scanner := bufio.NewScanner(stdout)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
log.Printf("\t%s\n", line)
}

e = command.Wait()
if e != nil {
return fmt.Errorf("could not execute command: %s", e)
}
return nil
}

// fileServer sets up a http.FileServer handler to serve static files from a http.FileSystem
// example taken from here: https://github.com/go-chi/chi/blob/master/_examples/fileserver/main.go
func fileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit URL parameters.")
}

fs := http.StripPrefix(path, http.FileServer(root))

if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"

r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
}))
}
1 change: 1 addition & 0 deletions cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ var versionCmd = &cobra.Command{
fmt.Printf(" git branch: %s\n", gitBranch)
fmt.Printf(" git hash: %s\n", gitHash)
fmt.Printf(" build date: %s\n", buildDate)
fmt.Printf(" env: %s\n", env)
fmt.Printf(" GOOS: %s\n", runtime.GOOS)
fmt.Printf(" GOARCH: %s\n", runtime.GOARCH)
},
Expand Down
14 changes: 12 additions & 2 deletions glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion glide.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import:
- package: github.com/sirupsen/logrus
version: 070c81def33f6362a8267b6a4e56fb7bf23fc6b5
- package: github.com/Sirupsen/logrus
version: 070c81def33f6362a8267b6a4e56fb7bf23fc6b5
repo: [email protected]:sirupsen/logrus
vcs: git
version: 070c81def33f6362a8267b6a4e56fb7bf23fc6b5
- package: golang.org/x/crypto
version: 2509b142fb2b797aa7587dad548f113b2c0f20ce
- package: golang.org/x/sys
Expand All @@ -40,3 +40,7 @@ import:
version: a26df67722de7fcf1a8e22cd934e63e553dd3875
- package: github.com/mitchellh/mapstructure
version: v1.1.2
- package: github.com/go-chi/chi
version: v4.0.2
- package: github.com/shurcooL/vfsgen
version: 6a9ea43bcacdf716a5c1b38efff722c07adf0069
13 changes: 13 additions & 0 deletions gui/filesystem_vfsdata_debug.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// +build debug

package gui

import (
"net/http"
"path/filepath"
)

var guiBuildDir = filepath.Join("gui", "web", "build")

// file system for GUI
var FS = http.Dir(guiBuildDir)
23 changes: 23 additions & 0 deletions gui/web/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
68 changes: 68 additions & 0 deletions gui/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.<br>
You will also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

### Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

### Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

### Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

### Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

### `npm run build` fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
25 changes: 25 additions & 0 deletions gui/web/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "gui",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-scripts": "2.1.8"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Binary file added gui/web/public/favicon.ico
Binary file not shown.
41 changes: 41 additions & 0 deletions gui/web/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Loading

0 comments on commit 857214c

Please sign in to comment.