Repository: markcheno/go-vue-starter Branch: master Commit: e4f64e150983 Files: 45 Total size: 45.9 KB Directory structure: gitextract_tjk8vlva/ ├── .gitignore ├── .vscode/ │ └── launch.json ├── Godeps/ │ ├── Godeps.json │ └── Readme ├── LICENSE ├── README.md ├── api/ │ ├── api.go │ ├── quotes.go │ └── users.go ├── auth/ │ └── auth.go ├── client/ │ ├── .babelrc │ ├── .editorconfig │ ├── .eslintignore │ ├── .eslintrc.js │ ├── .gitignore │ ├── .postcssrc.js │ ├── README.md │ ├── build/ │ │ ├── build.js │ │ ├── check-versions.js │ │ ├── dev-client.js │ │ ├── dev-server.js │ │ ├── utils.js │ │ ├── vue-loader.conf.js │ │ ├── webpack.base.conf.js │ │ ├── webpack.dev.conf.js │ │ └── webpack.prod.conf.js │ ├── config/ │ │ ├── dev.env.js │ │ ├── index.js │ │ └── prod.env.js │ ├── index.html │ ├── package.json │ ├── src/ │ │ ├── App.vue │ │ ├── auth/ │ │ │ └── index.js │ │ ├── components/ │ │ │ ├── Home.vue │ │ │ ├── Login.vue │ │ │ ├── SecretQuote.vue │ │ │ ├── Signup.vue │ │ │ └── UserInfo.vue │ │ └── main.js │ └── static/ │ └── .gitkeep ├── models/ │ ├── db.go │ ├── quotes.go │ └── users.go ├── routes/ │ └── routes.go └── server.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # file types *.o *.a *.so *.exe *.test *.prof *.db *.DS_Store # folders vendor node_modules tmp ================================================ FILE: .vscode/launch.json ================================================ { "version": "0.2.0", "configurations": [ { "name": "Launch", "type": "go", "request": "launch", "mode": "debug", "remotePath": "", "port": 2345, "host": "127.0.0.1", "program": "${fileDirname}", "env": {}, "args": [], "showLog": true } ] } ================================================ FILE: Godeps/Godeps.json ================================================ { "ImportPath": "github.com/markcheno/go-vue-starter", "GoVersion": "go1.8", "GodepVersion": "v79", "Deps": [ { "ImportPath": "github.com/auth0/go-jwt-middleware", "Rev": "f3f7de3b9e394e3af3b88e1b9457f6f71d1ae0ac" }, { "ImportPath": "github.com/dgrijalva/jwt-go", "Comment": "v3.0.0-17-g2268707", "Rev": "2268707a8f0843315e2004ee4f1d021dc08baedf" }, { "ImportPath": "github.com/gorilla/mux", "Comment": "v1.3.0-5-g599cba5", "Rev": "599cba5e7b6137d46ddf58fb1765f5d928e69604" }, { "ImportPath": "github.com/jinzhu/gorm", "Comment": "v1.0-138-g45ccb13", "Rev": "45ccb134373e7d9fa76d5987a6fed6cd5a5adfd4" }, { "ImportPath": "github.com/jinzhu/gorm/dialects/postgres", "Comment": "v1.0-138-g45ccb13", "Rev": "45ccb134373e7d9fa76d5987a6fed6cd5a5adfd4" }, { "ImportPath": "github.com/jinzhu/gorm/dialects/sqlite", "Comment": "v1.0-138-g45ccb13", "Rev": "45ccb134373e7d9fa76d5987a6fed6cd5a5adfd4" }, { "ImportPath": "github.com/jinzhu/inflection", "Rev": "1c35d901db3da928c72a72d8458480cc9ade058f" }, { "ImportPath": "github.com/lib/pq", "Comment": "go1.0-cutoff-166-g2704adc", "Rev": "2704adc878c21e1329f46f6e56a1c387d788ff94" }, { "ImportPath": "github.com/lib/pq/hstore", "Comment": "go1.0-cutoff-166-g2704adc", "Rev": "2704adc878c21e1329f46f6e56a1c387d788ff94" }, { "ImportPath": "github.com/lib/pq/oid", "Comment": "go1.0-cutoff-166-g2704adc", "Rev": "2704adc878c21e1329f46f6e56a1c387d788ff94" }, { "ImportPath": "github.com/mattn/go-sqlite3", "Comment": "v1.2.0-80-gcf7286f", "Rev": "cf7286f069c3ef596efcc87781a4653a2e7607bd" }, { "ImportPath": "github.com/satori/go.uuid", "Comment": "v1.1.0-8-g5bf94b6", "Rev": "5bf94b69c6b68ee1b541973bb8e1144db23a194b" }, { "ImportPath": "github.com/urfave/negroni", "Comment": "v0.2.0-104-gc0db5fe", "Rev": "c0db5feaa33826cd5117930c8f4ee5c0f565eec6" }, { "ImportPath": "golang.org/x/crypto/bcrypt", "Rev": "9ef620b9ca2f82b55030ffd4f41327fa9e77a92c" }, { "ImportPath": "golang.org/x/crypto/blowfish", "Rev": "9ef620b9ca2f82b55030ffd4f41327fa9e77a92c" }, { "ImportPath": "golang.org/x/net/context", "Rev": "d1e1b351919c6738fdeb9893d5c998b161464f0c" } ] } ================================================ FILE: Godeps/Readme ================================================ This directory tree is generated automatically by godep. Please do not edit. See https://github.com/tools/godep for more information. ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Mark Chenoweth Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # go-vue-starter Copyright 2017 Mark Chenoweth ## Golang Starter project with Vue.js single page client ### Work in progress... ### Features: - Middleware: [Negroni](https://github.com/urfave/negroni) - Router: [Gorilla](https://github.com/gorilla/mux) - Orm: [Gorm](https://github.com/jinzhu/gorm) (sqlite or postgres) - Jwt authentication: [jwt-go](https://github.com/dgrijalva/jwt-go) and [go-jwt-middleware](https://github.com/auth0/go-jwt-middleware) - [Vue.js](https://vuejs.org/) spa client with webpack - User management ### TODO: - config from file - email confirmation - logrus - letsencrypt tls ### To get started: ``` bash # clone repository go get github.com/markcheno/go-vue-starter cd $GOPATH/src/github.com/markcheno/go-vue-starter # install Go dependencies (and make sure ports 3000/8080 are open) go get -u ./... go run server.go # open a new terminal and change to the client dir cd client # install dependencies npm install # serve with hot reload at localhost:8080 npm run dev # build for production with minification npm run build ``` ### License MIT License - see LICENSE for more details ================================================ FILE: api/api.go ================================================ package api import ( "github.com/markcheno/go-vue-starter/models" ) // API - type API struct { users *models.UserManager quotes *models.QuoteManager } // NewAPI - func NewAPI(db *models.DB) *API { usermgr, _ := models.NewUserManager(db) quotemgr, _ := models.NewQuoteManager(db) return &API{ users: usermgr, quotes: quotemgr, } } ================================================ FILE: api/quotes.go ================================================ package api import "net/http" // Quote - func (api *API) Quote(w http.ResponseWriter, req *http.Request) { quote := api.quotes.RandomQuote() w.Write([]byte(quote.Text)) } // SecretQuote - func (api *API) SecretQuote(w http.ResponseWriter, req *http.Request) { quote := api.quotes.RandomQuote() w.Write([]byte(quote.Text)) } ================================================ FILE: api/users.go ================================================ package api import ( "encoding/json" "net/http" "github.com/markcheno/go-vue-starter/auth" "github.com/markcheno/go-vue-starter/models" ) // UserJSON - json data expected for login/signup type UserJSON struct { Username string `json:"username"` Password string `json:"password"` } // UserSignup - func (api *API) UserSignup(w http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) jsondata := UserJSON{} err := decoder.Decode(&jsondata) if err != nil || jsondata.Username == "" || jsondata.Password == "" { http.Error(w, "Missing username or password", http.StatusBadRequest) return } if api.users.HasUser(jsondata.Username) { http.Error(w, "username already exists", http.StatusBadRequest) return } user := api.users.AddUser(jsondata.Username, jsondata.Password) jsontoken := auth.GetJSONToken(user) w.Header().Set("Content-Type", "application/json") w.Write([]byte(jsontoken)) } // UserLogin - func (api *API) UserLogin(w http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) jsondata := UserJSON{} err := decoder.Decode(&jsondata) if err != nil || jsondata.Username == "" || jsondata.Password == "" { http.Error(w, "Missing username or password", http.StatusBadRequest) return } user := api.users.FindUser(jsondata.Username) if user.Username == "" { http.Error(w, "username not found", http.StatusBadRequest) return } if !api.users.CheckPassword(user.Password, jsondata.Password) { http.Error(w, "bad password", http.StatusBadRequest) return } jsontoken := auth.GetJSONToken(user) w.Header().Set("Content-Type", "application/json") w.Write([]byte(jsontoken)) } // GetUserFromContext - return User reference from header token func (api *API) GetUserFromContext(req *http.Request) *models.User { userclaims := auth.GetUserClaimsFromContext(req) user := api.users.FindUserByUUID(userclaims["uuid"].(string)) return user } // UserInfo - example to get func (api *API) UserInfo(w http.ResponseWriter, req *http.Request) { user := api.GetUserFromContext(req) js, _ := json.Marshal(user) w.Header().Set("Content-Type", "application/json") w.Write(js) } ================================================ FILE: auth/auth.go ================================================ package auth import ( "net/http" "time" jwtmiddleware "github.com/auth0/go-jwt-middleware" jwt "github.com/dgrijalva/jwt-go" "github.com/markcheno/go-vue-starter/models" ) // signingKey set up a global string for our secret var signingKey = []byte("knrjkevdckjh") // JwtMiddleware handler for jwt tokens var JwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{ ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { return signingKey, nil }, UserProperty: "user", Debug: false, SigningMethod: jwt.SigningMethodHS256, }) // GetToken create a jwt token with user claims func GetToken(user *models.User) string { token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["uuid"] = user.UUID claims["exp"] = time.Now().Add(time.Hour * 24).Unix() signedToken, _ := token.SignedString(signingKey) return signedToken } // GetJSONToken create a JSON token string func GetJSONToken(user *models.User) string { token := GetToken(user) jsontoken := "{\"id_token\": \"" + token + "\"}" return jsontoken } // GetUserClaimsFromContext return "user" claims as a map from request func GetUserClaimsFromContext(req *http.Request) map[string]interface{} { //claims := context.Get(req, "user").(*jwt.Token).Claims.(jwt.MapClaims) claims := req.Context().Value("user").(*jwt.Token).Claims.(jwt.MapClaims) return claims } ================================================ FILE: client/.babelrc ================================================ { "presets": [ ["env", { "modules": false }], "stage-2" ], "plugins": ["transform-runtime"], "comments": false, "env": { "test": { "presets": ["env", "stage-2"], "plugins": [ "istanbul" ] } } } ================================================ FILE: client/.editorconfig ================================================ root = true [*] charset = utf-8 indent_style = space indent_size = 2 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true ================================================ FILE: client/.eslintignore ================================================ build/*.js config/*.js ================================================ FILE: client/.eslintrc.js ================================================ // http://eslint.org/docs/user-guide/configuring module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style extends: 'standard', // required to lint *.vue files plugins: [ 'html' ], // add your custom rules here 'rules': { // allow paren-less arrow functions 'arrow-parens': 0, // allow async-await 'generator-star-spacing': 0, // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 } } ================================================ FILE: client/.gitignore ================================================ .DS_Store node_modules/ dist/ npm-debug.log* yarn-debug.log* yarn-error.log* test/unit/coverage test/e2e/reports selenium-debug.log ================================================ FILE: client/.postcssrc.js ================================================ // https://github.com/michael-ciniawsky/postcss-load-config module.exports = { "plugins": { // to edit target browsers: use "browserlist" field in package.json "autoprefixer": {} } } ================================================ FILE: client/README.md ================================================ # starter > Go/Vue starter project ## 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 # run unit tests npm run unit # run e2e tests npm run e2e # run all tests npm test ``` For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). ================================================ FILE: client/build/build.js ================================================ require('./check-versions')() process.env.NODE_ENV = 'production' var ora = require('ora') var rm = require('rimraf') var path = require('path') var chalk = require('chalk') var webpack = require('webpack') var config = require('../config') var webpackConfig = require('./webpack.prod.conf') var spinner = ora('building for production...') spinner.start() rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, function (err, stats) { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n') 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' )) }) }) ================================================ FILE: client/build/check-versions.js ================================================ var chalk = require('chalk') var semver = require('semver') var packageConfig = require('../package.json') var shell = require('shelljs') function exec (cmd) { return require('child_process').execSync(cmd).toString().trim() } var 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 () { var warnings = [] for (var i = 0; i < versionRequirements.length; i++) { var 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 (var i = 0; i < warnings.length; i++) { var warning = warnings[i] console.log(' ' + warning) } console.log() process.exit(1) } } ================================================ FILE: client/build/dev-client.js ================================================ /* eslint-disable */ require('eventsource-polyfill') var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') hotClient.subscribe(function (event) { if (event.action === 'reload') { window.location.reload() } }) ================================================ FILE: client/build/dev-server.js ================================================ require('./check-versions')() var config = require('../config') if (!process.env.NODE_ENV) { process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) } var opn = require('opn') var path = require('path') var express = require('express') var webpack = require('webpack') var proxyMiddleware = require('http-proxy-middleware') var webpackConfig = process.env.NODE_ENV === 'testing' ? require('./webpack.prod.conf') : require('./webpack.dev.conf') // default port where dev server listens for incoming traffic var port = process.env.PORT || config.dev.port // automatically open browser, if not set will be false var autoOpenBrowser = !!config.dev.autoOpenBrowser // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware var proxyTable = config.dev.proxyTable var app = express() var compiler = webpack(webpackConfig) var devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: true }) var hotMiddleware = require('webpack-hot-middleware')(compiler, { log: () => {} }) // force page reload when html-webpack-plugin template changes compiler.plugin('compilation', function (compilation) { compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() }) }) // proxy api requests Object.keys(proxyTable).forEach(function (context) { var options = proxyTable[context] if (typeof options === 'string') { options = { target: options } } app.use(proxyMiddleware(options.filter || context, options)) }) // handle fallback for HTML5 history API app.use(require('connect-history-api-fallback')()) // serve webpack bundle output app.use(devMiddleware) // enable hot-reload and state-preserving // compilation error display app.use(hotMiddleware) // serve pure static assets var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) app.use(staticPath, express.static('./static')) var uri = 'http://localhost:' + port var _resolve var readyPromise = new Promise(resolve => { _resolve = resolve }) console.log('> Starting dev server...') devMiddleware.waitUntilValid(() => { console.log('> Listening at ' + uri + '\n') // when env is testing, don't need open it if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { opn(uri) } _resolve() }) var server = app.listen(port) module.exports = { mounted: readyPromise, close: () => { server.close() } } ================================================ FILE: client/build/utils.js ================================================ var path = require('path') var config = require('../config') var ExtractTextPlugin = require('extract-text-webpack-plugin') exports.assetsPath = function (_path) { var assetsSubDirectory = process.env.NODE_ENV === 'production' ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) } exports.cssLoaders = function (options) { options = options || {} var cssLoader = { loader: 'css-loader', options: { minimize: process.env.NODE_ENV === 'production', sourceMap: options.sourceMap } } // generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) { var loaders = [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) { var output = [] var loaders = exports.cssLoaders(options) for (var extension in loaders) { var loader = loaders[extension] output.push({ test: new RegExp('\\.' + extension + '$'), use: loader }) } return output } ================================================ FILE: client/build/vue-loader.conf.js ================================================ var utils = require('./utils') var config = require('../config') var isProduction = process.env.NODE_ENV === 'production' module.exports = { loaders: utils.cssLoaders({ sourceMap: isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap, extract: isProduction }) } ================================================ FILE: client/build/webpack.base.conf.js ================================================ var path = require('path') var utils = require('./utils') var config = require('../config') var vueLoaderConfig = require('./vue-loader.conf') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = { 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: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test')] }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] } } ================================================ FILE: client/build/webpack.dev.conf.js ================================================ var utils = require('./utils') var webpack = require('webpack') var config = require('../config') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') var HtmlWebpackPlugin = require('html-webpack-plugin') var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') // add hot-reload related code to entry chunks Object.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) }) module.exports = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // cheap-module-eval-source-map is faster for development devtool: '#cheap-module-eval-source-map', plugins: [ new webpack.DefinePlugin({ 'process.env': config.dev.env }), // https://github.com/glenjamin/webpack-hot-middleware#installation--usage new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true }), new FriendlyErrorsPlugin() ] }) ================================================ FILE: client/build/webpack.prod.conf.js ================================================ var path = require('path') var utils = require('./utils') var webpack = require('webpack') var config = require('../config') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') var CopyWebpackPlugin = require('copy-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin') var ExtractTextPlugin = require('extract-text-webpack-plugin') var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') var env = process.env.NODE_ENV === 'testing' ? require('../config/test.env') : config.build.env var webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : 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 webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: true }), // extract css into its own file new ExtractTextPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css') }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: { 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: process.env.NODE_ENV === 'testing' ? 'index.html' : 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' }), // split vendor js into its own file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module, count) { // 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', chunks: ['vendor'] }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ] }) if (config.build.productionGzip) { var 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) { var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig ================================================ FILE: client/config/dev.env.js ================================================ var merge = require('webpack-merge') var prodEnv = require('./prod.env') module.exports = merge(prodEnv, { NODE_ENV: '"development"' }) ================================================ FILE: client/config/index.js ================================================ // see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: false, // 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 }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', // proxyTable: {}, proxyTable: { '/api': { target: 'http://localhost:3000/api', changeOrigin: true, pathRewrite: { '^/api': '' } } }, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } } ================================================ FILE: client/config/prod.env.js ================================================ module.exports = { NODE_ENV: '"production"' } ================================================ FILE: client/index.html ================================================ Quote Server
================================================ FILE: client/package.json ================================================ { "name": "starter", "version": "1.0.0", "description": "Go/Vue starter project", "author": "Mark Chenoweth", "private": true, "scripts": { "dev": "node build/dev-server.js", "start": "node build/dev-server.js", "build": "node build/build.js", "lint": "eslint --ext .js,.vue src" }, "dependencies": { "hoek": "^5.0.3", "mime": "^2.3.1", "npm": "^6.14.6", "tough-cookie": "^2.4.3", "vue": "^2.5.16", "vue-resource": "^1.5.0", "vue-router": "^2.8.1" }, "devDependencies": { "autoprefixer": "^6.7.2", "babel-core": "^6.26.2", "babel-eslint": "^7.2.3", "babel-loader": "^6.2.10", "babel-plugin-transform-runtime": "^6.22.0", "babel-preset-env": "^1.6.1", "babel-preset-stage-2": "^6.22.0", "babel-register": "^6.26.0", "chalk": "^1.1.3", "chromedriver": "^2.38.2", "compression-webpack-plugin": "^2.0.0", "connect-history-api-fallback": "^1.5.0", "copy-webpack-plugin": "^4.5.1", "css-loader": "^2.1.1", "eslint": "^4.19.1", "eslint-config-standard": "^6.2.1", "eslint-friendly-formatter": "^2.0.7", "eslint-loader": "^1.9.0", "eslint-plugin-html": "^4.0.1", "eslint-plugin-promise": "^3.7.0", "eslint-plugin-standard": "^2.0.1", "eventsource-polyfill": "^0.9.6", "express": "^4.18.2", "extract-text-webpack-plugin": "^2.1.2", "file-loader": "^0.10.0", "friendly-errors-webpack-plugin": "^1.7.0", "html-webpack-plugin": "^2.30.1", "http-proxy-middleware": "^0.19.1", "opn": "^4.0.2", "optimize-css-assets-webpack-plugin": "^5.0.1", "ora": "^1.4.0", "rimraf": "^2.6.2", "semver": "^5.5.0", "shelljs": "^0.8.5", "url-loader": "^1.1.2", "vue-loader": "^11.1.4", "vue-style-loader": "^2.0.0", "vue-template-compiler": "^2.5.16", "webpack": "^2.7.0", "webpack-bundle-analyzer": "^4.8.0", "webpack-dev-middleware": "^1.12.2", "webpack-hot-middleware": "^2.25.3", "webpack-merge": "^2.6.1" }, "engines": { "node": ">= 4.0.0", "npm": ">= 3.0.0" }, "browserslist": [ "> 1%", "last 2 versions", "not ie <= 8" ] } ================================================ FILE: client/src/App.vue ================================================ ================================================ FILE: client/src/auth/index.js ================================================ const API_URL = '/api/user/' const LOGIN_URL = API_URL + 'login' const SIGNUP_URL = API_URL + 'signup' export default { login (context, creds, redirect) { context.$http.post(LOGIN_URL, creds).then(response => { localStorage.setItem('id_token', response.body.id_token) if (redirect) { context.$router.replace(redirect) } }, response => { context.error = response.statusText }) }, signup (context, creds, redirect) { context.$http.post(SIGNUP_URL, creds).then(response => { localStorage.setItem('id_token', response.body.id_token) if (redirect) { context.$router.replace(redirect) } }, response => { context.error = response.statusText }) }, logout (context) { localStorage.removeItem('id_token') context.$router.replace('/home') }, isAuthenticated () { var jwt = localStorage.getItem('id_token') if (jwt) { return true } return false }, getAuthHeader () { return { 'Authorization': 'Bearer ' + localStorage.getItem('id_token') } } } ================================================ FILE: client/src/components/Home.vue ================================================ ================================================ FILE: client/src/components/Login.vue ================================================ ================================================ FILE: client/src/components/SecretQuote.vue ================================================ ================================================ FILE: client/src/components/Signup.vue ================================================ ================================================ FILE: client/src/components/UserInfo.vue ================================================ ================================================ FILE: client/src/main.js ================================================ // 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 Home from '@/components/Home' import Login from '@/components/Login' import Signup from '@/components/Signup' import SecretQuote from '@/components/SecretQuote' import UserInfo from '@/components/UserInfo' import VueResource from 'vue-resource' Vue.use(VueResource) import VueRouter from 'vue-router' Vue.use(VueRouter) Vue.config.productionTip = true import auth from './auth' function requireAuth (to, from, next) { if (!auth.isAuthenticated()) { this.$router.replace('/login') } else { next() } } const router = new VueRouter({ mode: 'history', // base: __dirname, routes: [ { path: '/', component: Home }, { path: '/home', name: 'home', component: Home }, { path: '/login', name: 'login', component: Login }, { path: '/signup', name: 'signup', component: Signup }, { path: '/secretquote', name: 'secretquote', component: SecretQuote, beforeEnter: requireAuth }, { path: '/userinfo', name: 'userinfo', component: UserInfo, beforeEnter: requireAuth } ] }) /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '', components: { App } }) ================================================ FILE: client/static/.gitkeep ================================================ ================================================ FILE: models/db.go ================================================ package models import ( "github.com/jinzhu/gorm" // postgress db driver _ "github.com/jinzhu/gorm/dialects/postgres" // sqlite db driver _ "github.com/jinzhu/gorm/dialects/sqlite" ) // DB abstraction type DB struct { *gorm.DB } // NewPostgresDB - postgres database func NewPostgresDB(dataSourceName string) *DB { db, err := gorm.Open("postgres", dataSourceName) if err != nil { panic(err) } if err = db.DB().Ping(); err != nil { panic(err) } //db.LogMode(true) return &DB{db} } // NewSqliteDB - sqlite database func NewSqliteDB(databaseName string) *DB { db, err := gorm.Open("sqlite3", databaseName) if err != nil { panic(err) } if err = db.DB().Ping(); err != nil { panic(err) } //db.LogMode(true) return &DB{db} } ================================================ FILE: models/quotes.go ================================================ package models import ( "math/rand" "github.com/jinzhu/gorm" // postgress db driver _ "github.com/jinzhu/gorm/dialects/postgres" // import sqlite3 driver _ "github.com/jinzhu/gorm/dialects/sqlite" ) // Quote struct type Quote struct { gorm.Model Text string } // QuoteManager struct type QuoteManager struct { db *DB } // NewQuoteManager - Create a quote manager that can be used for retrieving quotes func NewQuoteManager(db *DB) (*QuoteManager, error) { db.AutoMigrate(&Quote{}) quotemgr := QuoteManager{} quotemgr.db = db return "emgr, nil } // RandomQuote - return a random quote func (qm *QuoteManager) RandomQuote() *Quote { quote := Quote{ Text: quotes[rand.Intn(len(quotes))], } return "e } var quotes = []string{ "Chuck Norris doesn't call the wrong number. You answer the wrong phone.", "Chuck Norris has already been to Mars; that's why there are no signs of life.", "Chuck Norris and Superman once fought each other on a bet. The loser had to start wearing his underwear on the outside of his pants.", "Some magicans can walk on water, Chuck Norris can swim through land.", "Chuck Norris once urinated in a semi truck's gas tank as a joke....that truck is now known as Optimus Prime.", "Chuck Norris doesn't flush the toilet, he scares the sh*t out of it", "Chuck Norris counted to infinity - twice.", "Chuck Norris can cut through a hot knife with butter", "Chuck Norris is the reason why Waldo is hiding.", "Death once had a near-Chuck Norris experience", "When the Boogeyman goes to sleep every night, he checks his closet for Chuck Norris.", "Chuck Norris can slam a revolving door.", "Chuck Norris once kicked a horse in the chin. Its decendants are known today as Giraffes.", "Chuck Norris will never have a heart attack. His heart isn't nearly foolish enough to attack him.", "Chuck Norris once got bit by a rattle snake........ After three days of pain and agony ..................the rattle snake died", "Chuck Norris can win a game of Connect Four in only three moves.", "When Chuck Norris does a pushup, he isn't lifting himself up, he's pushing the Earth down.", "There is no theory of evolution. Just a list of animals Chuck Norris allows to live.", "Chuck Norris can light a fire by rubbing two ice-cubes together.", "Chuck Norris doesn’t wear a watch. HE decides what time it is.", "The original title for Alien vs. Predator was Alien and Predator vs Chuck Norris.", "The film was cancelled shortly after going into preproduction. No one would pay nine dollars to see a movie fourteen seconds long.", "Chuck Norris doesn't read books. He stares them down until he gets the information he wants.", "Chuck Norris made a Happy Meal cry.", "Outer space exists because it's afraid to be on the same planet with Chuck Norris.", "If you spell Chuck Norris in Scrabble, you win. Forever.", "Chuck Norris can make snow angels on a concrete slab.", "Chuck Norris destroyed the periodic table, because Chuck Norris only recognizes the element of surprise.", "Chuck Norris has to use a stunt double when he does crying scenes.", "Chuck Norris' hand is the only hand that can beat a Royal Flush.", "There is no theory of evolution. Just a list of creatures Chuck Norris has allowed to live.", "Chuck Norris does not sleep. He waits.", "Chuck Norris tells a GPS which way to go.", "Some people wear Superman pajamas. Superman wears Chuck Norris pajamas.", "Chuck Norris's tears cure cancer ..... to bad he has never cried", "Chuck Norris doesn't breathe, he holds air hostage.", "Chuck Norris had a staring contest with Medusa, and won.", "When life hands Chuck Norris lemons, he makes orange juice.", "When Chuck Norris goes on a picnic, the ants bring him food.", "Chuck Norris gives Freddy Krueger nightmares.", "They once made a Chuck Norris toilet paper, but there was a problem: It wouldn't take shit from anybody.", "Chuck Norris can punch a cyclops between the eyes.", "Chuck Norris doesn't mow his lawn, he stands on the porch and dares it to grow", "Chuck Norris put out a forest fire. using only gasoline", "Chuck Norris CAN believe it's not butter.", "Custom t-shirts provided by Spreadshirt", } ================================================ FILE: models/users.go ================================================ package models import ( "github.com/jinzhu/gorm" // postgress db driver _ "github.com/jinzhu/gorm/dialects/postgres" // import sqlite3 driver _ "github.com/jinzhu/gorm/dialects/sqlite" uuid "github.com/satori/go.uuid" "golang.org/x/crypto/bcrypt" ) // User struct type User struct { gorm.Model `json:"-"` Username string `gorm:"not null;unique" json:"username"` Password string `gorm:"not null" json:"-"` UUID string `gorm:"not null;unique" json:"uuid"` } // UserManager struct type UserManager struct { db *DB } // NewUserManager - Create a new *UserManager that can be used for managing users. func NewUserManager(db *DB) (*UserManager, error) { db.AutoMigrate(&User{}) usermgr := UserManager{} usermgr.db = db return &usermgr, nil } // HasUser - Check if the given username exists. func (state *UserManager) HasUser(username string) bool { if err := state.db.Where("username=?", username).Find(&User{}).Error; err != nil { return false } return true } // FindUser - func (state *UserManager) FindUser(username string) *User { user := User{} state.db.Where("username=?", username).Find(&user) return &user } // FindUserByUUID - func (state *UserManager) FindUserByUUID(uuid string) *User { user := User{} state.db.Where("uuid=?", uuid).Find(&user) return &user } // AddUser - Creates a user and hashes the password func (state *UserManager) AddUser(username, password string) *User { passwordHash := state.HashPassword(username, password) guid, _ := uuid.NewV4() user := &User{ Username: username, Password: passwordHash, UUID: guid.String(), } state.db.Create(&user) return user } // HashPassword - Hash the password (takes a username as well, it can be used for salting). func (state *UserManager) HashPassword(username, password string) string { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { panic("Permissions: bcrypt password hashing unsuccessful") } return string(hash) } // CheckPassword - compare a hashed password with a possible plaintext equivalent func (state *UserManager) CheckPassword(hashedPassword, password string) bool { if bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) != nil { return false } return true } ================================================ FILE: routes/routes.go ================================================ package routes import ( "net/http" "github.com/gorilla/mux" "github.com/markcheno/go-vue-starter/api" "github.com/markcheno/go-vue-starter/auth" "github.com/urfave/negroni" ) // NewRoutes builds the routes for the api func NewRoutes(api *api.API) *mux.Router { mux := mux.NewRouter() // client static files mux.Handle("/", http.FileServer(http.Dir("./client/dist/"))).Methods("GET") mux.PathPrefix("/static/js").Handler(http.StripPrefix("/static/js/", http.FileServer(http.Dir("./client/dist/static/js/")))) // api a := mux.PathPrefix("/api").Subrouter() // users u := a.PathPrefix("/user").Subrouter() u.HandleFunc("/signup", api.UserSignup).Methods("POST") u.HandleFunc("/login", api.UserLogin).Methods("POST") u.Handle("/info", negroni.New( negroni.HandlerFunc(auth.JwtMiddleware.HandlerWithNext), negroni.Wrap(http.HandlerFunc(api.UserInfo)), )) // quotes q := a.PathPrefix("/quote").Subrouter() q.HandleFunc("/random", api.Quote).Methods("GET") q.Handle("/protected/random", negroni.New( negroni.HandlerFunc(auth.JwtMiddleware.HandlerWithNext), negroni.Wrap(http.HandlerFunc(api.SecretQuote)), )) return mux } ================================================ FILE: server.go ================================================ package main import ( "github.com/markcheno/go-vue-starter/api" "github.com/markcheno/go-vue-starter/models" "github.com/markcheno/go-vue-starter/routes" "github.com/urfave/negroni" ) func main() { db := models.NewSqliteDB("data.db") api := api.NewAPI(db) routes := routes.NewRoutes(api) n := negroni.Classic() n.UseHandler(routes) n.Run(":3000") }