thttp

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: MIT Imports: 17 Imported by: 0

README

Go Doc

Qucik Start

Install

go get github.com/isayme/go-thttp@latest

Usage

package main

import (
	"log"

	"github.com/isayme/go-thttp"
)

func main() {
	app := thttp.New()

	// curl http://127.0.0.1:8080/version
	app.Get("/version", func(ctx thttp.Context) error {
		return ctx.JSON(200, map[string]string{
			"version": "v1.0.0",
		})
	})

	// curl http://127.0.0.1:8080/tasks/123
	app.Get("/tasks/:tid", func(ctx thttp.Context) error {
		return ctx.JSON(200, map[string]string{
			"tid": ctx.PathParam("tid"),
		})
	})

	// group route
	g := app.Group("/v1")

	// curl http://127.0.0.1:8080/v1/notes/123
	g.Get("/notes/{nid}", func(ctx thttp.Context) error {
		return ctx.JSON(200, map[string]string{
			"nid": ctx.PathParam("nid"),
		})
	})

	// curl http://127.0.0.1:8080/static/index.html
	// curl http://127.0.0.1:8080/static/img/favicon.ico
	app.Get("/static/*path", func(ctx thttp.Context) error {
		return ctx.JSON(200, map[string]string{
			"path": ctx.PathParam("path"),
		})
	})

	addr := ":8080"
	log.Printf("server start, listen on %s", addr)
	log.Fatal(app.Start(addr))
}

Route Pattern

Static

// match /users
app.Get("/users")

Param

// match /users/abc
// match /users/123
app.Get("/users/:id")
app.Get("/users/{id}")

regex is not supported.

Catch-All (wildcard)

// match /users/abc
// match /users/abc/def/ghi
app.Get("/users/*others")
app.Get("/users/{others...}")

// this is not supported
app.Get("/users/*")

Documentation

Index

Constants

View Source
const (
	HeaderContentType        = "Content-Type"
	HeaderXRequestID         = "X-Request-ID"
	HeaderLocation           = "Location"
	HeaderContentDisposition = "Content-Disposition"
)
View Source
const (
	MIMEApplicationJSON = "application/json"
)

Variables

This section is empty.

Functions

func RegisterRouter added in v0.1.2

func RegisterRouter(routerType RouterType, newRouter NewRouterFunc)

RegisterRouter registers a new router implementation.

Types

type App

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

func New

func New(options ...OptionFunc) *App

New creates a new thttp application. Options can be passed to customize the app behavior. Default router is net/http, can be changed via THTTP_ROUTER_TYPE env or WithRouterType option.

func (*App) Any

