init util library
This commit is contained in:
@@ -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,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user