Skip to content

Instantly share code, notes, and snippets.

@alexedwards
alexedwards / Makefile
Last active April 26, 2024 17:21
Boilerplate Makefile for Go projects
# Change these variables as necessary.
MAIN_PACKAGE_PATH := ./cmd/example
BINARY_NAME := example
# ==================================================================================== #
# HELPERS
# ==================================================================================== #
## help: print this help message
.PHONY: help
.
├── books
│   ├── handlers.go
│   └── models.go
├── config
│   └── db.go
└── main.go
@alexedwards
alexedwards / main_test.go
Last active April 17, 2024 03:46
MaxOpenConns benchmark
package main
import (
"database/sql"
"testing"
"time"
_ "github.com/lib/pq"
)
@alexedwards
alexedwards / _tree
Created October 27, 2020 07:40
Config package with global variable
.
├── config
│ └── config.go
├── go.mod
├── go.sum
├── main.go
└── models
└── books
└── books.go
@alexedwards
alexedwards / cache.go
Last active April 10, 2024 00:53
Generic in-memory cache implementation in Go
package cache
import (
"sync"
"time"
)
// Cache is a basic in-memory key-value cache implementation.
type Cache[K comparable, V any] struct {
items map[K]V // The map storing key-value pairs.
@alexedwards
alexedwards / gist:dc3145c8e2e6d2fd6cd9
Last active April 9, 2024 05:30
Example of working with Go's database/sql and NULL fields
CREATE TABLE books (
isbn char(14) NOT NULL,
title varchar(255),
author varchar(255),
price decimal(5,2)
);
INSERT INTO books (isbn, title, author, price) VALUES
('978-1503261969', 'Emma', 'Jayne Austen', 9.44),
('978-1514274873', 'Journal of a Soldier', NULL, 5.49),
@alexedwards
alexedwards / _tree
Created October 27, 2020 07:52
Dependency injection via closure (handlers in multiple packages)
.
├── go.mod
├── handlers
│ ├── books
│ │ └── books.go
│ └── env.go
├── main.go
└── models
└── models.go
@alexedwards
alexedwards / Makefile
Created May 2, 2023 16:04
Makefile targets for working with sqlite
## db/connect: create to the local database
.PHONY: db/connect
db/connect:
sqlite3 db.sqlite
## db/migrations/new name=$1: create a new migration
.PHONY: db/migrations/new
db/migrations/new:
go run -tags 'sqlite3' github.com/golang-migrate/migrate/v4/cmd/migrate@latest create -seq -ext=.sql -dir=./resources/migrations ${name}
@alexedwards
alexedwards / main.go
Last active March 11, 2024 10:20
Password hashing and verification with Argon2id
package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"log"
"strings"
@alexedwards
alexedwards / main.go
Last active February 19, 2024 07:16
JSON encoding benchmarks
package main
import (
"encoding/json"
"net/http"
)
func main() {}
func healthcheckHandlerEncoder(w http.ResponseWriter, r *http.Request) {