Initial commit

This commit is contained in:
wpetit 2020-02-19 22:13:06 +01:00
commit bdf1e63b06
21 changed files with 654 additions and 0 deletions

4
.gitignore.gotpl Normal file
View File

@ -0,0 +1,4 @@
/release
/data
/vendor
/bin

28
Makefile.gotpl Normal file
View File

@ -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

15
README.md.gotpl Normal file
View File

@ -0,0 +1,15 @@
# {{ .ProjectName }}
## Démarrer avec les sources
```
make build
```
## FAQ
### Générer une version de distribution
```
make release
```

View File

@ -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
}

112
cmd/server/main.go.gotpl Normal file
View File

@ -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))
}
}

View File

@ -0,0 +1,18 @@
{{define "base"}}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{block "title" . -}}{{- end}}</title>
{{- block "head_style" . -}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css" />
{{end}}
{{- block "head_script" . -}}{{end}}
</head>
<body>
{{- block "body" . -}}{{- end -}}
{{- block "body_script" . -}}{{end}}
</body>
</html>
{{end}}

View File

@ -0,0 +1,23 @@
{{define "flash"}}
<div class="flash has-margin-top-small has-margin-bottom-small">
{{- 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 -}}
</div>
{{end}}
{{define "flash_message" -}}
<div class="message {{.MessageClass}}">
<div class="message-body">
<span class="has-text-weight-bold">{{.Title}}</span> {{.Message}}
</div>
</div>
{{- end}}

View File

@ -0,0 +1,7 @@
{{define "footer"}}
<p class="has-margin-top-small has-text-right is-size-7 has-text-grey">
Version: {{ .BuildInfo.ProjectVersion }} -
Réf.: {{ .BuildInfo.GitRef }} -
Date de construction: {{ .BuildInfo.BuildDate }}
</p>
{{end}}

View File

@ -0,0 +1,11 @@
{{define "header"}}
<div class="columns is-mobile">
<div class="column is-4-tablet is-8-mobile">
<div class="columns is-mobile is-gapless">
<div class="column is-narrow">
<h1 class="is-size-3 title"><a href="/" rel="Homepage" class="has-text-black">Your project</a></h1>
</div>
</div>
</div>
</div>
{{end}}

View File

@ -0,0 +1,11 @@
{{define "title"}}Accueil{{end}}
{{define "body"}}
<section class="home is-fullheight section">
<div class="container">
{{template "header" .}}
<h1>Bienvenue !</h1>
{{template "footer" .}}
</div>
</section>
{{end}}
{{template "base" .}}

1
go.mod.gotpl Normal file
View File

@ -0,0 +1 @@
module {{ .ProjectNamespace }}

71
internal/config/config.go Normal file
View File

@ -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
}

View File

@ -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
}
}

View File

@ -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
}

24
internal/route/helper.go Normal file
View File

@ -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
}

20
internal/route/home.go Normal file
View File

@ -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))
}
}

View File

@ -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
}

View File

@ -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

View File

@ -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

13
modd.conf Normal file
View File

@ -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
}

8
scaffold.yml Normal file
View File

@ -0,0 +1,8 @@
version: 1
vars:
- type: string
name: ProjectName
description: Project Name
- type: string
name: ProjectNamespace
description: The Go module namespace