httpd

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2024 License: MIT Imports: 13 Imported by: 7

Documentation

Overview

Package httpd implements a simple HTTP router with path parameters support.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/http"

	"github.com/whoisnian/glb/httpd"
)

func pingHandler(store *httpd.Store) {
	store.Respond200([]byte("pong"))
}

func sayHandler(store *httpd.Store) {
	name := store.RouteParam("name")
	msg := store.RouteParam("msg")
	store.Respond200([]byte(name + " say: " + msg))
}

func anyHandler(store *httpd.Store) {
	path := store.RouteParamAny()
	method := store.R.Method
	store.RespondJson(map[string]string{
		"method": method,
		"path":   path,
	})
}

func printResp(resp *http.Response, err error) {
	if err != nil {
		fmt.Println(err)
	} else {
		data, _ := io.ReadAll(resp.Body)
		defer resp.Body.Close()
		fmt.Println(string(data))
	}
}

func main() {
	mux := httpd.NewMux()
	mux.Handle("/test/ping", http.MethodGet, pingHandler)
	mux.Handle("/test/say/:name/:msg", http.MethodPost, sayHandler)
	mux.Handle("/test/any/*", httpd.MethodAll, anyHandler)

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		panic(err)
	}
	server := &http.Server{Addr: ln.Addr().String(), Handler: mux}
	go func() {
		if err := server.Serve(ln); err != nil && err != http.ErrServerClosed {
			panic(err)
		}
	}()
	defer server.Shutdown(context.Background())

	printResp(http.Get("http://" + server.Addr + "/test/ping"))
	printResp(http.Post("http://"+server.Addr+"/test/say/cat/meow", "application/octet-stream", nil))
	printResp(http.Get("http://" + server.Addr + "/test/any/hello/world"))

}
Output:

pong
cat say: meow
{"method":"GET","path":"hello/world"}

Index

Examples

Constants

View Source
const MethodAll string = "*"

Variables

This section is empty.

Functions

This section is empty.

Types

type HandlerFunc

type HandlerFunc func(*Store)

func CreateHandler

func CreateHandler(httpHandler http.HandlerFunc) HandlerFunc

CreateHandler converts 'http.HandlerFunc' to 'httpd.HandlerFunc'.

type Mux

type Mux struct {
	// contains filtered or unexported fields
}

func NewMux

func NewMux() *Mux

NewMux allocates and returns a new Mux.

func (*Mux) Handle

func (mux *Mux) Handle(path string, method string, handler HandlerFunc)

Handle registers the handler for the given routePath and method.

func (*Mux) HandleNoRoute added in v1.3.0

func (mux *Mux) HandleNoRoute(handler HandlerFunc)

func (*Mux) HandleRelay added in v1.3.0

func (mux *Mux) HandleRelay(handler HandlerFunc)

func (*Mux) ServeHTTP

func (mux *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the matched handler.

type Params added in v1.0.0

type Params struct {
	K, V []string
}

Params consists of a pair of key-value slice.

func (*Params) Get added in v1.0.0

func (ps *Params) Get(key string) (value string, ok bool)

Get gets the first param value associated with the given key. The ok result indicates whether param was found.

type ResponseWriter added in v1.3.0

type ResponseWriter struct {
	Origin http.ResponseWriter
	Status int
}

ResponseWriter records response status with http.ResponseWriter.

func (*ResponseWriter) Flush added in v1.3.0

func (w *ResponseWriter) Flush()

Flush implements the standard http.Flusher interface.

func (*ResponseWriter) FlushError added in v1.3.0

func (w *ResponseWriter) FlushError() error

FlushError attempts to invoke FlushError() of the standard http.ResponseWriter.

func (*ResponseWriter) Header added in v1.3.0

func (w *ResponseWriter) Header() http.Header

func (*ResponseWriter) Write added in v1.3.0

func (w *ResponseWriter) Write(bytes []byte) (int, error)

func (*ResponseWriter) WriteHeader added in v1.3.0

func (w *ResponseWriter) WriteHeader(code int)

type RouteInfo added in v1.3.0

type RouteInfo struct {
	Path        string
	Method      string
	HandlerName string
	HandlerFunc HandlerFunc
}

RouteInfo exports route information for logs and metrics.

type Store

type Store struct {
	W *ResponseWriter
	R *http.Request
	P *Params
	I *RouteInfo
	// contains filtered or unexported fields
}

Store consists of responseWriter, request, routeParams and routeInfo.

func (*Store) CookieValue

func (store *Store) CookieValue(name string) string

CookieValue returns the value of specified cookie, or empty string if cookie not found.

func (*Store) Error404

func (store *Store) Error404(msg string)

Error404 is similar to `http.Error()`.

func (*Store) Error500

func (store *Store) Error500(msg string)

Error500 is similar to `http.Error()`.

func (*Store) GetClientIP added in v1.3.0

func (store *Store) GetClientIP() string

GetClientIP looks for possible client IP by the following order:

  • Header["X-Client-IP"]
  • Header["X-Forwarded-For"]
  • Header["X-Real-IP"]
  • Request.RemoteAddr

Warning: Malicious clients may use request header for IP spoofing.

func (*Store) GetID added in v1.3.0

func (store *Store) GetID() string

GetID returns the Store's ID like FVHNU2LS-gjdgxz.

func (*Store) Redirect

func (store *Store) Redirect(url string, code int)

Redirect is similar to `http.Redirect()`.

func (*Store) Respond200

func (store *Store) Respond200(content []byte) error

Respond200 replies 200 to client request with optional body.

func (*Store) RespondJson

func (store *Store) RespondJson(v interface{}) error

RespondJson replies json body to client request.

func (*Store) RouteParam

func (store *Store) RouteParam(name string) (value string)

RouteParam returns the value of specified route param, or empty string if param not found.

func (*Store) RouteParamAny

func (store *Store) RouteParamAny() string

RouteParamAny returns the value of route param "/*".

Jump to

Keyboard shortcuts

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