静态资源嵌入

develop
ouqiang 7 years ago
parent 06859f3464
commit e497261789

3
.gitignore vendored

@ -37,4 +37,5 @@ profile/*
/gocron_package
/gocron-node_package
node_modules
node_modules
internal/statik

@ -56,12 +56,13 @@
4. 浏览器访问 http://localhost:5920
### 源码安装
1. 安装Go 1.9+, Node.js, Yarn
2. `go get -d github.com/ouqiang/gocron`
3. 安装依赖 `make install-vue`
4. 前端打包 `make build-vue`
5. 编译Go代码 `make`
6. 启动
- 安装Go 1.9+, Node.js, Yarn
- `go get -d github.com/ouqiang/gocron`
- 安装依赖 `make install-vue`
- 前端打包 `make build-vue`
- 静态资源嵌入 `make statik`
- 编译Go代码 `make`
- 启动
* gocron `./bin/gocron web`
* gocron-node `./bin/gocron-node`

@ -1,4 +1,5 @@
// Command gocron
//go:generate statik -src=../../web/public -dest=../../internal -f
package main

@ -66,6 +66,9 @@ func Read(filename string) (*Setting, error) {
s.ApiSignEnable = section.Key("api.sign.enable").MustBool(true)
s.ConcurrencyQueue = section.Key("concurrency.queue").MustInt(500)
s.AuthSecret = section.Key("auth_secret").MustString("")
if s.AuthSecret == "" {
s.AuthSecret = utils.RandAuthToken()
}
s.EnableTLS = section.Key("enable_tls").MustBool(false)
s.CAFile = section.Key("ca_file").MustString("")

@ -2,7 +2,9 @@ package utils
import (
"crypto/md5"
crand "crypto/rand"
"encoding/hex"
"fmt"
"math/rand"
"os"
"strings"
@ -11,6 +13,16 @@ import (
"github.com/Tang-RoseChild/mahonia"
)
func RandAuthToken() string {
buf := make([]byte, 32)
_, err := crand.Read(buf)
if err != nil {
return RandString(64)
}
return fmt.Sprintf("%x", buf)
}
// 生成长度为length的随机字符串
func RandString(length int64) string {
sources := []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

@ -4,8 +4,6 @@ import (
"fmt"
"strconv"
"crypto/rand"
"github.com/go-macaron/binding"
"github.com/ouqiang/gocron/internal/models"
"github.com/ouqiang/gocron/internal/modules/app"
@ -97,12 +95,6 @@ func Store(ctx *macaron.Context, form InstallForm) string {
// 配置写入文件
func writeConfig(form InstallForm) error {
buf := make([]byte, 32)
_, err := rand.Read(buf)
if err != nil {
return fmt.Errorf("生成认证密钥失败: %s", err)
}
dbConfig := []string{
"db.engine", form.DbType,
"db.host", form.DbHost,
@ -120,7 +112,7 @@ func writeConfig(form InstallForm) error {
"api.secret", "",
"enable_tls", "false",
"concurrency.queue", "500",
"auth_secret", fmt.Sprintf("%x", buf),
"auth_secret", utils.RandAuthToken(),
"ca_file", "",
"cert_file", "",
"key_file", "",

@ -1,7 +1,9 @@
package routers
import (
"path/filepath"
"io"
"log"
"net/http"
"strconv"
"strings"
"time"
@ -19,7 +21,10 @@ import (
"github.com/ouqiang/gocron/internal/routers/task"
"github.com/ouqiang/gocron/internal/routers/tasklog"
"github.com/ouqiang/gocron/internal/routers/user"
"github.com/rakyll/statik/fs"
"gopkg.in/macaron.v1"
_ "github.com/ouqiang/gocron/internal/statik"
)
// URL前缀
@ -27,16 +32,30 @@ const urlPrefix = "/api"
var staticDir = "public"
var statikFS http.FileSystem
func init() {
var err error
statikFS, err = fs.New()
if err != nil {
log.Fatal(err)
}
}
// 路由注册
func Register(m *macaron.Macaron) {
if macaron.Env != macaron.PROD {
staticDir = "web/public"
}
m.SetURLPrefix(urlPrefix)
// 所有GET方法自动注册HEAD方法
m.SetAutoHead(true)
m.Get("/", func(ctx *macaron.Context) {
ctx.ServeFileContent(filepath.Join(app.AppDir, staticDir, "index.html"))
file, err := statikFS.Open("/index.html")
if err != nil {
logger.Error("读取首页文件失败: %s", err)
ctx.WriteHeader(http.StatusInternalServerError)
return
}
io.Copy(ctx.Resp, file)
})
// 系统安装
m.Group("/install", func() {
@ -128,7 +147,15 @@ func RegisterMiddleware(m *macaron.Macaron) {
if macaron.Env != macaron.DEV {
m.Use(gzip.Gziper())
}
m.Use(macaron.Static(filepath.Join(app.AppDir, staticDir)))
m.Use(
macaron.Static(
"",
macaron.StaticOptions{
Prefix: staticDir,
FileSystem: statikFS,
},
),
)
if macaron.Env == macaron.DEV {
m.Use(toolbox.Toolboxer(m))
}
@ -146,7 +173,7 @@ func checkAppInstall(ctx *macaron.Context) {
if app.Installed {
return
}
if ctx.Req.URL.Path == "/install/store" {
if ctx.Req.URL.Path == "/install/store" || ctx.Req.URL.Path == "/" {
return
}
jsonResp := utils.JsonResponse{}

@ -38,7 +38,7 @@ enable-race:
$(eval RACE = -race)
.PHONY: package
package: build-vue
package: build-vue statik
bash ./package.sh
.PHONY: build-vue
@ -50,6 +50,11 @@ build-vue:
install-vue:
cp web/vue && yarn install
.PHONY: statik
statik:
go get github.com/rakyll/statik
go generate ./...
.PHONY: clean
clean:
rm bin/gocron

@ -178,7 +178,7 @@ run() {
package_gocron() {
BINARY_NAME='gocron'
MAIN_FILE="./cmd/gocron/gocron.go"
INCLUDE_FILE=(Dockerfile-release README.md web/public)
INCLUDE_FILE=(Dockerfile-release README.md)
run

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2014 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -0,0 +1,45 @@
# statik
[![Build Status](https://travis-ci.org/rakyll/statik.svg?branch=master)](https://travis-ci.org/rakyll/statik)
statik allows you to embed a directory of static files into your Go binary to be later served from an http.FileSystem.
Is this a crazy idea? No, not necessarily. If you're building a tool that has a Web component, you typically want to serve some images, CSS and JavaScript. You like the comfort of distributing a single binary, so you don't want to mess with deploying them elsewhere. If your static files are not large in size and will be browsed by a few people, statik is a solution you are looking for.
## Usage
Install the command line tool first.
go get github.com/rakyll/statik
statik is a tiny program that reads a directory and generates a source file contains its contents. The generated source file registers the directory contents to be used by statik file system.
The command below will walk on the public path and generate a package called `statik` under the current working directory.
$ statik -src=/path/to/your/project/public
In your program, all your need to do is to import the generated package, initialize a new statik file system and serve.
~~~ go
import (
"github.com/rakyll/statik/fs"
_ "./statik" // TODO: Replace with the absolute import path
)
// ...
statikFS, err := fs.New()
if err != nil {
log.Fatal(err)
}
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS)))
http.ListenAndServe(":8080", nil)
~~~
Visit http://localhost:8080/public/path/to/file to see your file.
There is also a working example under [example](https://github.com/rakyll/statik/tree/master/example) directory, follow the instructions to build and run it.
Note: The idea and the implementation are hijacked from [camlistore](http://camlistore.org/). I decided to decouple it from its codebase due to the fact I'm actively in need of a similar solution for many of my projects.

@ -0,0 +1,233 @@
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package contains a program that generates code to register
// a directory and its contents as zip data for statik file system.
package main
import (
"archive/zip"
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"time"
)
const (
namePackage = "statik"
nameSourceFile = "statik.go"
)
var (
flagSrc = flag.String("src", path.Join(".", "public"), "The path of the source directory.")
flagDest = flag.String("dest", ".", "The destination path of the generated package.")
flagNoMtime = flag.Bool("m", false, "Ignore modification times on files.")
flagNoCompress = flag.Bool("Z", false, "Do not use compression to shrink the files.")
flagForce = flag.Bool("f", false, "Overwrite destination file if it already exists.")
flagTags = flag.String("tags", "", "Write build constraint tags")
)
// mtimeDate holds the arbitrary mtime that we assign to files when
// flagNoMtime is set.
var mtimeDate = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
func main() {
flag.Parse()
file, err := generateSource(*flagSrc)
if err != nil {
exitWithError(err)
}
destDir := path.Join(*flagDest, namePackage)
err = os.MkdirAll(destDir, 0755)
if err != nil {
exitWithError(err)
}
err = rename(file.Name(), path.Join(destDir, nameSourceFile))
if err != nil {
exitWithError(err)
}
}
// rename tries to os.Rename, but fall backs to copying from src
// to dest and unlink the source if os.Rename fails.
func rename(src, dest string) error {
// Try to rename generated source.
if err := os.Rename(src, dest); err == nil {
return nil
}
// If the rename failed (might do so due to temporary file residing on a
// different device), try to copy byte by byte.
rc, err := os.Open(src)
if err != nil {
return err
}
defer func() {
rc.Close()
os.Remove(src) // ignore the error, source is in tmp.
}()
if _, err = os.Stat(dest); !os.IsNotExist(err) {
if *flagForce {
if err = os.Remove(dest); err != nil {
return fmt.Errorf("file %q could not be deleted", dest)
}
} else {
return fmt.Errorf("file %q already exists; use -f to overwrite", dest)
}
}
wc, err := os.Create(dest)
if err != nil {
return err
}
defer wc.Close()
if _, err = io.Copy(wc, rc); err != nil {
// Delete remains of failed copy attempt.
os.Remove(dest)
}
return err
}
// Walks on the source path and generates source code
// that contains source directory's contents as zip contents.
// Generates source registers generated zip contents data to
// be read by the statik/fs HTTP file system.
func generateSource(srcPath string) (file *os.File, err error) {
var (
buffer bytes.Buffer
zipWriter io.Writer
)
zipWriter = &buffer
f, err := ioutil.TempFile("", namePackage)
if err != nil {
return
}
zipWriter = io.MultiWriter(zipWriter, f)
defer f.Close()
w := zip.NewWriter(zipWriter)
if err = filepath.Walk(srcPath, func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
// Ignore directories and hidden files.
// No entry is needed for directories in a zip file.
// Each file is represented with a path, no directory
// entities are required to build the hierarchy.
if fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
return nil
}
relPath, err := filepath.Rel(srcPath, path)
if err != nil {
return err
}
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
fHeader, err := zip.FileInfoHeader(fi)
if err != nil {
return err
}
if *flagNoMtime {
// Always use the same modification time so that
// the output is deterministic with respect to the file contents.
fHeader.SetModTime(mtimeDate)
}
fHeader.Name = filepath.ToSlash(relPath)
if !*flagNoCompress {
fHeader.Method = zip.Deflate
}
f, err := w.CreateHeader(fHeader)
if err != nil {
return err
}
_, err = f.Write(b)
return err
}); err != nil {
return
}
if err = w.Close(); err != nil {
return
}
var tags string
if *flagTags != "" {
tags = "\n// +build " + *flagTags + "\n"
}
// then embed it as a quoted string
var qb bytes.Buffer
fmt.Fprintf(&qb, `// Code generated by statik. DO NOT EDIT.
%s
package %s
import (
"github.com/rakyll/statik/fs"
)
func init() {
data := "`, tags, namePackage)
FprintZipData(&qb, buffer.Bytes())
fmt.Fprint(&qb, `"
fs.Register(data)
}
`)
if err = ioutil.WriteFile(f.Name(), qb.Bytes(), 0644); err != nil {
return
}
return f, nil
}
// FprintZipData converts zip binary contents to a string literal.
func FprintZipData(dest *bytes.Buffer, zipData []byte) {
for _, b := range zipData {
if b == '\n' {
dest.WriteString(`\n`)
continue
}
if b == '\\' {
dest.WriteString(`\\`)
continue
}
if b == '"' {
dest.WriteString(`\"`)
continue
}
if (b >= 32 && b <= 126) || b == '\t' {
dest.WriteByte(b)
continue
}
fmt.Fprintf(dest, "\\x%02x", b)
}
}
// Prints out the error message and exists with a non-success signal.
func exitWithError(err error) {
fmt.Println(err)
os.Exit(1)
}

@ -130,6 +130,12 @@
"revision": "82b3d2997d337a2174b708d0ffe3f711ffb1eddf",
"revisionTime": "2018-04-18T01:28:05Z"
},
{
"checksumSHA1": "aoYDmf0vxCZJOvIwTdElHi2IXH4=",
"path": "github.com/rakyll/statik",
"revision": "fcdcb7b85139b8b9ca1d8ef1d98d8593e90d117f",
"revisionTime": "2018-03-30T20:43:14Z"
},
{
"checksumSHA1": "cVGA2CJTJsCAVa5VKTM8k/ma/BU=",
"path": "github.com/silenceper/pool",

@ -58,7 +58,7 @@ module.exports = {
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
assetsPublicPath: '/public/',
/**
* Source Maps

@ -33,7 +33,7 @@
</el-col>
</el-row>
<el-row>
<el-col :span="6">
<el-col :span="7">
<el-form-item label="任务类型">
<el-select v-model.trim="form.level" :disabled="form.id !== '' ">
<el-option
@ -57,7 +57,7 @@
</el-select>
</el-form-item>
</el-col>
<el-col :span="11">
<el-col :span="10">
<el-form-item label="子任务ID" v-if="form.level === 1">
<el-input v-model.trim="form.dependency_task_id" placeholder="多个ID逗号分隔"></el-input>
</el-form-item>

Loading…
Cancel
Save