htlog

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2024 License: MIT Imports: 4 Imported by: 1

README

gregoryv/htlog provides a log middleware for Go http.Handler

Quick start

 go get github.com/gregoryv/htlog

then use it

 var h http.Handler

 // use default middleware
 router := htlog.UseDefault(h)

Depending on the configured Println a request can be logged as

2024/11/28 20:25:00 GET /?password=... 200 7.544µs

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultClean = QueryHide("access_token", "password", "secret")

DefaultClean is used by UseDefault constructor.

Functions

func QueryHide

func QueryHide(words ...string) func(u *url.URL) string

QueryHide returns a cleanup func for use in Middleware. Each word matching a query parameter is replaced with a "..." value.

func UseDefault added in v0.2.0

func UseDefault(next http.Handler) http.HandlerFunc

UseDefault middleware logging all requests using log.Println.

Types

type Middleware

type Middleware struct {
	// Println is used to print request method, path, response status
	// and duration
	Println func(...any)

	// Clean is used to hide query parameters if needed
	Clean func(u *url.URL) string
}
Example
package main

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/gregoryv/htlog"
)

func main() {
	// define a custom
	customLog := htlog.Middleware{
		Println: func(a ...any) {
			fmt.Println(a...)
		},
		Clean: func(u *url.URL) string {
			return u.Path
		},
	}

	http.Handle("/", customLog.Use(serveHello()))
	http.ListenAndServe(":8080", nil)
}

func serveHello() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello, world!")
	}
}

func (*Middleware) Use

func (m *Middleware) Use(next http.Handler) http.HandlerFunc

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL