Merge pull request 'Switch to lets-go for project' (#1) from drew/lets-go into main
Reviewed-on: #1main
commit
cd7c75c707
@ -0,0 +1,52 @@
|
|||||||
|
root = "."
|
||||||
|
testdata_dir = "testdata"
|
||||||
|
tmp_dir = "tmp"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
args_bin = ["-logging=DEBUG"]
|
||||||
|
bin = "./tmp/main"
|
||||||
|
cmd = "go build -o ./tmp/main cmd/ratchetd/main.go"
|
||||||
|
delay = 1000
|
||||||
|
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||||
|
exclude_file = []
|
||||||
|
exclude_regex = ["_test.go"]
|
||||||
|
exclude_unchanged = false
|
||||||
|
follow_symlink = false
|
||||||
|
full_bin = ""
|
||||||
|
include_dir = []
|
||||||
|
include_ext = ["go", "tpl", "tmpl", "html", "go.tmpl"]
|
||||||
|
include_file = []
|
||||||
|
kill_delay = "0s"
|
||||||
|
log = "build-errors.log"
|
||||||
|
poll = false
|
||||||
|
poll_interval = 0
|
||||||
|
post_cmd = []
|
||||||
|
pre_cmd = []
|
||||||
|
rerun = false
|
||||||
|
rerun_delay = 500
|
||||||
|
send_interrupt = false
|
||||||
|
stop_on_error = false
|
||||||
|
|
||||||
|
[color]
|
||||||
|
app = ""
|
||||||
|
build = "yellow"
|
||||||
|
main = "magenta"
|
||||||
|
runner = "green"
|
||||||
|
watcher = "cyan"
|
||||||
|
|
||||||
|
[log]
|
||||||
|
main_only = false
|
||||||
|
silent = false
|
||||||
|
time = false
|
||||||
|
|
||||||
|
[misc]
|
||||||
|
clean_on_exit = false
|
||||||
|
|
||||||
|
[proxy]
|
||||||
|
app_port = 0
|
||||||
|
enabled = false
|
||||||
|
proxy_port = 0
|
||||||
|
|
||||||
|
[screen]
|
||||||
|
clear_on_rebuild = false
|
||||||
|
keep_scroll = true
|
@ -1,7 +1,32 @@
|
|||||||
|
SQL_DATABASE?=./ratchet.db
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -v ./...
|
go test -v ./...
|
||||||
PHONEY: test
|
PHONEY: test
|
||||||
|
|
||||||
serve:
|
serve:
|
||||||
go run ./cmd/ratchetd/main.go
|
go run ./cmd/ratchetd/main.go
|
||||||
PHONEY: serve
|
PHONEY: serve
|
||||||
|
|
||||||
|
|
||||||
|
# SQLite Commands
|
||||||
|
|
||||||
|
sql-cli:
|
||||||
|
sqlite3 $(SQL_DATABASE) -cmd ".headers on" -cmd ".mode box" -cmd ".tables"
|
||||||
|
|
||||||
|
init-db: run-migrate
|
||||||
|
sqlite3 $(SQL_DATABASE) "PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;"
|
||||||
|
|
||||||
|
seed-db:
|
||||||
|
sqlite3 $(SQL_DATABASE) "INSERT INTO snippets (title, content, expires_at) VALUES ('placeholder', 'placeholder content', datetime('now', '+6 months'));"
|
||||||
|
|
||||||
|
run-migrate:
|
||||||
|
migrate -database sqlite3://$(SQL_DATABASE) -path ./migrations up
|
||||||
|
|
||||||
|
# Checks system dependencies needed to run the local dev environment
|
||||||
|
check-system-deps:
|
||||||
|
@echo "Checking system dependencies..."
|
||||||
|
@command -v air > /dev/null || (echo "Missing air command. go install github.com/air-verse/air@latest"; exit 1)
|
||||||
|
@command -v sqlite3 > /dev/null || (echo "Missing sqlite3 command. brew install sqlite"; exit 1)
|
||||||
|
@command -v migrate > /dev/null || (echo "Missing migrate command. go install -tags 'sqlite3' github.com/golang-migrate/migrate/v4/cmd/migrate@latest"; exit 1)
|
||||||
|
@echo "System dependencies fulfilled 👍"
|
@ -1,21 +1,61 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.runcible.io/learning/ratchet"
|
rdb "git.runcible.io/learning/ratchet/internal/database"
|
||||||
|
"git.runcible.io/learning/ratchet/internal/logging"
|
||||||
|
"git.runcible.io/learning/ratchet/internal/server"
|
||||||
|
// "git.runcible.io/learning/ratchet"
|
||||||
|
// ratchethttp "git.runcible.io/learning/ratchet/internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
// var (
|
||||||
version string
|
// version string
|
||||||
commit string
|
// commit string
|
||||||
)
|
// )
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
// CONFIGURATION
|
||||||
|
// Parse command line options
|
||||||
|
addr := flag.String("addr", "0.0.0.0", "HTTP network address")
|
||||||
|
port := flag.String("port", "5001", "HTTP port")
|
||||||
|
logLevel := flag.String("logging", "INFO", "Logging Level. Valid values [INFO, DEBUG, WARN, ERROR].")
|
||||||
|
dbPath := flag.String("database", "./ratchet.db", "A path to a sqlite3 database")
|
||||||
|
// must call parse or all values will be the defaults
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
// DEPENDENCY INJECTION FOR HANDLERS
|
||||||
|
// Setup Logging
|
||||||
|
logger := logging.InitLogging(*logLevel, false)
|
||||||
|
// Setup DB Connection Pool
|
||||||
|
db, err := rdb.OpenSqlite3DB(*dbPath)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
slog.Error(err.Error())
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
// Close db connection before exiting main.
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
tc, err := server.InitTemplateCache()
|
||||||
|
|
||||||
// Propagate build information to root package to share globally
|
// Propagate build information to root package to share globally
|
||||||
ratchet.Version = strings.TrimPrefix(version, "")
|
// ratchet.Version = strings.TrimPrefix(version, "")
|
||||||
ratchet.Commit = commit
|
// ratchet.Commit = commit
|
||||||
fmt.Fprintf(os.Stdout, "Version: %s\nCommit: %s\n", ratchet.Version, ratchet.Commit)
|
server := server.NewRatchetServer(logger, tc, db)
|
||||||
|
|
||||||
|
// START SERVING REQUESTS
|
||||||
|
slog.Debug("Herp dirp!")
|
||||||
|
slog.Info(fmt.Sprintf("Listening on http://%s:%s", *addr, *port))
|
||||||
|
//log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%s", *addr, *port), server))
|
||||||
|
// there is no log.Fatal equivalent. This is an approximation of the behavior
|
||||||
|
err = http.ListenAndServe(fmt.Sprintf("%s:%s", *addr, *port), server)
|
||||||
|
slog.Error(err.Error())
|
||||||
|
os.Exit(1)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
module git.runcible.io/learning/ratchet
|
module git.runcible.io/learning/ratchet
|
||||||
|
|
||||||
go 1.23.3
|
go 1.23.3
|
||||||
|
|
||||||
|
require github.com/mattn/go-sqlite3 v1.14.24
|
||||||
|
@ -0,0 +1,2 @@
|
|||||||
|
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
@ -1,4 +1,4 @@
|
|||||||
package ratchet
|
package apperror
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
@ -1,4 +1,4 @@
|
|||||||
package ratchet
|
package apperror
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
@ -0,0 +1,30 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OpenSqlite3DB is a wrapper
|
||||||
|
//
|
||||||
|
// TODO wtf dail uses context.Background(). Look into it more
|
||||||
|
func OpenSqlite3DB(dbPath string) (*sql.DB, error) {
|
||||||
|
full_database_path := "file:" + dbPath + "?cache=shared"
|
||||||
|
|
||||||
|
slog.Debug(fmt.Sprintf("Using database path: %s", full_database_path))
|
||||||
|
|
||||||
|
db, err := sql.Open("sqlite3", full_database_path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to open: %s", full_database_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = db.Ping()
|
||||||
|
if err != nil {
|
||||||
|
db.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return db, nil
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseLogLevel(levelStr string) slog.Level {
|
||||||
|
switch strings.ToUpper(levelStr) {
|
||||||
|
case "DEBUG":
|
||||||
|
return slog.LevelDebug
|
||||||
|
case "INFO":
|
||||||
|
return slog.LevelInfo
|
||||||
|
case "WARN":
|
||||||
|
return slog.LevelWarn
|
||||||
|
case "ERROR":
|
||||||
|
return slog.LevelError
|
||||||
|
default:
|
||||||
|
return slog.LevelInfo // Default level
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitLogggin initializes global structured logging for the entire application
|
||||||
|
func InitLogging(level string, addSource bool) *slog.Logger {
|
||||||
|
// Use os.Stderr
|
||||||
|
//
|
||||||
|
// Stderr is used for diagnostics and logging. Stdout is used for program
|
||||||
|
// output. Stderr also have greater likely hood of being seen if a programs
|
||||||
|
// output is being redirected.
|
||||||
|
parsedLogLevel := parseLogLevel(level)
|
||||||
|
loggerHandler := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: parsedLogLevel, AddSource: addSource})
|
||||||
|
logger := slog.New(loggerHandler)
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
return logger
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
// TODO migrate this to an apperror
|
||||||
|
var ErrNoRecord = errors.New("models: no record found")
|
@ -0,0 +1,65 @@
|
|||||||
|
// This file simply illustrates the use of transactions when performing operations on your sql db.
|
||||||
|
package model
|
||||||
|
|
||||||
|
import "database/sql"
|
||||||
|
|
||||||
|
type ExampleModel struct {
|
||||||
|
DB *sql.DB
|
||||||
|
// Prepared statements
|
||||||
|
//
|
||||||
|
// Prepared statements exist on database connections. Statement objects will therefore attempt to reuse the connection
|
||||||
|
// object from the connection pool that the statement was created on. If the connection was Closed or in use, it will
|
||||||
|
// be re-prepared on a new connection. This can increase load, create more connections than expected. Etc. Really its
|
||||||
|
// and optimization that you may not need to start looking at. When you do you have to look at load test data to get an
|
||||||
|
// idea for how it actually behaves.
|
||||||
|
//
|
||||||
|
// Another pattern is avoid recreated prepared statements on each invocation and instead attach them
|
||||||
|
// to the service instead. This doesn't really work well with transactions which have thier own tx.Prepare
|
||||||
|
// method
|
||||||
|
// InsertStmt *sql.Stmt
|
||||||
|
}
|
||||||
|
|
||||||
|
// func NewExampleModel(db *sql.DB) (*ExampleModel, error) {
|
||||||
|
// insertStmt, err := db.Prepare("INSERT INTO example (message, thought) VALUES (?, ?)")
|
||||||
|
// if err != nil {
|
||||||
|
// return nil, err
|
||||||
|
// }
|
||||||
|
// return &ExampleModel{DB: db, InsertStmt: insertStmt}, nil
|
||||||
|
// }
|
||||||
|
|
||||||
|
func (m *ExampleModel) ExampleTransaction() error {
|
||||||
|
// Calling the Begin() method on the connection pool creates a new sql.Tx
|
||||||
|
// object, which represents the in-progress database transaction.
|
||||||
|
tx, err := m.DB.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Defer a call to tx.Rollback() to ensure it is always called before the
|
||||||
|
// function returns. If the transaction succeeds it will be already be
|
||||||
|
// committed by the time tx.Rollback() is called, making tx.Rollback() a
|
||||||
|
// no-op. Otherwise, in the event of an error, tx.Rollback() will rollback
|
||||||
|
// the changes before the function returns.
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
// Call Exec() on the transaction, passing in your statement and any
|
||||||
|
// parameters. It's important to notice that tx.Exec() is called on the
|
||||||
|
// transaction object just created, NOT the connection pool. Although we're
|
||||||
|
// using tx.Exec() here you can also use tx.Query() and tx.QueryRow() in
|
||||||
|
// exactly the same way.
|
||||||
|
_, err = tx.Exec("INSERT INTO ...")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carry out another transaction in exactly the same way.
|
||||||
|
_, err = tx.Exec("UPDATE ...")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If there are no errors, the statements in the transaction can be committed
|
||||||
|
// to the database with the tx.Commit() method.
|
||||||
|
err = tx.Commit()
|
||||||
|
return err
|
||||||
|
}
|
@ -0,0 +1,147 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Snippet struct {
|
||||||
|
ID int
|
||||||
|
// Title string
|
||||||
|
// Content string
|
||||||
|
Title sql.NullString
|
||||||
|
Content sql.NullString
|
||||||
|
CreatedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
ExpiresAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnippetService struct {
|
||||||
|
DB *sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert inserts a new SnippetModel into the database
|
||||||
|
func (s *SnippetService) Insert(title, content string, expiresAt int) (int, error) {
|
||||||
|
slog.Debug(fmt.Sprintf("Inserting new snippet. Title: %s", title))
|
||||||
|
// Really don't prepare statements. There are a lot of gotcha's where they exist on the connection objects they were created. They can potentially
|
||||||
|
// recreate connections. It's an optimization you probably don't need at the moment.
|
||||||
|
stmt, err := s.DB.Prepare("INSERT INTO snippets (title, content, expires_at) VALUES ($1, $2, DATETIME(CURRENT_TIMESTAMP, '+' || $3 || ' DAY'))")
|
||||||
|
if err != nil {
|
||||||
|
slog.Debug("The prepared statement has an error")
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer stmt.Close()
|
||||||
|
|
||||||
|
// stmt.Exec returns a sql.Result. That also has access to the statement metadata
|
||||||
|
// use _ if you don't care about the result and only want to check the err.
|
||||||
|
|
||||||
|
// Exec will NOT reserve a connection. unlike db.Query which returns a sql.Rows that
|
||||||
|
// will hold on to a connection until .Close() is called.
|
||||||
|
res, err := stmt.Exec(title, content, expiresAt)
|
||||||
|
if err != nil {
|
||||||
|
slog.Debug("SQL DML statement returned an error.")
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the LastInsertId() method on the result to get the ID of our
|
||||||
|
// newly inserted record in the snippets table.
|
||||||
|
lastId, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
slog.Debug("An error occured when retrieving insert result id.")
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ID returned has the type int64, so we convert it to an int type
|
||||||
|
// before returning.
|
||||||
|
slog.Debug(fmt.Sprintf("Inserted new snippet. Snippet pk: %d", int(lastId)))
|
||||||
|
return int(lastId), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a specific Snippet by ID ignoring the record if expired.
|
||||||
|
func (s *SnippetService) Get(id int) (Snippet, error) {
|
||||||
|
|
||||||
|
stmt := `SELECT id, title, content, created_at, updated_at, expires_at FROM snippets
|
||||||
|
WHERE expires_at > CURRENT_TIMESTAMP AND id = $1`
|
||||||
|
|
||||||
|
// errors from DB.QueryRow() are deferred until Scan() is called.
|
||||||
|
// meaning you could also have used DB.QueryRow(...).Scan(...)
|
||||||
|
row := s.DB.QueryRow(stmt, id)
|
||||||
|
|
||||||
|
var snip Snippet
|
||||||
|
|
||||||
|
err := row.Scan(&snip.ID,
|
||||||
|
&snip.Title,
|
||||||
|
&snip.Content,
|
||||||
|
&snip.CreatedAt,
|
||||||
|
&snip.UpdatedAt,
|
||||||
|
&snip.ExpiresAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
slog.Debug("SQL DML statement returned an error.")
|
||||||
|
// Loop up the difference between errors.Is and errors.As
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return Snippet{}, ErrNoRecord
|
||||||
|
} else {
|
||||||
|
return Snippet{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return snip, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Latest retrieves up to latest 10 Snippets from the database.
|
||||||
|
func (s *SnippetService) Lastest() ([]Snippet, error) {
|
||||||
|
|
||||||
|
stmt := `SELECT id, title, content, created_at, updated_at, expires_at FROM snippets
|
||||||
|
WHERE expires_at > CURRENT_TIMESTAMP ORDER BY id DESC LIMIT 10`
|
||||||
|
|
||||||
|
rows, err := s.DB.Query(stmt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// We defer rows.Close() to ensure the sql.Rows resultset is
|
||||||
|
// always properly closed before the Latest() method returns. This defer
|
||||||
|
// statement should come *after* you check for an error from the Query()
|
||||||
|
// method. Otherwise, if Query() returns an error, you'll get a panic
|
||||||
|
// trying to close a nil resultset.
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var snippets []Snippet
|
||||||
|
|
||||||
|
// Use rows.Next to iterate through the rows in the resultset. This
|
||||||
|
// prepares the first (and then each subsequent) row to be acted on by the
|
||||||
|
// rows.Scan() method. If iteration over all the rows completes then the
|
||||||
|
// resultset automatically closes itself and frees-up the underlying
|
||||||
|
// database connection.
|
||||||
|
for rows.Next() {
|
||||||
|
var snip Snippet
|
||||||
|
|
||||||
|
err := rows.Scan(&snip.ID,
|
||||||
|
&snip.Title,
|
||||||
|
&snip.Content,
|
||||||
|
&snip.CreatedAt,
|
||||||
|
&snip.UpdatedAt,
|
||||||
|
&snip.ExpiresAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
snippets = append(snippets, snip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// When the rows.Next() loop has finished we call rows.Err() to retrieve any
|
||||||
|
// error that was encountered during the iteration. It's important to
|
||||||
|
// call this - don't assume that a successful iteration was completed
|
||||||
|
// over the whole resultset.
|
||||||
|
if err = rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return snippets, nil
|
||||||
|
}
|
@ -1,11 +1,15 @@
|
|||||||
package ratchet
|
package model
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.runcible.io/learning/ratchet/internal/apperror"
|
||||||
|
)
|
||||||
|
|
||||||
func TestUserValidation(t *testing.T) {
|
func TestUserValidation(t *testing.T) {
|
||||||
t.Run("user should return invalid", func(t *testing.T) {
|
t.Run("user should return invalid", func(t *testing.T) {
|
||||||
u := &User{}
|
u := &User{}
|
||||||
if ErrorCode(u.Validate()) != EINVALID {
|
if apperror.ErrorCode(u.Validate()) != apperror.EINVALID {
|
||||||
t.Errorf("User validation should have failed but passed instead.")
|
t.Errorf("User validation should have failed but passed instead.")
|
||||||
}
|
}
|
||||||
})
|
})
|
@ -0,0 +1,31 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
|
)
|
||||||
|
|
||||||
|
// serverError helper writes a log entry at Error level (including the request
|
||||||
|
// method and URI as attributes), then sends a generic 500 Internal Server Error
|
||||||
|
// response to the user.
|
||||||
|
func serverError(w http.ResponseWriter, r *http.Request, err error) {
|
||||||
|
logger := slog.Default()
|
||||||
|
var (
|
||||||
|
method = r.Method
|
||||||
|
uri = r.URL.RequestURI()
|
||||||
|
// Use debug.Stack() to get the stack trace. This returns a byte slice, which
|
||||||
|
// we need to convert to a string so that it's readable in the log entry.
|
||||||
|
trace = string(debug.Stack())
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.Error(err.Error(), "method", method, "uri", uri, "trace", trace)
|
||||||
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// clientError helper sends a specific status code and corresponding description
|
||||||
|
// to the user. We'll use this later in the book to send responses like 400 "Bad
|
||||||
|
// Request" when there's a problem with the request that the user sent
|
||||||
|
func clientError(w http.ResponseWriter, status int) {
|
||||||
|
http.Error(w, http.StatusText(status), status)
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.runcible.io/learning/ratchet/internal/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addRoutes(mux *http.ServeMux,
|
||||||
|
logger *slog.Logger,
|
||||||
|
tc *TemplateCache,
|
||||||
|
db *sql.DB,
|
||||||
|
snippetService *model.SnippetService) http.Handler {
|
||||||
|
|
||||||
|
// /{$} is used to prevent subtree path patterns from acting like a wildcard
|
||||||
|
// resulting in this route requiring an exact match on "/" only
|
||||||
|
// You can only include one HTTP method in a route pattern if you choose
|
||||||
|
// GET will match GET & HEAD http request methods
|
||||||
|
mux.Handle("GET /{$}", handleHome(logger, tc, snippetService))
|
||||||
|
mux.Handle("GET /snippet/view/{id}", handleSnippetView(logger, tc, snippetService))
|
||||||
|
mux.Handle("GET /snippet/create", handleSnippetCreateGet())
|
||||||
|
mux.Handle("POST /snippet/create", handleSnippetCreatePost(logger, tc, snippetService))
|
||||||
|
// mux.Handle("/something", handleSomething(logger, config))
|
||||||
|
// mux.Handle("/healthz", handleHealthzPlease(logger))
|
||||||
|
// mux.Handle("/", http.NotFoundHandler())
|
||||||
|
return mux
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.runcible.io/learning/ratchet/internal/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RatchetServer struct {
|
||||||
|
http.Handler
|
||||||
|
|
||||||
|
logger *slog.Logger
|
||||||
|
templateCache *TemplateCache
|
||||||
|
//Services used by HTTP routes
|
||||||
|
snippetService *model.SnippetService
|
||||||
|
UserService model.UserService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRatchetServer(logger *slog.Logger, tc *TemplateCache, db *sql.DB) *RatchetServer {
|
||||||
|
rs := new(RatchetServer)
|
||||||
|
rs.logger = logger
|
||||||
|
rs.snippetService = &model.SnippetService{DB: db}
|
||||||
|
|
||||||
|
rs.templateCache = tc
|
||||||
|
// TODO implement middleware that disables directory listings
|
||||||
|
fileServer := http.FileServer(http.Dir("./ui/static/"))
|
||||||
|
router := http.NewServeMux()
|
||||||
|
|
||||||
|
// Subtree pattern for static assets
|
||||||
|
router.Handle("GET /static/", http.StripPrefix("/static/", fileServer))
|
||||||
|
|
||||||
|
// Mux Router implements the Handler interface. AKA it has a ServeHTTP receiver.
|
||||||
|
// SEE we can really clean things up by moving this into routes.go and handlers.go
|
||||||
|
wrappedMux := addRoutes(router, rs.logger, rs.templateCache, db, rs.snippetService)
|
||||||
|
rs.Handler = CommonHeaderMiddleware(wrappedMux)
|
||||||
|
rs.Handler = RequestLoggingMiddleware(rs.Handler, logger)
|
||||||
|
rs.Handler = RecoveryMiddleware(rs.Handler)
|
||||||
|
return rs
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS snippets;
|
@ -0,0 +1,20 @@
|
|||||||
|
PRAGMA foreign_keys=1;
|
||||||
|
CREATE TABLE snippets (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT,
|
||||||
|
content TEXT,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
expires_at DATETIME NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Add an index on the created column.
|
||||||
|
CREATE INDEX idx_snippets_created ON snippets(created_at);
|
||||||
|
|
||||||
|
-- Add a trigger to keep timestamp updated.
|
||||||
|
CREATE TRIGGER snippet_update_timestamp
|
||||||
|
AFTER UPDATE ON snippets
|
||||||
|
FOR EACH ROW
|
||||||
|
BEGIN
|
||||||
|
UPDATE snippets SET updated_at = CURRENT_TIMESTAMP WHERE id = OLD.id;
|
||||||
|
END;
|
@ -0,0 +1,24 @@
|
|||||||
|
{{define "base" -}}
|
||||||
|
<!doctype html>
|
||||||
|
<html lang='en'>
|
||||||
|
<head>
|
||||||
|
<meta charset='utf-8'>
|
||||||
|
<title>{{template "title" .}}</title>
|
||||||
|
<link rel='stylesheet' href='/static/css/main.css'>
|
||||||
|
<link rel='shortcut icon' href='/static/img/favicon.ico' type='image/x-icon'>
|
||||||
|
<!-- Also link to some fonts hosted by Google -->
|
||||||
|
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700'>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<h1><a href='/'>Ratchet</a></h1>
|
||||||
|
</header>
|
||||||
|
{{template "nav" .}}
|
||||||
|
<main>
|
||||||
|
{{template "main" .}}
|
||||||
|
</main>
|
||||||
|
<footer>Powered by <a href='https://golang.org/'>Go</a> in {{ .CurrentYear }}</footer>
|
||||||
|
<script src='/static/js/main.js' type='text/javascript'></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
{{end}}
|
@ -0,0 +1,23 @@
|
|||||||
|
{{define "title"}}Home{{end}}
|
||||||
|
|
||||||
|
{{define "main" -}}
|
||||||
|
{{ if .Snippets}}
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th>Title</th>
|
||||||
|
<th>Created</th>
|
||||||
|
<th>ID</th>
|
||||||
|
</tr>
|
||||||
|
{{range .Snippets}}
|
||||||
|
<tr>
|
||||||
|
<td><a href='/snippet/view/{{.ID}}'>{{.Title.String}}</a></td>
|
||||||
|
<!-- this is an example of pipelineing instead of function call -->
|
||||||
|
<td>{{.CreatedAt | humanDate }}</td>
|
||||||
|
<td>#{{.ID}}</td>
|
||||||
|
</tr>
|
||||||
|
{{end}}
|
||||||
|
</table>
|
||||||
|
{{else}}
|
||||||
|
<p>There's nothing to see yet!</p>
|
||||||
|
{{end}}
|
||||||
|
{{- end -}}
|
@ -0,0 +1,19 @@
|
|||||||
|
{{define "title"}}Snippet #{{.Snippet.ID}}{{end}}
|
||||||
|
|
||||||
|
{{define "main"}}
|
||||||
|
{{ with .Snippet }}
|
||||||
|
<!-- This is a comment that will be stripped out by html/template -->
|
||||||
|
<div class="snippet">
|
||||||
|
<div class="metadata">
|
||||||
|
<strong>{{.Title.String }}</strong>
|
||||||
|
<span>#{{.ID}}</span>
|
||||||
|
</div>
|
||||||
|
<pre><code>{{.Content.String }}</code></pre>
|
||||||
|
<div class="metadata">
|
||||||
|
<time>Created: {{ humanDate .CreatedAt}}</time>
|
||||||
|
<time>Expires: {{ humanDate .ExpiresAt}}</time>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{ end }}
|
||||||
|
{{end}}
|
||||||
|
|
@ -0,0 +1,5 @@
|
|||||||
|
{{define "nav" -}}
|
||||||
|
<nav>
|
||||||
|
<a href='/'>Home</a>
|
||||||
|
</nav>
|
||||||
|
{{- end}}
|
@ -0,0 +1,313 @@
|
|||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
font-size: 18px;
|
||||||
|
font-family: "Ubuntu Mono", monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
line-height: 1.5;
|
||||||
|
background-color: #F1F3F6;
|
||||||
|
color: #34495E;
|
||||||
|
overflow-y: scroll;
|
||||||
|
}
|
||||||
|
|
||||||
|
header, nav, main, footer {
|
||||||
|
padding: 2px calc((100% - 800px) / 2) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
margin-top: 54px;
|
||||||
|
margin-bottom: 54px;
|
||||||
|
min-height: calc(100vh - 345px);
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 a {
|
||||||
|
font-size: 36px;
|
||||||
|
font-weight: bold;
|
||||||
|
background-image: url("/static/img/logo.png");
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-position: 0px 0px;
|
||||||
|
height: 36px;
|
||||||
|
padding-left: 50px;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 a:hover {
|
||||||
|
text-decoration: none;
|
||||||
|
color: #34495E;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
font-size: 22px;
|
||||||
|
margin-bottom: 36px;
|
||||||
|
position: relative;
|
||||||
|
top: -9px;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: #62CB31;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
color: #4EB722;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea, input:not([type="submit"]) {
|
||||||
|
font-size: 18px;
|
||||||
|
font-family: "Ubuntu Mono", monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
header {
|
||||||
|
background-image: -webkit-linear-gradient(left, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
|
||||||
|
background-image: -moz-linear-gradient(left, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
|
||||||
|
background-image: -ms-linear-gradient(left, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
|
||||||
|
background-image: linear-gradient(to right, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
|
||||||
|
background-size: 100% 6px;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
border-bottom: 1px solid #E4E5E7;
|
||||||
|
overflow: auto;
|
||||||
|
padding-top: 33px;
|
||||||
|
padding-bottom: 27px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
header a {
|
||||||
|
color: #34495E;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav {
|
||||||
|
border-bottom: 1px solid #E4E5E7;
|
||||||
|
padding-top: 17px;
|
||||||
|
padding-bottom: 15px;
|
||||||
|
background: #F7F9FA;
|
||||||
|
height: 60px;
|
||||||
|
color: #6A6C6F;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav a {
|
||||||
|
margin-right: 1.5em;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav form {
|
||||||
|
display: inline-block;
|
||||||
|
margin-left: 1.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav div {
|
||||||
|
width: 50%;
|
||||||
|
float: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav div:last-child {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav div:last-child a {
|
||||||
|
margin-left: 1.5em;
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav a.live {
|
||||||
|
color: #34495E;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav a.live:hover {
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
nav a.live:after {
|
||||||
|
content: '';
|
||||||
|
display: block;
|
||||||
|
position: relative;
|
||||||
|
left: calc(50% - 7px);
|
||||||
|
top: 9px;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
background: #F7F9FA;
|
||||||
|
border-left: 1px solid #E4E5E7;
|
||||||
|
border-bottom: 1px solid #E4E5E7;
|
||||||
|
-moz-transform: rotate(45deg);
|
||||||
|
-webkit-transform: rotate(-45deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
a.button, input[type="submit"] {
|
||||||
|
background-color: #62CB31;
|
||||||
|
border-radius: 3px;
|
||||||
|
color: #FFFFFF;
|
||||||
|
padding: 18px 27px;
|
||||||
|
border: none;
|
||||||
|
display: inline-block;
|
||||||
|
margin-top: 18px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.button:hover, input[type="submit"]:hover {
|
||||||
|
background-color: #4EB722;
|
||||||
|
color: #FFFFFF;
|
||||||
|
cursor: pointer;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
form div {
|
||||||
|
margin-bottom: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
form div:last-child {
|
||||||
|
border-top: 1px dashed #E4E5E7;
|
||||||
|
}
|
||||||
|
|
||||||
|
form input[type="radio"] {
|
||||||
|
margin-left: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
form input[type="text"], form input[type="password"], form input[type="email"] {
|
||||||
|
padding: 0.75em 18px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
form input[type=text], form input[type="password"], form input[type="email"], textarea {
|
||||||
|
color: #6A6C6F;
|
||||||
|
background: #FFFFFF;
|
||||||
|
border: 1px solid #E4E5E7;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
form label {
|
||||||
|
display: inline-block;
|
||||||
|
margin-bottom: 9px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: #C0392B;
|
||||||
|
font-weight: bold;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error + textarea, .error + input {
|
||||||
|
border-color: #C0392B !important;
|
||||||
|
border-width: 2px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
padding: 18px;
|
||||||
|
width: 100%;
|
||||||
|
height: 266px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
background: none;
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
color: #62CB31;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
color: #4EB722;
|
||||||
|
text-decoration: underline;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet {
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
border: 1px solid #E4E5E7;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet pre {
|
||||||
|
padding: 18px;
|
||||||
|
border-top: 1px solid #E4E5E7;
|
||||||
|
border-bottom: 1px solid #E4E5E7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet .metadata {
|
||||||
|
background-color: #F7F9FA;
|
||||||
|
color: #6A6C6F;
|
||||||
|
padding: 0.75em 18px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet .metadata span {
|
||||||
|
float: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet .metadata strong {
|
||||||
|
color: #34495E;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet .metadata time {
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet .metadata time:first-child {
|
||||||
|
float: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet .metadata time:last-child {
|
||||||
|
float: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
div.flash {
|
||||||
|
color: #FFFFFF;
|
||||||
|
font-weight: bold;
|
||||||
|
background-color: #34495E;
|
||||||
|
padding: 18px;
|
||||||
|
margin-bottom: 36px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
div.error {
|
||||||
|
color: #FFFFFF;
|
||||||
|
background-color: #C0392B;
|
||||||
|
padding: 18px;
|
||||||
|
margin-bottom: 36px;
|
||||||
|
font-weight: bold;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
table {
|
||||||
|
background: white;
|
||||||
|
border: 1px solid #E4E5E7;
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
td, th {
|
||||||
|
text-align: left;
|
||||||
|
padding: 9px 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
th:last-child, td:last-child {
|
||||||
|
text-align: right;
|
||||||
|
color: #6A6C6F;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr {
|
||||||
|
border-bottom: 1px solid #E4E5E7;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr:nth-child(2n) {
|
||||||
|
background-color: #F7F9FA;
|
||||||
|
}
|
||||||
|
|
||||||
|
footer {
|
||||||
|
border-top: 1px solid #E4E5E7;
|
||||||
|
padding-top: 17px;
|
||||||
|
padding-bottom: 15px;
|
||||||
|
background: #F7F9FA;
|
||||||
|
height: 60px;
|
||||||
|
color: #6A6C6F;
|
||||||
|
text-align: center;
|
||||||
|
}
|
Binary file not shown.
After Width: | Height: | Size: 1.1 KiB |
Binary file not shown.
After Width: | Height: | Size: 1.0 KiB |
@ -0,0 +1,8 @@
|
|||||||
|
var navLinks = document.querySelectorAll("nav a");
|
||||||
|
for (var i = 0; i < navLinks.length; i++) {
|
||||||
|
var link = navLinks[i]
|
||||||
|
if (link.getAttribute('href') == window.location.pathname) {
|
||||||
|
link.classList.add("live");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue