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) {
// a struct keeps the member order stable, as encoding/json/v2 does not sort map keys
store.RespondJson(http.StatusOK, struct {
Method string `json:"method"`
Path string `json:"path"`
}{
Method: store.R.Method,
Path: store.RouteParamAny(),
})
}
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 ¶
- Constants
- type HandlerFunc
- type Mux
- type Params
- type ResponseWriter
- func (w *ResponseWriter) Flush()
- func (w *ResponseWriter) FlushError() error
- func (w *ResponseWriter) Header() http.Header
- func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseWriter) Unwrap() http.ResponseWriter
- func (w *ResponseWriter) Write(bytes []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(code int)
- type RouteInfo
- type Store
- func (store *Store) CookieValue(name string) string
- func (store *Store) Error404(msg string)
- func (store *Store) Error500(msg string)
- func (store *Store) GetClientIP() string
- func (store *Store) Next()
- func (store *Store) Redirect(code int, url string)
- func (store *Store) Respond200(content []byte) error
- func (store *Store) RespondJson(code int, v any) error
- func (store *Store) RouteParam(name string) (value string)
- func (store *Store) RouteParamAny() string
Examples ¶
Constants ¶
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 (*Mux) Handle ¶
func (mux *Mux) Handle(path string, method string, handler HandlerFunc)
Handle registers the handler for the given routePath and method.
func (*Mux) HandleMiddleware ¶ added in v1.5.0
func (mux *Mux) HandleMiddleware(middleware ...HandlerFunc)
func (*Mux) HandleNoRoute ¶ added in v1.3.0
func (mux *Mux) HandleNoRoute(handler HandlerFunc)
type Params ¶ added in v1.0.0
type Params struct {
K, V []string
}
Params consists of a pair of key-value slice.
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) Hijack ¶ added in v1.5.7
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements the standard http.Hijacker interface.
func (*ResponseWriter) Unwrap ¶ added in v1.5.7
func (w *ResponseWriter) Unwrap() http.ResponseWriter
Unwrap returns the original http.ResponseWriter.
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
Middlewares *[]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 ¶
CookieValue returns the value of specified cookie, or empty string if cookie not found.
func (*Store) GetClientIP ¶ added in v1.3.0
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) Next ¶ added in v1.5.0
func (store *Store) Next()
Next should be used only in middleware to call the next middleware or handler.
func (*Store) Respond200 ¶
Respond200 replies 200 to client request with optional body.
func (*Store) RespondJson ¶
RespondJson replies json body to client request. It cannot be called after `store.W.WriteHeader()`.
func (*Store) RouteParam ¶
RouteParam returns the value of specified route param, or empty string if param not found.
func (*Store) RouteParamAny ¶
RouteParamAny returns the value of route param "/*".