From 83004c3098465dea85aecfd48d1a8c241df2ccf3 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Fri, 8 May 2026 22:49:46 -0400 Subject: [PATCH] init util library --- go.mod | 3 +++ util.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 go.mod create mode 100644 util.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6d2f6ac --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.yetaga.in/alazyreader/util + +go 1.26.3 diff --git a/util.go b/util.go new file mode 100644 index 0000000..cb47cec --- /dev/null +++ b/util.go @@ -0,0 +1,47 @@ +package util + +import ( + "encoding/json" + "fmt" + "log" + "net/http" +) + +// must panics if err is not nil +func must[T any](t T, err error) T { + if err != nil { + panic(err) + } + return t +} + +// attempt discards the value from a (value, err) function +func attempt[T any](_ T, err error) error { + return err +} + +// try discards the error from a (value, err) function +func try[T any](t T, _ error) T { + return t +} + +// writeJSON encodes the provided value as json and responds 200 +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(v); err != nil { + log.Printf("writeJSON error: %v", err) + } +} + +// writeError logs and responds with the given formatted error message as `{"error": msg}` +func writeError(w http.ResponseWriter, code int, msg string, args ...any) { + errMsg := fmt.Sprintf(msg, args...) + log.Println(errMsg) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + json.NewEncoder(w).Encode(struct { + Error string `json:"error"` + }{ + Error: errMsg, + }) +}