10 Commits
Author SHA1 Message Date
aziis98 d5897ac50f fix: lieve modifica ad db ed un typo 2023-06-15 17:24:05 +02:00
aziis98 01982942a8 chore: refactored sl and added an hooks system
modified: cmd/dev-server/main.go, cmd/server/main.go

    Aggiornati per utilizzare il nuovo sistema degli hooks, ora nei "main" vanno
    solo chiamate "ProvideValue", "Provide" e "ProvideHook" ed una finale
    di "Invoke" o "Use". Mentre nei vari servizi vanno solo chiamate "Use"
    o "UseHook"

modified: libs/sl/sl.go

    Rinominati "InjectValue" e "InjectLazy" a "Provide" e "ProvideFunc", altro
    refactor di varie cose ed aggiunto il concetto degli hook per poter
    iniettare anche più di un servizio dentro un altro in un preciso ordine.

modified: server/config/config.go

    Lieve refactor ed aggiunta la variabile "NPM_COMMAND" configurabile per la
    fase di development.

modified: server/listautenti/listautenti.go

    Ora questo è un vero e proprio servizio "state-less", fornisce solo una
    funzione che monta tutte le route necessarie a questo servizio. Più avanti
    dipenderà da LDAP quindi forse sarà leggermente più complicato.

modified: server/listautenti/listautenti_test.go

    Aggiornato questo test, ora usa il nuovo sistema e funge di nuovo.

deleted: server/routes/routes.go

    Il sistema degli hook è stato introdotto anche per semplificare questa cosa
    che ora infatti non serve più.

modified: server/server.go

    Ora il server non chiama più "InjectValue" con i sotto-router ma espone solo
    un hook che passa i sotto router come parametri, in questo modo è più
    facile aggiungere e togliere servizi direttamente alla radice quando viene
    configurata tutta l'applicazione.
