commit bdf1e63b061048601632bb42906ce173ee54a4fa Author: William Petit Date: Wed Feb 19 22:13:06 2020 +0100 Initial commit diff --git a/.gitignore.gotpl b/.gitignore.gotpl new file mode 100644 index 0000000..8a48925 --- /dev/null +++ b/.gitignore.gotpl @@ -0,0 +1,4 @@ +/release +/data +/vendor +/bin \ No newline at end of file diff --git a/Makefile.gotpl b/Makefile.gotpl new file mode 100644 index 0000000..1a258ee --- /dev/null +++ b/Makefile.gotpl @@ -0,0 +1,28 @@ +build: vendor + CGO_ENABLED=0 go build -mod=vendor -v -o bin/server ./cmd/server + +test: + go test -v -race ./... + +release: + @$(SHELL) ./misc/script/release.sh + +vendor: + go mod vendor + +tidy: + go mod tidy + +watch: + modd + +lint: + golangci-lint run --enable-all + +clean: + rm -rf release + rm -rf data + rm -rf vendor + rm -rf bin + +.PHONY: lint watch build vendor tidy release \ No newline at end of file diff --git a/README.md.gotpl b/README.md.gotpl new file mode 100644 index 0000000..874ac0a --- /dev/null +++ b/README.md.gotpl @@ -0,0 +1,15 @@ +# {{ .ProjectName }} + +## Démarrer avec les sources + +``` +make build +``` + +## FAQ + +### Générer une version de distribution + +``` +make release +``` \ No newline at end of file diff --git a/cmd/server/container.go.gotpl b/cmd/server/container.go.gotpl new file mode 100644 index 0000000..82292ca --- /dev/null +++ b/cmd/server/container.go.gotpl @@ -0,0 +1,78 @@ +package main + +import ( + "log" + "net/http" + + "gitlab.com/wpetit/goweb/template/html" + + "{{ .ProjectNamespace }}/internal/config" + "github.com/gorilla/sessions" + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/service" + "gitlab.com/wpetit/goweb/service/build" + "gitlab.com/wpetit/goweb/service/session" + "gitlab.com/wpetit/goweb/service/template" + "gitlab.com/wpetit/goweb/session/gorilla" +) + +func getServiceContainer(conf *config.Config) (*service.Container, error) { + // Initialize and configure service container + ctn := service.NewContainer() + + ctn.Provide(build.ServiceName, build.ServiceProvider(ProjectVersion, GitRef, BuildDate)) + + // Generate random cookie authentication key if none is set + if conf.HTTP.CookieAuthenticationKey == "" { + log.Println("could not find cookie authentication key. generating one...") + + cookieAuthenticationKey, err := gorilla.GenerateRandomBytes(64) + if err != nil { + return nil, errors.Wrap(err, "could not generate cookie authentication key") + } + + conf.HTTP.CookieAuthenticationKey = string(cookieAuthenticationKey) + } + + // Generate random cookie encryption key if none is set + if conf.HTTP.CookieEncryptionKey == "" { + log.Println("could not find cookie encryption key. generating one...") + + cookieEncryptionKey, err := gorilla.GenerateRandomBytes(32) + if err != nil { + return nil, errors.Wrap(err, "could not generate cookie encryption key") + } + + conf.HTTP.CookieEncryptionKey = string(cookieEncryptionKey) + } + + // Create and initialize HTTP session service provider + cookieStore := sessions.NewCookieStore( + []byte(conf.HTTP.CookieAuthenticationKey), + []byte(conf.HTTP.CookieEncryptionKey), + ) + + // Define default cookie options + cookieStore.Options = &sessions.Options{ + Path: "/", + HttpOnly: true, + MaxAge: conf.HTTP.CookieMaxAge, + SameSite: http.SameSiteStrictMode, + } + + ctn.Provide( + session.ServiceName, + gorilla.ServiceProvider("scaffold-test", cookieStore), + ) + + // Create and expose template service provider + // Create and expose template service provider + ctn.Provide(template.ServiceName, html.ServiceProvider( + conf.HTTP.TemplateDir, + )) + + // Create and expose config service provider + ctn.Provide(config.ServiceName, config.ServiceProvider(conf)) + + return ctn, nil +} diff --git a/cmd/server/main.go.gotpl b/cmd/server/main.go.gotpl new file mode 100644 index 0000000..b647809 --- /dev/null +++ b/cmd/server/main.go.gotpl @@ -0,0 +1,112 @@ +package main + +import ( + "net/http" + + "{{ .ProjectNamespace }}/internal/route" + "github.com/go-chi/chi" + "github.com/go-chi/chi/middleware" + "gitlab.com/wpetit/goweb/middleware/container" + + "flag" + "fmt" + "log" + + "os" + + "{{ .ProjectNamespace }}/internal/config" + "github.com/pkg/errors" +) + +//nolint: gochecknoglobals +var ( + configFile = "" + workdir = "" + dumpConfig = false + version = false +) + +// nolint: gochecknoglobals +var ( + GitRef = "unknown" + ProjectVersion = "unknown" + BuildDate = "unknown" +) + +//nolint: gochecknoinits +func init() { + flag.StringVar(&configFile, "config", configFile, "configuration file") + flag.StringVar(&workdir, "workdir", workdir, "working directory") + flag.BoolVar(&dumpConfig, "dump-config", dumpConfig, "dump configuration and exit") + flag.BoolVar(&version, "version", version, "show version and exit") +} + +func main() { + flag.Parse() + + if version { + fmt.Printf("%s (%s) - %s\n", ProjectVersion, GitRef, BuildDate) + + os.Exit(0) + } + + // Switch to new working directory if defined + if workdir != "" { + if err := os.Chdir(workdir); err != nil { + log.Fatalf("%+v", errors.Wrapf(err, "could not change working directory to '%s'", workdir)) + } + } + + // Load configuration file if defined, use default configuration otherwise + var conf *config.Config + + var err error + + if configFile != "" { + conf, err = config.NewFromFile(configFile) + if err != nil { + log.Fatalf("%+v", errors.Wrapf(err, "could not load config file '%s'", configFile)) + } + } else { + if dumpConfig { + conf = config.NewDumpDefault() + } else { + conf = config.NewDefault() + } + + } + + // Dump configuration if asked + if dumpConfig { + if err := config.Dump(conf, os.Stdout); err != nil { + log.Fatalf("%+v", errors.Wrap(err, "could not dump config")) + } + + os.Exit(0) + } + + // Create service container + ctn, err := getServiceContainer(conf) + if err != nil { + log.Fatalf("%+v", errors.Wrap(err, "could not create service container")) + } + + r := chi.NewRouter() + + // Define base middlewares + r.Use(middleware.Logger) + r.Use(middleware.Recoverer) + + // Expose service container on router + r.Use(container.ServiceContainer(ctn)) + + // Define routes + if err := route.Mount(r, conf); err != nil { + log.Fatalf("%+v", errors.Wrap(err, "could not mount http routes")) + } + + log.Printf("listening on '%s'", conf.HTTP.Address) + if err := http.ListenAndServe(conf.HTTP.Address, r); err != nil { + log.Fatalf("%+v", errors.Wrapf(err, "could not listen on '%s'", conf.HTTP.Address)) + } +} \ No newline at end of file diff --git a/cmd/server/template/blocks/base.html.tmpl b/cmd/server/template/blocks/base.html.tmpl new file mode 100644 index 0000000..f34cc87 --- /dev/null +++ b/cmd/server/template/blocks/base.html.tmpl @@ -0,0 +1,18 @@ +{{define "base"}} + + + + + + {{block "title" . -}}{{- end}} + {{- block "head_style" . -}} + + {{end}} + {{- block "head_script" . -}}{{end}} + + + {{- block "body" . -}}{{- end -}} + {{- block "body_script" . -}}{{end}} + + +{{end}} \ No newline at end of file diff --git a/cmd/server/template/blocks/flash.html.tmpl b/cmd/server/template/blocks/flash.html.tmpl new file mode 100644 index 0000000..577a6bc --- /dev/null +++ b/cmd/server/template/blocks/flash.html.tmpl @@ -0,0 +1,23 @@ +{{define "flash"}} +
+ {{- range .Flashes -}} + {{- if eq .Type "error" -}} + {{template "flash_message" map "Title" "Erreur" "MessageClass" "is-danger" "Message" .Message }} + {{- else if eq .Type "warn" -}} + {{template "flash_message" map "Title" "Attention" "MessageClass" "is-warning" "Message" .Message }} + {{- else if eq .Type "success" -}} + {{template "flash_message" map "Title" "Succès" "MessageClass" "is-success" "Message" .Message }} + {{- else -}} + {{template "flash_message" map "Title" "Information" "MessageClass" "is-info" "Message" .Message }} + {{- end -}} + {{- end -}} +
+{{end}} + +{{define "flash_message" -}} +
+
+ {{.Title}} {{.Message}} +
+
+{{- end}} \ No newline at end of file diff --git a/cmd/server/template/blocks/footer.html.tmpl b/cmd/server/template/blocks/footer.html.tmpl new file mode 100644 index 0000000..3b4081c --- /dev/null +++ b/cmd/server/template/blocks/footer.html.tmpl @@ -0,0 +1,7 @@ +{{define "footer"}} +

