httpz

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2025 License: MIT Imports: 9 Imported by: 1

README

Note that httpz is still unstable.

简体中文

httpz is a lightweight library built on top of net/http version 1.22. It takes inspiration from Echo's centralized error handling and chi's adherence to the standard library. The problem it aims to solve is that while net/http version 1.22 enhances routing, its functionality is not as user-friendly as other frameworks like Echo and chi.

It functions more like a set of helper functions for net/http rather than a full-fledged web framework. Thanks to net/http handling most of the heavy lifting, httpz has minimal code.

It has the following features:

  1. Centralized error handling

  2. Convenient route grouping, where you can set middleware for each group or for individual routes.

  3. Complete compatibility with the standard library.

Quick Start

Installation

To install httpz, Go 1.22 or higher is required.

go get github.com/aeilang/httpz

Hello World

import (
	"log/slog"
	"net/http"
	"os"

	"github.com/aeilang/httpz"
	"github.com/aeilang/httpz/middleware"
)

func main() {
	// Create a new mux
	mux := httpz.NewServeMux()

	// add logger middleware, it 's copy from chi/middleware
	mux.Use(middleware.Logger)

	// register a GET /hello route
	// GET /hello
	mux.Get("/hello", func(w http.ResponseWriter, r *http.Request) error {
		// rw is a helper responsewriter to send response
		rw := httpz.NewHelperRW(w)
		return rw.String(http.StatusOK, "hello httpz")
	})
  
  // just like net/http's ServerMux
	http.ListenAndServe(":8080", mux)
}

the middleware package if copied from chi/middleware.

The complete example can be found in the example directory

grouping:

// group return a new *ServeMux base on path "/api/"
api := mux.Group("/api/")

// register GET /well route for api group.
// GET /api/well
api.Get("/well", func(w http.ResponseWriter, r *http.Request) error {	
	rw := httpz.NewHelperRW(w)
	return rw.JSON(http.StatusOK, httpz.Map{
		"data": "well well httpz",
	})
})

Centralized error handling

// The parent mux of v2 is api,
// allowing you to group routes infinitely.
v2 := api.Group("/v2/")

// GET /api/v2/hello
v2.Get("/hello", func(w http.ResponseWriter, r *http.Request) error {
	// centralized error handling in tests
	return httpz.NewHTTPError(http.StatusBadRequest, "bad reqeust")
})

// GET /api/v2/well/randomID
v2.Get("/well/{id}", func(w http.ResponseWriter, r *http.Request) error {
	id := r.PathValue("id")
	
	// the default error handler just trigered by *HTTPError
	// another error will just be logged,not sending response.
	return errors.New("nomal error")
})

You can customize the error handling function:

// Create a new mux
mux := httpz.NewServeMux()

mux.ErrHandler = func(err error, w http.ResponseWriter) {
  // for example:
	http.Error(w, err.Error(), http.StatusInternalServerError)
}

The default error handling function is as follows:

// default centrailzed error handling function.
// only the *HTTPError will triger error response.
func DefaultErrHandlerFunc(err error, w http.ResponseWriter) {
	if he, ok := err.(*HTTPError); ok {
		rw := NewHelperRW(w)
		rw.JSON(he.StatusCode, Map{"msg": he.Msg})
	} else {
		slog.Error(err.Error())
	}
}

Feel free to contribute your code.

  • test

  • example

  • middleware

  • other

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultErrHandlerFunc

func DefaultErrHandlerFunc(err error, w http.ResponseWriter)

default centrailzed error handling function. only the *HTTPError will triger error response.

Types

type ErrHandlerFunc

type ErrHandlerFunc func(err error, w http.ResponseWriter)

centralized error handling function type.

type HTTPError

type HTTPError struct {
	StatusCode int
	Msg        string
	// contains filtered or unexported fields
}

The custom Error type is inspired by Echo.

func NewHTTPError

func NewHTTPError(statusCode int, msg string, errs ...error) *HTTPError

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

HandlerFunc defines the function signature for a handler. It returns an error, which is used for centralized error handling.

func Adator

func Adator(fn func(w http.ResponseWriter, r *http.Request)) HandlerFunc

type HelperResponseWriter

type HelperResponseWriter struct {
	http.ResponseWriter
}

A built-in type, used only to record the StatusCode and quickly send responses.

func (*HelperResponseWriter) Flush

func (rw *HelperResponseWriter) Flush()

implement http.Flusher

func (*HelperResponseWriter) HTML

func (rw *HelperResponseWriter) HTML(statusCode int, html string) error

send html

func (*HelperResponseWriter) Hijack

func (rw *HelperResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

implement http.Hijacker

func (*HelperResponseWriter) JSON

func (rw *HelperResponseWriter) JSON(statusCode int, data any) error

send json

func (*HelperResponseWriter) Push

func (rw *HelperResponseWriter) Push(target string, opts *http.PushOptions) error

implement http.Pusher

func (*HelperResponseWriter) String

func (rw *HelperResponseWriter) String(statusCode int, s string) error

send string

func (*HelperResponseWriter) Unwrap

get the wrapped ResponseWriter

func (*HelperResponseWriter) XML

func (rw *HelperResponseWriter) XML(statusCode int, data any, indent string) error

send xml

type Map

type Map map[string]any

type MiddlewareFunc

type MiddlewareFunc func(next http.Handler) http.Handler

Middleware function signatrue

type RouteMiddlewareFunc

type RouteMiddlewareFunc func(next HandlerFunc) HandlerFunc

type ServeMux

type ServeMux struct {
	http.ServeMux
	ErrHandlerFunc ErrHandlerFunc
	// contains filtered or unexported fields
}

ServeMux embeds http.ServeMux

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux return a new ServeMux

func (*ServeMux) Connect

func (sm *ServeMux) Connect(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) Delete

func (sm *ServeMux) Delete(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) Get

func (sm *ServeMux) Get(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

Here is the helper function:

func (*ServeMux) Group

func (sm *ServeMux) Group(prefix string) *ServeMux

Group creates a group mux based on a prefix.

func (*ServeMux) HandleFunc

func (sm *ServeMux) HandleFunc(pattern string, h HandlerFunc)

To rewrite the HandleFunc function signature

func (*ServeMux) Head

func (sm *ServeMux) Head(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) Options

func (sm *ServeMux) Options(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) Patch

func (sm *ServeMux) Patch(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) Post

func (sm *ServeMux) Post(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) Put

func (sm *ServeMux) Put(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) ServeHTTP

func (sm *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

To rewrite the ServeHTTP function

func (*ServeMux) Trace

func (sm *ServeMux) Trace(path string, h HandlerFunc, m ...RouteMiddlewareFunc)

func (*ServeMux) Use

func (sm *ServeMux) Use(m ...MiddlewareFunc)

Use adds middleware for the mux.

Directories

Path Synopsis
_example
hello_world command
Declaration: The middleware package is copied from chi/v5/middleware.
Declaration: The middleware package is copied from chi/v5/middleware.

Jump to

Keyboard shortcuts

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