Compare commits

..

9 commits
v1.8.0 ... main

Author SHA1 Message Date
9870d87d41
Add sliceutils.ContainsFunc 2025-04-11 12:38:41 +02:00
15887d9d2e
Add builder for Logging middleware
Builder offers option to add extra fields to log messages
2025-04-11 10:44:50 +02:00
e8aa16622b
Add generic math abs 2025-04-10 14:36:51 +02:00
4612ee993e
BREAKING CHANGE: Rename http module to webutils 2025-04-09 13:57:01 +02:00
9b6664399f
Fix header write order
Headers need to be written before status code
2025-04-09 13:11:12 +02:00
2bc73d2262
Add ProblemDetails support and deprecate HttpErr 2025-04-09 09:51:36 +02:00
0a22727d46
BREAKING CHANGE: Update ConfigureLogging
Now takes a writer as additional output next to stderr
to write logs to
2025-04-08 17:09:50 +02:00
0eafc6806b
fix(logrotate): Now creates dir needed
If the directory containing the target log file doesn't exist, try and
create the directory first
2025-03-24 17:28:38 +01:00
afcc54c831
BREAKING CHANGE: Remodelled logging setup
- other.ConfigureLoggingFromCliArgs has been renamed to
  other.ConfigureLogging
- The -logfile cli argument has been removed and replaced with an
  argument to other.ConfigureLogging. This argument takes a pointer to a
  string or nil. If it's a valid pointer, it's used just like the
  -logfile cli flag before
- The logfile, if requested via the previously mentioned parameter, can
  now be rotated by calling the returned function. If no logfile is
  specified, the returned function does nothing
2025-03-24 08:39:04 +01:00
9 changed files with 149 additions and 30 deletions

View file

@ -1,4 +1,4 @@
package http
package webutils
import (
"net/http"

View file

@ -1,4 +1,4 @@
package http
package webutils
import (
"context"

View file

@ -1,6 +1,7 @@
package http
package webutils
import (
"encoding/json"
"fmt"
"net/http"
)
@ -9,8 +10,63 @@ import (
// The error will have the given return code `code`
// and a json encoded body with the field "id" set to `errId`
// and a field "message" set to the `message`
//
// Deprecated: Use ProblemDetails or ProblemDetailsStatusOnly instead
func HttpErr(w http.ResponseWriter, errId int, message string, code int) {
w.WriteHeader(code)
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, "{\"id\": %d, \"message\": \"%s\"}", errId, message)
}
// Write an RFC 9457 compliant problem details response
// If details is not nil, it will be included.
// If extras is not nil, each key-value pair will be included at
// the root layer.
// Keys in extras that would overwrite the default elements will be ignored.
// Those would be "type", "status", "title" and "detail"
func ProblemDetails(
w http.ResponseWriter,
statusCode int,
errorType string,
errorTitle string,
details *string,
extras map[string]any,
) {
w.Header().Add("Content-Type", "application/problem+json")
w.WriteHeader(statusCode)
data := map[string]any{
"type": errorType,
"status": statusCode,
"title": errorTitle,
}
if details != nil {
data["detail"] = *details
}
if extras != nil {
for k, v := range extras {
if _, ok := data[k]; ok {
// Don't overwrite default fields
continue
}
data[k] = v
}
}
enc := json.NewEncoder(w)
enc.Encode(data)
}
// Write a simple problem details response.
// It only provides the status code, as defined in RFC 9457, section 4.2.1
func ProblemDetailsStatusOnly(w http.ResponseWriter, statusCode int) {
w.Header().Add("Content-Type", "application/problem+json")
w.WriteHeader(statusCode)
data := map[string]any{
"type": "about:blank",
"title": http.StatusText(statusCode),
"status": statusCode,
"reference": "RFC 9457",
}
enc := json.NewEncoder(w)
enc.Encode(data)
}

17
http/json.go Normal file
View file

@ -0,0 +1,17 @@
package webutils
import (
"encoding/json"
"fmt"
"net/http"
)
func SendJson(w http.ResponseWriter, data any) error {
encoded, err := json.Marshal(data)
if err != nil {
return err
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, string(encoded))
return nil
}

View file

@ -1,4 +1,4 @@
package http
package webutils
import (
"net/http"
@ -9,6 +9,33 @@ import (
"github.com/rs/zerolog/log"
)
func BuildLoggingMiddleware(extras map[string]string) HandlerBuilder {
return func(h http.Handler) http.Handler {
return ChainMiddlewares(h,
hlog.NewHandler(log.Logger),
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
if strings.HasPrefix(r.URL.Path, "/assets") {
return
}
logger := hlog.FromRequest(r).Info().
Str("method", r.Method).
Stringer("url", r.URL).
Int("status", status).
Int("size", size).
Dur("duration", duration)
for k, v := range extras {
logger = logger.Str(k, v)
}
logger.Send()
}),
hlog.RemoteAddrHandler("ip"),
hlog.UserAgentHandler("user_agent"),
hlog.RefererHandler("referer"),
hlog.RequestIDHandler("req_id", "Request-Id"),
)
}
}
func LoggingMiddleware(handler http.Handler) http.Handler {
return ChainMiddlewares(handler,
hlog.NewHandler(log.Logger),

View file

@ -4,6 +4,7 @@ package logrotate
import (
"os"
"path"
"sync"
"time"
)
@ -15,13 +16,13 @@ type RotateWriter struct {
}
// Make a new RotateWriter. Return nil if error occurs during setup.
func New(filename string) *RotateWriter {
func New(filename string) (*RotateWriter, error) {
w := &RotateWriter{filename: filename}
err := w.Rotate()
if err != nil {
return nil
return nil, err
}
return w
return w, nil
}
// Write satisfies the io.Writer interface.
@ -54,6 +55,13 @@ func (w *RotateWriter) Rotate() (err error) {
}
// Create a file.
dir := path.Dir(w.filename)
_, err = os.Stat(dir)
if err != nil {
if err = os.Mkdir(dir, os.ModeDir); err != nil {
return
}
}
w.fp, err = os.Create(w.filename)
return
}

13
math/math.go Normal file
View file

@ -0,0 +1,13 @@
package mathutils
type SignedNumber interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64
}
func Abs[T SignedNumber](num T) T {
if num > 0 {
return num
} else {
return num * -1
}
}

View file

@ -12,7 +12,6 @@ import (
var cliFlagLogLevel = "info"
var cliFlagLogJson = false
var cliFlagLogFile = ""
func SetupFlags() {
flag.StringVar(
@ -27,16 +26,13 @@ func SetupFlags() {
false,
"Log json objects to stderr instead of nicely formatted ones",
)
flag.StringVar(
&cliFlagLogFile,
"logfile",
"",
"Set the file to write json formatted log messages to",
)
}
func ConfigureLoggingFromCliArgs() {
configOutputs()
// Configure logging. Utilises the flags setup in [SetupFlags].
// If logWriter is not nil, will also write logs, as json objects,
// to the given writer
func ConfigureLogging(logWriter io.Writer) {
configOutputs(logWriter)
configLevel()
}
@ -60,22 +56,14 @@ func configLevel() {
log.Info().Str("new-level", cliFlagLogLevel).Msg("New logging level set")
}
func configOutputs() {
extraLogWriters := []io.Writer{}
if cliFlagLogFile != "" {
file, err := os.OpenFile(cliFlagLogFile, os.O_APPEND|os.O_CREATE, os.ModeAppend)
if err != nil {
log.Fatal().Err(err).Msg("Failed to open log file")
}
// NOTE: Technically this leaks a file handle
// Shouldn't matter though since the log file should be open until the very end
// Sooooo, eh. Don't care about adding an elaborate system to close the file at the very end.
// OS will do that anyway
extraLogWriters = append(extraLogWriters, file)
func configOutputs(logWriter io.Writer) {
console := zerolog.ConsoleWriter{Out: os.Stderr}
extraLogWriters := []io.Writer{console}
if logWriter != nil {
extraLogWriters = append(extraLogWriters, logWriter)
}
if !cliFlagLogJson {
console := zerolog.ConsoleWriter{Out: os.Stderr}
log.Logger = zerolog.New(zerolog.MultiLevelWriter(append([]io.Writer{console}, extraLogWriters...)...)).
log.Logger = zerolog.New(zerolog.MultiLevelWriter(extraLogWriters...)).
With().
Timestamp().
Logger()
@ -84,4 +72,5 @@ func configOutputs() {
append([]io.Writer{log.Logger}, extraLogWriters...)...,
)).With().Timestamp().Logger()
}
return
}

View file

@ -81,6 +81,15 @@ func Contains[T comparable](a []T, b T) bool {
return false
}
func ContainsFunc[T any](a []T, f func(t T) bool) bool {
for _, v := range a {
if f(v) {
return true
}
}
return false
}
func Compact[T any](a []T, compactor func(acc T, next T) T) T {
var acc T
for _, v := range a {