Skip to content

Instantly share code, notes, and snippets.

@alexedwards
alexedwards / gist:7838faf5f4936e2024657d6e306723e1
Last active June 30, 2025 14:28
Custom command-line flags with flag.Value and encoding.TextUnmarshaler
package main
// This example shows how to create a custom command-line flag by implementing
// the flag.Value interface. The flag accepts a comma-separated list of values
// and stores the contents in a DomainList type, which has the underlying type
// []string.
//
// Use it like:
// go run main.go -domains="example.com, example.org"
@alexedwards
alexedwards / main.go
Created May 10, 2025 09:41
httprouter example
func main() {
router := httprouter.New()
router.HandlerFunc("GET", "/", indexGet)
router.HandlerFunc("POST", "/", indexPost)
err := http.ListenAndServe(":3000", router)
log.Fatal(err)
}
func TestRouter(t *testing.T) {
used := ""
mw1 := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
used += "1"
next.ServeHTTP(w, r)
})
}
func TestChain(t *testing.T) {
used := ""
mw1 := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
used += "1"
next.ServeHTTP(w, r)
})
}
mux := http.NewServeMux()
mux.Handle("/", recoverMiddleware(requestIDMiddleware(loggingMiddleware(http.HandlerFunc(homeHandler)))))
mux.Handle("/about", recoverMiddleware(requestIDMiddleware(loggingMiddleware(http.HandlerFunc(aboutHandler)))))
mux.Handle("/admin", recoverMiddleware(requestIDMiddleware(loggingMiddleware(authenticationMiddleware(adminRoleCheckMiddleware(http.HandlerFunc(adminDashboardHandler)))))))
func (app *application) rateLimit(next http.Handler) http.Handler {
if !app.config.limiter.enabled {
return next
}
type client struct {
limiter *rate.Limiter
lastSeen time.Time
}
.
├── cmd
│   ├── cli
│   └── web
├── internal
│   ├── database
│   ├── request
│   ├── response
│   ├── templatefuncs
│   ├── validator
@alexedwards
alexedwards / cache.go
Last active May 1, 2025 00:58
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 / go-update
Created November 22, 2023 14:53
Bash script for updating Go
#!/bin/bash
# Check if the version argument is provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <go_version>"
exit 1
fi
# Version number provided as an argument
version="$1"
@alexedwards
alexedwards / go-update.sh
Last active November 2, 2023 08:59
Bash script to update Go on linux-amd64 (generated using Chat GPT)
#!/bin/bash
# Check if the version argument is provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <go_version>"
exit 1
fi
# Version number provided as an argument
version="$1"