func (app *App) Any(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Any registers a handler for all HTTP methods for the given pattern.

func (*App) Delete

func (app *App) Delete(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Delete registers a DELETE handler for the given pattern.

func (*App) Get

func (app *App) Get(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Get registers a GET handler for the given pattern.

func (*App) Group

func (app *App) Group(prefix string, middleware ...MiddlewareFunc) *Group

Group creates a route group with a common prefix and optional middlewares.

func (*App) Handle

func (app *App) Handle(method, pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Handle registers a handler for the given method and pattern. Pattern supports: static (/users), param (/users/:id), catch-all (/users/*path).

func (*App) Head

func (app *App) Head(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Head registers a HEAD handler for the given pattern.

func (*App) Logger

func (app *App) Logger() *slog.Logger

Logger returns the app's logger.

func (*App) Options

func (app *App) Options(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Options registers an OPTIONS handler for the given pattern.

func (*App) Patch

func (app *App) Patch(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Patch registers a PATCH handler for the given pattern.

func (*App) Post

func (app *App) Post(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Post registers a POST handler for the given pattern.

func (*App) Put

func (app *App) Put(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Put registers a PUT handler for the given pattern.

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*App) Start

func (app *App) Start(address string) error

Start starts the HTTP server and listens on the given address.

func (*App) Static

func (app *App) Static(pattern string, root string)

Static serves static files from the given root directory. Pattern should end with *path to capture the file path.

func (*App) Use

func (app *App) Use(middleware ...MiddlewareFunc)

Use registers global middlewares that apply to all routes.

type Context

type Context interface {
	// Context returns the underlying context.Context.
	Context() context.Context

	// Request returns the current http.Request.
	Request() *http.Request
	// SetRequest sets the http.Request.
	SetRequest(r *http.Request)

	// Response returns the http.ResponseWriter.
	Response() http.ResponseWriter
	// SetResponse sets the http.ResponseWriter.
	SetResponse(r http.ResponseWriter)

	// Get retrieves a value from the context storage.
	Get(key interface{}) interface{}
	// Set stores a value in the context storage.
	Set(key, value interface{})

	// Method returns the HTTP method (GET, POST, etc.).
	Method() string
	// SetPathParamGetter sets the path parameters.
	SetPathParamGetter(fn PathParamGetter)
	// PathParam returns the path parameter value by name.
	PathParam(name string) string
	// QueryParam returns the query parameter value by name.
	QueryParam(name string) string
	// QueryParams returns all query parameters as url.Values.
	QueryParams() url.Values
	// QueryString returns the raw query string.
	QueryString() string
	// FormParam returns the form parameter value by name.
	FormParam(name string) string
	// FormFile returns the uploaded file from the form.
	FormFile(name string) (*multipart.FileHeader, error)
	// MultipartForm returns the multipart form data.
	MultipartForm() (*multipart.Form, error)
	// Cookie returns the cookie by name.
	Cookie(name string) (*http.Cookie, error)
	// Cookies returns all cookies.
	Cookies() []*http.Cookie
	// SetCookie adds a cookie to the response.
	SetCookie(cookie *http.Cookie)
	// Header returns the header value by key.
	Header(key string) string
	// SetHeader sets a response header.
	SetHeader(key string, value string)
	// AddHeader adds a response header (allows multiple values).
	AddHeader(key string, value string)
	// DelHeader removes a response header.
	DelHeader(key string)

	// Blob writes binary data with the given content type.
	Blob(code int, contentType string, b []byte) error
	// JSON writes JSON data with the given status code.
	JSON(code int, i interface{}) error
	// String writes a plain text response.
	String(code int, s string) error
	// Stream streams data from an io.Reader.
	Stream(code int, contentType string, r io.Reader) error
	// Redirect redirects to the given URL with the given status code.
	Redirect(code int, url string) error

	// Logger returns the logger for this context.
	Logger() *slog.Logger
	// Reset resets the context for a new request.
	Reset(r *http.Request, w http.ResponseWriter, logger *slog.Logger)
}

Context represents the HTTP request context. It provides methods to access request data and write responses.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) Context

type ErrorHandlerFunc

type ErrorHandlerFunc func(ctx Context, err error) error

ErrorHandlerFunc is the function signature for error handlers.

type Group

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

Group represents a route group with a common prefix and optional middlewares.

func (*Group) Any

func (g *Group) Any(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Any registers a handler for all HTTP methods for the given pattern within the group.

func (*Group) Delete

func (g *Group) Delete(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Delete registers a DELETE handler for the given pattern within the group.

func (*Group) Get

func (g *Group) Get(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Get registers a GET handler for the given pattern within the group.

func (*Group) Group

func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group

Group creates a nested route group with a new prefix.

func (*Group) Handle

func (g *Group) Handle(method, pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Handle registers a handler for the given method and pattern within the group.

func (*Group) Head

func (g *Group) Head(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Head registers a HEAD handler for the given pattern within the group.

func (*Group) Options

func (g *Group) Options(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Options registers an OPTIONS handler for the given pattern within the group.

func (*Group) Patch

func (g *Group) Patch(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Patch registers a PATCH handler for the given pattern within the group.

func (*Group) Post

func (g *Group) Post(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Post registers a POST handler for the given pattern within the group.

func (*Group) Put

func (g *Group) Put(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Put registers a PUT handler for the given pattern within the group.

func (*Group) Use

func (g *Group) Use(middleware ...MiddlewareFunc)

Use registers middlewares for the group.

type HandlerFunc

type HandlerFunc func(ctx Context) error

HandlerFunc is the function signature for HTTP request handlers.

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

WrapHandler wraps an http.Handler into a thttp HandlerFunc.

func WrapHandlerFunc

func WrapHandlerFunc(h http.HandlerFunc) HandlerFunc

WrapHandlerFunc wraps an http.HandlerFunc into a thttp HandlerFunc.

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc is a function that wraps a handler. It takes the next handler and returns a new handler that can execute code before and after the next handler is called.

func WrapMiddleware

func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc

WrapMiddleware wraps a standard library middleware into a thttp MiddlewareFunc.

type NewRouterFunc added in v0.1.2

type NewRouterFunc func() Router

type OptionFunc added in v0.1.1

type OptionFunc func(app *App)

func WithErrorHandler

func WithErrorHandler(handler ErrorHandlerFunc) OptionFunc

func WithNotFoundHandler

func WithNotFoundHandler(handler HandlerFunc) OptionFunc

func WithPrefix

func WithPrefix(prefix string) OptionFunc

func WithRouterType

func WithRouterType(typ RouterType) OptionFunc

type PathParamGetter added in v0.1.2

type PathParamGetter interface {
	// Get returns the path parameter value by name.
	Get(name string) string
}

PathParamGetter is an interface for accessing path parameter values.

type Router

type Router interface {
	// Use registers middlewares for the router.
	Use(middleware ...MiddlewareFunc)

	// Handle registers a handler for the given method and pattern.
	Handle(method, pattern string, h HandlerFunc, middleware ...MiddlewareFunc)

	// Match finds a handler for the given request.
	// Returns the handler, path parameter function, and whether a match was found.
	Match(w http.ResponseWriter, r *http.Request) (HandlerFunc, PathParamGetter, bool)

	// FormatSegment converts a thttp Segment to the router's native pattern syntax.
	FormatSegment(seg Segment) string
}

Router is the interface that wraps the routing capabilities. Each router implementation (gin, echo, chi, etc.) must implement this interface.

type RouterType

type RouterType string

RouterType specifies the underlying router implementation. Supported types: net/http, julienschmidt/httprouter, gorilla/mux, gin-gonic/gin, go-chi/chi, labstack/echo.

const (
	RouterTypeStd        RouterType = "net/http"
	RouterTypeHttprouter RouterType = "julienschmidt/httprouter"
	RouterTypeGorillaMux RouterType = "gorilla/mux"
	RouterTypeGin        RouterType = "gin-gonic/gin"
	RouterTypeChi        RouterType = "go-chi/chi"
	RouterTypeEcho       RouterType = "labstack/echo"
)

type Segment

type Segment struct {
	Type SegmentType
	Raw  string
	Name string
}

Segment represents a parsed path segment.

func ParsePath

func ParsePath(pattern string) []Segment

ParsePath parses a URL pattern into segments. Supports: static (/users), param (/users/:id or /users/{id}), catch-all (/users/*path or /users/{path...}).

type SegmentType

type SegmentType int

SegmentType represents the type of a path segment.

const (
	Static   SegmentType = iota // static
	Param                       // param
	CatchAll                    // wildcard
)

type Skipper

type Skipper func(ctx Context) bool

Skipper is a function that determines whether to skip the middleware.

Directories

Path Synopsis
errorhandler command
graceful command
recovery command
static command

Jump to

Keyboard shortcuts

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