From eb10ca9ca381f84205579696bbb52169b0968620 Mon Sep 17 00:00:00 2001 From: Nathan Coad Date: Thu, 12 Sep 2024 08:57:44 +1000 Subject: [PATCH] initial --- Dockerfile | 34 +++ Makefile | 21 ++ README.md | 242 +++++++++++++++++++++ components/core/html.templ | 30 +++ components/home/home.templ | 8 + db/db.go | 55 +++++ db/local.go | 42 ++++ db/migrations/20240407203525_init.down.txt | 0 db/migrations/20240407203525_init.up.txt | 7 + db/migrations/20240912985300_init_up.sql | 0 db/queries/query.sql | 25 +++ dist/assets/js/htmx@v2.0.2.min.js | 1 + dist/dist.go | 8 + e2e/e2e_test.go | 237 ++++++++++++++++++++ e2e/home_test.go | 16 ++ e2e/testdata/seed.sql | 1 + go.mod | 43 ++++ go.sum | 116 ++++++++++ log/log.go | 100 +++++++++ main.go | 44 ++++ server/handler/handler.go | 24 ++ server/handler/home.go | 12 + server/middleware/cache.go | 18 ++ server/middleware/logging.go | 34 +++ server/middleware/middleware.go | 22 ++ server/router/router.go | 24 ++ server/server.go | 96 ++++++++ sqlc.yml | 10 + styles/input.css | 3 + tailwind.config.js | 14 ++ update_module.sh | 10 + upgrade_htmx.sh | 22 ++ upgrade_sqlc.sh | 13 ++ upgrade_templ.sh | 18 ++ version/version.go | 4 + 35 files changed, 1354 insertions(+) create mode 100644 Dockerfile create mode 100644 Makefile create mode 100644 README.md create mode 100644 components/core/html.templ create mode 100644 components/home/home.templ create mode 100644 db/db.go create mode 100644 db/local.go create mode 100644 db/migrations/20240407203525_init.down.txt create mode 100644 db/migrations/20240407203525_init.up.txt create mode 100644 db/migrations/20240912985300_init_up.sql create mode 100644 db/queries/query.sql create mode 100644 dist/assets/js/htmx@v2.0.2.min.js create mode 100644 dist/dist.go create mode 100644 e2e/e2e_test.go create mode 100644 e2e/home_test.go create mode 100644 e2e/testdata/seed.sql create mode 100644 go.mod create mode 100644 go.sum create mode 100644 log/log.go create mode 100644 main.go create mode 100644 server/handler/handler.go create mode 100644 server/handler/home.go create mode 100644 server/middleware/cache.go create mode 100644 server/middleware/logging.go create mode 100644 server/middleware/middleware.go create mode 100644 server/router/router.go create mode 100644 server/server.go create mode 100644 sqlc.yml create mode 100644 styles/input.css create mode 100644 tailwind.config.js create mode 100755 update_module.sh create mode 100755 upgrade_htmx.sh create mode 100755 upgrade_sqlc.sh create mode 100755 upgrade_templ.sh create mode 100644 version/version.go diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..fde6446 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +## Build +FROM golang:1.22-alpine AS build + +ARG VERSION='dev' + +RUN apk update && apk add --no-cache curl + +RUN curl -sLO https://github.com/tailwindlabs/tailwindcss/releases/latest/download/tailwindcss-linux-x64 \ + && chmod +x tailwindcss-linux-x64 \ + && mv tailwindcss-linux-x64 /usr/local/bin/tailwindcss + +RUN go install github.com/a-h/templ/cmd/templ@v0.2.663 \ + && go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest + +WORKDIR /app + +COPY ./ /app + +RUN templ generate -path ./components \ + && tailwindcss -i ./styles/input.css -o ./dist/assets/css/output@${VERSION}.css --minify \ + && sqlc generate + +RUN go build -ldflags="-s -w -X version.Value=${VERSION}" -o my-app + +## Deploy +FROM gcr.io/distroless/static-debian12 + +WORKDIR / + +COPY --from=build /app/my-app /my-app + +EXPOSE 8080 + +CMD ["/my-app"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ec88389 --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +format-templ: + @echo "Formatting templ files..." + @templ fmt . +generate-templ: + @echo "Generating templ files..." + @templ generate -path ./components +generate-templ-watch: + @echo "Generating templ files..." + @templ generate -path ./components -watch +generate-tailwind: + @echo "Generating tailwind files..." + @tailwindcss -i ./styles/input.css -o ./dist/assets/css/output@dev.css +generate-tailwind-watch: + @echo "Generating tailwind files..." + @tailwindcss -i ./styles/input.css -o ./dist/assets/css/output@dev.css --watch +run: + @echo "Running..." + @go run main.go +build: + @echo "Building..." + @go build -o ./app -ldflags="-s -w -X version.Value=1.0.0" diff --git a/README.md b/README.md new file mode 100644 index 0000000..e7a469e --- /dev/null +++ b/README.md @@ -0,0 +1,242 @@ +# Go + HTMX Template + +This is a template repository that comes with everything you need to build a Web Application using Go (templ) and HTMX. + +The template comes with a basic structure of using a SQL DB (`sqlc`), E2E testing (playwright), and styling (tailwindcss). + +## Getting Started + +In the top right, select the dropdown __Use this template__ and select __Create a new repository__. + +Once cloned, run the `update_module.sh` script to change the module to your module name. + +```shell +./update_module vctpule +``` + +## Technologies + +A few different technologies are configured to help getting off the ground easier. + +- [sqlc](https://sqlc.dev/) for database layer + - Stubbed to use SQLite + - This can be easily swapped with [sqlx](https://jmoiron.github.io/sqlx/) + - The script `upgrade_sqlc.sh` is available to upgrade GitHub Workflow files to latest sqlc version +- [Tailwind CSS](https://tailwindcss.com/) for styling + - Output is generated with the [CLI](https://tailwindcss.com/docs/installation) +- [templ](https://templ.guide/) for creating HTML + - The script `upgrade_templ.sh` is available to make upgrading easier +- [HTMX](https://htmx.org/) for HTML interaction + - The script `upgrade_htmx.sh` is available to make upgrading easier +- [air](https://github.com/cosmtrek/air) for live reloading of the application. +- [golang migrate](https://github.com/golang-migrate/migrate) for DB migrations. +- [playwright-go](https://github.com/playwright-community/playwright-go) for E2E testing. + +Everything else uses the standard library. + +## Structure + +```text +. +├── Makefile +├── components +│   ├── core +│   │   └── html.templ +│   └── home +│   └── home.templ +├── db +│   ├── db.go +│   ├── local.go +│   ├── migrations +│   │   ├── 20240407203525_init.down.sql +│   │   └── 20240407203525_init.up.sql +│   └── queries +│   └── query.sql +├── db.sqlite3 +├── dist +│   ├── assets +│   │   └── js +│   │   └── htmx@1.9.10.min.js +│   └── dist.go +├── e2e +│   ├── e2e_test.go +│   ├── home_test.go +│   └── testdata +│   └── seed.sql +├── go.mod +├── go.sum +├── log +│   └── log.go +├── main.go +├── server +│   ├── handler +│   │   ├── handler.go +│   │   └── home.go +│   ├── middleware +│   │   ├── cache.go +│   │   ├── logging.go +│   │   └── middleware.go +│   ├── router +│   │   └── router.go +│   └── server.go +├── sqlc.yml +├── styles +│   └── input.css +├── tailwind.config.js +└── version + └── version.go +``` + +### Components + +This is where `templ` files live. Anything you want to render to the user goes here. Note, all +`*.go` files will be ignored by `git` (configured in `.gitignore`). + +### DB + +This is the directory that `sqlc` generates to. Update `queries.sql` to build +your database operations. + +This project uses [golang migrate](https://github.com/golang-migrate/migrate) for DB +migrations. `sqlc` uses the `db/migrations` directory to generating DB tables. Call +`db.Migrate(..)` to automatically migrate your database to the latest version. To add migration +call the following command, + +```shell +migrate create -ext sql -dir db/migrations +``` + +This package can be easily update to use `sqlx` as well. + +### Dist + +This is where your assets live. Any Javascript, images, or styling needs to go in the +`dist/assets` directory. The directory will be embedded into the application. + +Note, the `dist/assets/css` will be ignored by `git` (configured in `.gitignore`) since the +files that are written to this directory are done by the Tailwind CSS CLI. Custom styles should +go in the `styles/input.css` file. + +### E2E + +To test the UI, the `e2e` directory contains the Go tests for performing End to end testing. To +run the tests, run the command + +```shell +go test -v ./... -tags=e2e +``` + +The end to end tests, will start up the app, on a random port, seeding the database using the +`seed.sql` file. Once the tests are complete, the app will be stopped. + +The E2E tests use Playwright (Go) for better integration into the Go tooling. + +### Log + +This contains helper function to create a `slog.Logger`. Log level and output type can be set +with then environment variables `LOG_LEVEL` and `LOG_OUTPUT`. The logger will write to +`stdout`. + +### Server + +This contains everything related to the HTTP server. It comes with a graceful shutdown handler +that handles `SIGINT`. + +#### Router + +This package sets up the routing for the application, such as the `/assets/` path and `/` path. +It uses the standard libraries mux for routing. You can easily swap out for other HTTP +routers such as [gorilla/mux](https://github.com/gorilla/mux). + +#### Middleware + +This package contains any middleware to configured with routes. + +#### Handler + +This package contains the handler to handle the actual routes. + +#### Styles + +This contains the `input.css` that the Tailwind CSS CLI uses to generate your output CSS. +Update `input.css` with any custom CSS you need and it will be included in the output CSS. + +#### Version + +This package allows you to set a version at build time. If not set, the version defaults to +`dev`. To set the version run the following command, + +```shell +go build -o ./app -ldflags="-X version.Value=1.0.0" +``` + +See the `Makefile` for building the application. + +## Run + +There are a couple builtin ways to run the application - using `air` or the `Makefile` helper +commands. + +### Prerequisites + +- Install [templ](https://templ.guide/quick-start/installation) +- Install [sqlc](https://docs.sqlc.dev/en/stable/overview/install.html) +- Install [tailwindcss CLI](https://tailwindcss.com/docs/installation) +- Install [air](https://github.com/cosmtrek/air#installation) + +### air + +`air` has been configured with the file `.air.toml` to allow live reloading of the application +when a file changes. + +To run, install `air` + +```shell +go install github.com/cosmtrek/air@latest +``` + +Then simply run the command + +```shell +air +``` + +#### Address Already In Use Error + +Sometimes, you may run into the issue _address already in use_. If this is the case, you +can run this command to find the PID to kill it. + +```shell +ps aux | grep tmp/main +``` + +### Makefile + +You can also run with the provided `Makefile`. There are commands to generate `templ` files and +tailwind output css. + +```shell +# Generate and watch templ +make generate-templ-watch + +# Genrate and watch tailwindcss +make generate-tailwind-watch + +# Run application +make run +``` + +## Github Workflow + +The repository comes with two Github workflows as well. One called `ci.yml` that lints and +tests your code. The other called `release.yml` that creates a tag, GitHub Release, and +attaches the Linux binary to the Release. + +Note, the version of `github.com/a-h/templ/cmd/templ` matches the version in `go.mod`. If these +do not match, the build will fail. When upgrading your `templ` version, make sure to update +`ci.yml` and `release.yml`. + +### GoReleaser + +If you need to compile for more than Linux, see [GoReleaser](https://goreleaser.com/) for a +better release process. diff --git a/components/core/html.templ b/components/core/html.templ new file mode 100644 index 0000000..dd02d77 --- /dev/null +++ b/components/core/html.templ @@ -0,0 +1,30 @@ +package core + +import "vctp/version" + +templ HTML(title string, content templ.Component) { + + + @head(title) + @body(content) + +} + +templ head(title string) { + + + + + { title } + + + +} + +templ body(content templ.Component) { + +
+ @content +
+ +} diff --git a/components/home/home.templ b/components/home/home.templ new file mode 100644 index 0000000..f089c7d --- /dev/null +++ b/components/home/home.templ @@ -0,0 +1,8 @@ +package home + +templ Home() { +
+

Welcome!

+

This is a simple home screen.

+
+} diff --git a/db/db.go b/db/db.go new file mode 100644 index 0000000..6306e3d --- /dev/null +++ b/db/db.go @@ -0,0 +1,55 @@ +package db + +import ( + "database/sql" + "embed" + "fmt" + "vctp/db/queries" + "log/slog" + + "github.com/golang-migrate/migrate/v4" + "github.com/golang-migrate/migrate/v4/database/sqlite3" + "github.com/golang-migrate/migrate/v4/source/iofs" +) + +//go:embed migrations/*.sql +var migrations embed.FS + +type Database interface { + DB() *sql.DB + Queries() *queries.Queries + Logger() *slog.Logger + Close() error +} + +func New(logger *slog.Logger, url string) (Database, error) { + db, err := newLocalDB(logger, url) + if err != nil { + return nil, err + } + if err = db.db.Ping(); err != nil { + return nil, err + } + return db, nil +} + +// Migrate runs the migrations on the database. Assumes the database is SQLite. +func Migrate(db Database) error { + driver, err := sqlite3.WithInstance(db.DB(), &sqlite3.Config{}) + if err != nil { + return fmt.Errorf("failed to create database driver: %w", err) + } + + iofsDriver, err := iofs.New(migrations, "migrations") + if err != nil { + return fmt.Errorf("failed to create iofs: %w", err) + } + defer iofsDriver.Close() + + m, err := migrate.NewWithInstance("iofs", iofsDriver, "sqlite3", driver) + if err != nil { + return fmt.Errorf("failed to create migration: %w", err) + } + + return m.Up() +} diff --git a/db/local.go b/db/local.go new file mode 100644 index 0000000..ca64839 --- /dev/null +++ b/db/local.go @@ -0,0 +1,42 @@ +package db + +import ( + "database/sql" + "vctp/db/queries" + "log/slog" + + _ "github.com/tursodatabase/libsql-client-go/libsql" + _ "modernc.org/sqlite" +) + +type LocalDB struct { + logger *slog.Logger + db *sql.DB + queries *queries.Queries +} + +var _ Database = (*LocalDB)(nil) + +func (d *LocalDB) DB() *sql.DB { + return d.db +} + +func (d *LocalDB) Queries() *queries.Queries { + return d.queries +} + +func (d *LocalDB) Logger() *slog.Logger { + return d.logger +} + +func (d *LocalDB) Close() error { + return d.db.Close() +} + +func newLocalDB(logger *slog.Logger, path string) (*LocalDB, error) { + db, err := sql.Open("libsql", "file:"+path) + if err != nil { + return nil, err + } + return &LocalDB{logger: logger, db: db, queries: queries.New(db)}, nil +} diff --git a/db/migrations/20240407203525_init.down.txt b/db/migrations/20240407203525_init.down.txt new file mode 100644 index 0000000..e69de29 diff --git a/db/migrations/20240407203525_init.up.txt b/db/migrations/20240407203525_init.up.txt new file mode 100644 index 0000000..bee06bc --- /dev/null +++ b/db/migrations/20240407203525_init.up.txt @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS authors ( + id INTEGER PRIMARY KEY, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + name TEXT NOT NULL, + bio TEXT +); + diff --git a/db/migrations/20240912985300_init_up.sql b/db/migrations/20240912985300_init_up.sql new file mode 100644 index 0000000..e69de29 diff --git a/db/queries/query.sql b/db/queries/query.sql new file mode 100644 index 0000000..b3eff66 --- /dev/null +++ b/db/queries/query.sql @@ -0,0 +1,25 @@ +-- name: GetAuthor :one +SELECT * FROM authors +WHERE id = ? LIMIT 1; + +-- name: ListAuthors :many +SELECT * FROM authors +ORDER BY name; + +-- name: CreateAuthor :one +INSERT INTO authors ( + name, bio +) VALUES ( + ?, ? +) +RETURNING *; + +-- name: UpdateAuthor :exec +UPDATE authors +SET name = ?, +bio = ? +WHERE id = ?; + +-- name: DeleteAuthor :exec +DELETE FROM authors +WHERE id = ?; diff --git a/dist/assets/js/htmx@v2.0.2.min.js b/dist/assets/js/htmx@v2.0.2.min.js new file mode 100644 index 0000000..c11fbbd --- /dev/null +++ b/dist/assets/js/htmx@v2.0.2.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.2"};Q.onLoad=$;Q.process=Dt;Q.on=be;Q.off=we;Q.trigger=de;Q.ajax=Hn;Q.find=r;Q.findAll=p;Q.closest=g;Q.remove=K;Q.addClass=Y;Q.removeClass=o;Q.toggleClass=W;Q.takeClass=ge;Q.swap=ze;Q.defineExtension=Bn;Q.removeExtension=Un;Q.logAll=z;Q.logNone=J;Q.parseInterval=h;Q._=_;const n={addTriggerHandler:Et,bodyContains:le,canAccessLocalStorage:j,findThisElement:Ee,filterValues:hn,swap:ze,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:T,getExpressionVars:Cn,getHeaders:dn,getInputValues:cn,getInternalData:ie,getSwapSpecification:pn,getTriggerSpecs:lt,getTarget:Ce,makeFragment:D,mergeObjects:ue,makeSettleInfo:xn,oobSwap:Te,querySelectorExt:ae,settleImmediately:Gt,shouldCancel:ht,triggerEvent:de,triggerErrorEvent:fe,withExtensions:Bt};const v=["get","post","put","delete","patch"];const O=v.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");const R=e("head");function e(e,t=false){return new RegExp(`<${e}(\\s[^>]*>|>)([\\s\\S]*?)<\\/${e}>`,t?"gim":"im")}function h(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function H(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function T(e,t){while(e&&!t(e)){e=u(e)}return e||null}function q(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;T(t,function(e){return!!(r=q(t,ce(e),n))});if(r!=="unset"){return r}}function f(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function L(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function N(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function A(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function I(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function P(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function k(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(P(e)){const t=I(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){w(e)}finally{e.remove()}}})}function D(e){const t=e.replace(R,"");const n=L(t);let r;if(n==="html"){r=new DocumentFragment;const i=N(e);A(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=N(t);A(r,i.body);r.title=i.title}else{const i=N('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){k(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function M(e){return typeof e==="function"}function X(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function F(t){const n=[];if(t){for(let e=0;e=0}function le(e){const t=e.getRootNode&&e.getRootNode();if(t&&t instanceof window.ShadowRoot){return ne().body.contains(t.host)}else{return ne().body.contains(e)}}function U(e){return e.trim().split(/\s+/)}function ue(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){w(e);return null}}function j(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function V(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function _(e){return vn(ne().body,function(){return eval(e)})}function $(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function z(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function J(){Q.logger=null}function r(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return r(ne(),e)}}function p(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return p(ne(),e)}}function E(){return window}function K(e,t){e=y(e);if(t){E().setTimeout(function(){K(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function G(e){return e instanceof HTMLElement?e:null}function Z(e){return typeof e==="string"?e:null}function d(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function Y(e,t,n){e=ce(y(e));if(!e){return}if(n){E().setTimeout(function(){Y(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function o(e,t,n){let r=ce(y(e));if(!r){return}if(n){E().setTimeout(function(){o(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function ge(e,t){e=y(e);se(e.parentElement.children,function(e){o(e,t)});Y(ce(e),t)}function g(e,t){e=ce(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||f(e,t)){return e}}while(e=e&&ce(u(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function pe(e,t){return e.substring(e.length-t.length)===t}function i(e){const t=e.trim();if(l(t,"<")&&pe(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(e,t,n){e=y(e);if(t.indexOf("closest ")===0){return[g(ce(e),i(t.substr(8)))]}else if(t.indexOf("find ")===0){return[r(d(e),i(t.substr(5)))]}else if(t==="next"){return[ce(e).nextElementSibling]}else if(t.indexOf("next ")===0){return[me(e,i(t.substr(5)),!!n)]}else if(t==="previous"){return[ce(e).previousElementSibling]}else if(t.indexOf("previous ")===0){return[ye(e,i(t.substr(9)),!!n)]}else if(t==="document"){return[document]}else if(t==="window"){return[window]}else if(t==="body"){return[document.body]}else if(t==="root"){return[H(e,!!n)]}else if(t.indexOf("global ")===0){return m(e,t.slice(7),true)}else{return F(d(H(e,!!n)).querySelectorAll(i(t)))}}var me=function(t,e,n){const r=d(H(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return r(d(t)||document,e)}else{return e}}function xe(e,t,n){if(M(t)){return{target:ne().body,event:Z(e),listener:t}}else{return{target:y(e),event:Z(t),listener:n}}}function be(t,n,r){_n(function(){const e=xe(t,n,r);e.target.addEventListener(e.event,e.listener)});const e=M(n);return e?n:r}function we(t,n,r){_n(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return M(n)?n:r}const ve=ne().createElement("output");function Se(e,t){const n=re(e,t);if(n){if(n==="this"){return[Ee(e,t)]}else{const r=m(e,n);if(r.length===0){w('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Ee(e,t){return ce(T(e,function(e){return te(ce(e),t)!=null}))}function Ce(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Ee(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Oe(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substr(0,e.indexOf(":"));t=e.substr(e.indexOf(":")+1,e.length)}else{s=e}const n=ne().querySelectorAll(t);if(n){se(n,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=d(n)}const r={shouldSwap:true,target:e,fragment:t};if(!de(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){_e(s,e,e,t,i)}se(i.elts,function(e){de(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function qe(e){se(p(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){e.parentNode.replaceChild(n,e)}})}function Le(l,e,u){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=d(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Re(t,i);u.tasks.push(function(){Re(t,s)})}}})}function Ne(e){return function(){o(e,Q.config.addedClass);Dt(ce(e));Ae(d(e));de(e,"htmx:load")}}function Ae(e){const t="[autofocus]";const n=G(f(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;Y(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ne(o))}}}function Ie(e,t){let n=0;while(n0}function ze(e,t,r,o){if(!o){o={}}e=y(e);const n=document.activeElement;let i={};try{i={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const s=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=D(t);s.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(l,r.settleDelay)}else{l()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(X(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}de(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(nt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function b(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function ot(e){let t;if(e.length>0&&Qe.test(e[0])){e.shift();t=b(e,et).trim();e.shift()}else{t=b(e,x)}return t}const it="input, textarea, select";function st(e,t,n){const r=[];const o=tt(t);do{b(o,We);const l=o.length;const u=b(o,/[,\[\s]/);if(u!==""){if(u==="every"){const c={trigger:"every"};b(o,We);c.pollInterval=h(b(o,/[,\[\s]/));b(o,We);var i=rt(e,o,"event");if(i){c.eventFilter=i}r.push(c)}else{const a={trigger:u};var i=rt(e,o,"event");if(i){a.eventFilter=i}while(o.length>0&&o[0]!==","){b(o,We);const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=h(b(o,x))}else if(f==="from"&&o[0]===":"){o.shift();if(Qe.test(o[0])){var s=ot(o)}else{var s=b(o,x);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const d=ot(o);if(d.length>0){s+=" "+d}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=ot(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=h(b(o,x))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=b(o,x)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=ot(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=b(o,x)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}b(o,We)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function lt(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||st(e,t,r)}if(n.length>0){return n}else if(f(e,"form")){return[{trigger:"submit"}]}else if(f(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(f(e,it)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function ut(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function at(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function dt(t,n,e){if(t instanceof HTMLAnchorElement&&at(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";if(r==="get"){}o=ee(t,"action")}e.forEach(function(e){mt(t,function(e,t){const n=ce(e);if(ft(n)){a(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ce(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(f(n,'input[type="submit"], button')&&g(n,"form")!==null){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function gt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function mt(s,l,e,u,c){const a=ie(s);let t;if(u.from){t=m(s,u.from)}else{t=[s]}if(u.changed){t.forEach(function(e){const t=ie(e);t.lastValue=e.value})}se(t,function(o){const i=function(e){if(!le(s)){o.removeEventListener(u.trigger,i);return}if(gt(s,e)){return}if(c||ht(e,s)){e.preventDefault()}if(pt(u,s,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(s)<0){t.handledFor.push(s);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!f(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=ie(o);const r=o.value;if(n.lastValue===r){return}n.lastValue=r}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){de(s,"htmx:trigger");l(s,e);a.throttle=E().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=E().setTimeout(function(){de(s,"htmx:trigger");l(s,e)},u.delay)}else{de(s,"htmx:trigger");l(s,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:i,on:o});o.addEventListener(u.trigger,i)})}let yt=false;let xt=null;function bt(){if(!xt){xt=function(){yt=true};window.addEventListener("scroll",xt);setInterval(function(){if(yt){yt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){wt(e)})}},200)}}function wt(e){if(!s(e,"data-hx-revealed")&&B(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){de(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){de(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function St(t,n,e){let i=false;se(v,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){Et(t,e,n,function(e,t){const n=ce(e);if(g(n,Q.config.disableSelector)){a(n);return}he(r,o,n,t)})})}});return i}function Et(r,e,t,n){if(e.trigger==="revealed"){bt();mt(r,n,t,e);wt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{mt(r,n,t,e)}}function Ct(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function qt(e){const t=g(ce(e.target),"button, input[type='submit']");const n=Nt(e);if(n){n.lastButtonClicked=t}}function Lt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function Nt(e){const t=g(ce(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",qt);e.addEventListener("focusin",qt);e.addEventListener("focusout",Lt)}function It(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function _t(t){if(!j()){return null}t=V(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){de(ne().body,"htmx:historyCacheMissLoad",i);const e=D(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=jt();const r=xn(n);Dn(e.title);Ve(n,t,r);Gt(r.tasks);Ut=o;de(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Yt(e){zt();e=e||location.pathname+location.search;const t=_t(e);if(t){const n=D(t.content);const r=jt();const o=xn(r);Dn(n.title);Ve(r,n,o);Gt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Ut=e;de(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Zt(e)}}}function Wt(e){let t=Se(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Qt(e){let t=Se(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function en(e,t){se(e,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function tn(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function sn(t,n,r,o,i){if(o==null||tn(t,o)){return}else{t.push(o)}if(nn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=F(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=F(o.files)}rn(s,e,n);if(i){ln(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){on(e.name,e.value,n)}else{t.push(e)}if(i){ln(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}rn(t,e,n)})}}function ln(e,t){const n=e;if(n.willValidate){de(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});de(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function un(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){sn(n,o,i,g(e,"form"),l)}sn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const c=s.lastButtonClicked||e;const a=ee(c,"name");rn(a,c.value,o)}const u=Se(e,"hx-include");se(u,function(e){sn(n,r,i,ce(e),l);if(!f(e,"form")){se(d(e).querySelectorAll(it),function(e){sn(n,r,i,e,l)})}});un(r,o);return{errors:i,formData:r,values:An(r)}}function an(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function fn(e){e=Ln(e);let n="";e.forEach(function(e,t){n=an(n,t,e)});return n}function dn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};wn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.substr(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function gn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function pn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!gn(e)){r.show="top"}if(n){const s=U(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=c;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.substr(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const d=l.substr("focus-scroll:".length);r.focusScroll=d=="true"}else if(e==0){r.swapStyle=l}else{w("Unknown modifier in hx-swap: "+l)}}}}return r}function mn(e){return re(e,"hx-encoding")==="multipart/form-data"||f(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function yn(t,n,r){let o=null;Bt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(mn(n)){return un(new FormData,Ln(r))}else{return fn(r)}}}function xn(e){return{tasks:[],elts:[e]}}function bn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function wn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.substr(11);t=true}else if(e.indexOf("js:")===0){e=e.substr(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return wn(ce(u(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Sn(e,t){return wn(e,"hx-vars",true,t)}function En(e,t){return wn(e,"hx-vals",false,t)}function Cn(e){return ue(Sn(e),En(e))}function On(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function Rn(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function C(e,t){return t.test(e.getAllResponseHeaders())}function Hn(e,t,n){e=e.toLowerCase();if(n){if(n instanceof Element||typeof n==="string"){return he(e,t,null,null,{targetOverride:y(n),returnPromise:true})}else{return he(e,t,y(n.source),n.event,{handler:n.handler,headers:n.headers,values:n.values,targetOverride:y(n.target),swapOverride:n.swap,select:n.select,returnPromise:true})}}else{return he(e,t,null,null,{returnPromise:true})}}function Tn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function qn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return de(e,"htmx:validateUrl",ue({url:o,sameHost:r},n))}function Ln(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Nn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(r){return new Proxy(r,{get:function(e,t){if(typeof t==="symbol"){return Reflect.get(e,t)}if(t==="toJSON"){return()=>Object.fromEntries(r)}if(t in e){if(typeof e[t]==="function"){return function(){return r[t].apply(r,arguments)}}else{return e[t]}}const n=r.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Nn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Mn;const X=i.select||null;if(!le(r)){oe(s);return e}const u=i.targetOverride||ce(Ce(r));if(u==null||u==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let c=ie(r);const a=c.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const N=ee(a,"formmethod");if(N!=null){if(N.toLowerCase()!=="dialog"){t=N}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:u,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(de(r,"htmx:confirm",G)===false){oe(s);return e}}let d=r;let h=re(r,"hx-sync");let g=null;let F=false;if(h){const A=h.split(":");const I=A[0].trim();if(I==="this"){d=Ee(r,"hx-sync")}else{d=ce(ae(r,I))}h=(A[1]||"drop").trim();c=ie(d);if(h==="drop"&&c.xhr&&c.abortable!==true){oe(s);return e}else if(h==="abort"){if(c.xhr){oe(s);return e}else{F=true}}else if(h==="replace"){de(d,"htmx:abort")}else if(h.indexOf("queue")===0){const Z=h.split(" ");g=(Z[1]||"last").trim()}}if(c.xhr){if(c.abortable){de(d,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(c.queuedRequests==null){c.queuedRequests=[]}if(g==="first"&&c.queuedRequests.length===0){c.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(g==="all"){c.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(g==="last"){c.queuedRequests=[];c.queuedRequests.push(function(){he(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;c.xhr=p;c.abortable=F;const m=function(){c.xhr=null;c.abortable=false;if(c.queuedRequests!=null&&c.queuedRequests.length>0){const e=c.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var y=prompt(B);if(y===null||!de(r,"htmx:prompt",{prompt:y,target:u})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let x=dn(r,u,y);if(t!=="get"&&!mn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=ue(x,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){un(j,Ln(i.values))}const V=Ln(Cn(r));const w=un(j,V);let v=hn(w,r);if(Q.config.getCacheBusterParam&&t==="get"){v.set("org.htmx.cache-buster",ee(u,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=wn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:v,parameters:An(v),unfilteredFormData:w,unfilteredParameters:An(w),headers:x,target:u,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!de(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;x=C.headers;v=Ln(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){de(r,"htmx:validation:halted",C);oe(s);m();return e}const $=n.split("#");const z=$[0];const O=$[1];let R=n;if(E){R=z;const Y=!v.keys().next().done;if(Y){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=fn(v);if(O){R+="#"+O}}}if(!qn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in x){if(x.hasOwnProperty(k)){const W=x[k];On(p,k,W)}}}const H={xhr:p,target:u,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Tn(r);H.pathInfo.responsePath=Rn(p);M(r,H);if(H.keepIndicators!==true){en(T,q)}de(r,"htmx:afterRequest",H);de(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){de(e,"htmx:afterRequest",H);de(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ue({error:e},H));throw e}};p.onerror=function(){en(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){en(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){en(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!de(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Wt(r);var q=Qt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){de(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});de(r,"htmx:beforeSend",H);const J=E?null:yn(p,r,v);p.send(J);return e}function In(e,t){const n=t.xhr;let r=null;let o=null;if(C(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(C(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(C(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const u=re(e,"hx-replace-url");const c=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(u){a="replace";f=u}else if(c){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function Pn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function kn(e){for(var t=0;t0){E().setTimeout(e,y.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ue({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Xn={};function Fn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Bn(e,t){if(t.init){t.init(n)}Xn[e]=ue(Fn(),t)}function Un(e){delete Xn[e]}function jn(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Xn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return jn(ce(u(e)),n,r)}var Vn=false;ne().addEventListener("DOMContentLoaded",function(){Vn=true});function _n(e){if(Vn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function $n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function Jn(){const e=zn();if(e){Q.config=ue(Q.config,e)}}_n(function(){Jn();$n();let e=ne().body;Dt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Yt();se(t,function(e){de(e,"htmx:restored",{document:ne(),triggerEvent:de})})}else{if(n){n(e)}}};E().setTimeout(function(){de(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/dist/dist.go b/dist/dist.go new file mode 100644 index 0000000..02c066e --- /dev/null +++ b/dist/dist.go @@ -0,0 +1,8 @@ +package dist + +import ( + "embed" +) + +//go:embed all:assets +var AssetsDir embed.FS diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go new file mode 100644 index 0000000..69d8618 --- /dev/null +++ b/e2e/e2e_test.go @@ -0,0 +1,237 @@ +//go:build e2e + +package e2e_test + +import ( + "bufio" + "database/sql" + "fmt" + "log" + "math/rand" + "net/url" + "os" + "os/exec" + "syscall" + "testing" + "time" + + "github.com/playwright-community/playwright-go" + _ "github.com/tursodatabase/libsql-client-go/libsql" + _ "modernc.org/sqlite" +) + +// global variables, can be used in any tests +var ( + pw *playwright.Playwright + browser playwright.Browser + context playwright.BrowserContext + page playwright.Page + expect playwright.PlaywrightAssertions + isChromium bool + isFirefox bool + isWebKit bool + browserName = getBrowserName() + browserType playwright.BrowserType + app *exec.Cmd + baseUrL *url.URL +) + +// defaultContextOptions for most tests +var defaultContextOptions = playwright.BrowserNewContextOptions{ + AcceptDownloads: playwright.Bool(true), + HasTouch: playwright.Bool(true), +} + +func TestMain(m *testing.M) { + beforeAll() + code := m.Run() + afterAll() + os.Exit(code) +} + +// beforeAll prepares the environment, including +// - start Playwright driver +// - launch browser depends on BROWSER env +// - init web-first assertions, alias as `expect` +func beforeAll() { + err := playwright.Install() + if err != nil { + log.Fatalf("could not install Playwright: %v", err) + } + + pw, err = playwright.Run() + if err != nil { + log.Fatalf("could not start Playwright: %v", err) + } + if browserName == "chromium" || browserName == "" { + browserType = pw.Chromium + } else if browserName == "firefox" { + browserType = pw.Firefox + } else if browserName == "webkit" { + browserType = pw.WebKit + } + // launch browser, headless or not depending on HEADFUL env + browser, err = browserType.Launch(playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(os.Getenv("HEADFUL") == ""), + }) + if err != nil { + log.Fatalf("could not launch: %v", err) + } + // init web-first assertions with 1s timeout instead of default 5s + expect = playwright.NewPlaywrightAssertions(1000) + isChromium = browserName == "chromium" || browserName == "" + isFirefox = browserName == "firefox" + isWebKit = browserName == "webkit" + + // start app + if err = startApp(); err != nil { + log.Fatalf("could not start app: %v", err) + } + time.Sleep(time.Second * 5) + if err = seedDB(); err != nil { + log.Fatalf("could not seed db: %v", err) + } +} + +func startApp() error { + port := getPort() + app = exec.Command("go", "run", "main.go") + app.Dir = "../" + app.Env = append( + os.Environ(), + "DB_URL=./test-db.sqlite3", + fmt.Sprintf("PORT=%d", port), + "LOG_LEVEL=DEBUG", + ) + + var err error + baseUrL, err = url.Parse(fmt.Sprintf("http://localhost:%d", port)) + if err != nil { + return err + } + + stdout, err := app.StdoutPipe() + if err != nil { + return err + } + stderr, err := app.StderrPipe() + if err != nil { + return err + } + + if err := app.Start(); err != nil { + return err + } + fmt.Printf("Started app on port %d, pid %d", port, app.Process.Pid) + + stdoutchan := make(chan string) + stderrchan := make(chan string) + go func() { + defer close(stdoutchan) + scanner := bufio.NewScanner(stdout) + for scanner.Scan() { + stdoutchan <- scanner.Text() + } + }() + go func() { + defer close(stderrchan) + scanner := bufio.NewScanner(stderr) + for scanner.Scan() { + stderrchan <- scanner.Text() + } + }() + + go func() { + for line := range stdoutchan { + fmt.Println("[STDOUT]", line) + } + }() + go func() { + for line := range stderrchan { + fmt.Println("[STDERR]", line) + } + }() + return nil +} + +func seedDB() error { + db, err := sql.Open("libsql", "file:../test-db.sqlite3") + if err != nil { + return err + } + b, err := os.ReadFile("./testdata/seed.sql") + if err != nil { + return err + } + _, err = db.Exec(string(b)) + if err != nil { + return err + } + return nil +} + +func getPort() int { + randomGenerator := rand.New(rand.NewSource(time.Now().UnixNano())) + return randomGenerator.Intn(9001-3000) + 3000 +} + +// afterAll does cleanup, e.g. stop playwright driver +func afterAll() { + if app != nil && app.Process != nil { + if err := syscall.Kill(-app.Process.Pid, syscall.SIGKILL); err != nil { + fmt.Println(err) + } + } + if err := pw.Stop(); err != nil { + log.Fatalf("could not start Playwright: %v", err) + } + if err := os.Remove("../test-db.sqlite3"); err != nil { + log.Fatalf("could not remove test-db.sqlite3: %v", err) + } +} + +// beforeEach creates a new context and page for each test, +// so each test has isolated environment. Usage: +// +// Func TestFoo(t *testing.T) { +// beforeEach(t) +// // your test code +// } +func beforeEach(t *testing.T, contextOptions ...playwright.BrowserNewContextOptions) { + t.Helper() + opt := defaultContextOptions + if len(contextOptions) == 1 { + opt = contextOptions[0] + } + context, page = newBrowserContextAndPage(t, opt) +} + +func getBrowserName() string { + browserName, hasEnv := os.LookupEnv("BROWSER") + if hasEnv { + return browserName + } + return "chromium" +} + +func newBrowserContextAndPage(t *testing.T, options playwright.BrowserNewContextOptions) (playwright.BrowserContext, playwright.Page) { + t.Helper() + context, err := browser.NewContext(options) + if err != nil { + t.Fatalf("could not create new context: %v", err) + } + t.Cleanup(func() { + if err := context.Close(); err != nil { + t.Errorf("could not close context: %v", err) + } + }) + p, err := context.NewPage() + if err != nil { + t.Fatalf("could not create new page: %v", err) + } + return context, p +} + +func getFullPath(relativePath string) string { + return baseUrL.ResolveReference(&url.URL{Path: relativePath}).String() +} diff --git a/e2e/home_test.go b/e2e/home_test.go new file mode 100644 index 0000000..33b1f66 --- /dev/null +++ b/e2e/home_test.go @@ -0,0 +1,16 @@ +//go:build e2e + +package e2e_test + +import ( + "github.com/stretchr/testify/require" + "testing" +) + +func TestHome(t *testing.T) { + beforeEach(t) + _, err := page.Goto(getFullPath("")) + require.NoError(t, err) + + require.NoError(t, expect.Locator(page.GetByText("Welcome!")).ToBeVisible()) +} diff --git a/e2e/testdata/seed.sql b/e2e/testdata/seed.sql new file mode 100644 index 0000000..d0eb825 --- /dev/null +++ b/e2e/testdata/seed.sql @@ -0,0 +1 @@ +-- TODO: fill this what you need for E2E testing diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5b8ea69 --- /dev/null +++ b/go.mod @@ -0,0 +1,43 @@ +module vctp + +go 1.23.1 + +require ( + github.com/a-h/templ v0.2.771 + github.com/golang-migrate/migrate/v4 v4.17.1 + github.com/playwright-community/playwright-go v0.4201.1 + github.com/stretchr/testify v1.8.4 + github.com/tursodatabase/libsql-client-go v0.0.0-20240812094001-348a4e45b535 + modernc.org/sqlite v1.32.0 +) + +require ( + github.com/antlr4-go/antlr/v4 v4.13.1 // indirect + github.com/coder/websocket v1.8.12 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/deckarep/golang-set/v2 v2.6.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-jose/go-jose/v3 v3.0.1 // indirect + github.com/go-stack/stack v1.8.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-sqlite3 v1.14.22 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 // indirect + golang.org/x/sys v0.24.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a // indirect + modernc.org/libc v1.59.9 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/strutil v1.2.0 // indirect + modernc.org/token v1.1.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..ff09c1e --- /dev/null +++ b/go.sum @@ -0,0 +1,116 @@ +github.com/a-h/templ v0.2.771 h1:4KH5ykNigYGGpCe0fRJ7/hzwz72k3qFqIiiLLJskbSo= +github.com/a-h/templ v0.2.771/go.mod h1:lq48JXoUvuQrU0VThrK31yFwdRjTCnIE5bcPCM9IP1w= +github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= +github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= +github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo= +github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/deckarep/golang-set/v2 v2.6.0 h1:XfcQbWM1LlMB8BsJ8N9vW5ehnnPVIw0je80NsVHagjM= +github.com/deckarep/golang-set/v2 v2.6.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-jose/go-jose/v3 v3.0.1 h1:pWmKFVtt+Jl0vBZTIpz/eAKwsm6LkIxDVVbFHKkchhA= +github.com/go-jose/go-jose/v3 v3.0.1/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8= +github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= +github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/golang-migrate/migrate/v4 v4.17.1 h1:4zQ6iqL6t6AiItphxJctQb3cFqWiSpMnX7wLTPnnYO4= +github.com/golang-migrate/migrate/v4 v4.17.1/go.mod h1:m8hinFyWBn0SA4QKHuKh175Pm9wjmxj3S2Mia7dbXzM= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc= +github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/playwright-community/playwright-go v0.4201.1 h1:fFX/02r3wrL+8NB132RcduR0lWEofxRDJEKuln+9uMQ= +github.com/playwright-community/playwright-go v0.4201.1/go.mod h1:hpEOnUo/Kgb2lv5lEY29jbW5Xgn7HaBeiE+PowRad8k= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/tursodatabase/libsql-client-go v0.0.0-20240812094001-348a4e45b535 h1:iLjJLq2A5J6L9zrhyNn+fpmxFvtEpYB4XLMr0rX3epI= +github.com/tursodatabase/libsql-client-go v0.0.0-20240812094001-348a4e45b535/go.mod h1:l8xTsYB90uaVdMHXMCxKKLSgw5wLYBwBKKefNIUnm9s= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA= +golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ= +golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= +golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= +modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= +modernc.org/ccgo/v4 v4.20.7 h1:skrinQsjxWfvj6nbC3ztZPJy+NuwmB3hV9zX/pthNYQ= +modernc.org/ccgo/v4 v4.20.7/go.mod h1:UOkI3JSG2zT4E2ioHlncSOZsXbuDCZLvPi3uMlZT5GY= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.5.0 h1:bJ9ChznK1L1mUtAQtxi0wi5AtAs5jQuw4PrPHO5pb6M= +modernc.org/gc/v2 v2.5.0/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= +modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a h1:CfbpOLEo2IwNzJdMvE8aiRbPMxoTpgAJeyePh0SmO8M= +modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.59.9 h1:k+nNDDakwipimgmJ1D9H466LhFeSkaPPycAs1OZiDmY= +modernc.org/libc v1.59.9/go.mod h1:EY/egGEU7Ju66eU6SBqCNYaFUDuc4npICkMWnU5EE3A= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= +modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= +modernc.org/sqlite v1.32.0 h1:6BM4uGza7bWypsw4fdLRsLxut6bHe4c58VeqjRgST8s= +modernc.org/sqlite v1.32.0/go.mod h1:UqoylwmTb9F+IqXERT8bW9zzOWN8qwAIcLdzeBZs4hA= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/log/log.go b/log/log.go new file mode 100644 index 0000000..c184073 --- /dev/null +++ b/log/log.go @@ -0,0 +1,100 @@ +package log + +import ( + "log/slog" + "os" +) + +// New creates a new logger with the given level and output. +func New(level Level, output Output) *slog.Logger { + var h slog.Handler + switch output { + case OutputJson: + h = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level.ToSlog()}) + case OutputText: + h = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level.ToSlog()}) + default: + h = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level.ToSlog()}) + } + return slog.New(h) +} + +// Level represents the log level. +type Level string + +// ToSlog converts the level to slog.Level. +func (l Level) ToSlog() slog.Level { + switch l { + case LevelDebug: + return slog.LevelDebug + case LevelInfo: + return slog.LevelInfo + case LevelWarn: + return slog.LevelWarn + case LevelError: + return slog.LevelError + default: + return slog.LevelInfo + } +} + +const ( + // LogDebug is the debug log level. + LevelDebug Level = "debug" + // LogInfo is the info log level. + LevelInfo Level = "info" + // LogWarn is the warn log level. + LevelWarn Level = "warn" + // LogError is the error log level. + LevelError Level = "error" +) + +// ToLevel converts the level to Level. +func ToLevel(level string) Level { + switch level { + case "debug": + return LevelDebug + case "info": + return LevelInfo + case "warn": + return LevelWarn + case "error": + return LevelError + default: + return LevelInfo + } +} + +// GetLevel returns the log level from the environment variable. +func GetLevel() Level { + level := os.Getenv("LOG_LEVEL") + return ToLevel(level) +} + +// Output represents the log output. +type Output string + +const ( + // OutputJson is the JSON log output. + OutputJson Output = "json" + // OutputText is the text log output. + OutputText Output = "text" +) + +// ToOutput converts the output to Output. +func ToOutput(output string) Output { + switch output { + case "json": + return OutputJson + case "text": + return OutputText + default: + return OutputText + } +} + +// GetOutput returns the log output from the environment variable. +func GetOutput() Output { + output := os.Getenv("LOG_OUTPUT") + return ToOutput(output) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..649db54 --- /dev/null +++ b/main.go @@ -0,0 +1,44 @@ +package main + +import ( + "errors" + "vctp/db" + "vctp/log" + "vctp/server" + "vctp/server/router" + "os" + + "github.com/golang-migrate/migrate/v4" +) + +func main() { + logger := log.New( + log.GetLevel(), + log.GetOutput(), + ) + + database, err := db.New(logger, "./db.sqlite3") + if err != nil { + logger.Error("Failed to create database", "error", err) + os.Exit(1) + } + defer database.Close() + + if err = db.Migrate(database); err != nil && !errors.Is(err, migrate.ErrNoChange) { + logger.Error("failed to migrate database", "error", err) + return + } + + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + svr := server.New( + logger, + ":"+port, + server.WithRouter(router.New(logger, database)), + ) + + svr.StartAndWait() +} diff --git a/server/handler/handler.go b/server/handler/handler.go new file mode 100644 index 0000000..8dfaea7 --- /dev/null +++ b/server/handler/handler.go @@ -0,0 +1,24 @@ +package handler + +import ( + "context" + "github.com/a-h/templ" + "vctp/db" + "log/slog" + "net/http" +) + +// Handler handles requests. +type Handler struct { + Logger *slog.Logger + Database db.Database +} + +func (h *Handler) html(ctx context.Context, w http.ResponseWriter, status int, t templ.Component) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + + if err := t.Render(ctx, w); err != nil { + h.Logger.Error("Failed to render component", "error", err) + } +} diff --git a/server/handler/home.go b/server/handler/home.go new file mode 100644 index 0000000..f3cbda5 --- /dev/null +++ b/server/handler/home.go @@ -0,0 +1,12 @@ +package handler + +import ( + "vctp/components/core" + "vctp/components/home" + "net/http" +) + +// Home handles the home page. +func (h *Handler) Home(w http.ResponseWriter, r *http.Request) { + h.html(r.Context(), w, http.StatusOK, core.HTML("Example Site", home.Home())) +} diff --git a/server/middleware/cache.go b/server/middleware/cache.go new file mode 100644 index 0000000..538482f --- /dev/null +++ b/server/middleware/cache.go @@ -0,0 +1,18 @@ +package middleware + +import ( + "vctp/version" + "net/http" +) + +// CacheMiddleware sets the Cache-Control header based on the version. +func CacheMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if version.Value == "dev" { + w.Header().Set("Cache-Control", "no-cache") + } else { + w.Header().Set("Cache-Control", "public, max-age=31536000") + } + next.ServeHTTP(w, r) + }) +} diff --git a/server/middleware/logging.go b/server/middleware/logging.go new file mode 100644 index 0000000..88b29cc --- /dev/null +++ b/server/middleware/logging.go @@ -0,0 +1,34 @@ +package middleware + +import ( + "log/slog" + "net/http" + "time" +) + +// LoggingMiddleware represents a logging middleware. +type LoggingMiddleware struct { + logger *slog.Logger + handler http.Handler +} + +// NewLoggingMiddleware creates a new logging middleware with the given logger and handler. +func NewLoggingMiddleware(logger *slog.Logger, handler http.Handler) *LoggingMiddleware { + return &LoggingMiddleware{ + logger: logger, + handler: handler, + } +} + +// ServeHTTP logs the request and calls the next handler. +func (l *LoggingMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { + start := time.Now() + l.handler.ServeHTTP(w, r) + l.logger.Debug( + "Request recieved", + slog.String("method", r.Method), + slog.String("path", r.URL.Path), + slog.String("remote", r.RemoteAddr), + slog.Duration("duration", time.Since(start)), + ) +} diff --git a/server/middleware/middleware.go b/server/middleware/middleware.go new file mode 100644 index 0000000..73cefc7 --- /dev/null +++ b/server/middleware/middleware.go @@ -0,0 +1,22 @@ +package middleware + +import "net/http" + +type Handler func(http.Handler) http.Handler + +func Chain(handlers ...Handler) Handler { + if len(handlers) == 0 { + return defaultHandler + } + + return func(next http.Handler) http.Handler { + for i := len(handlers) - 1; i >= 0; i-- { + next = handlers[i](next) + } + return next + } +} + +func defaultHandler(next http.Handler) http.Handler { + return next +} diff --git a/server/router/router.go b/server/router/router.go new file mode 100644 index 0000000..9d90322 --- /dev/null +++ b/server/router/router.go @@ -0,0 +1,24 @@ +package router + +import ( + "vctp/db" + "vctp/dist" + "vctp/server/handler" + "vctp/server/middleware" + "log/slog" + "net/http" +) + +func New(logger *slog.Logger, database db.Database) http.Handler { + h := &handler.Handler{ + Logger: logger, + Database: database, + } + + mux := http.NewServeMux() + + mux.Handle("/assets/", middleware.CacheMiddleware(http.FileServer(http.FS(dist.AssetsDir)))) + mux.HandleFunc("/", h.Home) + + return middleware.NewLoggingMiddleware(logger, mux) +} diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..8593928 --- /dev/null +++ b/server/server.go @@ -0,0 +1,96 @@ +package server + +import ( + "context" + "log/slog" + "net/http" + "os" + "os/signal" + "time" +) + +// Server represents an HTTP server. +type Server struct { + srv *http.Server + logger *slog.Logger +} + +// New creates a new server with the given logger, address and options. +func New(logger *slog.Logger, addr string, opts ...Option) *Server { + srv := &http.Server{ + Addr: addr, + WriteTimeout: 15 * time.Second, + ReadTimeout: 15 * time.Second, + } + for _, opt := range opts { + opt(&Server{srv: srv}) + } + + return &Server{ + srv: srv, + logger: logger, + } +} + +// Option represents a server option. +type Option func(*Server) + +// WithWriteTimeout sets the write timeout. +func WithWriteTimeout(timeout time.Duration) Option { + return func(s *Server) { + s.srv.WriteTimeout = timeout + } +} + +// WithReadTimeout sets the read timeout. +func WithReadTimeout(timeout time.Duration) Option { + return func(s *Server) { + s.srv.ReadTimeout = timeout + } +} + +// WithRouter sets the handler. +func WithRouter(handler http.Handler) Option { + return func(s *Server) { + s.srv.Handler = handler + } +} + +// StartAndWait starts the server and waits for a signal to shut down. +func (s *Server) StartAndWait() { + s.Start() + s.GracefulShutdown() +} + +// Start starts the server. +func (s *Server) Start() { + go func() { + s.logger.Info("starting server", "port", s.srv.Addr) + if err := s.srv.ListenAndServe(); err != nil { + s.logger.Warn("failed to start server", "error", err) + } + }() +} + +// GracefulShutdown shuts down the server gracefully. +func (s *Server) GracefulShutdown() { + c := make(chan os.Signal, 1) + // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) + // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught. + signal.Notify(c, os.Interrupt) + + // Block until we receive our signal. + <-c + + // Create a deadline to wait for. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + // Doesn't block if no connections, but will otherwise wait + // until the timeout deadline. + _ = s.srv.Shutdown(ctx) + // Optionally, you could run srv.Shutdown in a goroutine and block on + // <-ctx.Done() if your application should wait for other services + // to finalize based on context cancellation. + s.logger.Info("shutting down") + os.Exit(0) +} diff --git a/sqlc.yml b/sqlc.yml new file mode 100644 index 0000000..8faabbc --- /dev/null +++ b/sqlc.yml @@ -0,0 +1,10 @@ +version: 2 +sql: + - engine: sqlite + queries: + - db/queries/query.sql + schema: db/migrations + gen: + go: + package: queries + out: db/queries diff --git a/styles/input.css b/styles/input.css new file mode 100644 index 0000000..b5c61c9 --- /dev/null +++ b/styles/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; diff --git a/tailwind.config.js b/tailwind.config.js new file mode 100644 index 0000000..b5a7a9a --- /dev/null +++ b/tailwind.config.js @@ -0,0 +1,14 @@ +/** @type {import('tailwindcss').Config} */ +module.exports = { + content: [ + "./components/**/*.templ", + ], + theme: { + extend: {}, + }, + plugins: [ + require('@tailwindcss/forms'), + require('@tailwindcss/typography'), + ], +} + diff --git a/update_module.sh b/update_module.sh new file mode 100755 index 0000000..97fa08a --- /dev/null +++ b/update_module.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +if [ "$#" -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +new_module=$1 + +find . -type d -name .git -prune -o -type f -exec sed -i '' -e "s/vctp/${new_module}/g" {} \; diff --git a/upgrade_htmx.sh b/upgrade_htmx.sh new file mode 100755 index 0000000..48b2747 --- /dev/null +++ b/upgrade_htmx.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +if [ "$#" -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +old_version="" +new_version=$1 + +for filename in "./dist/assets/js"/*; do + if [[ "$filename" == "./dist/assets/js/htmx"* ]]; then + old_version=$(echo "$filename" | awk -F'@' '{gsub(/\.min\.js/, "", $2); print $2}') + break + fi +done + +curl -sL -o "./dist/assets/js/htmx@${new_version}.min.js" "https://github.com/bigskysoftware/htmx/releases/download/${new_version}/htmx.min.js" + +sed -i '' -e "s/${old_version}/${new_version}/g" "./components/core/html.templ" + +rm "./dist/assets/js/htmx@${old_version}.min.js" diff --git a/upgrade_sqlc.sh b/upgrade_sqlc.sh new file mode 100755 index 0000000..2f23faa --- /dev/null +++ b/upgrade_sqlc.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +url=$(curl -s 'https://downloads.sqlc.dev/') + +new_version=$(echo "$url" | sed -e 's/
  • /
  • \n/g' | tr -d '\n' | sed -e 's/
  • /\n
  • /g' | sed -e 's/<\/li>/<\/li>\n/g' | grep -o '
  • [^<]*]*>[^<]*[^<]*
  • ' | sed -e 's/<[^>]*>//g' | tail -n 1 | awk '{$1=$1;print}') + +old_version=$(grep 'sqlc-version' .github/workflows/ci.yml | awk '{print $2}' | tr -d "'" | head -n 1) + +for file in ".github/workflows"/*; do + if [ -f "$file" ]; then + sed -i '' -e "s/${old_version}/${new_version}/g" "$file" + fi +done diff --git a/upgrade_templ.sh b/upgrade_templ.sh new file mode 100755 index 0000000..8d49602 --- /dev/null +++ b/upgrade_templ.sh @@ -0,0 +1,18 @@ +#!/bin/sh + +old_version=$(grep 'github.com/a-h/templ' go.mod | awk '{print $2}') + +go install github.com/a-h/templ/cmd/templ@latest + +go get -u github.com/a-h/templ +go mod tidy + +new_version=$(grep 'github.com/a-h/templ' go.mod | awk '{print $2}') + +sed -i '' -e "s/${old_version}/${new_version}/g" "Dockerfile" + +for file in ".github/workflows"/*; do + if [ -f "$file" ]; then + sed -i '' -e "s/${old_version}/${new_version}/g" "$file" + fi +done diff --git a/version/version.go b/version/version.go new file mode 100644 index 0000000..bd6880f --- /dev/null +++ b/version/version.go @@ -0,0 +1,4 @@ +package version + +// Value is the version. This is set at build time. +var Value = "dev"