2023-06-14 12:41:34 +02:00
aziis98 be8c35229b chore: added serialization for db option type 2023-06-13 23:50:20 +02:00
BachoSeven e36fddb2b3 chore: refactor main 2023-06-13 23:35:49 +02:00
BachoSeven e34f91fce6 sl: add Invoke function 2023-06-13 23:34:15 +02:00
BachoSeven 064f42fb9f chore: fix typo; cleanup 2023-06-13 22:03:23 +02:00
aziis98 a541740a29 website style and circuits art 2023-05-26 18:20:47 +02:00
aziis98 d1fa37524d things 2023-05-17 00:13:25 +02:00
aziis98 762d350898 primo prototipo della homepage del sito 2023-05-16 11:40:58 +02:00
aziis98 15bc406494 Initial commit 2023-05-14 19:44:16 +02:00
68 changed files with 4912 additions and 2060 deletions
-2
View File
@@ -6,5 +6,3 @@ bin/
out/
dist/
node_modules/
.vscode/
-2
View File
@@ -1,2 +0,0 @@
# Needed by pnpm to work with "@preact/preset-vite"
shamefully-hoist=true
-31
View File
@@ -1,31 +0,0 @@
# Architettura
Questo è un progetto _fullstack_ con una backend scritta in [Go](https://go.dev/) ed una frontend in JS, più precisamente utilizziamo NodeJS con [Vite](https://vitejs.dev/) per build-are la frontend.
La cosa più interessante è l'integrazione tra **Vite** e la backend in **Go** per siti con più pagine (il nostro caso). Di base Vite supporta siti con più file html ma ha bisogno che gli venga detto quali sono tutti gli _entrypoint_ HTML. Vedremo che questo progetto usa una tecnica che ci permette di indicare una volta sola le cose nel codice in Go senza stare a tenere sincronizzato il codice in Go e la configurazione di Vite.
## Usage
Ci sono vari modi per lanciare la nostra applicazione in base all'_environment_, in particolare sono tutti isolati sotto forma di eseguibili in Go:
- Quando saremo in produzione l'unico server sarà quello di Go lanciato attraverso l'_entry-point_ [./cmd/server/main.go](./cmd/server/main.go)
In particolare prima di poter lanciare questo server bisogna aver eseguito [./cmd/build/main.go](./cmd/build/main.go) che esegue solo il codice relativo al router della nostra applicazione e genera un file `out/routes.json`. Poi bisogna eseguire `npm run build` che chiama Vite e genera il codice per tutte le route dentro la cartella `out/frontend/`.
- Quando siamo in development usiamo solo [./cmd/devserver/main.go](./cmd/devserver/main.go) che lancia in background il server di Vite (chiama `npm run dev` che a sua volta è un alias per `node server.js`) quindi possiamo vedere tutto in tempo reale da `localhost:3000`.
Più precisamente il server di Vite all'avvio richiede al server in Go tutte le route da montare utilizzando la route speciale `/api/development/routes` (in particolare Fiber ed ExpressJS hanno la stessa sintassi per definire le route quindi questa cosa è facile da fare).
Poi quando si prova ad andare su una pagina ci sono due casi
- Se la route era **statica** allora leggiamo il file html, lo facciamo processare a Vite e poi lo rimandiamo all'utente.
- Se invece la route era di tipo **dinamico** allora leggiamo sempre il file e lo processiamo con Vite però ora utilizziamo l'altra route speciale che esiste solo in fase di sviluppo `/api/development/render` che renderizza la pagina applicando il _templating del server_ e poi una volta finito inviamo la pagina al client.
Invece quando saremo in produzione tutte le pagina saranno già state renderizzate da Vite quindi saremo nel caso standard di _http server_ con views da renderizzare con il _template engine_ del caso prima di mandare la pagina al client.
- L'ultimo _entrypoint_ è [./cmd/build/main.go](./cmd/build/main.go) e lancia la nostra applicazione in una modalità "finta" senza server http ma vengono comunque registrate tutte le route utilizzando sempre il modulo `dev`. Questo ci permette di costruire l'albero delle route (statiche e dinamiche) che poi servirà a Vite quando faremo `npm run build`.
Ciò serve perché così ci basta definire tutte le route una volta sola nel Go e poi in automatico funzioneranno anche nel server di Vite senza dover ripetere due volte il codice. (questa è la parte più magica di _meta-programming_ di tutto il progetto)
![architecture-1](./docs/architecture-1.svg)
+9 -8
View File
@@ -1,10 +1,11 @@
.PHONY: test
test:
PROJECT_DIR="$(shell pwd)" go test -v ./...
.PHONY: all
all: frontend backend
.PHONY: build
build:
go run -v ./cmd/build
pnpm run build
go build -o ./out/bin/server ./cmd/server
.PHONY: frontend
frontend:
$(NPM) run build
.PHONY: backend
backend:
go build -v -o ./out/server ./cmd/server
+21 -16
View File
@@ -1,25 +1,30 @@
# Website 2
# PHC Website
Repo per il nuovo sito del PHC
## Docs
- [./ARCHITECTURE.md](./ARCHITECTURE.md)
Alcune note sull'architettura di questo progetto.
Sito web del PHC
## Usage
## Development
Come usare questo progetto
```bash shell
# Starts the backend on port :4000 and the frontend development server on port :3000
$ go run -v ./cmd/devserver
### Development
```sh
# Start the backend server and the frontend development server
$ go run -v ./cmd/dev-server
# Or using entr lo get live reload for go files
$ fd -e go | entr -r go run -v ./cmd/dev-server
```
## Production
### Production
```bash shell
# Generates "routes.json", builds all frontend artifacts and finally the main binary
$ make build
```sh
$ go run ./cmd/server
```
### Deploy
```sh
$ make all
```
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from 'astro/config'
// https://astro.build/config
export default defineConfig({
publicDir: './client/public',
srcDir: './client',
outDir: './out/client',
vite: {
server: {
proxy: {
'/api': 'http://127.0.0.1:4000',
},
},
},
})
+1
View File
@@ -0,0 +1 @@
/// <reference types="astro/client" />
+7
View File
@@ -0,0 +1,7 @@
---
import PageLayout from './PageLayout.astro'
const { frontmatter } = Astro.props
---
<PageLayout {...frontmatter} />
+28
View File
@@ -0,0 +1,28 @@
---
import '@fontsource/open-sans/latin.css'
import '@fontsource/source-sans-pro/latin.css'
import '@fontsource/source-code-pro/latin.css'
import '../styles/main.scss'
const { title, description, thumbnail, pageName } = Astro.props
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta property="og:title" content={title ?? 'PHC'} />
<meta property="og:description" content={description ?? 'Sito web del PHC'} />
{thumbnail && <meta property="og:image" content={thumbnail} />}
<link rel="icon" type="image/png" sizes="512x512" href="/assets/icon.png" />
<title>{title}</title>
</head>
<body class:list={['page-' + (pageName ?? 'unknown')]}>
<slot />
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
---
import BaseLayout from './BaseLayout.astro'
---
<BaseLayout {...Astro.props}>
<header>
<div class="logo">
<img src="/images/logo-circuit-board.svg" alt="phc logo" />
</div>
<div class="links">
<a role="button" href="#">Utenti</a>
<a role="button" href="#">Notizie</a>
<a role="button" href="#">Progetti</a>
<a role="button" href="#">About</a>
<a class="primary" role="button" href="#">Accedi</a>
</div>
</header>
<main>
<slot />
</main>
<footer>&copy; PHC 2023</footer>
</BaseLayout>
+199
View File
@@ -0,0 +1,199 @@
---
import PageLayout from '../layouts/PageLayout.astro'
---
<PageLayout pageName="homepage">
<section class="principal">
<div class="circuit-layer">
<canvas id="circuits-art"></canvas>
<script src="../scripts/circuits-art.ts"></script>
</div>
<div class="logo">
<img src="/images/logo-circuit-board.svg" alt="phc logo" />
</div>
<div class="whats-phc">
<div class="title">Cos'è il PHC?</div>
<div class="content">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Totam vero deserunt tempore reprehenderit atque, voluptate
dolorum excepturi libero pariatur sequi?
</p>
<p>
Laboriosam soluta ab a illum mollitia quaerat quia, veniam consequatur expedita dolore autem reiciendis quae rem
excepturi optio? Maiores, hic?
</p>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Exercitationem error atque amet. Tempora earum nemo eveniet
aspernatur quam quas, doloribus expedita quisquam dignissimos cupiditate inventore a modi optio harum veritatis,
adipisci ab ullam distinctio odio quod delectus ipsum, rerum animi.
</p>
</div>
</div>
</section>
<section class="news">
<div class="zig-zag">
<svg width="100%" height="2rem" viewBox="0 0 1 1" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMid meet">
<defs>
<pattern id="zig-zag-1" x="0" y="0" width="2" height="1" patternUnits="userSpaceOnUse">
<path fill="#C2A8EB" d="M 0,1 L 1,0 L 2,1 L 0,1"></path>
</pattern>
</defs>
<rect fill="url(#zig-zag-1)" x="0" y="0" width="1000" height="1"></rect>
</svg>
</div>
<div class="title">Ultime Notizie</div>
<div class="news-list">
<div class="news">
<div class="title">Lorem ipsum dolor sit.</div>
<div class="abstract">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis reprehenderit porro omnis enim deleniti esse quos,
architecto adipisci veritatis, iusto perferendis aperiam recusandae exercitationem doloribus, illum commodi
voluptatem pariatur eius!
</p>
<p>
Impedit ut quod aspernatur vitae vero incidunt cupiditate perferendis explicabo sunt possimus rerum expedita dicta
nesciunt enim mollitia iure ullam aut, pariatur, at cumque. Nemo obcaecati eaque recusandae fugit sed!
</p>
</div>
</div>
<div class="news">
<div class="title">Tempore provident impedit libero?</div>
<div class="abstract">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis reprehenderit porro omnis enim deleniti esse quos,
architecto adipisci veritatis, iusto perferendis aperiam recusandae exercitationem doloribus, illum commodi
voluptatem pariatur eius!
</p>
<p>
Impedit ut quod aspernatur vitae vero incidunt cupiditate perferendis explicabo sunt possimus rerum expedita dicta
nesciunt enim mollitia iure ullam aut, pariatur, at cumque. Nemo obcaecati eaque recusandae fugit sed!
</p>
<p>
Impedit ut quod aspernatur vitae vero incidunt cupiditate perferendis explicabo sunt possimus rerum expedita dicta
nesciunt enim mollitia iure ullam aut, pariatur, at cumque. Nemo obcaecati eaque recusandae fugit sed!
</p>
<p>
Impedit ut quod aspernatur vitae vero incidunt cupiditate perferendis explicabo sunt possimus rerum expedita dicta
nesciunt enim mollitia iure ullam aut, pariatur, at cumque. Nemo obcaecati eaque recusandae fugit sed!
</p>
</div>
</div>
<div class="news">
<div class="title">Alias molestias consectetur quam</div>
<div class="abstract">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis reprehenderit porro omnis enim deleniti esse quos,
architecto adipisci veritatis, iusto perferendis aperiam recusandae exercitationem doloribus, illum commodi
voluptatem pariatur eius!
</p>
</div>
</div>
<div class="news">
<div class="title">Inventore dignissimos sapiente nulla</div>
<div class="abstract">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis reprehenderit porro omnis enim deleniti esse quos,
architecto adipisci veritatis, iusto perferendis aperiam recusandae exercitationem doloribus, illum commodi
voluptatem pariatur eius!
</p>
<p>
Impedit ut quod aspernatur vitae vero incidunt cupiditate perferendis explicabo sunt possimus rerum expedita dicta
nesciunt enim mollitia iure ullam aut, pariatur, at cumque. Nemo obcaecati eaque recusandae fugit sed!
</p>
</div>
</div>
</div>
<a class="primary" href="#" role="button">Vai all'Archivio</a>
</section>
<section class="projects">
<div class="zig-zag">
<svg width="100%" height="2rem" viewBox="0 0 1 1" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMid meet">
<defs>
<pattern id="zig-zag-2" x="0" y="0" width="2" height="1" patternUnits="userSpaceOnUse">
<path fill="#f5f2cc" d="M 0,1 L 1,0 L 2,1 L 0,1"></path>
</pattern>
</defs>
<rect fill="url(#zig-zag-2)" x="0" y="0" width="1000" height="1"></rect>
</svg>
</div>
<div class="title">Progetti</div>
<div class="project-list">
<a href="#">
<div class="project">
<div class="image">
<div class="box"></div>
</div>
<div class="title">Gitea</div>
<div class="description">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptatibus quam iure dolor. Excepturi facere, ipsa
accusantium labore explicabo quaerat incidunt.
</div>
</div>
</a>
<a href="#">
<div class="project">
<div class="image">
<div class="box"></div>
</div>
<div class="title">Zulip</div>
<div class="description">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Repellendus, veritatis.</div>
</div>
</a>
<a href="#">
<div class="project">
<div class="image">
<div class="box"></div>
</div>
<div class="title">Orario</div>
<div class="description">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptatibus quam iure dolor. Excepturi facere, ipsa
accusantium labore explicabo quaerat incidunt.
</div>
</div>
</a>
<a href="#">
<div class="project">
<div class="image">
<div class="box"></div>
</div>
<div class="title">Problemi</div>
<div class="description">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Non, hic libero beatae voluptatem incidunt.
</div>
</div>
</a>
<a href="#">
<div class="project">
<div class="image">
<div class="box"></div>
</div>
<div class="title">Cluster "Steffè"</div>
<div class="description">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptatibus quam iure dolor. Excepturi facere, ipsa
accusantium labore explicabo quaerat incidunt.
</div>
</div>
</a>
</div>
</section>
<section class="wanna-be-macchinista">
<div class="zig-zag">
<svg width="100%" height="2rem" viewBox="0 0 1 1" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMid meet">
<defs>
<pattern id="zig-zag-3" x="0" y="0" width="2" height="1" patternUnits="userSpaceOnUse">
<path fill="#888" d="M 0,1 L 1,0 L 2,1 L 0,1"></path>
</pattern>
</defs>
<rect fill="url(#zig-zag-3)" x="0" y="0" width="1000" height="1"></rect>
</svg>
</div>
<div class="title">Vuoi diventare macchinista?</div>
</section>
</PageLayout>
View File
@@ -0,0 +1,87 @@
<svg width="1000" height="500" viewBox="0 0 1000 500" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="80" y="190" width="60" height="120" fill="#1E6733"/>
<rect x="160" y="50" width="150" height="60" fill="#1E6733"/>
<rect x="140" y="90" width="10" height="50" fill="#ECC333"/>
<rect x="140" y="200" width="10" height="50" fill="#ECC333"/>
<rect x="140" y="410" width="10" height="20" fill="#ECC333"/>
<rect x="140" y="350" width="10" height="50" fill="#ECC333"/>
<rect x="240" y="110" width="70" height="10" fill="#ECC333"/>
<rect x="250" y="130" width="60" height="130" fill="#1E6733"/>
<rect x="340" y="50" width="60" height="120" fill="#1E6733"/>
<rect x="340" y="190" width="60" height="120" fill="#1E6733"/>
<rect x="590" y="190" width="60" height="120" fill="#1E6733"/>
<rect x="690" y="180" width="60" height="120" fill="#1E6733"/>
<rect x="690" y="310" width="60" height="140" fill="#1E6733"/>
<rect x="690" y="50" width="60" height="120" fill="#1E6733"/>
<rect x="590" y="320" width="60" height="130" fill="#1E6733"/>
<rect x="590" y="50" width="60" height="130" fill="#1E6733"/>
<rect x="420" y="240" width="150" height="60" fill="#1E6733"/>
<rect x="340" y="320" width="60" height="130" fill="#1E6733"/>
<rect x="240" y="140" width="10" height="50" fill="#ECC333"/>
<rect x="350" y="170" width="40" height="10" fill="#ECC333"/>
<rect x="330" y="330" width="10" height="50" fill="#ECC333"/>
<rect x="160" y="200" width="80" height="60" fill="#1E6733"/>
<rect x="650" y="200" width="10" height="50" fill="#ECC333"/>
<rect x="750" y="330" width="10" height="60" fill="#ECC333"/>
<rect x="800" y="450" width="40" height="10" fill="#ECC333"/>
<rect x="850" y="450" width="30" height="10" fill="#ECC333"/>
<rect x="750" y="90" width="10" height="50" fill="#ECC333"/>
<rect x="810" y="110" width="60" height="10" fill="#ECC333"/>
<rect x="580" y="330" width="10" height="50" fill="#ECC333"/>
<rect x="580" y="60" width="10" height="50" fill="#ECC333"/>
<rect x="710" y="420" width="20" height="20" fill="#C4C4C4"/>
<rect x="710" y="390" width="20" height="20" fill="#C4C4C4"/>
<rect x="100" y="280" width="20" height="10" fill="#C4C4C4"/>
<rect x="100" y="260" width="20" height="10" fill="#C4C4C4"/>
<rect x="110" y="210" width="20" height="20" fill="#C4C4C4"/>
<rect x="350" y="430" width="40" height="10" fill="#303030"/>
<rect x="350" y="410" width="40" height="10" fill="#303030"/>
<rect x="350" y="390" width="40" height="10" fill="#303030"/>
<rect x="700" y="70" width="20" height="40" fill="#303030"/>
<rect x="700" y="120" width="20" height="40" fill="#303030"/>
<rect x="610" y="280" width="20" height="20" fill="#C4C4C4"/>
<rect x="600" y="240" width="20" height="20" fill="#C4C4C4"/>
<rect x="430" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="430" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="430" y="280" width="10" height="10" fill="#C4C4C4"/>
<rect x="445" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="445" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="460" y="280" width="40" height="10" fill="#C4C4C4"/>
<rect x="475" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="475" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="505" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="505" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="520" y="265" width="10" height="15" fill="#C4C4C4"/>
<rect x="505" y="280" width="25" height="10" fill="#C4C4C4"/>
<rect x="535" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="535" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="535" y="280" width="10" height="10" fill="#C4C4C4"/>
<rect x="445" y="280" width="10" height="10" fill="#C4C4C4"/>
<rect x="460" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="460" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="490" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="490" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="520" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="550" y="250" width="10" height="10" fill="#C4C4C4"/>
<rect x="550" y="265" width="10" height="10" fill="#C4C4C4"/>
<rect x="550" y="280" width="10" height="10" fill="#C4C4C4"/>
<rect x="620" y="210" width="20" height="20" fill="#C4C4C4"/>
<rect x="370" y="70" width="20" height="30" fill="#303030"/>
<rect x="370" y="110" width="20" height="30" fill="#303030"/>
<rect x="870" y="440" width="40" height="10" transform="rotate(-90 870 440)" fill="#303030"/>
<rect x="890" y="440" width="40" height="10" transform="rotate(-90 890 440)" fill="#303030"/>
<rect x="810" y="440" width="40" height="10" transform="rotate(-90 810 440)" fill="#303030"/>
<rect x="790" y="440" width="40" height="10" transform="rotate(-90 790 440)" fill="#303030"/>
<rect x="270" y="100" width="40" height="10" transform="rotate(-90 270 100)" fill="#303030"/>
<rect x="290" y="100" width="40" height="10" transform="rotate(-90 290 100)" fill="#303030"/>
<rect x="190" y="100" width="40" height="10" transform="rotate(-90 190 100)" fill="#303030"/>
<rect x="170" y="100" width="40" height="10" transform="rotate(-90 170 100)" fill="#303030"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M140 60V170C134.477 170 130 174.477 130 180H90C90 174.477 85.5228 170 80 170V60C85.5228 60 90 55.5228 90 50H130C130 55.5228 134.477 60 140 60Z" fill="#1E6733"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M130 320H90C90 325.523 85.5229 330 80 330V440C85.5229 440 90 444.477 90 450H130C130 444.477 134.477 440 140 440V330C134.477 330 130 325.523 130 320Z" fill="#1E6733"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M770 60C775.523 60 780 55.5228 780 50H910C910 55.5228 914.477 60 920 60V100C914.477 100 910 104.477 910 110H780C780 104.477 775.523 100 770 100V60Z" fill="#1E6733"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M770 400C775.523 400 780 395.523 780 390H910C910 395.523 914.477 400 920 400V440C914.477 440 910 444.477 910 450H780C780 444.477 775.523 440 770 440V400Z" fill="#1E6733"/>
<rect x="750" y="190" width="10" height="40" fill="#ECC333"/>
<rect x="750" y="240" width="10" height="20" fill="#ECC333"/>
<rect x="400" y="200" width="10" height="40" fill="#ECC333"/>
<rect x="400" y="250" width="10" height="20" fill="#ECC333"/>
</svg>

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 765 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

+8
View File
@@ -0,0 +1,8 @@
<svg width="100%" height="2rem" viewBox="0 0 1 1" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="zig-zag" x="0" y="0" width="2" height="1">
<path fill="#C2A8EB" d="M 0,0 L 1,1 L 2,0 L 0,0"/>
</pattern>
</defs>
<rect fill="url(#zig-zag)" x="0" y="0" width="100%" height="1" />
</svg>

After

Width:  |  Height:  |  Size: 344 B

+316
View File
@@ -0,0 +1,316 @@
const $canvas: HTMLCanvasElement = document.querySelector('#circuits-art')!
interface Grid<T> extends Iterable<[number, number, T]> {
has(point: [number, number]): boolean
get(point: [number, number]): T
set(point: [number, number], value: T): void
}
function createGrid<T>(): Grid<T> {
const cells: Record<string, T> = {}
return {
has([x, y]) {
return cells[`${x},${y}`] !== undefined
},
get([x, y]) {
return cells[`${x},${y}`]
},
set([x, y], value) {
cells[`${x},${y}`] = value
},
*[Symbol.iterator]() {
for (const [coord, value] of Object.entries(cells)) {
const [x, y] = coord.split(',').map(s => parseInt(s))
yield [x, y, value]
}
},
}
}
type WireCell = 'down' | 'down-left' | 'down-right' | 'dot'
type WireDirection = 'down' | 'down-left' | 'down-right'
type WireSteps = { position: Point2; direction: WireCell }[]
type Point2 = [number, number]
type State = {
grid: Grid<WireCell>
queuedWire: {
index: number
steps: WireSteps
} | null
badTries: 0
}
type Renderer = {
timer: number
}
let renderer: Renderer | null = null
const RENDERER_FPS = 30
function setup() {
console.log('Setting up circuits art...')
$canvas.width = $canvas.clientWidth
$canvas.height = $canvas.clientHeight
const g = $canvas.getContext('2d')!
const state: State = {
grid: createGrid(),
queuedWire: null,
badTries: 0,
}
const startTime = new Date()
const handle = setInterval(() => {
const time = new Date().getTime() - startTime.getTime()
update(state, g.canvas.width, g.canvas.height, time)
render(g, state, time)
}, 1000 / RENDERER_FPS)
renderer = { timer: handle }
}
function update(state: State, width: number, height: number, time: number) {
const w = (width / CELL_SIZE) | 0
// const h = (height / CELL_SIZE) | 0
if (state.badTries > 1000) {
console.log('finished')
clearInterval(renderer!.timer)
}
if (!state.queuedWire) {
const sx = randomInt(0, w)
if (!state.grid.has([sx, 0])) {
const steps = generateWire(state.grid, [sx, 0])
if (steps.length < 7) {
state.badTries++
return
}
state.queuedWire = {
index: 0,
steps,
}
state.grid.set(state.queuedWire.steps[0].position, 'dot')
return
}
state.badTries++
} else {
const wire = state.queuedWire
const step = wire.steps[wire.index]
state.grid.set(step.position, step.direction)
if (wire.index + 1 < wire.steps.length) {
state.grid.set(wire.steps[wire.index + 1].position, 'dot')
}
wire.index++
if (wire.index >= wire.steps.length) {
state.queuedWire = null
}
}
}
const CELL_SIZE = 27
const BACKGROUND_COLOR = '#ecffe3'
const WIRE_COLOR = '#a6ce94'
const RENDER_CELL: Record<WireCell, (g: CanvasRenderingContext2D) => void> = {
'down': g => {
g.strokeStyle = WIRE_COLOR
g.beginPath()
g.moveTo(0, 0)
g.lineTo(0, 1)
g.stroke()
},
'down-left': g => {
g.strokeStyle = WIRE_COLOR
g.beginPath()
g.moveTo(0, 0)
g.lineTo(-1, 1)
g.stroke()
},
'down-right': g => {
g.strokeStyle = WIRE_COLOR
g.beginPath()
g.moveTo(0, 0)
g.lineTo(+1, 1)
g.stroke()
},
'dot': g => {
g.fillStyle = BACKGROUND_COLOR
g.beginPath()
g.ellipse(0, 0, 0.15, 0.15, 0, 0, 2 * Math.PI)
g.fill()
g.strokeStyle = WIRE_COLOR
g.beginPath()
g.ellipse(0, 0, 0.15, 0.15, 0, 0, 2 * Math.PI)
g.stroke()
},
}
function render(g: CanvasRenderingContext2D, state: State, time: number) {
g.clearRect(0, 0, g.canvas.width, g.canvas.height)
g.resetTransform()
g.scale(CELL_SIZE, CELL_SIZE)
g.lineWidth = 3 / CELL_SIZE
const w = (g.canvas.width / CELL_SIZE) | 0
const h = (g.canvas.height / CELL_SIZE) | 0
for (let y = 0; y <= h + 1; y++) {
for (let x = 0; x <= w + 1; x++) {
if (!state.grid.has([x, y])) continue
const cell = state.grid.get([x, y])
g.save()
g.translate(x, y)
// g.fillStyle = '#f008'
// g.beginPath()
// g.rect(-0.25, -0.25, 0.5, 0.5)
// g.fill()
RENDER_CELL[cell](g)
g.restore()
}
}
// if (state.queuedWire) {
// for (const step of state.queuedWire.steps) {
// const [x, y] = step.position
// g.fillStyle = '#00f8'
// g.save()
// g.translate(x, y)
// g.beginPath()
// g.rect(-0.25, -0.25, 0.5, 0.5)
// g.fill()
// g.restore()
// }
// }
// const [mx, my] = state.mouse
// g.save()
// g.fillStyle = '#0008'
// g.translate(Math.floor(mx / CELL_SIZE), Math.floor(my / CELL_SIZE))
// g.beginPath()
// g.rect(0, 0, 1, 1)
// g.fill()
// g.restore()
}
setup()
window.addEventListener('resize', () => {
if (renderer) {
clearInterval(renderer.timer)
}
setup()
})
function randomInt(from: number, to: number) {
return Math.floor(Math.random() * (to - from + 1))
}
function randomChoice<T>(choices: T[]): T {
return choices[randomInt(0, choices.length - 1)]
}
function randomWeightedChoice<T>(choices: [T, number][]) {
return
}
// 3 + 4 + 5 + 6
randomWeightedChoice([
['a', 3],
['b', 4],
['c', 5],
['d', 6],
])
const DIR_TO_VEC: Record<WireDirection, Point2> = {
['down']: [0, 1],
['down-left']: [-1, 1],
['down-right']: [+1, 1],
}
type ShortCircuitBoolean = boolean | (() => boolean)
const callOrBoolean = (v: ShortCircuitBoolean): boolean => (typeof v === 'boolean' ? v : v())
const implies = (a: ShortCircuitBoolean, b: ShortCircuitBoolean) => !callOrBoolean(a) || callOrBoolean(b)
/**
* Tells whether a given direction is not blocked by some other cell in a given grid and starting position
*/
const DIR_AVAILABLE_PREDICATE: Record<WireDirection, (pos: Point2, grid: Grid<WireCell>) => boolean> = {
['down']: ([x, y], grid) =>
!grid.has([x, y + 1]) &&
implies(grid.has([x - 1, y]), () => grid.get([x - 1, y]) !== 'down-right') &&
implies(grid.has([x + 1, y]), () => grid.get([x + 1, y]) !== 'down-left'),
['down-left']: ([x, y], grid) => !grid.has([x - 1, y + 1]) && implies(grid.has([x - 1, y]), () => grid.get([x - 1, y]) === 'down-left'),
['down-right']: ([x, y], grid) =>
!grid.has([x + 1, y + 1]) && implies(grid.has([x + 1, y]), () => grid.get([x + 1, y]) === 'down-right'),
}
function pruneDirections(grid: Grid<WireCell>, position: Point2, directions: WireDirection[]): WireDirection[] {
return directions.filter(dir => DIR_AVAILABLE_PREDICATE[dir](position, grid))
}
function generateWire(grid: Grid<WireCell>, startingPoint: Point2): { position: Point2; direction: WireCell }[] {
const segmentLength = Math.floor(1 - Math.random() ** 2) * 10 + 30
let currentPosition = startingPoint
let currentDirection: WireDirection = randomChoice(['down', 'down', 'down', 'down-left', 'down-right'])
const steps: { position: Point2; direction: WireCell }[] = []
for (let i = 0; i < segmentLength; i++) {
const availableDirections = pruneDirections(grid, currentPosition, ['down', 'down-left', 'down-right'])
if (availableDirections.length === 0) {
break
} else {
const dir =
availableDirections.includes(currentDirection) && Math.random() < 0.25
? currentDirection
: randomChoice(availableDirections)
if ((currentDirection === 'down-left' && dir === 'down-right') || (currentDirection === 'down-right' && dir === 'down-left')) {
break
}
const [x, y] = currentPosition
const [dx, dy] = DIR_TO_VEC[dir]
steps.push({
position: [x, y],
direction: dir,
})
currentPosition = [x + dx, y + dy]
currentDirection = dir
}
}
const last = steps.at(-1)
if (last) {
last.direction = 'dot'
}
return steps
}
+474
View File
@@ -0,0 +1,474 @@
*,
*::before,
*::after {
box-sizing: border-box;
font: inherit;
margin: 0;
}
html,
body {
min-height: 100%;
height: 100%;
margin: 0;
font-family: 'Open Sans', sans-serif;
font-size: 18px;
color: #222;
}
html {
scroll-snap-type: y proximity;
scroll-padding-top: 4rem;
}
img {
display: block;
}
a {
color: inherit;
text-decoration: none;
}
//
// Typography
//
.text {
display: block;
line-height: 1.5;
p + p {
margin-top: 0.5rem;
}
}
//
// Controls
//
button,
.button,
[role='button'] {
appearance: none;
background: #fff;
border: 3px solid #222;
border-radius: 6px;
box-shadow: 4px 4px 0 0 #222;
transition: all 64ms linear;
&:hover {
background: #f0f0f0;
}
&:active {
transform: translate(2px, 2px);
box-shadow: 2px 2px 0 0 #222;
}
padding: 0.25rem 1.5rem;
text-decoration: none;
color: #222;
font-family: 'Source Sans Pro', sans-serif;
font-weight: 600;
&.primary {
background: #1e6733;
color: #f4fef7;
&:hover {
background: #2b8b47;
}
}
}
//
// Pages
//
header {
z-index: 10;
height: 6rem;
border-bottom: 4px solid #222;
background: #fff;
position: fixed;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
.logo {
padding-left: 0.5rem;
img {
height: 4rem;
}
}
.links {
display: flex;
align-items: center;
gap: 1.5rem;
padding: 0 1.5rem;
a {
font-size: 22px;
font-weight: 600;
}
}
}
footer {
min-height: 6rem;
border-top: 4px solid #222;
background: #444;
color: #fdfdfd;
display: grid;
place-content: center;
font-family: 'Source Sans Pro', sans-serif;
font-size: 20px;
}
.page-homepage {
header .logo {
visibility: hidden;
}
section {
position: relative;
min-height: calc(100vh - 6rem);
&:last-of-type {
min-height: calc(100vh - 10rem);
}
display: flex;
flex-direction: column;
align-items: center;
gap: 2rem;
scroll-snap-align: start;
& > .title {
font-weight: 700;
font-size: 60px;
font-family: 'Source Sans Pro', sans-serif;
padding-top: 4rem;
}
}
.zig-zag {
z-index: 5;
position: absolute;
width: 100%;
display: flex;
&:first-child {
bottom: 100%;
}
}
section.principal {
z-index: -2;
min-height: calc(100vh - 2rem);
flex-direction: row;
align-items: center;
justify-content: center;
gap: 6rem;
padding: 6rem 0;
background: #ecffe3;
// circuit color
// background: #a6ce94;
flex-wrap: wrap;
position: relative;
.circuit-layer {
z-index: -1;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
padding-top: 6rem;
canvas {
width: 100%;
height: 100%;
}
}
.logo {
max-width: 640px;
position: relative;
user-select: none;
img {
width: 100%;
filter: drop-shadow(6px 6px 0 #222) drop-shadow(4px 0 0 #222) drop-shadow(0 4px 0 #222) drop-shadow(-4px 0 0 #222)
drop-shadow(0 -4px 0 #222);
}
}
.whats-phc {
background: #e4c5ff;
border: 4px solid #222;
border-radius: 8px;
box-shadow: 6px 6px 0 0 #222;
padding: 2rem;
max-width: 37rem;
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
.title {
font-family: 'Source Sans Pro', sans-serif;
font-weight: 700;
font-size: 40px;
}
.content {
@extend .text;
}
}
}
section.news {
background: #c2a8eb;
gap: 3rem;
padding-bottom: 6rem;
.news-list {
display: flex;
flex-direction: row;
gap: 3rem;
padding: 0 3rem;
justify-content: center;
flex-wrap: wrap;
.news {
background: #fffbeb;
border: 3px solid #222;
border-radius: 9px;
box-shadow: 9px 9px 0 0 #222;
display: flex;
flex-direction: column;
width: 22rem;
max-height: 27rem;
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
background-color: #c67e14;
border: 2px solid #222;
&:hover {
background-color: #e69419;
}
}
a {
font-weight: 600;
text-decoration: none;
color: #c67e14;
&:hover {
text-decoration: underline solid 2px;
}
}
& > .title {
// border-bottom: 2px solid #222;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
padding: 1rem;
background: #f8e8b1;
font-family: 'Source Sans Pro', sans-serif;
font-weight: 700;
font-size: 32px;
}
& > .abstract {
flex-grow: 1;
padding: 1rem;
overflow-y: auto;
@extend .text;
}
& > .continue {
padding: 1rem;
display: grid;
align-items: end;
justify-content: end;
}
}
}
[role='button'] {
padding: 0.5rem 2rem;
&.primary {
// background: #824ed4;
// color: #f0e6ff;
background: #f8e8b1;
color: #000d;
&:hover {
// background: #8e5ddd;
}
}
}
}
section.projects {
background: #f5f2cc;
padding-bottom: 6rem;
.project-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr));
gap: 3rem;
padding: 0 6rem;
align-items: start;
.project {
// background: #fcddff;
// background: #ffa89c;
background: #a2d4f3;
color: #000e;
border: 3px solid #222;
border-radius: 9px;
box-shadow: 9px 9px 0 0 #222;
padding: 1rem;
display: grid;
grid-template-columns: auto 1fr;
grid-template-rows: auto 1fr;
gap: 0.25rem 1rem;
.title {
font-family: 'Source Sans Pro', sans-serif;
font-weight: 700;
font-size: 32px;
}
.image {
grid-row: span 2;
// place-self: center;
.box {
background: #0003;
border: 3px solid #0006;
border-radius: 6px;
width: 5rem;
height: 5rem;
}
}
.description {
font-size: 16px;
}
transition: all 128ms ease-out;
&:hover {
transform: translate(0, -8px);
}
}
}
}
section.wanna-be-macchinista {
background: #888;
color: #fdfdfd;
}
}
//
// Misc
//
::-webkit-scrollbar-track:vertical {
background-color: #f0f0f0;
border-left: 2px solid #222;
border-top: 2px solid #222;
border-bottom: 2px solid #222;
}
::-webkit-scrollbar-track:horizontal {
background-color: #f0f0f0;
border-top: 2px solid #222;
border-left: 2px solid #222;
border-right: 2px solid #222;
}
::-webkit-scrollbar-thumb {
background-color: #1e6733;
border: 2px solid #222;
}
::-webkit-scrollbar-thumb:hover {
background-color: #2b8b47;
}
::-webkit-scrollbar-corner {
background-color: #f0f0f0;
// border-left: 2px solid #222;
// border-top: 2px solid #222;
}
::-webkit-scrollbar {
width: 15px;
}
-44
View File
@@ -1,44 +0,0 @@
package main
import (
"encoding/json"
"log"
"os"
"git.phc.dm.unipi.it/phc/website/services/config"
"git.phc.dm.unipi.it/phc/website/services/database"
"git.phc.dm.unipi.it/phc/website/services/server"
"git.phc.dm.unipi.it/phc/website/services/server/dev"
"git.phc.dm.unipi.it/phc/website/sl"
)
func main() {
l := sl.New()
// sl.Inject[config.Interface](l, &config.EnvConfig{})
sl.InjectValue(l, config.Slot, &config.Config{
Mode: "production",
})
sl.InjectValue(l, database.Slot, database.Database(
&database.Memory{}),
)
if _, err := server.Configure(l); err != nil {
log.Fatal(err)
}
f, err := os.Create("out/routes.json")
if err != nil {
log.Fatal(err)
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err := enc.Encode(dev.UseRoutesMetadata(l)); err != nil {
log.Fatal(err)
}
log.Printf(`generated "out/routes.json"`)
}
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"bufio"
"io"
"log"
"os/exec"
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server"
"git.phc.dm.unipi.it/phc/website/server/config"
"git.phc.dm.unipi.it/phc/website/server/database"
"git.phc.dm.unipi.it/phc/website/server/listautenti"
"git.phc.dm.unipi.it/phc/website/server/model"
)
func init() {
log.SetFlags(0)
}
func main() {
l := sl.New()
//
// Setup the application
//
// Config
sl.ProvideFunc(l, config.Slot, config.Configure)
// Database
sl.Provide[database.Database](l, database.Slot, &database.Memory{
Users: []model.User{
{
Id: "e39ad8d5-a087-4cb2-8fd7-5a6ca3f6a534",
Username: "claire-doe",
FullName: db.NewOption("Claire Doe"),
Email: db.NewOption("claire.doe@example.org"),
},
{
Id: "9b7109cd-95a1-41e9-a9f6-001a32c20ca1",
Username: "john-smith",
FullName: db.NewOption("John Smith"),
Email: db.NewOption("john.smith@example.org"),
},
},
})
// Server
sl.ProvideFunc(l, server.Slot, server.Configure)
sl.ProvideHook(l, server.ApiRoutesHook,
listautenti.MountApiRoutesHook,
)
//
// Start the application
//
sl.MustInvoke(l, server.Slot)
r, w := io.Pipe()
cfg := sl.MustUse(l, config.Slot)
cmd := exec.Command(cfg.NpmCommand, "run", "dev")
cmd.Stdout = w
go func() {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
log.Printf(`[cmd/devserver] [vitejs] %s`, scanner.Text())
}
}()
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
-69
View File
@@ -1,69 +0,0 @@
package main
import (
"bufio"
"io"
"log"
"os/exec"
"git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/services/config"
"git.phc.dm.unipi.it/phc/website/services/database"
"git.phc.dm.unipi.it/phc/website/services/server"
"git.phc.dm.unipi.it/phc/website/sl"
)
func init() {
log.SetFlags(0)
}
func main() {
l := sl.New()
cfg := sl.InjectValue(l, config.Slot, &config.Config{
Mode: "development",
Host: ":4000",
})
sl.InjectValue[database.Database](l, database.Slot, &database.Memory{
Users: []model.User{
{
Id: "claire",
FullName: "Claire Doe",
Nickname: "claire-doe",
AuthSources: map[string]model.AuthSource{},
},
{
Id: "john",
FullName: "John Smith",
Nickname: "john-smith",
AuthSources: map[string]model.AuthSource{},
},
},
})
srv, err := server.Configure(l)
if err != nil {
log.Fatal(err)
}
go func() {
log.Fatal(srv.Router.Listen(cfg.Host))
}()
r, w := io.Pipe()
cmd := exec.Command("npm", "run", "dev")
cmd.Stdout = w
go func() {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
log.Printf(`[cmd/devserver] [vitejs] %s`, scanner.Text())
}
}()
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
+36 -21
View File
@@ -3,42 +3,57 @@ package main
import (
"log"
"git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/services/config"
"git.phc.dm.unipi.it/phc/website/services/database"
"git.phc.dm.unipi.it/phc/website/services/server"
"git.phc.dm.unipi.it/phc/website/sl"
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server"
"git.phc.dm.unipi.it/phc/website/server/config"
"git.phc.dm.unipi.it/phc/website/server/database"
"git.phc.dm.unipi.it/phc/website/server/listautenti"
"git.phc.dm.unipi.it/phc/website/server/model"
)
func main() {
l := sl.New()
cfg := sl.InjectValue(l, config.Slot, &config.Config{
Mode: "production",
Host: ":4000",
})
//
// Setup the application
//
sl.InjectValue[database.Database](l, database.Slot, &database.Memory{
// Config
sl.Provide(l, config.Slot, config.ExampleProductionConfig)
// Database
sl.Provide[database.Database](l, database.Slot, &database.Memory{
Users: []model.User{
{
Id: "claire",
FullName: "Claire Doe",
Nickname: "claire-doe",
AuthSources: map[string]model.AuthSource{},
Id: "e39ad8d5-a087-4cb2-8fd7-5a6ca3f6a534",
Username: "claire-doe",
FullName: db.NewOption("Claire Doe"),
Email: db.NewOption("claire.doe@example.org"),
},
{
Id: "john",
FullName: "John Smith",
Nickname: "john-smith",
AuthSources: map[string]model.AuthSource{},
Id: "9b7109cd-95a1-41e9-a9f6-001a32c20ca1",
Username: "john-smith",
FullName: db.NewOption("John Smith"),
Email: db.NewOption("john.smith@example.org"),
},
},
})
srv, err := server.Configure(l)
// Server
sl.ProvideFunc(l, server.Slot, server.Configure)
sl.ProvideHook(l, server.ApiRoutesHook,
listautenti.MountApiRoutesHook,
)
//
// Start the application
//
err := sl.Invoke(l, server.Slot)
if err != nil {
log.Fatal(err)
}
log.Fatal(srv.Router.Listen(cfg.Host))
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 220 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 251 KiB

-12
View File
@@ -1,12 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Homepage</title>
</head>
<body>
Homepage
</body>
</html>
-17
View File
@@ -1,17 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ .Title }} &bull; Articoli &bull; PHC</title>
<link rel="stylesheet" href="/styles/main.scss" />
<link rel="stylesheet" href="./typography.scss" />
</head>
<body>
<h1>Articolo "{{ .Example }}"</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque, quasi...</p>
</body>
</html>
-16
View File
@@ -1,16 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Articoli &bull; PHC</title>
<link rel="stylesheet" href="/styles/main.scss" />
</head>
<body>
<h1>Articoli</h1>
{{ .Example }}
</body>
</html>
-3
View File
@@ -1,3 +0,0 @@
h1 {
color: red;
}
-13
View File
@@ -1,13 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ListaUtenti</title>
</head>
<body>
<main class="page-lista-utenti"></main>
<script type="module" src="./src/main.jsx"></script>
</body>
</html>
@@ -1,3 +0,0 @@
.list {
background: red;
}
-13
View File
@@ -1,13 +0,0 @@
import { render } from 'preact'
import './lista-utenti.scss'
render(
<>
<h1>Lista Utenti</h1>
<div class="list">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Odit, illo molestiae. Sapiente cumque saepe maxime, temporibus ad
nulla id officiis impedit ut dolorem asperiores voluptate illo, molestiae facilis inventore. Ea.
</div>
</>,
document.querySelector('main')
)
-5
View File
@@ -1,5 +0,0 @@
*,
*::before,
*::after {
box-sizing: border-box;
}
+19 -13
View File
@@ -1,22 +1,28 @@
module git.phc.dm.unipi.it/phc/website
go 1.19
go 1.20
require (
github.com/alecthomas/repr v0.2.0
github.com/gofiber/fiber/v2 v2.41.0
github.com/joho/godotenv v1.4.0
github.com/valyala/fasthttp v1.43.0
)
require (
github.com/andybalholm/brotli v1.0.4 // indirect
github.com/klauspost/compress v1.15.9 // indirect
github.com/alecthomas/repr v0.2.0 // indirect
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/gofiber/fiber/v2 v2.44.0 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/klauspost/compress v1.16.5 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-isatty v0.0.18 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/philhofer/fwd v1.1.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94 // indirect
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee // indirect
github.com/tinylib/msgp v1.1.8 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.46.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.1.0 // indirect
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect
golang.org/x/sys v0.7.0 // indirect
gotest.tools v2.2.0+incompatible // indirect
)
+74 -21
View File
@@ -1,40 +1,93 @@
github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk=
github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/gofiber/fiber/v2 v2.41.0 h1:YhNoUS/OTjEz+/WLYuQ01xI7RXgKEFnGBKMagAu5f0M=
github.com/gofiber/fiber/v2 v2.41.0/go.mod h1:RdebcCuCRFp4W6hr3968/XxwJVg0K+jr9/Ae0PFzZ0Q=
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/gofiber/fiber/v2 v2.44.0 h1:Z90bEvPcJM5GFJnu1py0E1ojoerkyew3iiNJ78MQCM8=
github.com/gofiber/fiber/v2 v2.44.0/go.mod h1:VTMtb/au8g01iqvHyaCzftuM/xmZgKOZCtFzz6CdV9w=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI=
github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU=
github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw=
github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94 h1:rmMl4fXJhKMNWl+K+r/fq4FbbKI+Ia2m9hYBLm2h4G4=
github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94/go.mod h1:90zrgN3D/WJsDd1iXHT96alCoN2KJo6/4x1DZC3wZs8=
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d/go.mod h1:Gy+0tqhJvgGlqnTF8CVGP0AaGRjwBtXs/a5PA0Y3+A4=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee h1:8Iv5m6xEo1NR1AvpV+7XmhI4r39LGNzwUL4YpMuL5vk=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee/go.mod h1:qwtSXrKuJh/zsFQ12yEE89xfCrGKK63Rr7ctU/uCo4g=
github.com/tinylib/msgp v1.1.6/go.mod h1:75BAfg2hauQhs3qedfdDZmWAPcFMAvJE5b9rGOMufyw=
github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0=
github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.43.0 h1:Gy4sb32C98fbzVWZlTM1oTMdLWGyvxR03VhM6cBIU4g=
github.com/valyala/fasthttp v1.43.0/go.mod h1:f6VbjjoI3z1NDOZOv17o6RvtRSWxC77seBFc2uWtgiY=
github.com/valyala/fasthttp v1.46.0 h1:6ZRhrFg8zBXTRYY6vdzbFhqsBd7FVv123pV2m9V87U4=
github.com/valyala/fasthttp v1.46.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220906165146-f3363e06e74c/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc=
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
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.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
+250
View File
@@ -0,0 +1,250 @@
// This package provides a small framework to work with SQL databases using
// generics. The most important part for now is the "Ref[T]" type that lets
// us pass around typed IDs to table rows in a type safe manner.
//
// For now this library uses both generics for keeping the interface type safe
// and reflection to extract automatically some metedata from structs that
// represent tables.
package db
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
"strings"
"golang.org/x/exp/slices"
)
// Option è un valore che nel database può potenzialmente essere "NULL"
//
// NOTE/TODO: Magari si può fare una cosa fatta bene e nascondere
// l'implementazione al Go, ad esempio Option[string] può essere NULL o testo
// nel db mentre Option[time.Time] può essere codificato in json come
//
// "{ present: false }"
//
// oppure
//
// "{ present: true, value: '2023/04/...' }"
//
// in modo da semplificare leggermente la processazione in Go. Altrimenti si
// può separare in Option[T] e Nullable[T].
type Option[T any] struct {
present bool
value T
}
func (o Option[T]) MarshalJSON() ([]byte, error) {
if !o.present {
return []byte("null"), nil
}
return json.Marshal(o.value)
}
func (o Option[T]) UnmarshalJSON(v []byte) error {
if slices.Equal(v, []byte("null")) {
var zero T
o.present = false
o.value = zero
return nil
}
if err := json.Unmarshal(v, &o.value); err != nil {
return err
}
return nil
}
func NewOption[T any](value T) Option[T] {
return Option[T]{true, value}
}
func NewEmptyOption[T any]() Option[T] {
return Option[T]{present: false}
}
func (Option[T]) SqlType() string {
return "BLOB"
}
// func (v *Option[T]) Scan(a any) error {
// data, ok := a.([]byte)
// if !ok {
// return fmt.Errorf(`scan expected []byte`)
// }
// m := map[string]any{}
// if err := json.Unmarshal(data, m); err != nil {
// return err
// }
// if present, _ := m["present"].(bool); present {
// m["value"]
// }
// return nil
// }
// Ref è un id tipato da un'entità presente nel database. È il tipo fondamentale
// esportato da questo package. Non dovrebbe essere troppo importante ma
// internamente è una stringa, inoltre è consigliato che una struct
// con _primary key_ abbia un campo di tipo Ref a se stessa.
//
// type User struct {
// Id db.Ref[User] // meglio se unico e immutabile
// ...
// }
type Ref[T any] string
func (Ref[T]) SqlType() string {
return "TEXT"
}
func (v *Ref[T]) Scan(a any) error {
s, ok := a.(string)
if !ok {
return fmt.Errorf(`scan expected string`)
}
*v = Ref[T](s)
return nil
}
type sqlValue interface {
SqlType() string
sql.Scanner
}
type Table[T any] struct {
Name string
PrimaryKey func(value *T, pk ...string) Ref[T]
Columns [][2]string
}
var commonTypes = map[string]string{
"string": "TEXT",
"int": "INTEGER",
"int32": "INTEGER",
"int64": "INTEGER",
"float32": "REAL",
"float64": "REAL",
}
func toSqlType(typ reflect.Type) string {
st, ok := reflect.New(typ).Interface().(sqlValue)
if ok {
return st.SqlType()
}
return commonTypes[typ.Name()]
}
func AutoTable[T any](name string) Table[T] {
columns := [][2]string{}
pkIndex := -1
var zero T
typ := reflect.TypeOf(zero)
for i := 0; i < typ.NumField(); i++ {
fieldTyp := typ.Field(i)
isPK, _, typ, col := fieldInfo(fieldTyp)
if isPK {
pkIndex = i
}
columns = append(columns, [2]string{col, toSqlType(typ)})
}
if pkIndex == -1 {
panic(fmt.Sprintf("struct %T has no primary key field", zero))
}
// debug logging
// log.Printf("[auto table] struct %T has primary key %q", zero, typ.Field(pkIndex).Name)
return Table[T]{
Name: name,
PrimaryKey: func(value *T, pk ...string) Ref[T] {
// SAFETY: this is required to cast *Ref[T] to *string, internally
// they are the same type so this should be safe
ptr := reflect.ValueOf(value).Elem().Field(pkIndex).Addr().UnsafePointer()
pkPtr := (*string)(ptr)
if len(pk) > 0 {
*pkPtr = pk[0]
}
return Ref[T](*pkPtr)
},
Columns: columns,
}
}
func (table Table[T]) CreateIfNotExists(dbConn *sql.DB) error {
columns := make([]string, len(table.Columns))
for i, col := range table.Columns {
columns[i] = fmt.Sprintf("%s %s", col[0], col[1])
}
stmt := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s(%s)`,
table.Name,
strings.Join(columns, ", "),
)
_, err := dbConn.Exec(stmt)
return err
}
func Create[T any](dbConn *sql.DB, table Table[T], value T) (Ref[T], error) {
id := randomHex(15)
table.PrimaryKey(&value, id)
columns, values := structDatabaseColumnValues(&value)
stmt := fmt.Sprintf(`INSERT INTO %s(%s) VALUES (%s)`,
table.Name,
strings.Join(columns, ", "),
strings.Join(repeatSlice("?", len(columns)), ", "),
)
if _, err := dbConn.Exec(stmt, values...); err != nil {
return "", err
}
return Ref[T](id), nil
}
func Insert[T any](dbConn *sql.DB, table Table[T], value T) error {
columns, values := structDatabaseColumnValues(&value)
stmt := fmt.Sprintf(`INSERT INTO %s(%s) VALUES (%s)`,
table.Name,
strings.Join(columns, ", "),
strings.Join(repeatSlice("?", len(columns)), ", "),
)
_, err := dbConn.Exec(stmt, values...)
return err
}
func Read[T any](dbConn *sql.DB, table Table[T], id Ref[T]) (T, error) {
panic("todo")
}
func ReadAll[T any](dbConn *sql.DB, table Table[T]) ([]T, error) {
panic("todo")
}
func Update[T any](dbConn *sql.DB, table Table[T], id Ref[T], value T) error {
panic("todo")
}
func Delete[T any](dbConn *sql.DB, table Table[T], id Ref[T]) error {
panic("todo")
}
+88
View File
@@ -0,0 +1,88 @@
package db_test
import (
"context"
"database/sql"
"database/sql/driver"
"testing"
"git.phc.dm.unipi.it/phc/website/libs/db"
"gotest.tools/assert"
)
type mockDB struct {
*testing.T
LastQuery string
}
func (db *mockDB) Prepare(query string) (driver.Stmt, error) { return nil, nil }
func (db *mockDB) Close() error { return nil }
func (db *mockDB) Begin() (driver.Tx, error) { return nil, nil }
func (db *mockDB) Query(query string, args []driver.Value) (driver.Rows, error) {
db.LastQuery = query
db.Logf("[sql mock driver] [exec] query: '%s', args: %#v", query, args)
return nil, nil
}
func (db *mockDB) Exec(query string, args []driver.Value) (driver.Result, error) {
db.LastQuery = query
db.Logf("[sql mock driver] [exec] query: '%s', args: %#v", query, args)
return nil, nil
}
func (db *mockDB) Open(name string) (driver.Conn, error) {
return &mockDB{T: db.T}, nil
}
func (db *mockDB) Connect(context.Context) (driver.Conn, error) {
return db, nil
}
func (db *mockDB) Driver() driver.Driver {
return db
}
//
// Tests
//
func TestDb1(t *testing.T) {
type Product struct {
Id db.Ref[Product] `db:"id*"`
Title string `db:"title"`
Quantity int `db:"quantity"`
}
products := db.AutoTable[Product]("products")
mock := &mockDB{T: t}
conn := sql.OpenDB(mock)
err := products.CreateIfNotExists(conn)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, mock.LastQuery,
`CREATE TABLE IF NOT EXISTS products(id TEXT, title TEXT, quantity INTEGER)`,
)
ref1, err := db.Create(conn, products, Product{Title: "Foo", Quantity: 27})
if err != nil {
t.Fatal(err)
}
assert.Assert(t, string(ref1) != "")
assert.Equal(t, mock.LastQuery,
`INSERT INTO products(id, title, quantity) VALUES (?, ?, ?)`,
)
if err := db.Insert(conn, products, Product{Id: "123", Title: "Bar", Quantity: 42}); err != nil {
t.Fatal(err)
}
assert.Equal(t, mock.LastQuery,
`INSERT INTO products(id, title, quantity) VALUES (?, ?, ?)`,
)
}
+1
View File
@@ -0,0 +1 @@
package db
+118
View File
@@ -0,0 +1,118 @@
package db
import (
"crypto/rand"
"encoding/hex"
"reflect"
"strings"
)
func randomHex(len int) string {
buff := make([]byte, len/2+1)
rand.Read(buff)
str := hex.EncodeToString(buff)
return str[:len]
}
func fieldInfo(fieldTyp reflect.StructField) (bool, string, reflect.Type, string) {
fieldName := fieldTyp.Name
columnName, ok := fieldTyp.Tag.Lookup("db")
if !ok {
columnName = strings.ToLower(fieldName)
}
if ok && columnName[len(columnName)-1] == '*' {
return true, fieldName, fieldTyp.Type, columnName[:len(columnName)-1]
}
return false, fieldName, fieldTyp.Type, columnName
}
func fieldPrimaryKey(fieldTyp reflect.StructField) bool {
isPK, _, _, _ := fieldInfo(fieldTyp)
return isPK
}
// structDatabaseColumnValues takes a pointer to a struct and returns a pair
// of slices, one with the column names and the other with pointers to all
// its exported fields.
//
// The column name can be changed using the "db" tag attribute on that field
func structDatabaseColumnValues(s any) ([]string, []any) {
v := reflect.ValueOf(s).Elem()
numFields := v.NumField()
names := []string{}
values := []any{}
for i := 0; i < numFields; i++ {
fieldTyp := v.Type().Field(i)
fieldVal := v.Field(i)
if fieldTyp.IsExported() {
key := strings.ToLower(fieldTyp.Name)
if name, ok := fieldTyp.Tag.Lookup("db"); ok {
key = name
// primary key has a "*" at the end, exclude from column name
if key[len(key)-1] == '*' {
key = key[:len(key)-1]
}
}
names = append(names, key)
values = append(values, fieldVal.Addr().Interface())
}
}
return names, values
}
func structPrimaryKeyPtr(s any) (*string, bool) {
v := reflect.ValueOf(s).Elem()
for i := 0; i < v.NumField(); i++ {
fieldTyp := v.Type().Field(i)
fieldVal := v.Field(i)
if fieldTyp.IsExported() {
if fieldPrimaryKey(fieldTyp) {
// SAFETY: this is required to cast *Ref[T] to *string, internally
// they are the same type so this should be safe
ptr := fieldVal.Addr().UnsafePointer()
return (*string)(ptr), true
}
}
}
return nil, false
}
// structDatabasePrimaryKeyColumn takes a pointer to a struct and returns the
// name of the field with the primary key
func structDatabasePrimaryKeyColumn(s any) (field, column string, ok bool) {
v := reflect.ValueOf(s).Elem()
for i := 0; i < v.NumField(); i++ {
fieldTyp := v.Type().Field(i)
if fieldTyp.IsExported() {
key := fieldTyp.Name
if value, ok := fieldTyp.Tag.Lookup("db"); ok {
if value[len(value)-1] == '*' {
return key, value[:len(value)-1], true
}
}
}
}
return "", "", false
}
func repeatSlice[T any](value T, count int) []T {
s := make([]T, count)
for i := 0; i < count; i++ {
s[i] = value
}
return s
}
+277
View File
@@ -0,0 +1,277 @@
// The [sl] package has two main concepts, the [ServiceLocator] itself is the
// main object that one should pass around through the application. A
// [ServiceLocator] has a list of slots that can be filled with
// [ProvideFunc] and [Provide] and retrieved with [Use]. Slots should
// be unique by type and they can only be created with the [NewSlot] function.
//
// The usual way to use this module is to make slots for Go interfaces and
// then pass implementations using the [Provide] and
// [ProvideFunc] functions.
//
// Services can be of various types:
// - a service with no dependencies can be directly injected inside a
// ServiceLocator using [Provide].
// - a service with dependencies on other service should use
// [ProvideFunc]. This lets the service configure itself when needed
// and makes the developer not think about correctly ordering the
// recursive configuration of its dependencies.
// - a service can also be private, in this case the slot for a service
// should be a private field in the service package. This kind of
// services should also provide a way to inject them into a
// ServiceLocator.
// - a package can also just provide a slot with some value. This is useful
// for using the ServiceLocator to easily pass around values, effectively
// threating slots just as dynamically scoped variables.
package sl
import (
"fmt"
"log"
"os"
)
// Logger is the debug logger
//
// TODO: in the future this will be disabled and discard by default.
//
// As this is the service locator module it was meaning less to pass this
// through the ServiceLocator itself (without making the whole module more
// complex)
var Logger *log.Logger = log.New(os.Stderr, "[service locator] ", log.Lmsgprefix)
// slot is just a "typed" unique "symbol".
//
// This must be defined like so and not for example "struct{ typeName string }"
// because we might want to have more slots for the same type.
type slot[T any] *struct{}
type Hook[T any] func(*ServiceLocator, T) error
// hook is just a typed unique symbol
type hook[T any] *struct{}
// NewSlot is the only way to create instances of the slot type. Each instance
// is unique.
//
// This then lets you attach a service instance of type "T" to a
// [ServiceLocator] object.
func NewSlot[T any]() slot[T] {
return slot[T](new(struct{}))
}
// NewHook is the only way to create instances of the hook type. Each instance
// is unique.
//
// This lets you have a service dispatch an hook
func NewHook[T any]() hook[T] {
return hook[T](new(struct{}))
}
// slotEntry represents a service that can lazily configured
// (using "configureFunc"). Once configured the instance is kept in the "value"
// field and "created" will always be "true". The field "typeName" just for
// debugging purposes.
type slotEntry struct {
// typeName is just used for debugging purposes
typeName string
// configureFunc is used by lazily provided slot values to tell how to
// configure them self when required
configureFunc func(*ServiceLocator) (any, error)
// configured tells if this slot is already configured
configured bool
// value for this slot
value any
}
// checkConfigured tries to call configure on this slot entry if not already configured
func (s *slotEntry) checkConfigured(l *ServiceLocator) error {
if !s.configured {
v, err := s.configureFunc(l)
if err != nil {
return err
}
Logger.Printf(`[slot: %s] configured service of type %T`, s.typeName, v)
s.configured = true
s.value = v
}
return nil
}
type hookEntry struct {
// typeName is just used for debugging purposes
typeName string
// listeners is a list of functions to call when this hook is called
listeners []func(*ServiceLocator, any) error
}
// ServiceLocator is the main context passed around to retrive service
// instances, the interface uses generics so to inject and retrive service
// instances you should use the functions [Provide], [ProvideFunc] and [Use].
// This is essentially a dictionary indexed by slots that are them self just
// typed unique symbols
type ServiceLocator struct {
providers map[any]*slotEntry
hooks map[any]*hookEntry
}
// New creates a new [ServiceLocator] context to pass around in the application.
func New() *ServiceLocator {
return &ServiceLocator{
providers: map[any]*slotEntry{},
hooks: map[any]*hookEntry{},
}
}
// Provide will inject a concrete instance inside the ServiceLocator "l" for
// the given "slotKey". This should be used for injecting "static" services, for
// instances whose construction depend on other services you should use the
// [ProvideFunc] function.
//
// This is generic over "T" to check that instances for the given slot type
// check as "T" can also be an interface.
func Provide[T any](l *ServiceLocator, slotKey slot[T], value T) T {
typeName := getTypeName[T]()
Logger.Printf(`[slot: %s] provided value of type %T`, typeName, value)
l.providers[slotKey] = &slotEntry{
typeName: typeName,
configured: true,
value: value,
}
return value
}
// ProvideFunc will inject an instance inside the given ServiceLocator
// and "slotKey" that is created only when requested with a call to the
// [Use] function.
//
// This is generic over "T" to check that instances for the given slot type
// check as "T" can also be an interface.
func ProvideFunc[T any](l *ServiceLocator, slotKey slot[T], createFunc func(*ServiceLocator) (T, error)) {
typeName := getTypeName[T]()
Logger.Printf(`[slot: %s] inject lazy provider`, typeName)
l.providers[slotKey] = &slotEntry{
typeName: typeName,
configureFunc: func(l *ServiceLocator) (any, error) { return createFunc(l) },
configured: false,
}
}
// Use retrieves the value of type T associated with the given slot key from
// the provided ServiceLocator instance.
//
// If the ServiceLocator does not have a value for the slot key, or if the
// value wasn't correctly configured (in the case of a lazy slot), an error
// is returned.
func Use[T any](l *ServiceLocator, slotKey slot[T]) (T, error) {
var zero T
slot, ok := l.providers[slotKey]
if !ok {
return zero, fmt.Errorf(`no injected value for type %s`, getTypeName[T]())
}
err := slot.checkConfigured(l)
if err != nil {
return zero, err
}
v := slot.value.(T)
Logger.Printf(`[slot: %s] using slot with value of type %T`, getTypeName[T](), v)
return v, nil
}
func MustUse[T any](l *ServiceLocator, slotKey slot[T]) T {
v, err := Use(l, slotKey)
if err != nil {
log.Fatal(err)
}
return v
}
func Invoke[T any](l *ServiceLocator, slotKey slot[T]) error {
slot, ok := l.providers[slotKey]
if !ok {
return fmt.Errorf(`no injected value for type %s`, getTypeName[T]())
}
err := slot.checkConfigured(l)
if err != nil {
return err
}
v := slot.value.(T)
Logger.Printf(`[slot: %s] invoked slot with value of type %T`, getTypeName[T](), v)
return nil
}
func MustInvoke[T any](l *ServiceLocator, slotKey slot[T]) {
if err := Invoke(l, slotKey); err != nil {
log.Fatal(err)
}
}
func ProvideHook[T any](l *ServiceLocator, hookKey hook[T], listeners ...Hook[T]) {
typeName := getTypeName[T]()
Logger.Printf(`[hook: %s] injecting hooks`, typeName)
// cast type safe listeners to internal untyped version to put inside the hook map
anyListeners := make([]func(*ServiceLocator, any) error, len(listeners))
for i, l := range listeners {
ll := l
anyListeners[i] = func(l *ServiceLocator, a any) error {
t, ok := a.(T)
if !ok {
panic(`illegal state`)
}
return ll(l, t)
}
}
l.hooks[hookKey] = &hookEntry{
typeName: typeName,
listeners: anyListeners,
}
}
func UseHook[T any](l *ServiceLocator, hookKey hook[T], value T) error {
hookEntry, ok := l.hooks[hookKey]
if !ok {
return fmt.Errorf(`no injected hooks for hook of type %s`, hookEntry.typeName)
}
Logger.Printf(`[hook: %s] calling hook with value of type %T`, hookEntry.typeName, value)
for _, hookFunc := range hookEntry.listeners {
if err := hookFunc(l, value); err != nil {
return err
}
}
return nil
}
func MustUseHook[T any](l *ServiceLocator, hookKey hook[T], value T) {
if err := UseHook(l, hookKey, value); err != nil {
log.Fatal(err)
}
}
// getTypeName is a trick to get the name of a type (even if it is an
// interface type)
func getTypeName[T any]() string {
var zero T
return fmt.Sprintf(`%T`, &zero)[1:]
}
+10
View File
@@ -0,0 +1,10 @@
package util
import (
"regexp"
)
// CompactIndentedLines removes all indentation from a string and also removes all newlines, usefull in tests
func CompactIndentedLines(s string) string {
return regexp.MustCompile(`(?m)\n\s+`).ReplaceAllString(s, "")
}
-18
View File
@@ -1,18 +0,0 @@
import fetch from 'node-fetch'
import { readFile } from 'fs/promises'
export async function getBuildRoutesMetadata(file) {
console.log('Loading routes from disk...')
const routesRaw = await readFile(file, 'utf8')
return JSON.parse(routesRaw)
}
export async function getDevRoutesMetadata(url) {
console.log('Loading routes from go server...')
const routesReq = await fetch(url)
const routes = await routesReq.json()
return routes
}
-15
View File
@@ -1,15 +0,0 @@
package model
type User struct {
Id string
FullName string
Nickname string
AuthSources map[string]AuthSource
}
type AuthSource struct {
Provider string
AuthToken string
}
+15 -13
View File
@@ -1,21 +1,23 @@
{
"name": "website",
"name": "website-frontend",
"version": "1.0.0",
"description": "Frontend for the PHC website",
"type": "module",
"scripts": {
"dev": "node server.js",
"build": "vite build --emptyOutDir"
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview"
},
"license": "MIT",
"dependencies": {
"@fontsource/open-sans": "^4.5.14",
"@fontsource/source-code-pro": "^4.5.14",
"@fontsource/source-sans-pro": "^4.5.11",
"astro": "^2.3.1",
"sass": "^1.62.1"
},
"devDependencies": {
"@preact/preset-vite": "^2.5.0",
"axios": "^1.2.6",
"express": "^4.18.2",
"morgan": "^1.10.0",
"node-fetch": "^3.3.0",
"sass": "^1.57.1",
"vite": "^4.0.4"
},
"dependencies": {
"preact": "^10.11.3"
"typescript": "^5.0.4"
}
}
+2368 -813
View File
File diff suppressed because it is too large Load Diff
-93
View File
@@ -1,93 +0,0 @@
import express from 'express'
import { createServer as createViteServer } from 'vite'
import { getDevRoutesMetadata } from './meta/routes.js'
import fetch from 'node-fetch'
import { readFile } from 'fs/promises'
import { dirname, resolve } from 'path'
import morgan from 'morgan'
import { fileURLToPath } from 'url'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
async function main() {
const routes = await getDevRoutesMetadata('http://127.0.0.1:4000/api/development/routes')
console.log('Found static routes:')
for (const [route, file] of Object.entries(routes.static)) {
console.log(`- ${route} -> "${file}"`)
}
console.log('Found dynamic routes:')
for (const [route, file] of Object.entries(routes.dynamic)) {
console.log(`- ${route} -> "${file}"`)
}
const app = express()
app.use(morgan(':method :url :status :response-time ms - :res[content-length]'))
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'custom',
})
app.use(vite.middlewares)
for (const [route, file] of Object.entries(routes.static)) {
app.get(route, async (req, res) => {
console.log(`Requested static route "${route}":`)
let htmlPage = await readFile(resolve(__dirname, './frontend/', file), 'utf8')
// Replace "./" with the absolute path of the html page
htmlPage = htmlPage.replace(/\.\//g, '/' + dirname(file) + '/')
console.log(`- applying vite transformations for "${file}"`)
const html = await vite.transformIndexHtml(file, htmlPage)
console.log(`- sending resulting page for "${route}"`)
res.writeHead(200, { 'Content-Type': 'text/html' }).end(html)
})
}
for (const [route, file] of Object.entries(routes.dynamic)) {
app.get(route, async (req, res) => {
console.log(`Requested dynamic route "${route}":`)
let htmlPage = await readFile(resolve(__dirname, './frontend/', file), 'utf8')
// Replace "./" with the absolute path of the html page
htmlPage = htmlPage.replace(/\.\//g, '/' + dirname(file) + '/')
console.log(`- applying vite transformations for "${file}"`)
const html = await vite.transformIndexHtml(file, htmlPage)
console.log(`- applying server transformations for "${file}"`)
const templateHtmlReq = await fetch('http://127.0.0.1:4000/api/development/render', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
route,
page: html,
request: {
params: req.params,
query: req.query,
},
}),
})
const renderedHtml = await templateHtmlReq.json()
console.log(`- sending resulting page for "${route}"`)
res.writeHead(200, { 'Content-Type': 'text/html' }).end(renderedHtml)
})
}
app.listen(3000, () => {
console.log(`Listening on port 3000...`)
})
}
main()
+54
View File
@@ -0,0 +1,54 @@
package config
import (
"git.phc.dm.unipi.it/phc/website/libs/sl"
"github.com/joho/godotenv"
)
type Config struct {
Mode string
Host string
NpmCommand string
}
var Slot = sl.NewSlot[Config]()
func setFromEnvOrDefault(target *string, m map[string]string, key string, defaultValue string) {
v, ok := m[key]
if ok {
*target = v
} else {
*target = defaultValue
}
}
func Configure(l *sl.ServiceLocator) (Config, error) {
env, err := godotenv.Read(".env")
if err != nil {
return Config{}, err
}
var cfg Config
setFromEnvOrDefault(&cfg.Mode, env, "MODE", "production")
setFromEnvOrDefault(&cfg.Host, env, "HOST", ":4000")
setFromEnvOrDefault(&cfg.NpmCommand, env, "NPM_COMMAND", "npm")
return cfg, nil
}
var ExampleProductionConfig = Config{
Mode: "production",
Host: ":4000",
NpmCommand: "npm",
}
var ExampleDevelopmentConfig = Config{
Mode: "development",
Host: ":4000",
NpmCommand: "npm",
}
+82
View File
@@ -0,0 +1,82 @@
package database
import (
"fmt"
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server/model"
)
var Slot = sl.NewSlot[Database]()
// Database is the main database service interface
type Database interface {
// User
CreateUser(user model.User) (db.Ref[model.User], error)
ReadUser(id db.Ref[model.User]) (model.User, error)
ReadUsers() ([]model.User, error)
UpdateUser(user model.User) error
DeleteUser(id db.Ref[model.User]) error
// Accounts
CreateAccount(account model.Account) (db.Ref[model.Account], error)
ReadAccount(id db.Ref[model.Account]) (model.Account, error)
UpdateAccount(user model.Account) error
DeleteAccount(id db.Ref[model.Account]) error
// Users & Accounts
ReadUserAccounts(user db.Ref[model.User]) ([]model.Account, error)
}
// Memory is an in-memory implementation of [Database] that can be used for testing
type Memory struct {
Database // TODO: Per ora almeno così facciamo compilare il codice
Users []model.User
}
func (m *Memory) CreateUser(user model.User) (db.Ref[model.User], error) {
m.Users = append(m.Users, user)
return db.Ref[model.User](user.Id), nil
}
func (m *Memory) ReadUser(id db.Ref[model.User]) (model.User, error) {
for _, u := range m.Users {
if u.Id == id {
return u, nil
}
}
return model.User{}, fmt.Errorf(`no user with id "%s"`, id)
}
func (m *Memory) ReadUsers() ([]model.User, error) {
return m.Users, nil
}
func (m *Memory) UpdateUser(user model.User) error {
for i, u := range m.Users {
if u.Id == user.Id {
m.Users[i] = user
return nil
}
}
return fmt.Errorf(`no user with id "%s"`, user.Id)
}
func (m *Memory) DeleteUser(id db.Ref[model.User]) error {
for i, u := range m.Users {
if u.Id == id {
m.Users = append(m.Users[:i], m.Users[i+1:]...)
return nil
}
}
return fmt.Errorf(`no user with id "%s"`, id)
}
+10
View File
@@ -0,0 +1,10 @@
package tables
import (
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/server/model"
)
var Users = db.AutoTable[model.User]("users")
var Accounts = db.AutoTable[model.Account]("accounts")
+28
View File
@@ -0,0 +1,28 @@
package listautenti
import (
"github.com/gofiber/fiber/v2"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server/database"
)
func MountApiRoutesHook(l *sl.ServiceLocator, api fiber.Router) error {
db, err := sl.Use(l, database.Slot)
if err != nil {
return err
}
api.Get("/lista-utenti", func(c *fiber.Ctx) error {
users, err := db.ReadUsers()
if err != nil {
return err
}
// TODO: Pre-process data to strip server only fields...
return c.JSON(users)
})
return nil
}
+111
View File
@@ -0,0 +1,111 @@
package listautenti_test
import (
"context"
"fmt"
"io"
"net"
"net/http"
"testing"
"gotest.tools/assert"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/libs/util"
"git.phc.dm.unipi.it/phc/website/server"
"git.phc.dm.unipi.it/phc/website/server/config"
"git.phc.dm.unipi.it/phc/website/server/database"
"git.phc.dm.unipi.it/phc/website/server/listautenti"
"git.phc.dm.unipi.it/phc/website/server/model"
)
func TestApiListaUtenti(t *testing.T) {
memDB := &database.Memory{
Users: []model.User{
{
Id: "e39ad8d5-a087-4cb2-8fd7-5a6ca3f6a534",
Username: "claire-doe",
FullName: db.NewOption("Claire Doe"),
Email: db.NewOption("claire.doe@example.org"),
},
{
Id: "9b7109cd-95a1-41e9-a9f6-001a32c20ca1",
Username: "john-smith",
FullName: db.NewOption("John Smith"),
Email: db.NewOption("john.smith@example.org"),
},
},
}
l := sl.New()
// Config
sl.Provide(l, config.Slot, config.ExampleProductionConfig)
// Database
sl.Provide[database.Database](l, database.Slot, memDB)
// Server
sl.ProvideFunc(l, server.Slot, server.Configure)
sl.ProvideHook(l, server.ApiRoutesHook,
listautenti.MountApiRoutesHook,
)
// Initialize server instance
srv, err := sl.Use(l, server.Slot)
assert.NilError(t, err)
//
// Try doing the request
//
req, err := http.NewRequest("GET", "http://localhost:4000/api/lista-utenti", nil)
assert.NilError(t, err)
ln := fasthttputil.NewInmemoryListener()
defer ln.Close()
go func() {
err := fasthttp.Serve(ln, srv.Router.Handler())
if err != nil {
panic(fmt.Errorf("failed to serve: %v", err))
}
}()
client := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return ln.Dial()
},
},
}
res, err := client.Do(req)
assert.NilError(t, err)
body, err := io.ReadAll(res.Body)
assert.NilError(t, err)
assert.Equal(t, string(body), util.CompactIndentedLines(`
[
{
"Id":"e39ad8d5-a087-4cb2-8fd7-5a6ca3f6a534",
"Username":"claire-doe",
"FullName":"Claire Doe",
"Email":"claire.doe@example.org"
},
{
"Id":"9b7109cd-95a1-41e9-a9f6-001a32c20ca1",
"Username":"john-smith",
"FullName":"John Smith",
"Email":"john.smith@example.org"
}
]
`))
}
+37
View File
@@ -0,0 +1,37 @@
package model
import "git.phc.dm.unipi.it/phc/website/libs/db"
type User struct {
// Id è l'id unico di questo utente, non è modificabile una volta creato
// l'utente.
Id db.Ref[User] `db:"id"`
// Username è il nome leggibile di questo utente utilizzato anche per le
// route per singolo utente, deve essere unico nel sito.
//
// NOTE: Quando un utente accede per la prima volta di default gli viene
// chiesto se usare quello dell'account che sta usando o se cambiarlo
// (in teoria non dovrebbe essere un problema poterlo modificare
// successivamente).
Username string `db:"username"`
// FullName da mostrare in giro per il sito
FullName db.Option[string] `db:"full_name"`
// Email per eventuale contatto
Email db.Option[string] `db:"email"`
}
type ProviderType string
const AteneoProvider ProviderType = "ateneo"
const PoissonProvider ProviderType = "poisson"
type Account struct {
Id db.Ref[Account] `db:"id"` // Id of this entity
UserId db.Ref[User] `db:"user_id"` // UserId tells the owner of this account binding
Provider ProviderType `db:"provider"` // Provider is the name of the authentication method
Token string `db:"token"` // Token to use to make requests on behalf of this user
}
+37
View File
@@ -0,0 +1,37 @@
package server
import (
"log"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server/config"
"github.com/gofiber/fiber/v2"
)
type Server struct{ Router *fiber.App }
var Slot = sl.NewSlot[*Server]()
var ApiRoutesHook = sl.NewHook[fiber.Router]()
func Configure(l *sl.ServiceLocator) (*Server, error) {
cfg, err := sl.Use(l, config.Slot)
if err != nil {
return nil, err
}
r := fiber.New(fiber.Config{})
r.Static("/assets", "./out/frontend/assets")
api := r.Group("/api")
if err := sl.UseHook(l, ApiRoutesHook, api); err != nil {
return nil, err
}
go func() {
log.Fatal(r.Listen(cfg.Host))
}()
return &Server{r}, nil
}
-35
View File
@@ -1,35 +0,0 @@
package config
import (
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/joho/godotenv"
)
var Slot = sl.NewSlot[*Config]()
type Config struct {
Mode string
Host string
}
func Load(l *sl.ServiceLocator) (*Config, error) {
m, err := godotenv.Read(".env")
if err != nil {
return nil, err
}
mode := "production"
if v, ok := m["MODE"]; ok {
mode = v
}
host := ":4000"
if v, ok := m["HOST"]; ok {
host = v
}
return &Config{
mode,
host,
}, nil
}
-63
View File
@@ -1,63 +0,0 @@
package database
import (
"fmt"
"git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/sl"
)
var Slot = sl.NewSlot[Database]()
type Database interface {
CreateUser(user model.User) error
ReadUser(id string) (model.User, error)
ReadUsers() ([]model.User, error)
UpdateUser(id string, user model.User) error
DeleteUser(id string) error
}
type Memory struct {
Users []model.User
}
func (m *Memory) CreateUser(user model.User) error {
m.Users = append(m.Users, user)
return nil
}
func (m *Memory) ReadUser(id string) (model.User, error) {
for _, u := range m.Users {
if u.Id == id {
return u, nil
}
}
return model.User{}, fmt.Errorf(`no user with id "%s"`, id)
}
func (m *Memory) ReadUsers() ([]model.User, error) {
return m.Users, nil
}
func (m *Memory) UpdateUser(id string, user model.User) error {
for i, u := range m.Users {
if u.Id == id {
m.Users[i] = user
return nil
}
}
return fmt.Errorf(`no user with id "%s"`, id)
}
func (m *Memory) DeleteUser(id string) error {
for i, u := range m.Users {
if u.Id == id {
m.Users = append(m.Users[:i], m.Users[i+1:]...)
return nil
}
}
return fmt.Errorf(`no user with id "%s"`, id)
}
-58
View File
@@ -1,58 +0,0 @@
package articles
import (
"html/template"
"git.phc.dm.unipi.it/phc/website/services/server/dev"
"git.phc.dm.unipi.it/phc/website/services/server/router"
"git.phc.dm.unipi.it/phc/website/sl"
)
func Configure(l *sl.ServiceLocator) error {
router.UseRouteTemplatedPage(l, "/articles",
"pages/articles/index.html",
func(w dev.ResponseWriter, r dev.Request) error {
tmpl := template.New("")
tmpl, err := tmpl.Parse(string(r.Page()))
if err != nil {
return err
}
ctx := map[string]any{
"Example": "Bla bla",
}
if err := tmpl.Execute(w, ctx); err != nil {
return err
}
return nil
},
)
router.UseRouteTemplatedPage(l, "/articles/:slug",
"pages/articles/article.html",
func(w dev.ResponseWriter, r dev.Request) error {
tmpl := template.New("")
tmpl, err := tmpl.Parse(string(r.Page()))
if err != nil {
return err
}
ctx := map[string]any{
"Title": r.Param("slug"),
"Example": "Bla bla " + r.Param("slug"),
}
if err := tmpl.Execute(w, ctx); err != nil {
return err
}
return nil
},
)
return nil
}
-169
View File
@@ -1,169 +0,0 @@
package dev
import (
"bytes"
"fmt"
"io"
"log"
"os"
"path"
"git.phc.dm.unipi.it/phc/website/services/config"
"git.phc.dm.unipi.it/phc/website/services/server/routes"
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/alecthomas/repr"
"github.com/gofiber/fiber/v2"
)
// Logger is the debug logger, in the future this will be disabled and discard by default.
var Logger *log.Logger = log.New(os.Stderr, "[services/server/dev] ", log.Lmsgprefix)
// slot represents a private "write only" service
var slot = sl.NewSlot[*devService]()
// InjectInto a [*sl.ServiceLocator] an instance of the dev service
func InjectInto(l *sl.ServiceLocator) {
sl.InjectLazy(l, slot, Configure)
}
func UseRoutesMetadata(l *sl.ServiceLocator) map[string]any {
dev, err := sl.Use(l, slot)
if err != nil {
Logger.Fatal(err)
}
return map[string]any{
"static": dev.staticRoutes,
"dynamic": dev.dynamicRoutes,
}
}
type Request interface {
Page() []byte
Param(key string) string
Query(key string) string
}
type ResponseWriter interface {
io.Writer
}
// devServerRequest is used when handling request from the dev server where params and queries are parsed by express
type devServerRequest struct {
page []byte
params map[string]string
query map[string]string
}
func (r devServerRequest) Page() []byte {
return r.page
}
func (r devServerRequest) Param(key string) string {
return r.params[key]
}
func (r devServerRequest) Query(key string) string {
return r.query[key]
}
// Handler is a custom routes handler
type Handler func(ResponseWriter, Request) error
type devService struct {
staticRoutes map[string]string
dynamicRoutes map[string]string
dynamicRoutesHandlers map[string]Handler
}
func Configure(l *sl.ServiceLocator) (*devService, error) {
d := &devService{
map[string]string{},
map[string]string{},
map[string]Handler{},
}
r, err := sl.Use(l, routes.Root)
if err != nil {
return nil, err
}
config, _ := sl.Use(l, config.Slot)
if config.Mode != "development" {
return d, nil
}
r.Get("/api/development/routes", func(c *fiber.Ctx) error {
return c.JSON(map[string]any{
"static": d.staticRoutes,
"dynamic": d.dynamicRoutes,
})
})
r.Post("/api/development/render", func(c *fiber.Ctx) error {
var data struct {
Route string `json:"route"`
HtmlPage string `json:"page"`
Request struct {
ParamsMap map[string]string `json:"params"`
QueryMap map[string]string `json:"query"`
} `json:"request"`
}
if err := c.BodyParser(&data); err != nil {
return err
}
Logger.Printf(`server rendering route "%s"`, data.Route)
Logger.Printf(`- params: %s`, repr.String(data.Request.ParamsMap))
Logger.Printf(`- query: %s`, repr.String(data.Request.QueryMap))
handler, ok := d.dynamicRoutesHandlers[data.Route]
if !ok {
return fmt.Errorf(`no handler for "%s"`, data.Route)
}
var buf bytes.Buffer
if err := handler(&buf, devServerRequest{
[]byte(data.HtmlPage),
data.Request.ParamsMap,
data.Request.QueryMap,
}); err != nil {
return err
}
return c.JSON(buf.String())
})
return d, nil
}
// RegisterRoute will register the provided "mountPoint" to the "frontendHtml" page
func RegisterRoute(l *sl.ServiceLocator, mountPoint, frontendFile string) {
dev, err := sl.Use(l, slot)
if err != nil {
Logger.Fatal(err)
}
dev.staticRoutes[mountPoint] = frontendFile
Logger.Printf(`registered vite route "%v" for "%v"`, frontendFile, mountPoint)
}
func RegisterDynamicRoute(l *sl.ServiceLocator, mountPoint, frontendFile string, handler Handler) {
dev, err := sl.Use(l, slot)
if err != nil {
Logger.Fatal(err)
}
dev.dynamicRoutes[mountPoint] = frontendFile
dev.dynamicRoutesHandlers[mountPoint] = handler
Logger.Printf(`registered vite route "%v" for "%v"`, frontendFile, mountPoint)
}
func GetArtifactPath(frontendFile string) string {
return path.Join("./out/frontend/", frontendFile)
}
@@ -1,35 +0,0 @@
package listautenti
import (
"git.phc.dm.unipi.it/phc/website/services/database"
"git.phc.dm.unipi.it/phc/website/services/server/router"
"git.phc.dm.unipi.it/phc/website/services/server/routes"
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/gofiber/fiber/v2"
)
func Configure(l *sl.ServiceLocator) error {
router.UseRoutePage(l, "/utenti", "pages/lista-utenti/index.html")
db, err := sl.Use(l, database.Slot)
if err != nil {
return err
}
r, err := sl.Use(l, routes.Root)
if err != nil {
return err
}
r.Get("/api/lista-utenti", func(c *fiber.Ctx) error {
users, err := db.ReadUsers()
if err != nil {
return err
}
return c.JSON(users)
})
return nil
}
@@ -1,78 +0,0 @@
package listautenti_test
import (
"context"
"fmt"
"io"
"net"
"net/http"
"testing"
"git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/services/database"
"git.phc.dm.unipi.it/phc/website/services/server/routes"
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
)
func Test1(t *testing.T) {
l := sl.New()
sl.InjectValue[database.Database](l, database.Slot, &database.Memory{
Users: []model.User{
{
Id: "claire",
FullName: "Claire Doe",
Nickname: "claire-doe",
AuthSources: map[string]model.AuthSource{},
},
{
Id: "john",
FullName: "John Smith",
Nickname: "john-smith",
AuthSources: map[string]model.AuthSource{},
},
},
})
r := fiber.New()
sl.InjectValue(l, routes.Root, fiber.Router(r))
req, err := http.NewRequest("GET", "http://localhost:4000/api/lista-utenti", nil)
if err != nil {
t.Error(err)
}
ln := fasthttputil.NewInmemoryListener()
defer ln.Close()
go func() {
err := fasthttp.Serve(ln, r.Handler())
if err != nil {
panic(fmt.Errorf("failed to serve: %v", err))
}
}()
client := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return ln.Dial()
},
},
}
res, err := client.Do(req)
if err != nil {
t.Error(err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
t.Log(string(body))
}
-73
View File
@@ -1,73 +0,0 @@
package router
import (
"bytes"
"log"
"os"
"git.phc.dm.unipi.it/phc/website/services/server/dev"
"git.phc.dm.unipi.it/phc/website/services/server/routes"
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/gofiber/fiber/v2"
)
// assert type of [ServerRequest] is [dev.Request]
var _ dev.Request = ServerRequest{}
// ServerRequest is used when the request is directly for the Go server
type ServerRequest struct {
page []byte
fiberContext *fiber.Ctx
}
func (r ServerRequest) Page() []byte {
return r.page
}
func (ctx ServerRequest) Param(key string) string {
return ctx.fiberContext.Params(key)
}
func (ctx ServerRequest) Query(key string) string {
return ctx.fiberContext.Query(key)
}
func UseRoutePage(l *sl.ServiceLocator, route, frontendFile string) {
root, err := sl.Use(l, routes.Root)
if err != nil {
log.Fatal(err)
}
dev.RegisterRoute(l, route, frontendFile)
root.Get(route, func(c *fiber.Ctx) error {
return c.SendFile(dev.GetArtifactPath(frontendFile))
})
}
func UseRouteTemplatedPage(l *sl.ServiceLocator, route, frontendFile string, handler dev.Handler) {
r, err := sl.Use(l, routes.Root)
if err != nil {
log.Fatal(err)
}
dev.RegisterDynamicRoute(l, route, frontendFile, handler)
r.Get(route, func(c *fiber.Ctx) error {
rawPage, err := os.ReadFile(dev.GetArtifactPath(frontendFile))
if err != nil {
return err
}
var buf bytes.Buffer
if err := handler(&buf, ServerRequest{
rawPage,
c,
}); err != nil {
return err
}
return c.Type(".html").Send(buf.Bytes())
})
}
-9
View File
@@ -1,9 +0,0 @@
package routes
import (
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/gofiber/fiber/v2"
)
var Root = sl.NewSlot[fiber.Router]()
-30
View File
@@ -1,30 +0,0 @@
package server
import (
"git.phc.dm.unipi.it/phc/website/services/server/articles"
"git.phc.dm.unipi.it/phc/website/services/server/dev"
"git.phc.dm.unipi.it/phc/website/services/server/listautenti"
"git.phc.dm.unipi.it/phc/website/services/server/routes"
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/gofiber/fiber/v2"
)
type Server struct{ Router *fiber.App }
func Configure(l *sl.ServiceLocator) (*Server, error) {
r := fiber.New(fiber.Config{})
r.Static("/assets", "./out/frontend/assets")
sl.InjectValue(l, routes.Root, fiber.Router(r))
dev.InjectInto(l)
if err := listautenti.Configure(l); err != nil {
return nil, err
}
if err := articles.Configure(l); err != nil {
return nil, err
}
return &Server{r}, nil
}
-127
View File
@@ -1,127 +0,0 @@
// The [sl] package has two main concepts, the [ServiceLocator] itself is the main object that one should pass around through the application. A [ServiceLocator] has a list of slots that can be filled with [InjectLazy] and [InjectValue] and retrieved with [Use]. As slots should be unique they can only be created with the [NewSlot] function.
//
// The usual way to use this module is to make slots for go interfaces and then pass implementations using the [InjectValue] and [InjectLazy] functions.
//
// Services can be of various types:
// - a service with no dependencies can be directly injected inside a ServiceLocator using [InjectValue].
// - a service with dependencies on other service should use [InjectLazy]. This lets the service to initialize itself when required and makes the developer not think the topological sort to put onto the DAG of service dependencies.
// - a service can also be private, in this case the slot for a service should be a private field in the service package. This kind of services should also provide a way to inject them into a ServiceLocator.
// - a package also just provide a slot. This is useful for using the ServiceLocator to easily pass around values, effectively threating slots just as dynamically scoped variables.
package sl
import (
"fmt"
"log"
"os"
)
// Logger is the debug logger, in the future this will be disabled and discard by default.
//
// As this is the service locator module it was meaning less to pass this through the ServiceLocator itself (without making the whole module more complex)
var Logger *log.Logger = log.New(os.Stderr, "[sl] ", log.Lmsgprefix)
// slot is just a "typed" unique "symbol".
type slot[T any] *struct{}
// NewSlot is the only way to create instances of the slot type. Each instance is unique.
//
// This then lets you attach a service instance of type "T" to a [ServiceLocator] object.
func NewSlot[T any]() slot[T] {
return slot[T](new(struct{}))
}
// slotEntry represents a service that can lazily initialized (using "createFunc"). Once initialized the instance is kept in the "value" field. The field "typeName" just for debugging purposes.
type slotEntry struct {
createFunc func(*ServiceLocator) (any, error)
created bool
value any
typeName string
}
func (s *slotEntry) checkInitialized(l *ServiceLocator) error {
if !s.created {
v, err := s.createFunc(l)
if err != nil {
return err
}
Logger.Printf(`initialized lazy value of type %T for slot of type %s`, v, s.typeName)
s.created = true
s.value = v
}
return nil
}
// ServiceLocator is the main context passed around to retrive service instances, the interface uses generics so to inject and retrive service instances you should use the functions [InjectValue], [InjectLazy] and [Use].
type ServiceLocator struct {
providers map[any]*slotEntry
}
// New creates a new [ServiceLocator] context to pass around in the application.
func New() *ServiceLocator {
return &ServiceLocator{
providers: map[any]*slotEntry{},
}
}
// InjectValue will inject a concrete instance inside the ServiceLocator "l" for the given "slotKey". This should be used for injecting "static" services, for instances whose construction depend on other services you should use the [InjectLazy] function.
//
// This is generic over "T" to check that instances for the given slot type check as "T" can also be an interface.
func InjectValue[T any](l *ServiceLocator, slotKey slot[T], value T) T {
Logger.Printf(`injected value of type %T for slot of type %s`, value, getTypeName[T]())
l.providers[slotKey] = &slotEntry{
nil,
true,
value,
getTypeName[T](),
}
return value
}
// InjectLazy will inject an instance inside the given ServiceLocator and "slotKey" that is created only when requested with a call to the [Use] function.
//
// This is generic over "T" to check that instances for the given slot type check as "T" can also be an interface.
func InjectLazy[T any](l *ServiceLocator, slotKey slot[T], createFunc func(*ServiceLocator) (T, error)) {
Logger.Printf(`injected lazy for slot of type %s`, getTypeName[T]())
l.providers[slotKey] = &slotEntry{
createFunc: func(l *ServiceLocator) (any, error) {
return createFunc(l)
},
created: false,
value: nil,
typeName: getTypeName[T](),
}
}
// Use retrieves the value of type T associated with the given slot key from the provided ServiceLocator instance.
//
// If the ServiceLocator does not have a value for the slot key, or if the value wasn't correctly initialized (in the case of a lazy slot), an error is returned.
func Use[T any](l *ServiceLocator, slotKey slot[T]) (T, error) {
var zero T
slot, ok := l.providers[slotKey]
if !ok {
return zero, fmt.Errorf(`no injected value for type %s`, getTypeName[T]())
}
err := slot.checkInitialized(l)
if err != nil {
return zero, err
}
v := slot.value.(T)
Logger.Printf(`using slot of type %s with value of type %T`, getTypeName[T](), v)
return v, nil
}
// getTypeName is a trick to get the name of a type (even if it is an interface type)
func getTypeName[T any]() string {
var zero T
return fmt.Sprintf(`%T`, &zero)[1:]
}
+29
View File
@@ -0,0 +1,29 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
// Enable top-level await, and other modern ESM features.
"target": "ESNext",
"module": "ESNext",
// Enable node-style module resolution, for things like npm package imports.
"moduleResolution": "node",
// Enable JSON imports.
"resolveJsonModule": true,
// Enable stricter transpilation for better output.
"isolatedModules": true,
// Astro directly run TypeScript code, no transpilation needed.
"noEmit": true,
"strictNullChecks": true,
// Report an error when importing a file using a casing different from the casing on disk.
"forceConsistentCasingInFileNames": true,
// Properly support importing CJS modules in ESM
"esModuleInterop": true,
// Skip typechecking libraries and .d.ts files
"skipLibCheck": true,
// Add alias for assets folder for easy reference to assets
"baseUrl": ".",
"paths": {},
// TypeScript 5.0 changed how `isolatedModules` and `importsNotUsedAsValues` works, deprecating the later
// Until the majority of users are on TypeScript 5.0, we'll have to supress those deprecation errors
"ignoreDeprecations": "5.0"
}
}
-44
View File
@@ -1,44 +0,0 @@
import { defineConfig } from 'vite'
import { join } from 'path'
import preactPlugin from '@preact/preset-vite'
import { getBuildRoutesMetadata } from './meta/routes.js'
/** @type {import('vite').UserConfig} */
const sharedConfig = {
// all files processed by ViteJS are inside this folder
root: './frontend',
// for now the only plugin is Preact
plugins: [preactPlugin()],
}
export default defineConfig(async config => {
if (config.command === 'build') {
const routes = await getBuildRoutesMetadata('out/routes.json')
const allHtmlEntrypoints = [...Object.values(routes.static), ...Object.values(routes.dynamic)].map(file =>
join(__dirname, 'frontend', file)
)
console.dir(allHtmlEntrypoints)
return {
...sharedConfig,
build: {
outDir: '../out/frontend',
rollupOptions: {
input: allHtmlEntrypoints,
},
},
}
} else {
return {
...sharedConfig,
server: {
port: 3000,
proxy: {
'/api': 'http://localhost:4000/',
},
},
}
}
})