+ Version: {{ .BuildInfo.ProjectVersion }} - + Réf.: {{ .BuildInfo.GitRef }} - + Date de construction: {{ .BuildInfo.BuildDate }} +

+{{end}} \ No newline at end of file diff --git a/cmd/server/template/blocks/header.html.tmpl b/cmd/server/template/blocks/header.html.tmpl new file mode 100644 index 0000000..6971f8b --- /dev/null +++ b/cmd/server/template/blocks/header.html.tmpl @@ -0,0 +1,11 @@ +{{define "header"}} +
+
+
+ +
+
+
+{{end}} \ No newline at end of file diff --git a/cmd/server/template/layouts/home.html.tmpl b/cmd/server/template/layouts/home.html.tmpl new file mode 100644 index 0000000..d6366a8 --- /dev/null +++ b/cmd/server/template/layouts/home.html.tmpl @@ -0,0 +1,11 @@ +{{define "title"}}Accueil{{end}} +{{define "body"}} +
+
+ {{template "header" .}} +

Bienvenue !

+ {{template "footer" .}} +
+
+{{end}} +{{template "base" .}} diff --git a/go.mod.gotpl b/go.mod.gotpl new file mode 100644 index 0000000..1ab3379 --- /dev/null +++ b/go.mod.gotpl @@ -0,0 +1 @@ +module {{ .ProjectNamespace }} \ No newline at end of file diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..38d9394 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,71 @@ +package config + +import ( + "io" + "io/ioutil" + "time" + + "github.com/pkg/errors" + + "gopkg.in/yaml.v2" +) + +type Config struct { + HTTP HTTPConfig `yaml:"http"` +} + +// NewFromFile retrieves the configuration from the given file +func NewFromFile(filepath string) (*Config, error) { + config := NewDefault() + + data, err := ioutil.ReadFile(filepath) + if err != nil { + return nil, errors.Wrapf(err, "could not read file '%s'", filepath) + } + + if err := yaml.Unmarshal(data, config); err != nil { + return nil, errors.Wrapf(err, "could not unmarshal configuration") + } + + return config, nil +} + +type HTTPConfig struct { + Address string `yaml:"address"` + CookieAuthenticationKey string `yaml:"cookieAuthenticationKey"` + CookieEncryptionKey string `yaml:"cookieEncryptionKey"` + CookieMaxAge int `yaml:"cookieMaxAge"` + TemplateDir string `yaml:"templateDir"` + PublicDir string `yaml:"publicDir"` +} + +func NewDumpDefault() *Config { + config := NewDefault() + return config +} + +func NewDefault() *Config { + return &Config{ + HTTP: HTTPConfig{ + Address: ":3000", + CookieAuthenticationKey: "", + CookieEncryptionKey: "", + CookieMaxAge: int((time.Hour * 1).Seconds()), // 1 hour + TemplateDir: "template", + PublicDir: "public", + }, + } +} + +func Dump(config *Config, w io.Writer) error { + data, err := yaml.Marshal(config) + if err != nil { + return errors.Wrap(err, "could not dump config") + } + + if _, err := w.Write(data); err != nil { + return err + } + + return nil +} diff --git a/internal/config/provider.go b/internal/config/provider.go new file mode 100644 index 0000000..0e768ed --- /dev/null +++ b/internal/config/provider.go @@ -0,0 +1,9 @@ +package config + +import "gitlab.com/wpetit/goweb/service" + +func ServiceProvider(config *Config) service.Provider { + return func(ctn *service.Container) (interface{}, error) { + return config, nil + } +} diff --git a/internal/config/service.go b/internal/config/service.go new file mode 100644 index 0000000..e57c05d --- /dev/null +++ b/internal/config/service.go @@ -0,0 +1,33 @@ +package config + +import ( + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/service" +) + +const ServiceName service.Name = "config" + +// From retrieves the config service in the given container +func From(container *service.Container) (*Config, error) { + service, err := container.Service(ServiceName) + if err != nil { + return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName) + } + + srv, ok := service.(*Config) + if !ok { + return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName) + } + + return srv, nil +} + +// Must retrieves the config service in the given container or panic otherwise +func Must(container *service.Container) *Config { + srv, err := From(container) + if err != nil { + panic(err) + } + + return srv +} diff --git a/internal/route/helper.go b/internal/route/helper.go new file mode 100644 index 0000000..cf7c774 --- /dev/null +++ b/internal/route/helper.go @@ -0,0 +1,24 @@ +package route + +import ( + "net/http" + + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/middleware/container" + "gitlab.com/wpetit/goweb/service/template" + "gitlab.com/wpetit/goweb/template/html" +) + +func extendTemplateData(w http.ResponseWriter, r *http.Request, data template.Data) template.Data { + ctn := container.Must(r.Context()) + data, err := template.Extend(data, + html.WithFlashes(w, r, ctn), + template.WithBuildInfo(w, r, ctn), + ) + + if err != nil { + panic(errors.Wrap(err, "could not extend template data")) + } + + return data +} diff --git a/internal/route/home.go b/internal/route/home.go new file mode 100644 index 0000000..5b58e36 --- /dev/null +++ b/internal/route/home.go @@ -0,0 +1,20 @@ +package route + +import ( + "net/http" + + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/middleware/container" + "gitlab.com/wpetit/goweb/service/template" +) + +func serveHomePage(w http.ResponseWriter, r *http.Request) { + ctn := container.Must(r.Context()) + tmpl := template.Must(ctn) + + data := extendTemplateData(w, r, template.Data{}) + + if err := tmpl.RenderPage(w, "home.html.tmpl", data); err != nil { + panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path)) + } +} diff --git a/internal/route/mount.go.gotpl b/internal/route/mount.go.gotpl new file mode 100644 index 0000000..1f5a78e --- /dev/null +++ b/internal/route/mount.go.gotpl @@ -0,0 +1,34 @@ +package route + +import ( + "{{ .ProjectNamespace }}/internal/config" + + "github.com/go-chi/chi" + "github.com/gorilla/csrf" + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/static" + "gitlab.com/wpetit/goweb/session/gorilla" +) + +func Mount(r *chi.Mux, config *config.Config) error { + csrfSecret, err := gorilla.GenerateRandomBytes(32) + if err != nil { + return errors.Wrap(err, "could not generate CSRF secret") + } + + csrfMiddleware := csrf.Protect( + csrfSecret, + csrf.Secure(false), + ) + + r.Group(func(r chi.Router) { + r.Use(csrfMiddleware) + + r.Get("/", serveHomePage) + }) + + notFoundHandler := r.NotFoundHandler() + r.Get("/*", static.Dir(config.HTTP.PublicDir, "", notFoundHandler)) + + return nil +} diff --git a/misc/script/release.sh.gotpl b/misc/script/release.sh.gotpl new file mode 100644 index 0000000..5cbe882 --- /dev/null +++ b/misc/script/release.sh.gotpl @@ -0,0 +1,123 @@ +#!/bin/bash + +set -eo pipefail + +OS_TARGETS=(linux) +ARCH_TARGETS=${ARCH_TARGETS:-amd64 arm 386} + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +PROJECT_DIR="$DIR/../.." + +function build { + + local name=$1 + local srcdir=$2 + local os=$3 + local arch=$4 + + local dirname="$name-$os-$arch" + local destdir="$PROJECT_DIR/release/$dirname" + + rm -rf "$destdir" + mkdir -p "$destdir" + + echo "building $dirname..." + + CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" go build \ + -mod=vendor \ + -ldflags="-s -w -X 'main.GitRef=$(current_commit_ref)' -X 'main.ProjectVersion=$(current_version)' -X 'main.BuildDate=$(current_date)'" \ + -gcflags=-trimpath="${PWD}" \ + -asmflags=-trimpath="${PWD}" \ + -o "$destdir/bin/$name" \ + "$srcdir" + + if [ ! -z "$(which upx)" ]; then + upx --best "$destdir/bin/$name" + fi + +} + +function current_date { + date '+%Y-%m-%d %H:%M' +} + +function current_commit_ref { + git log -n 1 --pretty="format:%h" +} + +function current_version { + local latest_tag=$(git describe --abbrev=0 2>/dev/null) + echo ${latest_tag:-0.0.0} +} + +function copy { + + local name=$1 + local os=$2 + local arch=$3 + local src=$4 + local dest=$5 + + local dirname="$name-$os-$arch" + local destdir="$PROJECT_DIR/release/$dirname" + + echo "copying '$src' to '$destdir/$dest'..." + + mkdir -p "$(dirname $destdir/$dest)" + + cp -rfL $src "$destdir/$dest" + +} + +function dump_default_conf { + # Generate and copy configuration file + local command=$1 + local os=$2 + local arch=$3 + local tmp_conf=$(mktemp) + + go run "$PROJECT_DIR/cmd/$command" -dump-config > "$tmp_conf" + copy "$command" $os $arch "$tmp_conf" "$command.yml" + rm -f "$tmp_conf" +} + +function compress { + + local name=$1 + local os=$2 + local arch=$3 + + local dirname="$name-$os-$arch" + local destdir="$PROJECT_DIR/release/$dirname" + + echo "compressing $dirname..." + tar -czf "$destdir.tar.gz" -C "$destdir/../" "$dirname" +} + +function release_server { + + local os=$1 + local arch=$2 + + build 'server' "$PROJECT_DIR/cmd/server" $os $arch + + dump_default_conf 'server' $os $arch + + copy 'server' $os $arch "$PROJECT_DIR/README.md" "README.md" + copy 'server' $os $arch "$PROJECT_DIR/cmd/server/public" "public" + copy 'server' $os $arch "$PROJECT_DIR/cmd/server/template" "template" + + compress 'server' $os $arch + +} + +function main { + + for os in ${OS_TARGETS[@]}; do + for arch in ${ARCH_TARGETS[@]}; do + release_server $os $arch + done + done +} + +main \ No newline at end of file diff --git a/misc/systemd/server.service.gotpl b/misc/systemd/server.service.gotpl new file mode 100644 index 0000000..3b9cacd --- /dev/null +++ b/misc/systemd/server.service.gotpl @@ -0,0 +1,11 @@ +[Unit] +Description={{ .ProjectName }} +After=network-online.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/server -workdir /usr/local/share/server -config /etc/server/config.yml +Restart=on-failure + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/modd.conf b/modd.conf new file mode 100644 index 0000000..26c484a --- /dev/null +++ b/modd.conf @@ -0,0 +1,13 @@ +**/*.go +!**/*_test.go +data/config.yml +!**/rice-box.go +modd.conf { + prep: make build + prep: [ -e data/config.yml ] || ( mkdir -p data && bin/server -dump-config > data/config.yml ) + daemon: bin/server -workdir "./cmd/server" -config ../../data/config.yml +} + +**/*.go { + prep: make test +} \ No newline at end of file diff --git a/scaffold.yml b/scaffold.yml new file mode 100644 index 0000000..63e4278 --- /dev/null +++ b/scaffold.yml @@ -0,0 +1,8 @@ +version: 1 +vars: + - type: string + name: ProjectName + description: Project Name + - type: string + name: ProjectNamespace + description: The Go module namespace \ No newline at end of file