Skip to content

Instantly share code, notes, and snippets.

@alexedwards
alexedwards / handler.go
Created September 6, 2026 18:34
Example of streaming JSON objects in a HTTP response
func (app *application) exampleHandler(w http.ResponseWriter, r *http.Request) {
enc := jsontext.NewEncoder(w)
rc := http.NewResponseController(w)
w.Header().Set("Content-Type", "application/x-ndjson")
for i := range 5 {
data := map[string]int{
"count": i,
}
func (app *application) readJSONArray(w http.ResponseWriter, r *http.Request, dst any) error {
return app.readJSON(w, r, dst, jsontext.KindBeginArray)
}
func (app *application) readJSONObject(w http.ResponseWriter, r *http.Request, dst any) error {
return app.readJSON(w, r, dst, jsontext.KindBeginObject)
}
func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst any, expectedFirstToken jsontext.Kind) error {
err := json.UnmarshalRead(r.Body, dst)
@alexedwards
alexedwards / main.go
Last active August 13, 2026 17:19
JSON decoding benchmarks
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"io"
"net/http"
)
var input struct {
@alexedwards
alexedwards / main.go
Created August 7, 2026 16:29
JSON encoding benchmarks
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"net/http"
)
var data = map[string]string{
"status": "available",
@alexedwards
alexedwards / main.go
Last active August 13, 2026 16:09
JSON encoding benchmarks
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"net/http"
)
var data = map[string]string{
"status": "available",
@alexedwards
alexedwards / logger.go
Last active April 14, 2026 08:08
Levelled and structure logger using log package only
package logger
import (
"fmt"
"log"
"os"
"strings"
)
type Level int
import (
"strings"
"testing"
"golang.org/x/net/html"
"github.com/andybalholm/cascadia"
)
func containsHTMLNode(t *testing.T, htmlBody, cssSelector string) bool {
doc, err := html.Parse(strings.NewReader(htmlBody))
if err != nil {
@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)
})
}