httputil

package
v0.0.0-...-94dd193 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: MIT Imports: 4 Imported by: 3

Documentation

Overview

Package httputil provides utilities on top of the net/http package.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewServer

func NewServer(addr string, h http.Handler, opts ...Option) *http.Server

NewServer creates an HTTP Server with pre-configured timeouts and a secure TLS Config.

Types

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware is a chainable decorator for HTTP Handlers.

func Chain

func Chain(outer Middleware, others ...Middleware) Middleware

Chain is a helper function for composing middlewares. Requests will traverse them in the order they're declared. That is, the first middleware is treated as the outermost middleware.

Chain is identical to the go-kit helper for Endpoint Middleware.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	h := Chain(
		annotate("one"),
		annotate("two"),
		annotate("three"),
	)(myHandler())

	srv := httptest.NewServer(h)
	defer srv.Close()

	resp, err := http.Get(srv.URL)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

}

func annotate(s string) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			fmt.Println("annotate: ", s)
			next.ServeHTTP(w, r)
		})
	}
}

func myHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	})
}
Output:

annotate:  one
annotate:  two
annotate:  three

type Option

type Option func(*http.Server)

Option configures an HTTP Server.

func WithIdleTimeout

func WithIdleTimeout(t time.Duration) Option

WithIdleTimeout sets the IdleTimeout option

func WithReadHeaderTimeout

func WithReadHeaderTimeout(t time.Duration) Option

WithReadHeaderTimeout sets the ReadHeaderTimeout option

func WithReadTimeout

func WithReadTimeout(t time.Duration) Option

WithReadTimeout sets the ReadTimeout option

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) Option

WithTLSConfig allows overriding the default TLS Config in the call to NewServer.

func WithWriteTimeout

func WithWriteTimeout(t time.Duration) Option

WithWriteTimeout sets the WriteTimeout option

Jump to

Keyboard shortcuts

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