Commit 8ebfa65c authored by abbycin's avatar abbycin

init

parents
.DS_Store
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
/package-lock.json
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.exe
*.db
*.log
server.json
mo/
*.zip
web = "dist"
address = ":8888"
session_key = "elder"
session_val = "+1s"
session_ttl = 12 # hour
[logging]
filename = "log/backend"
roll_size = 10 # MB
roll_interval = 720 # hour
level = "info"
panic_on_fatal = true
\ No newline at end of file
package conf
import (
"backend/logging"
"github.com/BurntSushi/toml"
"log"
"path/filepath"
"strings"
"time"
)
type Logging struct {
FileName string `toml:"filename"`
RollSize int64 `toml:"roll_size"`
RollInterval time.Duration `toml:"roll_interval"`
Level string `toml:"level"`
PanicOnFatal bool `toml:"panic_on_fatal"`
}
type Config struct {
Web string `toml:"web"`
Address string `toml:"address"`
SessionKey string `toml:"session_key"`
SessionVal string `toml:"session_val"`
SessionTTL int64 `toml:"session_ttl"`
Logging Logging `toml:"logging"`
}
func Init(cfg string) *Config {
var res Config
_, err := toml.DecodeFile(cfg, &res)
if err != nil {
log.Panicf("can't decode configuration file: %s", err.Error())
}
return &res
}
func (c *Config) str2Level() int {
l := strings.ToLower(c.Logging.Level)
switch l {
case "info":
return logging.INFO
case "debug":
return logging.DEBUG
case "warn":
return logging.WARN
case "error":
return logging.ERROR
case "fatal":
return logging.FATAL
default:
panic("invalid level " + c.Logging.Level)
}
}
func (c *Config) GetLogger(cwd string) *logging.Logger {
return &logging.Logger{
RollSize: c.Logging.RollSize * (1 << 20),
RollInterval: c.Logging.RollInterval * time.Hour,
FileName: filepath.Join(cwd, c.Logging.FileName),
Level: c.str2Level(),
PanicOnFatal: c.Logging.PanicOnFatal,
}
}
module backend
go 1.13
require (
github.com/BurntSushi/toml v0.3.1
github.com/gin-contrib/cors v1.3.1
github.com/gin-gonic/gin v1.6.3
github.com/golang/protobuf v1.4.2 // indirect
github.com/kardianos/service v1.0.0
github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
)
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gin-contrib/cors v1.3.1 h1:doAsuITavI4IOcd0Y19U4B+O0dNWihRyX//nn4sEmgA=
github.com/gin-contrib/cors v1.3.1/go.mod h1:jjEJ4268OPZUcU7k9Pm653S7lXUGcqMADzFA61xsmDk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do=
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY=
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/kardianos/service v1.0.0 h1:HgQS3mFfOlyntWX8Oke98JcJLqt1DBcHR4kxShpYef0=
github.com/kardianos/service v1.0.0/go.mod h1:8CzDhVuCuugtsHyZoTvsOBuvonN/UDBvl0kH+BUxvbo=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U=
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299 h1:DYfZAGf2WMFjMxbgTjaC+2HC7NkNAQs+6Q8b9WEB/F4=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
/***********************************************
File Name: logging
Author: Abby Cin
Mail: abbytsing@gmail.com
Created Time: 10/31/19 7:41 AM
***********************************************/
package logging
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
const (
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
FATAL = 4
)
type Logger struct {
FileName string `json:"filename" toml:"filename"`
RollSize int64 `json:"roll_size" toml:"roll_size"`
RollInterval time.Duration `json:"roll_interval" toml:"roll_interval"`
Level int `json:"level" toml:"level"`
PanicOnFatal bool `json:"panic_on_fatal" toml:"panic_on_fatal"`
genName func() string
format func(int, string, int) string
dir string
idx int
roll bool
level [5]string
sizeCounter int64
timePoint time.Time
file *os.File
mtx sync.Mutex
}
var backend = Logger{}
func init() {
backend.roll = false
backend.PanicOnFatal = true
backend.level = [5]string{"DEBUG", "INFO ", "WARN ", "ERROR", "FATAL"}
backend.format = func(level int, file string, line int) string {
// fuck golang
return fmt.Sprintf("[%s %s] %s:%d ", time.Now().Format("2006-01-02 15:04:05.000"), backend.level[level], file, line)
}
backend.file = os.Stdout
}
func Init(cfg *Logger) error {
backend.roll = true
backend.RollSize = cfg.RollSize
backend.RollInterval = cfg.RollInterval
backend.Level = cfg.Level
backend.PanicOnFatal = cfg.PanicOnFatal
backend.dir = filepath.Dir(cfg.FileName)
backend.FileName = filepath.Base(strings.TrimSuffix(cfg.FileName, filepath.Ext(cfg.FileName)))
backend.sizeCounter = 0
backend.timePoint = time.Now()
backend.idx = 0
prefix := fmt.Sprintf("%s-%s", backend.FileName, time.Now().Format("20060102"))
abs, err := filepath.Abs(backend.dir)
if err != nil {
return err;
}
if _, err := os.Stat(abs); os.IsNotExist(err) {
os.Mkdir(abs, 0755)
}
entries, err := ioutil.ReadDir(abs)
if err != nil {
return err
}
// /path/to/prefix-20190617-pid-1.log
for _, e := range entries {
if strings.HasPrefix(e.Name(), prefix) {
tmp, err := strconv.Atoi(strings.Split(strings.TrimSuffix(e.Name(), filepath.Ext(e.Name())), "-")[3])
if err != nil {
return err
}
if backend.idx < tmp {
backend.idx = tmp
}
}
}
backend.genName = func() string {
cur := time.Now().Format("20060102")
backend.idx += 1
return fmt.Sprintf("%s/%s-%s-%d-%d.log", backend.dir, backend.FileName, cur, os.Getpid(), backend.idx)
}
backend.file, err = os.Create(backend.genName())
return err
}
func (b *Logger) dispatch(level int, f string, args ...interface{}) {
b.mtx.Lock()
defer b.mtx.Unlock()
if level < b.Level {
return
}
if b.roll && (b.sizeCounter > b.RollSize || time.Since(b.timePoint) > b.RollInterval) {
b.sizeCounter = 0
b.timePoint = time.Now()
Release()
b.file, _ = os.Create(b.genName())
}
_, file, line, _ := runtime.Caller(2) // golang is horrible
data := []byte(b.format(level, path.Base(file), line) + fmt.Sprintf(f, args...))
n, err := b.file.Write(append(data, '\n'))
if err != nil {
panic(err)
}
b.sizeCounter += int64(n)
}
func Release() {
_ = backend.file.Sync()
_ = backend.file.Close()
}
func Sync() error {
return backend.file.Sync()
}
func Info(f string, args ...interface{}) {
backend.dispatch(INFO, f, args...)
}
func Debug(f string, args ...interface{}) {
backend.dispatch(DEBUG, f, args...)
}
func Warn(f string, args ...interface{}) {
backend.dispatch(WARN, f, args...)
}
func Error(f string, args ...interface{}) {
backend.dispatch(ERROR, f, args...)
}
func Fatal(f string, args ...interface{}) {
backend.dispatch(FATAL, f, args...)
if backend.PanicOnFatal {
panic("fatal error")
}
}
package main
import (
"backend/conf"
"backend/logging"
"backend/middleware"
"backend/service"
"backend/session"
"database/sql"
"flag"
_ "github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
srv "github.com/kardianos/service"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
"path/filepath"
)
var logger srv.Logger
type Program struct {}
func (p *Program) run() {
exe, err := os.Executable()
if err != nil {
log.Fatal(err)
}
cwd := filepath.Dir(exe)
config := conf.Init(filepath.Join(cwd, "backend.toml"))
if err := logging.Init(config.GetLogger(cwd)); err != nil {
log.Panicf("can't init logger: %s\n", err)
}
defer logging.Release()
db, err := sql.Open("sqlite3", filepath.Join(cwd, "backend.db"))
if err != nil {
panic(err)
}
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
//r.Use(cors.Default())
mgr := session.NewSessionManager(config.SessionKey, config.SessionVal, config.SessionTTL)
auth := middleware.NewAuth(mgr)
// login
u := service.NewUserManage(db, mgr)
r.POST("/api/login", u.Serve)
r.PUT("/api/login", auth.Serve, u.Serve)
r.DELETE("/api/login", auth.Serve, u.Serve)
// db
d := service.NewDBManage()
r.GET("/api/db", auth.Serve, d.Serve)
r.PUT("/api/db", auth.Serve, d.Serve)
// server
s := service.NewServer(d)
r.GET("/api/server", auth.Serve, s.Retrieve)
r.POST("/api/server", auth.Serve, s.Serve)
r.PUT("/api/server", auth.Serve, s.Update)
r.Static("/static", filepath.Join(cwd, config.Web, "static"))
r.StaticFile("/", filepath.Join(cwd, config.Web, "index.html"))
r.Run(config.Address)
}
func (p *Program) Start(s srv.Service) error {
logger.Info("srv.Start")
go p.run()
return nil
}
func (p *Program) Run(s srv.Service) {
logger.Info("srv.Run")
}
func (p *Program) Stop(s srv.Service) error {
logger.Info("srv.Stop")
return nil
}
func main() {
srvFlag := flag.String("run", "", "control the service")
flag.Parse()
srvConf := &srv.Config {
Name: "httpservermgr",
DisplayName: "httpserver management",
Description: "manipulate tophttpserver",
}
p := &Program{}
s, err := srv.New(p, srvConf)
if err != nil {
log.Fatal(err)
}
logger, err = s.Logger(nil)
if err != nil {
log.Fatal(err)
}
if len(*srvFlag) != 0 {
err := srv.Control(s, *srvFlag)
if err != nil {
log.Fatalf("error: %v\nvalid actions: %q\n", err, srv.ControlAction)
}
return
}
err = s.Run()
if err != nil {
logger.Error(err)
}
}
/***********************************************
File Name: auth
Author: Abby Cin
Mail: abbytsing@gmail.com
Created Time: 10/31/19 7:52 PM
***********************************************/
package middleware
import (
"backend/session"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
type Auth struct {
mgr *session.SessionManager
excl map[string][]string
}
func NewAuth(mgr *session.SessionManager) *Auth {
r := &Auth{
mgr: mgr,
}
return r
}
func (a *Auth) Serve(c *gin.Context) {
ss := a.mgr.StartSession(c.Writer, c.Request)
status := ss.Get(a.mgr.SessionKey())
id := ss.Get(ss.Id())
if status != a.mgr.SessionVal() || id == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": -1,
"error": "unauthorized",
})
c.Abort()
return
}
if c.Request.Method == http.MethodPut || c.Request.Method == http.MethodPost {
n := c.Request.Header.Get("Content-Length")
r, e := strconv.ParseInt(n, 10, 64)
if e != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": -1,
"error": "invaild content length",
})
c.Abort()
return
}
if r > (10 << 20) {
c.JSON(http.StatusBadRequest, gin.H{
"code": -1,
"error": "body too large",
})
c.Abort()
return
}
}
c.Next()
}
package service
import (
"github.com/gin-gonic/gin"
"net/http"
)
func newError(c *gin.Context, code int, msg string) {
c.JSON(http.StatusOK, gin.H{
"code": code,
"msg": msg,
})
}
func skipBom(data []byte) []byte {
if len(data) < 3 {
return data
}
// little endian only
if data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF {
return data[3:]
}
return data
}
\ No newline at end of file
package service
import (
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"os"
"path"
"sync"
)
type DBManage struct {
dbcfg string
mtx sync.Mutex
}
func NewDBManage() *DBManage {
return &DBManage{
dbcfg: "",
mtx: sync.Mutex{},
}
}
func (d *DBManage) Serve(c *gin.Context) {
if c.Request.Method == http.MethodPut {
d.HandleUpdate(c)
} else if c.Request.Method == http.MethodGet {
d.HandleGet(c)
} else {
newError(c, -1, "404 not found")
}
}
func (d *DBManage) update(c *gin.Context) error {
if _, err := os.Stat(d.dbcfg); os.IsNotExist(err) {
return errors.New("please make sure you have set server root correctly")
}
data, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
return err
}
j := make(map[string]interface{})
err = json.Unmarshal(data, &j)
if err == nil {
tmp, err := json.MarshalIndent(j, "", " ")
if err == nil {
data = tmp
}
}
f, err := os.OpenFile(d.dbcfg, os.O_WRONLY | os.O_TRUNC, 00644)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(data)
return err
}
func (d *DBManage) UpdateServerRoot(root string) {
d.dbcfg = path.Join(root, "config", "tophttpserver.database.json")
}
func (d *DBManage) HandleUpdate(c *gin.Context) {
d.mtx.Lock()
defer d.mtx.Unlock()
err := d.update(c)
if err != nil {
newError(c, -1, err.Error())
return
}
newError(c, 0, "ok")
}
func (d *DBManage) get(c *gin.Context) (map[string]interface{}, error) {
if _, err := os.Stat(d.dbcfg); os.IsNotExist(err) {
return nil, errors.New("please make sure you have set server root correctly")
}
data, err := ioutil.ReadFile(d.dbcfg)
if err != nil {
return nil, err
}
m := make(map[string]interface{})
if len(data) == 0 {
data = []byte("{}")
}
err = json.Unmarshal(skipBom(data), &m)
if err != nil {
return nil, err
}
return m, nil
}
func (d *DBManage) HandleGet(c *gin.Context) {
d.mtx.Lock()
defer d.mtx.Unlock()
m, err := d.get(c)
if err != nil {
newError(c, -1, err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": m,
"msg": "ok",
})
}
\ No newline at end of file
package service
import (
"backend/logging"
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strconv"
"sync"
)
type Command struct {
Cmd string `json:"command"`
}
type ServerConf struct {
ServerRoot string `json:"server_root"`
TestUrl string `json:"test_url"`
}
func (s *ServerConf) binary() string {
if runtime.GOOS == "windows" {
return path.Join(s.ServerRoot, "library", "tophttpserver.exe")
} else if runtime.GOOS == "linux" {
return path.Join(s.ServerRoot, "bin", "tophttpserver")
}
return ""
}
type Server struct {
mtx sync.Mutex
file string
db *DBManage
cfg *ServerConf
cmd map[string]func(*Server) error
}
func (s *Server) ServerRoot() string {
return s.cfg.ServerRoot
}
func getPid(name string) int {
var pid int
files, err := ioutil.ReadDir("/proc")
for _, f := range files {
if !f.IsDir() {
continue
}
pid, err = strconv.Atoi(f.Name())
// not process
if err != nil {
continue
}
data, err := ioutil.ReadFile(path.Join("/proc", f.Name(), "cmdline"))
if err != nil {
continue
}
if len(data) < 2 {
continue
}
str := string(data[0: len(data)-1]) // cmdline has trialling '\0' (its NULL terminated c string)
if str == name {
return pid
}
}
return -1
}
func restart(s *Server) error {
if runtime.GOOS == "windows" {
return exec.Command("taskkill", "/f", "/im", "tophttpserver.exe").Run()
} else if runtime.GOOS == "linux" {
pid := getPid(s.cfg.binary())
if pid < 0 {
return errors.New("can't find pid")
}
return exec.Command("kill", "-15", strconv.Itoa(pid)).Run()
}
return errors.New("platform not support")
}
func monitor(*Server) error {
return nil
}
func NewServer(db *DBManage) *Server {
exe, err := os.Executable()
if err != nil {
logging.Fatal("can't get current directory: %s", err)
}
file := filepath.Join(filepath.Dir(exe), "server.json")
f, err := os.Open(file)
if err != nil {
f, err = os.OpenFile(file, os.O_CREATE | os.O_TRUNC, 00644)
}
if err == nil {
f.Close()
}
return &Server{
mtx: sync.Mutex{},
file: file,
db: db,
cfg: new(ServerConf),
cmd: map[string]func(*Server) error{
"restart": restart,
"monitor": monitor,
},
}
}
func (s *Server) Serve(c *gin.Context) {
s.mtx.Lock()
defer s.mtx.Unlock()
var cmd Command
err := c.BindJSON(&cmd)
if err != nil {
newError(c, -1, err.Error())
return
}
println("command", cmd.Cmd)
fp, ok := s.cmd[cmd.Cmd]
if !ok {
newError(c, -1, fmt.Sprintf("bad request, no such command: %s", cmd.Cmd))
return
}
err = fp(s)
if err != nil {
newError(c, -1, err.Error())
return
}
newError(c, 0, "ok")
}
func (s *Server) Retrieve(c *gin.Context) {
s.mtx.Lock()
defer s.mtx.Unlock()
data, err := ioutil.ReadFile(s.file)
if err != nil {
newError(c, -1, err.Error())
return
}
data = skipBom(data)
if len(data) == 0 {
data = []byte("{}")
}
err = json.Unmarshal(data, s.cfg)
if err != nil {
newError(c, -1, err.Error())
return
}
s.db.UpdateServerRoot(s.ServerRoot())
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": s.cfg,
"msg": "ok",
})
}
func (s *Server) update(c *gin.Context) error {
data, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
return err
}
err = json.Unmarshal(data, s.cfg)
if err == nil {
tmp, err := json.MarshalIndent(s.cfg, "", " ")
if err == nil {
data = tmp
}
}
f, err := os.OpenFile(s.file, os.O_WRONLY | os.O_TRUNC, 00644)
if err != nil {
return err
}
defer f.Close()
s.db.UpdateServerRoot(s.ServerRoot())
_, err = f.Write(data)
return err
}
func (s *Server) Update(c *gin.Context) {
s.mtx.Lock()
defer s.mtx.Unlock()
err := s.update(c)
if err != nil {
newError(c, -1, err.Error())
} else {
newError(c, 0, "ok")
}
}
\ No newline at end of file
package service
import (
"backend/session"
"crypto/md5"
"database/sql"
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
)
// User Management
type Identity struct {
UserName string `json:username`
Password string `json:password`
}
type UserManage struct {
Id Identity
DB *sql.DB
ss *session.SessionManager
}
func NewUserManage(db *sql.DB, ss *session.SessionManager) *UserManage {
_, err := db.Exec(`create table if not exists user(username varchar(20) unique, password varchar(33))`)
if err != nil {
panic(err)
}
return &UserManage{
Id: Identity{},
DB: db,
ss: ss,
}
}
func (u *UserManage) loginImpl(c *gin.Context) error {
epass := fmt.Sprintf("%x", md5.Sum([]byte(u.Id.Password)))
rows, err := u.DB.Query("select count(username) from user")
if err != nil {
return err
}
count := -1
for rows.Next() {
rows.Scan(&count)
}
// first time login
if count == 0 {
tx, err := u.DB.Begin()
if err != nil {
return err
}
_, err = tx.Exec("insert into user(username, password) values(?, ?)", u.Id.UserName, epass)
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
return err
}
// validate
rows, err = u.DB.Query("select username from user where username = ? and password = ?", u.Id.UserName, epass)
if err != nil {
return err
}
count = 0
for rows.Next() {
count += 1
}
if count == 0 {
return errors.New("invalid id or pass")
}
return nil
}
func (u *UserManage) login(c *gin.Context) {
ss := u.ss.StartSession(c.Writer, c.Request)
status := ss.Get(u.ss.SessionKey())
if status != u.ss.SessionVal() {
err := c.BindJSON(&u.Id)
if err != nil {
newError(c, -1, err.Error())
return
}
err = u.loginImpl(c)
if err == nil {
ss.Set(u.ss.SessionKey(), u.ss.SessionVal())
ss.Set(ss.Id(), u.Id.UserName)
newError(c, 0, "ok")
} else {
newError(c, -1, err.Error())
}
} else {
newError(c, 0, "ok")
}
}
func (u *UserManage) changePassImpl(c *gin.Context) error {
data, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
return err
}
p := make(map[string]interface{})
err = json.Unmarshal(data, &p)
if err != nil {
return err
}
ss := u.ss.StartSession(c.Writer, c.Request)
username := ss.Get(ss.Id())
password := p["password"].(string)
epass := fmt.Sprintf("%x", md5.Sum([]byte(password)))
stmt, err := u.DB.Prepare("update user set password = ? where username = ?")
if err != nil {
return err
}
tx, err := u.DB.Begin()
if err != nil {
return err
}
_, err = tx.Stmt(stmt).Exec(epass, username)
if err != nil {
err = tx.Rollback()
} else {
err = tx.Commit()
}
return err
}
func (u *UserManage) changePass(c *gin.Context) {
err := u.changePassImpl(c)
if err != nil {
newError(c, -1, err.Error())
} else {
u.ss.Clear()
newError(c, 0, "ok")
}
}
func (u *UserManage) logout(c *gin.Context) {
u.ss.SessionDestroy(c.Writer, c.Request)
newError(c, 0, "ok")
}
func (u *UserManage) Serve(c *gin.Context) {
if c.Request.Method == http.MethodPost {
u.login(c)
} else if c.Request.Method == http.MethodPut {
u.changePass(c)
} else if c.Request.Method == http.MethodDelete {
u.logout(c)
} else {
newError(c, -1, "404 not found")
}
}
func (u *UserManage) Close() {
_ = u.DB.Close()
}
/***********************************************
File Name: session
Author: Abby Cin
Mail: abbytsing@gmail.com
Created Time: 10/13/19 2:36 PM
***********************************************/
package session
import (
"backend/logging"
"container/list"
"crypto/md5"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"sync"
"time"
)
var gId int64
func init() {
gId = 0
}
func newId() int64 {
r := gId
gId++
return r
}
func buildId() string {
tmp := md5.Sum([]byte(strconv.FormatInt(newId(), 10)))
return fmt.Sprintf("%x", tmp)
}
type ISession interface {
Set(key, val string) error
Get(key string) string
Del(key string) error
Id() string
}
type ISessionBackend interface {
Init(id string) (ISession, error)
Get(id string) (ISession, error)
Del(id string) error
Update(id string)
Clean(maxLifetime time.Duration)
}
type SessionManager struct {
mtx sync.Mutex
name string
value string
maxAge time.Duration
backend ISessionBackend
}
// fuck golang, no generics
type DefaultBackend struct {
mtx sync.Mutex
sessions map[string]*list.Element
queue *list.List
}
type DefaultSession struct {
id string
cookie map[string]string
lastTime time.Time
backend ISessionBackend
}
func NewDefaultBackend() *DefaultBackend {
return &DefaultBackend{
mtx: sync.Mutex{},
sessions: make(map[string]*list.Element),
queue: list.New(),
}
}
func (b *DefaultBackend) Init(id string) (ISession, error) {
b.mtx.Lock()
defer b.mtx.Unlock()
r := &DefaultSession{
id: id,
cookie: make(map[string]string),
lastTime: time.Now(),
backend: b,
}
e := b.queue.PushBack(r)
b.sessions[id] = e
return r, nil
}
func (b *DefaultBackend) Update(id string) {
b.mtx.Lock()
defer b.mtx.Unlock()
if e, ok := b.sessions[id]; ok {
e.Value.(*DefaultSession).lastTime = time.Now()
b.queue.MoveToFront(e)
}
}
func (b *DefaultBackend) Get(id string) (ISession, error) {
b.mtx.Lock()
defer b.mtx.Unlock()
e, ok := b.sessions[id]
if !ok {
return nil, errors.New("no such session")
}
return e.Value.(*DefaultSession), nil
}
func (b *DefaultBackend) Del(id string) error {
b.mtx.Lock()
defer b.mtx.Unlock()
if e, ok := b.sessions[id]; ok {
delete(b.sessions, id)
b.queue.Remove(e)
}
return nil
}
func (b *DefaultBackend) Clean(exp time.Duration) {
b.mtx.Lock()
defer b.mtx.Unlock()
cur := time.Now()
for {
e := b.queue.Back()
if e == nil {
return
}
if s := e.Value.(*DefaultSession); cur.Sub(s.lastTime) > exp {
b.queue.Remove(e)
delete(b.sessions, s.Id())
} else {
break
}
}
}
func (s *DefaultSession) Id() string {
return s.id
}
func (s *DefaultSession) Set(k, v string) error {
s.cookie[k] = v
s.backend.Update(s.Id())
return nil
}
func (s *DefaultSession) Get(k string) string {
if e, ok := s.cookie[k]; ok {
s.backend.Update(s.Id())
return e
}
return ""
}
func (s *DefaultSession) Del(k string) error {
if _, ok := s.cookie[k]; ok {
delete(s.cookie, k)
s.backend.Update(s.Id())
}
return nil
}
func NewSessionManager(sessionKey, sessionVal string, ttl int64) *SessionManager {
return &SessionManager{
mtx: sync.Mutex{},
name: sessionKey,
value: sessionVal,
maxAge: time.Duration(ttl) * time.Hour,
backend: NewDefaultBackend(),
}
}
func (m *SessionManager) newSession(w http.ResponseWriter, r *http.Request) (ISession, error) {
sid := buildId()
session, e := m.backend.Init(sid)
if e != nil {
logging.Info("SessionManager::newSession: %s", e.Error())
}
cookie := http.Cookie{Name: m.name, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(m.maxAge)}
http.SetCookie(w, &cookie)
return session, e
}
func (m *SessionManager) StartSession(w http.ResponseWriter, r *http.Request) (session ISession) {
m.mtx.Lock()
defer m.mtx.Unlock()
cookie, e := r.Cookie(m.name)
if e != nil || cookie.Value == "" {
session, _ = m.newSession(w, r)
} else {
sid, e := url.QueryUnescape(cookie.Value)
if e != nil {
logging.Error("unescape cookie: %s", e.Error())
}
session, e = m.backend.Get(sid)
if e != nil {
logging.Info("session id is not exists(maybe a previous session), create a new one")
session, _ = m.newSession(w, r)
}
}
return
}
func (m *SessionManager) SessionKey() string {
return m.name
}
func (m *SessionManager) SessionVal() string {
return m.value
}
func (m *SessionManager) SessionDestroy(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(m.name)
if err != nil || cookie.Value == "" {
return
} else {
m.mtx.Lock()
defer m.mtx.Unlock()
m.backend.Del(cookie.Value)
expiration := time.Now()
cookie := http.Cookie{Name: m.name, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1}
http.SetCookie(w, &cookie)
}
}
func (m *SessionManager) Clear() {
m.backend.Clean(0)
}
func (m *SessionManager) StartGC() {
go m.GC()
}
func (m *SessionManager) GC() {
m.mtx.Lock()
defer m.mtx.Unlock()
m.backend.Clean(m.maxAge)
time.AfterFunc(m.maxAge, func() { m.GC() })
}
const archiver = require('archiver');
const fs = require('fs');
const process = require('process');
const path = require('path');
const sys = require('child_process');
function rm(dst) {
if(!fs.existsSync(dst)) {
return;
}
let stat = fs.statSync(dst);
if(stat.isDirectory()) {
let stack = [];
let files = [];
let dirs = [dst];
let root = fs.readdirSync(dst);
for (let r of root) {
let p = path.join(dst, r);
let stat = fs.statSync(p);
if (stat.isDirectory()) {
stack.push(p);
dirs.push(p);
} else {
files.push(p);
}
}
while (stack.length > 0) {
let p = stack.pop();
let root = fs.readdirSync(p);
for (let r of root) {
let sp = path.join(p, r);
let stat = fs.statSync(sp);
if (stat.isDirectory()) {
stack.push(sp);
dirs.push(sp);
} else if (stat.isFile()) {
files.push(sp);
}
}
}
for(let f of files) {
fs.unlinkSync(f);
}
dirs.sort((l, r) => {
let ll = l.length;
let rl = r.length;
if (ll < rl) {
return 1;
} else if (ll == rl) {
return 0;
} else {
return -1;
}
});
let end = 0;
for (let i = 0; i < dirs.length; ++i) {
if (dirs[end] != dirs[i]) {
dirs[++end] = dirs[i];
}
}
end += 1;
for (let i = 0; i < end; ++i) {
if (fs.readdirSync(dirs[i]).length == 0) {
fs.rmdirSync(dirs[i]);
}
}
}
}
function mv(src, dst) {
if (!fs.existsSync(src)) {
throw `${src} is not exists`;
}
let lstat = fs.statSync(src);
if (lstat.isFile()) {
if (!fs.existsSync(dst)) {
fs.renameSync(src, dst);
return;
}
if(fs.existsSync(dst)) {
let rstat = fs.statSync(dst);
if(rstat.isFile()) {
fs.unlinkSync(dst);
}
else if(rstat.isDirectory()) {
dst = path.join(dst, path.basename(src));
}
else {
throw `unsupport dst type ${dst}`;
}
}
if(fs.existsSync(dst)) {
fs.unlinkSync(dst);
}
fs.renameSync(src, dst);
return;
}
if (lstat.isDirectory()) {
if(!fs.existsSync(dst)) {
fs.mkdirSync(dst, { recursive: true });
}
let rstat = fs.statSync(dst);
if(rstat.isFile()) {
throw `can't move from directory to a file`;
}
if(!rstat.isDirectory()) {
throw `unsupport dst type ${dst}`;
}
let stack = [];
let files = [];
let root = fs.readdirSync(src);
for(let r of root) {
let p = path.join(src, r);
let stat = fs.statSync(p);
if(stat.isDirectory()) {
stack.push(p);
files.push([p, true]);
} else {
files.push([p, false]);
}
}
while(stack.length > 0) {
let p = stack.pop();
let root = fs.readdirSync(p);
for(let r of root) {
let sp = path.join(p, r);
let stat = fs.statSync(sp);
if(stat.isDirectory()) {
stack.push(sp);
files.push([sp, true]);
} else if(stat.isFile()) {
files.push([sp, false]);
}
}
}
let dirs = [];
src = path.join(path.dirname(src), path.basename(src));
dirs.push(src);
for(let f of files) {
let d = path.join(dst, f[0].substr(src.length));
let b = "";
if(f[1]) {
fs.mkdirSync(d, { recursive: true });
dirs.push(f[0]);
b = f[0];
} else {
try {
fs.mkdirSync(path.dirname(d), { recursive: true });
} catch(e) {
// ignore error
}
fs.renameSync(f[0], d);
b = path.dirname(f[0]);
}
}
dirs.sort((l, r) => {
let ll = l.length;
let rl = r.length;
if(ll < rl) {
return 1;
} else if(ll == rl) {
return 0;
} else {
return -1;
}
});
let end = 0;
for(let i = 0; i < dirs.length; ++i) {
if(dirs[end] != dirs[i]) {
dirs[++end] = dirs[i];
}
}
end += 1;
for(let i = 0; i < end; ++i) {
if(fs.readdirSync(dirs[i]).length == 0) {
fs.rmdirSync(dirs[i]);
}
}
return;
}
throw `unsupport src type ${src}`;
}
function cp(src, dst) {
let copy = (src, dst) => {
let from = fs.createReadStream(src);
let to = fs.createWriteStream(dst);
from.pipe(to);
};
if (!fs.existsSync(src)) {
throw `${src} is not exists`;
}
let lstat = fs.statSync(src);
if (lstat.isFile()) {
if(!fs.existsSync(dst)) {
copy(src, dst);
return;
}
if (fs.existsSync(dst)) {
let rstat = fs.statSync(dst);
if(rstat.isFile()) {
fs.unlinkSync(dst);
}
else if(rstat.isDirectory()) {
dst = path.join(dst, path.basename(src));
}
else {
throw `unsupport dst type ${dst}`
}
}
if(fs.existsSync(dst)) {
fs.unlinkSync(dst);
}
copy(src, dst);
return;
}
if (lstat.isDirectory()) {
if (!fs.existsSync(dst)) {
fs.mkdirSync(dst, { recursive: true });
}
let rstat = fs.statSync(dst);
if (rstat.isFile()) {
throw `can't copy from directory to a file`;
}
if (!rstat.isDirectory()) {
throw `unsupport dst type ${dst}`;
}
let stack = [];
let files = [];
let root = fs.readdirSync(src);
for (let r of root) {
let p = path.join(src, r);
let stat = fs.statSync(p);
if (stat.isDirectory()) {
stack.push(p);
} else if (stat.isFile()) {
files.push(p);
}
}
while (stack.length > 0) {
let p = stack.pop();
let root = fs.readdirSync(p);
for (let r of root) {
let sp = path.join(p, r)
let stat = fs.statSync(sp);
if (stat.isDirectory()) {
stack.push(sp);
} else if (stat.isFile()) {
files.push(sp);
}
}
}
src = path.join(path.dirname(src), path.basename(src));
for (let f of files) {
let d = path.join(dst, f.substr(src.length));
try {
fs.mkdirSync(path.dirname(d), { recursive: true });
} catch (e) {
// ignore error
}
copy(f, d);
}
return;
}
throw `unsuppot src type ${src}`;
}
function build_frontend(dst) {
const oldpath = process.cwd();
let d = path.join(oldpath, dst);
process.chdir('frontend');
sys.execSync('npm install');
sys.execSync('npm run build');
cp('dist', path.join(d, 'dist'));
process.chdir(oldpath);
}
function build_backend(dst) {
const oldpath = process.cwd();
let d = path.join(oldpath, dst);
process.chdir('backend');
sys.execSync('go build');
if(process.platform === 'win32') {
mv('backend.exe', d);
} else {
mv('backend', d);
}
cp('backend.toml', d);
process.chdir(oldpath);
}
function build() {
let dst = 'mo';
if(fs.existsSync(dst)) {
rm(dst);
}
fs.mkdirSync(dst);
build_frontend(dst);
build_backend(dst);
let out = `${dst}.zip`;
if(fs.existsSync(out)) {
fs.unlinkSync(out);
}
let zip = fs.createWriteStream(out);
let archive = archiver('zip', {
zlib: {level: 9}
});
archive.pipe(zip);
archive.on('error', err => { throw err; });
archive.directory(dst, dst);
archive.finalize();
}
build();
\ No newline at end of file
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"]
}
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
/build/
/config/
/dist/
/*.js
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {}
}
}
# mo
> +1s
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
'use strict'
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
const versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
}
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (let i = 0; i < warnings.length; i++) {
const warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options)
for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
const createLintingRule = () => ({
// test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// enforce: 'pre',
// include: [resolve('src'), resolve('test')],
// options: {
// formatter: require('eslint-friendly-formatter'),
// emitWarning: !config.dev.showEslintErrorsInOverlay
// }
})
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>mo</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
{
"name": "mo",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@ant-design/colors": {
"version": "3.2.2",
"resolved": "https://registry.npm.taobao.org/@ant-design/colors/download/@ant-design/colors-3.2.2.tgz?cache=0&sync_timestamp=1582898544811&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40ant-design%2Fcolors%2Fdownload%2F%40ant-design%2Fcolors-3.2.2.tgz",
"integrity": "sha1-WtQ9YZ6RHzSI66wwPWBuZqhCOQM=",
"requires": {
"tinycolor2": "^1.4.1"
}
},
"@ant-design/icons": {
"version": "2.1.1",
"resolved": "https://registry.npm.taobao.org/@ant-design/icons/download/@ant-design/icons-2.1.1.tgz",
"integrity": "sha1-e5wI3/1PXUHbZn2dvl4BB9C9mko="
},
"@ant-design/icons-vue": {
"version": "2.0.0",
"resolved": "https://registry.npm.taobao.org/@ant-design/icons-vue/download/@ant-design/icons-vue-2.0.0.tgz",
"integrity": "sha1-A1f1AQpATp80qHpLQbKgjfaR284=",
"requires": {
"@ant-design/colors": "^3.1.0",
"babel-runtime": "^6.26.0"
}
},
"add-dom-event-listener": {
"version": "1.1.0",
"resolved": "https://registry.npm.taobao.org/add-dom-event-listener/download/add-dom-event-listener-1.1.0.tgz",
"integrity": "sha1-apLbOg3Qq8JU4JXA8dwUrLuq4xA=",
"requires": {
"object-assign": "4.x"
}
},
"ant-design-vue": {
"version": "1.6.0",
"resolved": "https://registry.npm.taobao.org/ant-design-vue/download/ant-design-vue-1.6.0.tgz",
"integrity": "sha1-Zz4J46xW/rFBVKcR5SNX+3UYzDI=",
"requires": {
"@ant-design/icons": "^2.1.1",
"@ant-design/icons-vue": "^2.0.0",
"add-dom-event-listener": "^1.0.2",
"array-tree-filter": "^2.1.0",
"async-validator": "^3.0.3",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-runtime": "6.x",
"classnames": "^2.2.5",
"component-classes": "^1.2.6",
"dom-align": "^1.10.4",
"dom-closest": "^0.2.0",
"dom-scroll-into-view": "^2.0.0",
"enquire.js": "^2.1.6",
"intersperse": "^1.0.0",
"is-mobile": "^2.2.1",
"is-negative-zero": "^2.0.0",
"ismobilejs": "^1.0.0",
"json2mq": "^0.2.0",
"lodash": "^4.17.5",
"moment": "^2.21.0",
"mutationobserver-shim": "^0.3.2",
"node-emoji": "^1.10.0",
"omit.js": "^1.0.0",
"raf": "^3.4.0",
"resize-observer-polyfill": "^1.5.1",
"shallow-equal": "^1.0.0",
"shallowequal": "^1.0.2",
"vue-ref": "^2.0.0",
"warning": "^4.0.0"
}
},
"array-tree-filter": {
"version": "2.1.0",
"resolved": "https://registry.npm.taobao.org/array-tree-filter/download/array-tree-filter-2.1.0.tgz",
"integrity": "sha1-hzrAD+yDdJ8lWsjdCDgUtPYykZA="
},
"async-validator": {
"version": "3.3.0",
"resolved": "https://registry.npm.taobao.org/async-validator/download/async-validator-3.3.0.tgz",
"integrity": "sha1-HZIZO75g1tbIskZpLHAF6e0UqO4="
},
"axios": {
"version": "0.19.2",
"resolved": "https://registry.npm.taobao.org/axios/download/axios-0.19.2.tgz",
"integrity": "sha1-PqNsXYgY0NX4qKl6bTa4bNwAyyc=",
"requires": {
"follow-redirects": "1.5.10"
}
},
"babel-helper-vue-jsx-merge-props": {
"version": "2.0.3",
"resolved": "https://registry.npm.taobao.org/babel-helper-vue-jsx-merge-props/download/babel-helper-vue-jsx-merge-props-2.0.3.tgz",
"integrity": "sha1-Iq69OzOQIyjlEyk6jkmSs4T58bY="
},
"babel-runtime": {
"version": "6.26.0",
"resolved": "https://registry.npm.taobao.org/babel-runtime/download/babel-runtime-6.26.0.tgz",
"integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=",
"requires": {
"core-js": "^2.4.0",
"regenerator-runtime": "^0.11.0"
}
},
"classnames": {
"version": "2.2.6",
"resolved": "https://registry.npm.taobao.org/classnames/download/classnames-2.2.6.tgz",
"integrity": "sha1-Q5Nb/90pHzJtrQogUwmzjQD2UM4="
},
"component-classes": {
"version": "1.2.6",
"resolved": "https://registry.npm.taobao.org/component-classes/download/component-classes-1.2.6.tgz",
"integrity": "sha1-xkI5TDYYpNiwuJGe/Mu9kw5c1pE=",
"requires": {
"component-indexof": "0.0.3"
}
},
"component-indexof": {
"version": "0.0.3",
"resolved": "https://registry.npm.taobao.org/component-indexof/download/component-indexof-0.0.3.tgz",
"integrity": "sha1-EdCRMSI5648yyPJa6csAL/6NPCQ="
},
"core-js": {
"version": "2.6.11",
"resolved": "https://registry.npm.taobao.org/core-js/download/core-js-2.6.11.tgz?cache=0&sync_timestamp=1586450708853&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcore-js%2Fdownload%2Fcore-js-2.6.11.tgz",
"integrity": "sha1-OIMUafmSK97Y7iHJ3EaYXgOZMIw="
},
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npm.taobao.org/debug/download/debug-3.1.0.tgz?cache=0&sync_timestamp=1589880401175&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fdebug%2Fdownload%2Fdebug-3.1.0.tgz",
"integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=",
"requires": {
"ms": "2.0.0"
}
},
"dom-align": {
"version": "1.12.0",
"resolved": "https://registry.npm.taobao.org/dom-align/download/dom-align-1.12.0.tgz?cache=0&sync_timestamp=1589856094502&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fdom-align%2Fdownload%2Fdom-align-1.12.0.tgz",
"integrity": "sha1-VvtxVt8LkQmYMDZNLUj4iWP1opw="
},
"dom-closest": {
"version": "0.2.0",
"resolved": "https://registry.npm.taobao.org/dom-closest/download/dom-closest-0.2.0.tgz",
"integrity": "sha1-69n5HRvyLo1vR3h2u80+yQIWwM8=",
"requires": {
"dom-matches": ">=1.0.1"
}
},
"dom-matches": {
"version": "2.0.0",
"resolved": "https://registry.npm.taobao.org/dom-matches/download/dom-matches-2.0.0.tgz",
"integrity": "sha1-0nKLQWqHUzmA6wibhI0lPPI6dYw="
},
"dom-scroll-into-view": {
"version": "2.0.1",
"resolved": "https://registry.npm.taobao.org/dom-scroll-into-view/download/dom-scroll-into-view-2.0.1.tgz",
"integrity": "sha1-DezIUigB/Y0/HGujVadNOCxfmJs="
},
"enquire.js": {
"version": "2.1.6",
"resolved": "https://registry.npm.taobao.org/enquire.js/download/enquire.js-2.1.6.tgz",
"integrity": "sha1-PoeAybi4NQhMP2DhZtvDwqPImBQ="
},
"follow-redirects": {
"version": "1.5.10",
"resolved": "https://registry.npm.taobao.org/follow-redirects/download/follow-redirects-1.5.10.tgz?cache=0&sync_timestamp=1585479417937&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Ffollow-redirects%2Fdownload%2Ffollow-redirects-1.5.10.tgz",
"integrity": "sha1-e3qfmuov3/NnhqlP9kPtB/T/Xio=",
"requires": {
"debug": "=3.1.0"
}
},
"intersperse": {
"version": "1.0.0",
"resolved": "https://registry.npm.taobao.org/intersperse/download/intersperse-1.0.0.tgz",
"integrity": "sha1-8lYfsc/vn1J3zDNHoiiGtDUaUYE="
},
"is-mobile": {
"version": "2.2.1",
"resolved": "https://registry.npm.taobao.org/is-mobile/download/is-mobile-2.2.1.tgz?cache=0&sync_timestamp=1581934142150&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fis-mobile%2Fdownload%2Fis-mobile-2.2.1.tgz",
"integrity": "sha1-EPIyABLEEMwoX+7LE0Br1Ybxsvg="
},
"is-negative-zero": {
"version": "2.0.0",
"resolved": "https://registry.npm.taobao.org/is-negative-zero/download/is-negative-zero-2.0.0.tgz",
"integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE="
},
"ismobilejs": {
"version": "1.1.1",
"resolved": "https://registry.npm.taobao.org/ismobilejs/download/ismobilejs-1.1.1.tgz",
"integrity": "sha1-xWygro5Sskyg8iul7zIVot27qg4="
},
"js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npm.taobao.org/js-tokens/download/js-tokens-4.0.0.tgz",
"integrity": "sha1-GSA/tZmR35jjoocFDUZHzerzJJk="
},
"json2mq": {
"version": "0.2.0",
"resolved": "https://registry.npm.taobao.org/json2mq/download/json2mq-0.2.0.tgz",
"integrity": "sha1-tje9O6nqvhIsg+lyBIOusQ0skEo=",
"requires": {
"string-convert": "^0.2.0"
}
},
"lodash": {
"version": "4.17.15",
"resolved": "https://registry.npm.taobao.org/lodash/download/lodash-4.17.15.tgz",
"integrity": "sha1-tEf2ZwoEVbv+7dETku/zMOoJdUg="
},
"lodash.toarray": {
"version": "4.4.0",
"resolved": "https://registry.npm.taobao.org/lodash.toarray/download/lodash.toarray-4.4.0.tgz",
"integrity": "sha1-JMS/zWsvuji/0FlNsRedjptlZWE="
},
"loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npm.taobao.org/loose-envify/download/loose-envify-1.4.0.tgz",
"integrity": "sha1-ce5R+nvkyuwaY4OffmgtgTLTDK8=",
"requires": {
"js-tokens": "^3.0.0 || ^4.0.0"
}
},
"moment": {
"version": "2.26.0",
"resolved": "https://registry.npm.taobao.org/moment/download/moment-2.26.0.tgz?cache=0&sync_timestamp=1589957212921&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmoment%2Fdownload%2Fmoment-2.26.0.tgz",
"integrity": "sha1-Xh+Cxrr8pug+gIswyHBe7Q3L05o="
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npm.taobao.org/ms/download/ms-2.0.0.tgz?cache=0&sync_timestamp=1581667532618&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fms%2Fdownload%2Fms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"mutationobserver-shim": {
"version": "0.3.5",
"resolved": "https://registry.npm.taobao.org/mutationobserver-shim/download/mutationobserver-shim-0.3.5.tgz",
"integrity": "sha1-bzXOhYZ7IaoeWPeIktCrTu6ULA4="
},
"node-emoji": {
"version": "1.10.0",
"resolved": "https://registry.npm.taobao.org/node-emoji/download/node-emoji-1.10.0.tgz",
"integrity": "sha1-iIar0l2ce7YYAqZYUj0fjSqJsto=",
"requires": {
"lodash.toarray": "^4.4.0"
}
},
"object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npm.taobao.org/object-assign/download/object-assign-4.1.1.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fobject-assign%2Fdownload%2Fobject-assign-4.1.1.tgz",
"integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
},
"omit.js": {
"version": "1.0.2",
"resolved": "https://registry.npm.taobao.org/omit.js/download/omit.js-1.0.2.tgz",
"integrity": "sha1-kaFPDrqEBm36AVvzDkdMR/MLyFg=",
"requires": {
"babel-runtime": "^6.23.0"
}
},
"performance-now": {
"version": "2.1.0",
"resolved": "https://registry.npm.taobao.org/performance-now/download/performance-now-2.1.0.tgz",
"integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns="
},
"raf": {
"version": "3.4.1",
"resolved": "https://registry.npm.taobao.org/raf/download/raf-3.4.1.tgz",
"integrity": "sha1-B0LpmkplUvRF1z4+4DKK8P8e3jk=",
"requires": {
"performance-now": "^2.1.0"
}
},
"regenerator-runtime": {
"version": "0.11.1",
"resolved": "https://registry.npm.taobao.org/regenerator-runtime/download/regenerator-runtime-0.11.1.tgz?cache=0&sync_timestamp=1584052481783&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fregenerator-runtime%2Fdownload%2Fregenerator-runtime-0.11.1.tgz",
"integrity": "sha1-vgWtf5v30i4Fb5cmzuUBf78Z4uk="
},
"resize-observer-polyfill": {
"version": "1.5.1",
"resolved": "https://registry.npm.taobao.org/resize-observer-polyfill/download/resize-observer-polyfill-1.5.1.tgz",
"integrity": "sha1-DpAg3T0hAkRY1OvSfiPkAmmBBGQ="
},
"shallow-equal": {
"version": "1.2.1",
"resolved": "https://registry.npm.taobao.org/shallow-equal/download/shallow-equal-1.2.1.tgz",
"integrity": "sha1-TBar+lYEOqINBQMk76aJQLDaedo="
},
"shallowequal": {
"version": "1.1.0",
"resolved": "https://registry.npm.taobao.org/shallowequal/download/shallowequal-1.1.0.tgz",
"integrity": "sha1-GI1SHelbkIdAT9TctosT3wrk5/g="
},
"string-convert": {
"version": "0.2.1",
"resolved": "https://registry.npm.taobao.org/string-convert/download/string-convert-0.2.1.tgz",
"integrity": "sha1-aYLMMEn7tM2F+LJFaLnZvznu/5c="
},
"tinycolor2": {
"version": "1.4.1",
"resolved": "https://registry.npm.taobao.org/tinycolor2/download/tinycolor2-1.4.1.tgz",
"integrity": "sha1-9PrTM0R7wLB9TcjpIJ2POaisd+g="
},
"vue": {
"version": "2.6.11",
"resolved": "https://registry.npm.taobao.org/vue/download/vue-2.6.11.tgz",
"integrity": "sha1-dllNh31LEiNEBuhONSdcbVFBJcU="
},
"vue-ref": {
"version": "2.0.0",
"resolved": "https://registry.npm.taobao.org/vue-ref/download/vue-ref-2.0.0.tgz?cache=0&sync_timestamp=1586427009516&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fvue-ref%2Fdownload%2Fvue-ref-2.0.0.tgz",
"integrity": "sha1-SDCE1zKr7RHaeWd4qCZqOvDqGpw="
},
"vue-router": {
"version": "3.2.0",
"resolved": "https://registry.npm.taobao.org/vue-router/download/vue-router-3.2.0.tgz",
"integrity": "sha1-2jUZX/43/fC+yfX49yeB0qdxiBU="
},
"warning": {
"version": "4.0.3",
"resolved": "https://registry.npm.taobao.org/warning/download/warning-4.0.3.tgz",
"integrity": "sha1-Fungd+uKhtavfWSqHgX9hbRnjKM=",
"requires": {
"loose-envify": "^1.0.0"
}
}
}
}
{
"name": "mo",
"version": "1.0.0",
"description": "+1s",
"author": "abbycin <abbytsing@gmail.com>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"lint": "eslint --ext .js,.vue src",
"build": "node build/build.js"
},
"dependencies": {
"ant-design-vue": "^1.6.0",
"lodash": "^4.17.15",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-eslint": "^8.2.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"chalk": "^2.0.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.0",
"eslint": "^4.15.0",
"eslint-config-standard": "^10.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^3.0.1",
"eslint-plugin-vue": "^4.0.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.9.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
\ No newline at end of file
<template>
<div>
<a-menu class="header-menu" mode="horizontal" @click="onSelected">
<a-sub-menu>
<span slot="title" class="wrapper">
<a-icon type="setting"/>
</span>
<a-menu-item key="change_pass">
修改密码
</a-menu-item>
<a-menu-item key="logout">
注销
</a-menu-item>
</a-sub-menu>
</a-menu>
</div>
</template>
<script>
import {request} from "@/js/req";
export default {
name: 'HeaderMenu',
data() {
return {};
},
methods: {
onSelected(item) {
if(item.key === "change_pass") {
this.$router.push('/manage/user');
} else {
request('DELETE', '/api/login', null, (ok) => {
if(ok.code !== 0) {
throw ok.msg;
}
this.$router.push('/');
}, (err) => {
this.$message.error(`错误: ${err}`);
});
}
}
}
}
</script>
<style scoped>
.header-menu {
float: right;
}
</style>
\ No newline at end of file
<template>
<div>
<pre>
如何使用:
1, 切换到 Server
2, 填写 Server Root, 如: E:/tophttpserver/1.1.9
3, 填写测试连接的地址 Test URL,目前只支持GET方法
4, 切换到 DB,如果前面没有填错就会看到数据库配置的卡片
分表需要填写数据库连接名(DB中的标题)
</pre>
</div>
</template>
<script>
export default {
name: 'Intro',
data() {
return {};
}
}
</script>
\ No newline at end of file
<template>
<div id="login" class="hello">
<a-form id="login_form" v-bind:form="form" @submit="handleSubmit">
<a-form-item :validate-status="userNameError() ? 'error' : ''" :help="userNameError() || ''">
<a-input
v-decorator="[
'userName',
{ rules: [{ required: true, message: '请输入用户名!' }] },
]"
placeholder="Username"
>
<a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />
</a-input>
</a-form-item>
<a-form-item :validate-status="passwordError() ? 'error' : ''" :help="passwordError() || ''">
<a-input
v-decorator="[
'password',
{ rules: [{ required: true, message: '请输入密码!' }] },
]"
type="password"
placeholder="Password"
>
<a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
</a-input>
</a-form-item>
<a-form-item>
<a-button id="login_btn" type="primary" html-type="submit">Log in</a-button>
</a-form-item>
</a-form>
</div>
</template>
<script>
import {request} from '@/js/req';
export default {
name: "Login",
data() {
return {
form: this.$form.createForm(this, { name: "horizontal" }),
// other way for v-decorator
formRules: {
remember_me: [
"remember-me",
{ valuePropName: "unchecked", initialValue: false }
]
}
};
},
methods: {
userNameError() {
const { getFieldError, isFieldTouched } = this.form;
return isFieldTouched("userName") && getFieldError("userName");
},
passwordError() {
const { getFieldError, isFieldTouched } = this.form;
return isFieldTouched("password") && getFieldError("password");
},
handleSubmit(e) {
e.preventDefault();
let self = this;
let valid = true;
let values = {};
this.form.validateFields(function(err, data) {
if(err) {
valid = false;
} else {
values = data;
}
});
if(!valid) {
this.$message.error('用户名和密码不能为空');
} else {
request('POST', '/api/login', values, (data) => {
if(data.code !== 0) {
throw data.msg;
}
this.$router.push('/manage');
}, (err) => {
this.$message.error(`错误: ${err}`);
});
}
}
}
};
</script>
<style>
#login_form {
max-width: 300px;
}
#login_btn {
float: right;
}
#login {
width: 300px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -150px;
}
</style>
\ No newline at end of file
<template>
<div>
<div>
<a-input v-model="searchText" size="large" placeholder="搜索 标题" @change="filterData" />
<a-row>
<a-col :span="8">
<a-input-search placeholder="输入数据库名" size="large" @search="partition">
<a-button :disabled="partitionIsRunning" type="primary" slot="enterButton">分表</a-button>
</a-input-search>
</a-col>
<a-col :span="4"></a-col>
<a-col :span="10" style="float: right">
<a-button type="dashed" size="large" @click="addOne">
<a-icon type="plus" />新建连接
</a-button>
<a-button type="danger" size="large" @click="applyChange">
<a-icon type="check" />应用修改
</a-button>
<a-button type="primary" size="large" @click="resetChange">
<a-icon type="undo" />重置修改
</a-button>
</a-col>
</a-row>
<a-modal
:visible="editorVisible"
title="编辑连接"
@cancel="closeEditor(false)"
@ok="closeEditor(true)"
width="60%"
>
<a-form layout="vertical" :form="form" :label-col="{span: 8}" :wrapper-col="{ span: 16 }">
<a-form-item label="Title">
<a-input v-decorator="['title', { rules: [{ required: true, message: '请输入标题'}]}]" />
</a-form-item>
<a-form-item label="Database Type">
<a-select
v-decorator="['database_type', { rules: [{required: true, message: '请选择数据库类型'}]}]"
placeholder="从以下的数据库类型中选择一个"
>
<a-select-option value="pg">PostgreSQL</a-select-option>
<a-select-option value="mysql">MySQL</a-select-option>
<a-select-option value="oracle">Oracle</a-select-option>
<a-select-option value="mssql">SQL Server</a-select-option>
<a-select-option value="sqlite">SQLite</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Database Host">
<a-input
v-decorator="[
'database_host',
{
rules: [{ required: true, message: '请输入 database host!' }],
}
]"
placeholder="例如 127.0.0.1:5433,sqlite的话随便填"
/>
</a-form-item>
<a-form-item label="Database Name">
<a-input
v-decorator="[
'database_name',
{
rules: [{ required: true, message: '请输入 database name!'}]
}
]"
placeholder="例如 XXX_DEV,sqlite则填数据库文件(.db)的绝对路径"
/>
</a-form-item>
<a-form-item label="Database User">
<a-input v-decorator="['database_user']" />
</a-form-item>
<a-form-item label="Database Password">
<a-input v-decorator="['database_pwd']" />
</a-form-item>
<a-form-item label="Database Encrypt">
<a-input v-decorator="['database_encrypt']" placeholder="默认不填,仅支持 EB642" />
</a-form-item>
<a-form-item label="Database Options">
<a-input v-decorator="['database_options']" />
</a-form-item>
<a-form-item label="Close Timeout">
<a-input v-decorator="['auto_close_timeout']" />
</a-form-item>
</a-form>
</a-modal>
</div>
<div style="margin-top:20px">
<a-list :grid="{ gutter: 16, column: 4 }" :data-source="data">
<a-list-item slot="renderItem" slot-scope="item, index">
<a-card :title="item.title">
<a slot="extra" @click="removeOne(index)">
<a-icon type="close"></a-icon>
</a>
<a slot="extra" @click="editOne(index)">
<a-icon type="edit"></a-icon>
</a>
<pre>
{{ JSON.stringify(item, null, ' ') }}
</pre>
</a-card>
</a-list-item>
</a-list>
</div>
</div>
</template>
<script>
import _ from "lodash";
import { request } from "@/js/req";
let data = [];
export default {
name: "ManageDB",
data() {
return {
data,
editorVisible: false,
orgData: _.cloneDeep(data),
modified: [],
searchText: "",
isNewItem: false,
currIndex: -1,
partitionIsRunning: false
};
},
beforeCreate() {
this.form = this.$form.createForm(this, { name: "editor" });
},
mounted() {
// Antd setFiledsValue issue
// https://github.com/ant-design/ant-design/issues/8880
let p = [
"title",
"database_type",
"database_host",
"database_name",
"database_user",
"database_pwd",
"database_encrypt",
"database_options",
"auto_close_timeout"
];
p.forEach(v => {
this.form.getFieldDecorator(v, { initialValue: "" });
});
request(
"GET",
"/api/db",
null,
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
this.data = [];
for (let [title, v] of Object.entries(ok.data)) {
this.data.push({ title, ...v });
}
this.orgData = _.cloneDeep(this.data);
},
err => {
this.$message.error(`错误: ${err}`);
}
);
},
methods: {
removeOne(index) {
this.modified.push(this.data[index].title);
this.data.splice(index, 1);
},
editOne(index) {
this.currIndex = index;
this.form.setFieldsValue(this.data[index]);
this.editorVisible = true;
},
addOne() {
this.isNewItem = true;
this.form.resetFields();
this.editorVisible = true;
},
closeEditor(ok) {
// cancel
if (!ok) {
this.isNewItem = false;
this.currIndex = -1;
this.editorVisible = false;
} else {
// confirm
let values = {};
let valid = true;
this.form.validateFields((e, d) => {
if (e) {
valid = false;
} else {
values = _.pickBy(d, x => {
return (
!_.isNull(x) && !_.isUndefined(x) && _.toString(x).length > 0
);
});
}
});
if (valid) {
for (let i = 0; i < this.data.length; ++i) {
if (this.data[i].title == values.title && this.currIndex < 0) {
this.$message.error(`标题 ${values.title} 已经存在`);
return;
}
}
if (this.isNewItem) {
this.data.unshift(values);
} else {
this.modified.push(this.data[this.currIndex].title);
this.data[this.currIndex] = values;
}
this.editorVisible = false;
this.isNewItem = false;
this.currIndex = -1;
}
}
},
applyChange() {
let newData = new Map();
this.data.forEach(x => {
newData.set(x.title, x);
});
let oldData = new Map();
this.orgData.forEach(x => {
oldData.set(x.title, x);
});
// remove modified from orgdata first, in case who remove old one and create a new one that same to modified one
this.modified.forEach(x => {
oldData.delete(x);
});
this.modified = [];
for (let [k, v] of newData) {
oldData.set(k, v);
}
this.orgData = [];
let payload = {};
for (let [_, v] of oldData) {
let title = v.title;
payload[title] = v;
delete payload[title].title;
}
for (let item of this.orgData) {
let title = item.title;
payload[title] = { ...item };
delete payload[title].title;
}
request(
"PUT",
"/api/db",
payload,
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
for(let [_, v] of oldData) {
this.orgData.push(v);
}
this.$message.info("所以更改提交成功");
},
err => {
this.$message.error(`error: ${err}`);
}
);
},
resetChange() {
this.data = _.cloneDeep(this.orgData);
this.searchText = "";
this.$message.info("所以更改已回退");
},
filterData(e) {
e.preventDefault();
this.data = this.orgData.filter(item => {
let lower = item.title.toLowerCase();
return lower.indexOf(this.searchText.toLowerCase()) != -1;
});
},
partition(dbname) {
if(dbname === null || dbname.length === 0) {
this.$message.error(`数据库不能为空`);
return;
}
let url = window.localStorage.getItem("service_url");
if (!url) {
this.$message.error(`错误: 无法获得服务端地址`);
return;
}
let getu = u => {
if (u.length == 0) {
return u;
}
let idx = 0;
let count = 0;
while (idx < u.length) {
if (u[idx] == "/") {
count += 1;
}
if (count > 2 && u[idx] == "/") {
break;
}
idx += 1;
}
if (idx == u.length) {
return u;
}
return u.substring(0, idx);
};
this.partitionIsRunning = true;
url = `${getu(url)}/api/${dbname}/ikm6/system/runCreatePartitionTableTask`;
request("GET", url, null, ok => {
this.partitionIsRunning = false;
this.$message.info(`分表请求已提交,结果为: ${ok}`);
}, err => {
this.partitionIsRunning = false;
this.$message.error(`分表创建出错,结果为:${err}`);
});
}
}
};
</script>
\ No newline at end of file
<template>
<a-form :form="form" @submit="handleUpdate">
<a-form-item
v-bind="formItemLayout"
label="Server Root"
extra="绝对路径,例如 /opt/tophttpserver/1.1.9"
>
<a-input
v-decorator="[
'server_root',
{
rules: [
{
required: true,
message: '请输入 server root!',
},
],
},
]"
/>
</a-form-item>
<a-form-item v-bind="formItemLayout" label="Service URL" extra="检查tophttpserver是否可用,仅支持GET">
<a-row :gutter="24">
<a-col :span="22">
<a-input
v-decorator="[
'test_url',
{ rules: [{ required: true, message: '请输入 service url!' }] },
]"
/>
</a-col>
<a-col :span="2">
<a-button @click="handleTest">测试</a-button>
</a-col>
</a-row>
</a-form-item>
<a-form-item v-bind="tailFormItemLayout">
<a-button :disabled="restart" type="danger" @click="handleRestart">重启 httpserver</a-button>
<a-button type="primary" html-type="submit" style="float: right">更新配置</a-button>
</a-form-item>
</a-form>
</template>
<script>
import { request } from "@/js/req";
export default {
name: "ManageServer",
data() {
return {
restart: window.localStorage.getItem("disable_restart") === "true"
};
},
beforeCreate() {
this.form = this.$form.createForm(this, { name: "serverForm" });
},
mounted() {
let p = ["server_root", "test_url"];
p.forEach(v => {
this.form.getFieldDecorator(v, { initalValue: "" });
});
request(
"GET",
"/api/server",
null,
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
window.localStorage.setItem("service_url", ok.data.test_url);
this.form.setFieldsValue(ok.data);
},
err => {
this.$message.error(`错误: ${err}`);
}
);
},
methods: {
handleUpdate() {
let data = {};
let err = "";
try {
this.form.validateFields((e, values) => {
if (e) {
err = "server root 或 service url 为空";
return;
}
if (
!values.server_root ||
values.server_root.length === 0 ||
!values.test_url ||
values.test_url.length === 0
) {
err = "server root 或 service url 为空";
return;
}
data = values;
});
if(data.test_url.indexOf('http://') == -1 && data.test_url.indexOf('https://') == -1) {
throw "非法的 service url";
}
if (err) {
throw err;
}
} catch (e) {
this.$message.error(`错误: ${e}`);
return;
}
request(
"PUT",
"/api/server",
data,
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
window.localStorage.setItem("service_url", data.test_url);
this.$message.info("更改已成功提交到服务端");
},
err => {
this.$message.error(`错误: ${err}`);
}
);
},
handleTest() {
let url = this.form.getFieldValue("test_url");
if(!url || (url.indexOf('http://') == -1 && url.indexOf('https://') == -1)) {
this.$message.error("请设置正确的 service url");
return;
}
fetch(url)
.then(response => {
return response.text();
})
.then(txt => {
this.restart = false;
window.localStorage.setItem("disable_restart", "false");
this.$message.info("服务可用");
})
.catch(err => {
this.$message.error(`服务不可用:${err}`);
});
},
handleRestart() {
request(
"POST",
"/api/server",
{ command: "restart" },
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
this.$message.info("服务重启请求已发送,稍后可测试是否已启动");
this.restart = true;
window.localStorage.setItem("disable_restart", "true");
},
err => {
this.$message.error(`服务重启失败:${err}`);
}
);
}
}
};
</script>
\ No newline at end of file
<template>
<a-form class="user" :form="form" @submit="handleSubmit">
<h3>Change Password</h3>
<a-form-item v-bind="formItemLayout" label="新的密码" has-feedback>
<a-input v-decorator="['new_pass', { rules: [{ required: true, message: '请输入新密码'}]}]" type="password" />
</a-form-item>
<a-form-item v-bind="formItemLayout" label="确认密码" has-feedback>
<a-input v-decorator="['retype', { rules: [{ required: true, message: '请再次输入新密码'}]}]" type="password" />
</a-form-item>
<a-form-item v-bind="tailFormItemLayout">
<a-button id="ok-btn" type="primary" html-type="submit">Ok</a-button>
</a-form-item>
</a-form>
</template>
<script>
import {request} from "@/js/req";
export default {
name: "ManageUser",
data() {
return {
form: this.$form.createForm(this, { name: "horizental" })
};
},
methods: {
handleSubmit(e) {
e.preventDefault();
let values = {};
let error = null;
this.form.validateFields(function(err, data) {
if (err) {
error = err;
} else {
values = data;
}
});
if (error) {
this.$message.error(`错误: ${err}`);
} else {
if(values.new_pass !== values.retype) {
this.$message.error("密码不匹配!");
return;
}
request('PUT', '/api/login', {password: values.new_pass}, (data) => {
if(data.code !== 0) {
throw data.msg;
}
this.$message.info('密码已修改');
setTimeout(() => { this.$router.push('/')}, 1000);
}, (err) => {
this.$message.error(`error: ${err}`);
});
}
}
}
};
</script>
<style scoped>
.user {
max-width: 300px;
}
#ok-btn {
float: right;
}
</style>
\ No newline at end of file
<template>
<div class="layout-container">
<a-row>
<a-col :span="24">
<HeaderMenu />
</a-col>
</a-row>
<a-row>
<a-col :span="4">
<SideMenu />
</a-col>
<a-col :span="18">
<router-view />
</a-col>
<a-col :span="2">
</a-col>
</a-row>
</div>
</template>
<script>
import SideMenu from "@/components/sidemenu";
import HeaderMenu from "@/components/header";
export default {
name: "Manage",
data() {
return {};
},
components: {
SideMenu,
HeaderMenu
}
};
</script>
\ No newline at end of file
<template>
<div style="width: 256px">
<a-button type="primary" style="margin-bottom: 16px" @click="toggleCollapsed">
<a-icon :type="collapsed ? 'menu-unfold' : 'menu-fold'" />
</a-button>
<a-menu
:default-selected-keys="['1']"
mode="inline"
theme="light"
:inline-collapsed="collapsed"
v-on:click="selectionChanged"
>
<a-menu-item key="1">
<span>main</span>
</a-menu-item>
<a-menu-item key="2">
<span>DB</span>
</a-menu-item>
<a-menu-item key="3">
<span>Server</span>
</a-menu-item>
</a-menu>
</div>
</template>
<script>
export default {
name: "SideMenu",
data() {
return {
collapsed: true,
rm: {
"1": "/manage/intro",
"2": "/manage/db",
"3": "/manage/server"
}
};
},
methods: {
toggleCollapsed() {
//this.collapsed = !this.collapsed;
},
selectionChanged(item) {
this.$router.push(this.rm[item.key]);
}
}
};
</script>
\ No newline at end of file
function request(method, url, data, ok, err) {
let promise = null;
if(method === "GET") {
promise = fetch(url);
} else if(method === "DELETE") {
promise = fetch(url, {method: method});
} else {
promise = fetch(url, {
method: method,
body: JSON.stringify(data),
headers: {
'content-type': 'application/json'
}
})
}
promise.then(response => {
if(response.ok) {
return response.json();
} else {
response.text().then(txt => {
throw txt;
}).catch(e => {
err(e);
});
return null;
}
}).then(j => {
if(j) {
ok(j);
}
}).catch(e => {
err(e);
});
}
export {request};
\ No newline at end of file
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'
Vue.config.productionTip = false
Vue.use(Antd);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/login'
import Manage from '@/components/manage'
import ManageUser from '@/components/manage-user'
import ManageDB from '@/components/manage-db'
import ManageServer from '@/components/manage-server'
import Intro from '@/components/intro'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Login',
component: Login
},
{
path: '/manage',
name: 'Manage',
component: Manage,
redirect: 'manage/intro', // can't use `/manage/user`, why?
children: [
{
path: 'intro',
name: 'Intro',
component: Intro
},
{
path: 'user',
name: 'User',
component: ManageUser
},
{
path: 'db',
name: 'DataBase',
component: ManageDB
},
{
path: 'server',
name: 'HTTPServer',
component: ManageServer
}
]
}
]
})
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment