srv

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 14 Imported by: 0

README

srv

A simple and flexible HTTP server framework for Go.

Features

  • Clean and intuitive API for defining routes and handlers
  • Middleware support at both server and route group levels
  • Route grouping for better organization
  • Built on top of Go's standard net/http package

Getting Started

Install the dependency.

go get github.com/cfichtmueller/srv

Create your server.

package main

import "github.com/cfichtmueller/srv"

func main() {
    s := srv.NewServer().Use(srv.LoggingMiddleware())

    s.GET("/api/motd", func(c *srv.Context) *srv.Response {
        return srv.Respond().Json(map[string]any {
            "message": "Hello World",
        })
    })

    if err := s.ListenAndServe(":8080"); err != nil {
        log.Fatal(err)
    }
}

Documentation

Index

Constants

View Source
const (
	SecFetchSiteCrossSite  = "cross-site"
	SecFetchSiteSameOrigin = "same-origin"
	SecFetchSiteSameSite   = "same-site"
	SecFetchSiteNone       = "none"
	SecFetchModeCors       = "cors"
	SecFetchModeNavigate   = "navigate"
	SecFetchModeNoCors     = "no-cors"
	SecFetchModeSameOrigin = "same-origin"
	SecFetchModeWebsocket  = "websocket"

	SecFetchDestAudio         = "audio"
	SecFetchDestAudioWorklet  = "audioworklet"
	SecFetchDestDocument      = "document"
	SecFetchDestEmbed         = "embed"
	SecFetchDestEmpty         = "empty"
	SecFetchDestFencedframe   = "fencedframe"
	SecFetchDestFont          = "font"
	SecFetchDestFrame         = "frame"
	SecFetchDestIframe        = "iframe"
	SecFetchDestImage         = "image"
	SecFetchDestManifest      = "manifest"
	SecFetchDestObject        = "object"
	SecFetchDestPaintworklet  = "paintworklet"
	SecFetchDestReport        = "report"
	SecFetchDestScript        = "script"
	SecFetchDestServiceworker = "serviceworker"
	SecFetchDestSharedworker  = "sharedworker"
	SecFetchDestStyle         = "style"
	SecFetchDestTrack         = "track"
	SecFetchDestVideo         = "video"
	SecFetchDestWebidentity   = "webidentity"
	SecFetchDestWorker        = "worker"
	SecFetchDestXslt          = "xslt"

	SecPurposePrefetch = "prefetch"
)
View Source
const (
	XFrameOptionsDENY                               = "DENY"
	XFrameOptionsSAMEORIGIN                         = "SAMEORIGIN"
	XPermittedCrossDomainPoliciesNONE               = "none"
	XPermittedCrossDomainPoliciesMASTER_ONLY        = "master-only"
	XPermittedCrossDomainPoliciesBY_CONTENT_TYPE    = "by-content-type"
	XPermittedCrossDomainPoliciesBY_FTP_FILENAME    = "by-ftp-filename"
	XPermittedCrossDomainPoliciesALL                = "all"
	XPermittedCrossDomainPoliciesNONE_THIS_RESPONSE = "none-this-response"

	TransferEncodingChunked  = "chunked"
	TransferEncodingCompress = "compress"
	TransferEncodingDeflate  = "deflate"
	TransferEncodingGzip     = "gzip"
)
View Source
const (
	ValidationCodeTooFewItems  = "too_few_items"
	ValidationCodeTooManyItems = "too_many_items"
	ValidationCodeRequired     = "required"
	ValidationCodeTooShort     = "too_short"
	ValidationCodeTooLong      = "too_long"
	ValidationCodeInvalid      = "invalid"
)
View Source
const (
	DefaultMaxMultipartMemory = 64 << 20
)

Variables

View Source
var (
	ErrNoBody = errors.New("no requestbody")
)

Functions

func ContentDispositionAttachment added in v0.6.0

func ContentDispositionAttachment(filename string) string

ContentDispositionAttachment returns the value of the Content-Disposition header for an attachment.

func ContentDispositionInline added in v0.6.0

func ContentDispositionInline(filename string) string

ContentDispositionInline returns the value of the Content-Disposition header for an inline file.

func Validate added in v0.2.0

func Validate(v *ValidationError) error

Validate converts a ValidationError to a standard error. If the ValidationError is nil, it returns nil.

Types

type BodyFn

type BodyFn func(w io.Writer) error

type Context

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

Context represents the context of an HTTP request.

func NewContext

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

NewContext creates a new Context with the given http.ResponseWriter and http.Request.

func (*Context) Accept

func (c *Context) Accept() string

Accept returns the value of the Accept header.

func (*Context) AcceptEncoding

func (c *Context) AcceptEncoding() string

AcceptEncoding returns the value of the Accept-Encoding header.

func (*Context) AcceptLanguage

func (c *Context) AcceptLanguage() string

AcceptLanguage returns the value of the Accept-Language header.

func (*Context) AccessControlRequestHeaders

func (c *Context) AccessControlRequestHeaders() ([]string, bool)

AccessControlRequestHeaders returns the value of the Access-Control-Request-Headers header.

func (*Context) AccessControlRequestMethod

func (c *Context) AccessControlRequestMethod() string

AccessControlRequestMethod returns the value of the Access-Control-Request-Method header.

func (*Context) Authorization

func (c *Context) Authorization() string

Authorization returns the value of the Authorization header.

func (*Context) BindJSON deprecated

func (c *Context) BindJSON(data any) *Response

BindJSON tries to bind a json payload. Returns a response if the binding was unsuccessful

Deprecated: Use BindJson instead.

func (*Context) BindJson added in v0.6.0

func (c *Context) BindJson(data any) *Response

BindJson tries to bind a json payload. Returns a response if the binding was unsuccessful

func (*Context) BindJsonOptional added in v0.6.0

func (c *Context) BindJsonOptional(data any) (bool, *Response)

BindJsonOptional tries to bind a json payload. Returns a response if the binding was unsuccessful. If the request body is empty, it returns false and nil. If the request body is not empty, it returns true and nil if the binding was successful.

func (*Context) CacheControl

func (c *Context) CacheControl() string

CacheControl returns the value of the Cache-Control header.

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP returns the client IP address from the request. When proxies are trusted, the address is resolved from proxy headers like X-Forwarded-For. Otherwise, the direct remote address is used.

func (*Context) ConditionalIfMatch

func (c *Context) ConditionalIfMatch(localEtag string) *Response

ConditionalIfMatch makes the request conditional. Returns a response when the precondition fails.

func (*Context) ConditionalIfModifiedSince

func (c *Context) ConditionalIfModifiedSince(lastModified ...time.Time) *Response

ConditionalIfModifiedSince makes the request conditional. Returns a response when the precondition fails.

func (*Context) ConditionalIfNoneMatch

func (c *Context) ConditionalIfNoneMatch(localEtag string) *Response

ConditionalIfNoneMatch makes the request conditional. Returns a response when the precondition fails.

func (*Context) ConditionalIfUnmodifiedSince added in v0.5.0

func (c *Context) ConditionalIfUnmodifiedSince(lastModified ...time.Time) *Response

ConditionalIfUnmodifiedSince makes the request conditional. Returns a response when the precondition fails.

func (*Context) Connection

func (c *Context) Connection() string

Connection returns the value of the Connection header.

func (*Context) ContentDisposition

func (c *Context) ContentDisposition() string

ContentDisposition returns the value of the Content-Disposition header.

func (*Context) ContentEncoding

func (c *Context) ContentEncoding() string

ContentEncoding returns the value of the Content-Encoding header.

func (*Context) ContentLanguage

func (c *Context) ContentLanguage() string

ContentLanguage returns the value of the Content-Language header.

func (*Context) ContentLength

func (c *Context) ContentLength() (int64, bool)

ContentLength returns the value of the Content-Length header.

func (*Context) ContentLocation

func (c *Context) ContentLocation() string

ContentLocation returns the value of the Content-Location header.

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType returns the value of the Content-Type header.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies returns the cookies from the request.

func (*Context) Date

func (c *Context) Date() (time.Time, bool)

Date returns the value of the Date header.

func (*Context) Deadline

func (c *Context) Deadline() (time.Time, bool)

Deadline invokes Deadline on the underlying request context.

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done invokes Done on the underlying request context.

func (*Context) Err

func (c *Context) Err() error

Err invokes Err on the underlying request context.

func (*Context) Expect

func (c *Context) Expect() string

Expect returns the value of the Expect header.

func (*Context) FormValues

func (c *Context) FormValues() url.Values

FormValues returns the values from a POST urlencoded form or multipart form

func (*Context) Forwarded

func (c *Context) Forwarded() string

Forwarded returns the value of the Forwarded header.

func (*Context) From

func (c *Context) From() string

From returns the value of the From header.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get returns the value of the given key in the context.

func (*Context) GetRawData

func (c *Context) GetRawData() ([]byte, error)

GetRawData reads the request body and returns the raw data. Returns ErrNoBody if the request body is nil.

func (*Context) HasQuery

func (c *Context) HasQuery(key string) bool

HasQuery checks if the request has a query parameter with the given key.

func (*Context) Header

func (c *Context) Header(name string) string

Header returns the value of the specified header from the request.

func (*Context) Host

func (c *Context) Host() string

Host returns the value of the Host header.

func (*Context) HxBoosted

func (c *Context) HxBoosted() bool

HxBoosted returns true if the request is an HX-Boosted request.

func (*Context) HxCurrentUrl

func (c *Context) HxCurrentUrl() string

HxCurrentUrl returns the current URL from the HX-Current-URL header.

func (*Context) HxHistoryRestoreRequest

func (c *Context) HxHistoryRestoreRequest() bool

HxHistoryRestoreRequest returns true if this request is for history restoration.

func (*Context) HxPrompt

func (c *Context) HxPrompt() string

HxPrompt returns the user response to an hx-prompt.

func (*Context) HxRequest

func (c *Context) HxRequest() bool

HxRequest returns true if the request is an HX request.

func (*Context) HxTarget

func (c *Context) HxTarget() string

HxTarget returns the target element of the request.

func (*Context) HxTrigger

func (c *Context) HxTrigger() string

HxTrigger returns the ID of the triggered element if it exists.

func (*Context) HxTriggerName

func (c *Context) HxTriggerName() string

HxTriggerName returns the name of the triggered element if it exists.

func (*Context) IfMatch

func (c *Context) IfMatch() string

IfMatch returns the value of the If-Match header.

func (*Context) IfModifiedSince

func (c *Context) IfModifiedSince() (time.Time, bool, error)

IfModifiedSince returns the value of the If-Modified-Since header.

func (*Context) IfNoneMatch

func (c *Context) IfNoneMatch() string

IfNoneMatch returns the value of the If-None-Match header.

func (*Context) IfRange

func (c *Context) IfRange() string

IfRange returns the value of the If-Range header.

func (*Context) IfUnmodifiedSince

func (c *Context) IfUnmodifiedSince() (time.Time, bool, error)

IfUnmodifiedSince returns the value of the If-Unmodified-Since header.

func (*Context) IntQuery

func (c *Context) IntQuery(key string) (int, *Response)

IntQuery is a shortcut for IntQueryOrDefault(key, 0)

func (*Context) IntQueryOrDefault

func (c *Context) IntQueryOrDefault(key string, defaultValue int) (int, *Response)

IntQueryOrDefault returns the value of the specified query parameter from the request or the default value if the parameter is not present.

func (*Context) KeepAlive

func (c *Context) KeepAlive() string

KeepAlive returns the value of the Keep-Alive header.

func (c *Context) Link() string

Link returns the value of the Link header.

func (*Context) MaxForwards

func (c *Context) MaxForwards() (int, bool, error)

MaxForwards returns the value of the Max-Forwards header.

func (*Context) MustGet

func (c *Context) MustGet(key string) any

MustGet panics if the key is not found in the context.

func (*Context) Origin

func (c *Context) Origin() string

Origin returns the value of the Origin header.

func (*Context) PathValue

func (c *Context) PathValue(name string) string

PathValue returns the value of the specified path parameter from the request.

func (*Context) Prefer

func (c *Context) Prefer() string

Prefer returns the value of the Prefer header.

func (*Context) ProxyAuthorization

func (c *Context) ProxyAuthorization() string

ProxyAuthorization returns the value of the Proxy-Authorization header.

func (*Context) Query

func (c *Context) Query(key string) string

Query returns the value of the specified query parameter from the request.

func (*Context) QueryArray added in v0.6.0

func (c *Context) QueryArray(key string) (values []string, ok bool)

QueryArray returns the values of the specified query parameter from the request.

func (*Context) Range

func (c *Context) Range() string

Range returns the value of the Range header.

func (*Context) Referer

func (c *Context) Referer() string

Referer returns the value of the Referer header.

func (*Context) RemoteIP

func (c *Context) RemoteIP() string

RemoteIP returns the remote IP address from the request.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns the http.Request associated with the Context.

func (*Context) SecFetchDest

func (c *Context) SecFetchDest() string

SecFetchDest returns the value of the Sec-Fetch-Dest header.

func (*Context) SecFetchMode

func (c *Context) SecFetchMode() string

SecFetchMode returns the value of the Sec-Fetch-Mode header.

func (*Context) SecFetchSite

func (c *Context) SecFetchSite() string

SecFetchSite returns the value of the Sec-Fetch-Site header.

func (*Context) SecFetchUser

func (c *Context) SecFetchUser() bool

SecFetchUser returns the value of the Sec-Fetch-User header.

func (*Context) SecPurpose

func (c *Context) SecPurpose() string

SecPurpose returns the value of the Sec-Purpose header.

func (*Context) Server

func (c *Context) Server() string

Server returns the value of the Server header.

func (*Context) ServiceWorker

func (c *Context) ServiceWorker() bool

ServiceWorker returns the value of the Service-Worker header.

func (*Context) ServiceWorkerNavigationPreload

func (c *Context) ServiceWorkerNavigationPreload() string

ServiceWorkerNavigationPreload returns the value of the Service-Worker-Navigation-Preload header.

func (*Context) Set

func (c *Context) Set(key string, value any)

Set sets the value of the given key in the context.

func (*Context) StringQuery

func (c *Context) StringQuery(key string) (string, *Response)

StringQuery returns the value of the specified query parameter from the request.

func (*Context) StringQueryOrDefault

func (c *Context) StringQueryOrDefault(key string, defaultValue string) (string, *Response)

StringQueryOrDefault returns the value of the specified query parameter from the request or the default value if the parameter is not present.

func (*Context) TE

func (c *Context) TE() string

TE returns the value of the TE header.

func (*Context) Trailer

func (c *Context) Trailer() string

Trailer returns the value of the Trailer header.

func (*Context) TransferEncoding

func (c *Context) TransferEncoding() string

TransferEncoding returns the value of the Transfer-Encoding header.

func (*Context) UpgradeInsecureRequests

func (c *Context) UpgradeInsecureRequests() (bool, bool)

UpgradeInsecureRequests returns the value of the Upgrade-Insecure-Requests header.

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent returns the value of the User-Agent header.

func (*Context) Value

func (c *Context) Value(key any) any

Value invokes Value on the underlying request context.

func (*Context) Via

func (c *Context) Via() string

Via returns the value of the Via header.

func (*Context) WithContext added in v0.4.0

func (c *Context) WithContext(ctx context.Context) *Context

WithContext returns a copy of c with its request context replaced by the given context.

type ErrorDto

type ErrorDto struct {
	Code    string `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
}

ErrorDto represents an error response with a code and message.

type Group

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

func (*Group) ANY added in v0.5.0

func (g *Group) ANY(path string, handler Handler, middleware ...Middleware)

ANY adds a new route for all methods with the given path, handler, and middleware.

func (*Group) DELETE

func (g *Group) DELETE(path string, handler Handler, middleware ...Middleware)

DELETE adds a new route for the DELETE method with the given path, handler, and middleware.

func (*Group) GET

func (g *Group) GET(path string, handler Handler, middleware ...Middleware)

GET adds a new route for the GET method with the given path, handler, and middleware.

func (*Group) Group

func (g *Group) Group(path string, middleware ...Middleware) *Group

Group creates a new Group with the given path.

func (*Group) HEAD

func (g *Group) HEAD(path string, handler Handler, middleware ...Middleware)

HEAD adds a new route for the HEAD method with the given path, handler, and middleware.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handler Handler, middleware ...Middleware)

OPTIONS adds a new route for the OPTIONS method with the given path, handler, and middleware.

func (*Group) PATCH added in v0.5.0

func (g *Group) PATCH(path string, handler Handler, middleware ...Middleware)

PATCH adds a new route for the PATCH method with the given path, handler, and middleware.

func (*Group) POST

func (g *Group) POST(path string, handler Handler, middleware ...Middleware)

POST adds a new route for the POST method with the given path, handler, and middleware.

func (*Group) PUT

func (g *Group) PUT(path string, handler Handler, middleware ...Middleware)

PUT adds a new route for the PUT method with the given path, handler, and middleware.

type Handler

type Handler func(c *Context) *Response

Handler represents a function that handles an HTTP request and returns a Response.

type IPResolver

type IPResolver struct {
	RemoteIPHeaders      []string
	TrustRemoteIdHeaders bool
}

func NewIPResolver

func NewIPResolver(remoteIPHeaders []string, trustRemoteIdHeaders bool) *IPResolver

func (*IPResolver) Resolve

func (r *IPResolver) Resolve(req *http.Request) []string

type Middleware

type Middleware func(c *Context, next Handler) *Response

Middleware represents a function that processes an HTTP request and returns a Response.

func LoggingMiddleware

func LoggingMiddleware() Middleware

LoggingMiddleware logs the request and response status.

type Response

type Response struct {
	StatusCode int
	// contains filtered or unexported fields
}

Response represents an HTTP response that can be customized with status codes, headers, and body content. It provides a fluent interface for building responses with various common HTTP status codes and payloads.

func Respond

func Respond() *Response

Respond creates a new Response with default status code 200 OK and empty headers.

func (*Response) Accept

func (r *Response) Accept(value string) *Response

Accept sets the "Accept" header in the response.

func (*Response) AcceptEncoding

func (r *Response) AcceptEncoding(value string) *Response

AcceptEncoding sets the "Accept-Encoding" header in the response.

func (*Response) AcceptPatch

func (r *Response) AcceptPatch(value string) *Response

AcceptPatch sets the "Accept-Patch" header in the response.

func (*Response) AcceptPost

func (r *Response) AcceptPost(value string) *Response

AcceptPost sets the "Accept-Post" header in the response.

func (*Response) AcceptRanges

func (r *Response) AcceptRanges() *Response

AcceptRanges sets the "Accept-Ranges" header in the response.

func (*Response) AccessControlAllowCredentials

func (r *Response) AccessControlAllowCredentials() *Response

AccessControlAllowCredentials sets the "Access-Control-Allow-Credentials" header in the response.

func (*Response) AccessControlAllowHeaders

func (r *Response) AccessControlAllowHeaders(headers ...string) *Response

AccessControlAllowHeaders sets the "Access-Control-Allow-Headers" header in the response.

func (*Response) AccessControlAllowMethods

func (r *Response) AccessControlAllowMethods(methods ...string) *Response

AccessControlAllowMethods sets the "Access-Control-Allow-Methods" header in the response.

func (*Response) AccessControlAllowOrigin

func (r *Response) AccessControlAllowOrigin(origin string) *Response

AccessControlAllowOrigin sets the "Access-Control-Allow-Origin" header in the response.

func (*Response) AccessControlExposeHeaders

func (r *Response) AccessControlExposeHeaders(headers ...string) *Response

AccessControlExposeHeaders sets the "Access-Control-Expose-Headers" header in the response.

func (*Response) AccessControlMaxAge

func (r *Response) AccessControlMaxAge(maxAge int) *Response

AccessControlMaxAge sets the "Access-Control-Max-Age" header in the response.

func (*Response) AfterWrite

func (r *Response) AfterWrite(fn func()) *Response

AfterWrite adds a function to be called after the response is written.

func (*Response) Age

func (r *Response) Age(deltaSeconds int) *Response

Age sets the "Age" header in the response.

func (*Response) Allow

func (r *Response) Allow(methods ...string) *Response

Allow sets the "Allow" header in the response.

func (*Response) BadRequest

func (r *Response) BadRequest(body ...any) *Response

BadRequest sets the HTTP status code to 400 Bad Request and optionally sets the response body.

func (*Response) Body

func (r *Response) Body(contentType string, data []byte) *Response

Body sets the response body to the provided data and sets the Content-Type header.

func (*Response) BodyFn

func (r *Response) BodyFn(contentType string, bodyFn BodyFn) *Response

BodyFn creates the response body from a function.

func (*Response) BodyReader added in v0.6.0

func (r *Response) BodyReader(contentType string, reader io.Reader) *Response

BodyReader creates the response body from a reader.

func (*Response) CacheControl

func (r *Response) CacheControl(directive string) *Response

CacheControl sets the "Cache-Control" header in the response.

func (*Response) ClearSiteData

func (r *Response) ClearSiteData(directive string) *Response

ClearSiteData sets the "Clear-Site-Data" header in the response.

func (*Response) Conflict

func (r *Response) Conflict(body ...any) *Response

Conflict sets the HTTP status code to 409 Conflict and optionally sets the response body.

func (*Response) Connection

func (r *Response) Connection(value string) *Response

Connection sets the "Connection" header in the response.

func (*Response) ContentDisposition

func (r *Response) ContentDisposition(disposition string) *Response

ContentDisposition sets the "Content-Disposition" header in the response.

Use srv.ContentDispositionAttachment and srv.ContentDispositionInline to create the appropriate values.

func (*Response) ContentEncoding

func (r *Response) ContentEncoding(encoding string) *Response

ContentEncoding sets the "Content-Encoding" header in the response.

func (*Response) ContentLanguage

func (r *Response) ContentLanguage(language string) *Response

ContentLanguage sets the "Content-Language" header in the response.

func (*Response) ContentLength

func (r *Response) ContentLength(length int64) *Response

ContentLength sets the "Content-Length" header in the response.

func (*Response) ContentLocation

func (r *Response) ContentLocation(location string) *Response

ContentLocation sets the "Content-Location" header in the response.

func (*Response) ContentRange

func (r *Response) ContentRange(value string) *Response

ContentRange sets the "Content-Range" header in the response.

func (*Response) ContentSecurityPolicy

func (r *Response) ContentSecurityPolicy(directive string) *Response

ContentSecurityPolicy sets the "Content-Security-Policy" header in the response.

func (*Response) ContentSecurityPolicyReportOnly

func (r *Response) ContentSecurityPolicyReportOnly(directive string) *Response

ContentSecurityPolicyReportOnly sets the "Content-Security-Policy-Report-Only" header in the response.

func (*Response) ContentType

func (r *Response) ContentType(contentType string) *Response

ContentType sets the "Content-Type" header in the response.

func (*Response) Cookie

func (r *Response) Cookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) *Response

Cookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Response) CookieRaw

func (r *Response) CookieRaw(cookie *http.Cookie) *Response

CookieRaw adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Response) Created

func (r *Response) Created(body ...any) *Response

Created sets the HTTP status code to 201 Created and optionally sets the response body.

func (*Response) CrossOriginEmbedderPolicy

func (r *Response) CrossOriginEmbedderPolicy(policy string) *Response

CrossOriginEmbedderPolicy sets the "Cross-Origin-Embedder-Policy" header in the response.

func (*Response) CrossOriginOpenerPolicy

func (r *Response) CrossOriginOpenerPolicy(policy string) *Response

CrossOriginOpenerPolicy sets the "Cross-Origin-Opener-Policy" header in the response.

func (*Response) CrossOriginResourcePolicy

func (r *Response) CrossOriginResourcePolicy(policy string) *Response

CrossOriginResourcePolicy sets the "Cross-Origin-Resource-Policy" header in the response.

func (*Response) Date

func (r *Response) Date(t time.Time) *Response

Date sets the "Date" header in the response.

func (*Response) ETag

func (r *Response) ETag(etag string) *Response

ETag sets the "ETag" header in the response. The etag value will be automatically wrapped in quotes.

func (*Response) Error

func (r *Response) Error(err error) *Response

Error sets the HTTP status code to 500 Internal Server Error and sets the response body to an ErrorDto. If err is nil, the error message will be empty. Otherwise, the error message will be set to err.Error().

func (*Response) Expires

func (r *Response) Expires(t time.Time) *Response

Expires sets the "Expires" header in the response. The time will be automatically converted to UTC and formatted according to RFC 7231.

func (*Response) Forbidden

func (r *Response) Forbidden(body ...any) *Response

Forbidden sets the HTTP status code to 403 Forbidden and optionally sets the response body.

func (*Response) Found

func (r *Response) Found(location string) *Response

Found sets the HTTP status code to 302 Found and sets the Location header.

func (*Response) Header

func (r *Response) Header(key, value string) *Response

Header sets a header in the response.

func (*Response) Html

func (r *Response) Html(html string) *Response

Html sets the response body to an HTML string. The Content-Type header is automatically set to "text/html;charset=UTF-8".

func (*Response) HxLocation

func (r *Response) HxLocation(location string) *Response

HxLocation sets the HX-Location header.

func (*Response) HxPushUrl

func (r *Response) HxPushUrl(url string) *Response

HxPushUrl sets the HX-Push-Url header.

func (*Response) HxRedirect

func (r *Response) HxRedirect(location string) *Response

HXRedirect sets the HX-Redirect header.

func (*Response) HxRefresh

func (r *Response) HxRefresh() *Response

HxRefresh sets the HX-Refresh header to true.

func (*Response) HxReplaceUrl

func (r *Response) HxReplaceUrl(url string) *Response

HxReplaceUrl sets the HX-Replace-Url header.

func (*Response) HxReselect

func (r *Response) HxReselect(selector string) *Response

HxReselect sets the HX-Reselect header.

func (*Response) HxReswap

func (r *Response) HxReswap(value string) *Response

HxReswap sets the HX-Reswap header.

func (*Response) HxRetarget

func (r *Response) HxRetarget(selector string) *Response

HxRetarget sets the HX-Retarget header.

func (*Response) HxTrigger

func (r *Response) HxTrigger(event string) *Response

HxTrigger sets the HX-Trigger header.

func (*Response) HxTriggerAfterSettle

func (r *Response) HxTriggerAfterSettle(event string) *Response

HxTriggerAfterSettle sets the HX-Trigger-After-Settle header.

func (*Response) HxTriggerAfterSwap

func (r *Response) HxTriggerAfterSwap(event string) *Response

HxTriggerAfterSwap sets the HX-Trigger-After-Swap header.

func (*Response) InternalServerError

func (r *Response) InternalServerError(body ...any) *Response

func (*Response) Json

func (r *Response) Json(data any) *Response

Json sets the response body to a JSON-encoded representation of the provided data. The Content-Type header is automatically set to "application/json;charset=UTF-8".

func (*Response) KeepAlive

func (r *Response) KeepAlive(timeout int, max int) *Response

KeepAlive sets the "Keep-Alive" header in the response.

func (*Response) LastModified

func (r *Response) LastModified(t time.Time) *Response

LastModified sets the "Last-Modified" header in the response. The time will be automatically converted to UTC and formatted according to RFC 7231.

func (r *Response) Link(link string) *Response

Link sets the "Link" header in the response.

func (*Response) Location

func (r *Response) Location(location string) *Response

Location sets the "Location" header in the response.

func (*Response) MethodNotAllowed

func (r *Response) MethodNotAllowed(body ...any) *Response

MethodNotAllowed sets the HTTP status code to 405 Method Not Allowed and optionally sets the response body.

func (*Response) MovedPermanently

func (r *Response) MovedPermanently(location string) *Response

MovedPermanently sets the HTTP status code to 301 Moved Permanently and sets the Location header.

func (*Response) NoContent

func (r *Response) NoContent() *Response

NoContent sets the HTTP status code to 204 No Content.

func (*Response) NoVarySearch

func (r *Response) NoVarySearch(rules string) *Response

NoVarySearch sets the "No-Vary-Search" header in the response.

func (*Response) NotAcceptable

func (r *Response) NotAcceptable(body ...any) *Response

NotAcceptable sets the HTTP status code to 406 Not Acceptable and optionally sets the response body.

func (*Response) NotFound

func (r *Response) NotFound(body ...any) *Response

NotFound sets the HTTP status code to 404 Not Found and optionally sets the response body.

func (*Response) NotModified

func (r *Response) NotModified() *Response

NotModified sets the HTTP status code to 304 Not Modified.

func (*Response) PreconditionFailed

func (r *Response) PreconditionFailed() *Response

PreconditionFailed sets the HTTP status code to 412 Precondition Failed.

func (*Response) PreferenceApplied

func (r *Response) PreferenceApplied(preference string) *Response

PreferenceApplied sets the "Preference-Applied" header in the response.

func (*Response) ProxyAuthRequired

func (r *Response) ProxyAuthRequired(body ...any) *Response

ProxyAuthRequired sets the HTTP status code to 407 Proxy Authentication Required.

func (*Response) ProxyAuthenticate

func (r *Response) ProxyAuthenticate(challenge string) *Response

ProxyAuthenticate sets the "Proxy-Authenticate" header in the response.

func (*Response) ReferrerPolicy

func (r *Response) ReferrerPolicy(policy string) *Response

ReferrerPolicy sets the "Referrer-Policy" header in the response.

func (*Response) Refresh

func (r *Response) Refresh(timeSeconds int, url string) *Response

Refresh sets the "Refresh" header in the response.

func (*Response) ReportingEndpoints

func (r *Response) ReportingEndpoints(endpoints ...string) *Response

ReportingEndpoints sets the "Reporting-Endpoints" header in the response.

func (*Response) RetryAfterDate

func (r *Response) RetryAfterDate(t time.Time) *Response

RetryAfterDate sets the "Retry-After" header in the response.

func (*Response) RetryAfterSeconds

func (r *Response) RetryAfterSeconds(seconds int) *Response

RetryAfterSeconds sets the "Retry-After" header in the response.

func (*Response) Server

func (r *Response) Server(server string) *Response

Server sets the "Server" header in the response.

func (*Response) ServerTiming

func (r *Response) ServerTiming(timing string) *Response

ServerTiming sets the "Server-Timing" header in the response.

func (*Response) ServiceWorkerAllowed

func (r *Response) ServiceWorkerAllowed(scope string) *Response

ServiceWorkerAllowed sets the "Service-Worker-Allowed" header in the response.

func (*Response) SourceMap

func (r *Response) SourceMap(url string) *Response

SourceMap sets the "SourceMap" header in the response.

func (*Response) Status

func (r *Response) Status(status int) *Response

Status sets the HTTP status code for the response.

func (*Response) StrictTransportSecurity

func (r *Response) StrictTransportSecurity(value string) *Response

StrictTransportSecurity sets the "Strict-Transport-Security" header in the response.

func (*Response) Text

func (r *Response) Text(text string) *Response

Text sets the response body to a plain text string. The Content-Type header is automatically set to "text/plain;charset=UTF-8".

func (*Response) TimingAllowOrigin

func (r *Response) TimingAllowOrigin(origin string) *Response

TimingAllowOrigin sets the "Timing-Allow-Origin" header in the response.

func (*Response) Trailer

func (r *Response) Trailer(headerNames string) *Response

Trailer sets the "Trailer" header in the response.

func (*Response) TransferEncoding

func (r *Response) TransferEncoding(encodings ...string) *Response

TransferEncoding sets the "Transfer-Encoding" header in the response.

func (*Response) Unauthorized

func (r *Response) Unauthorized(body ...any) *Response

Unauthorized sets the HTTP status code to 401 Unauthorized and optionally sets the response body.

func (*Response) Vary

func (r *Response) Vary(headers ...string) *Response

Vary sets the "Vary" header in the response.

func (*Response) Via

func (r *Response) Via(via string) *Response

Via sets the "Via" header in the response. The value will be added to the existing "Via" header.

func (*Response) Write

func (r *Response) Write(w http.ResponseWriter) error

Write writes the response to the http.ResponseWriter. It sets the headers and writes the body to the writer.

func (*Response) WwwHauthenticate

func (r *Response) WwwHauthenticate(challenge string) *Response

WwwAuthenticate sets the "WWW-Authenticate" header in the response.

func (*Response) XContentTypeOptions

func (r *Response) XContentTypeOptions() *Response

XContentTypeOptions sets the "X-Content-Type-Options" header in the response.

func (*Response) XFrameOptions

func (r *Response) XFrameOptions(directive string) *Response

XFrameOptions sets the "X-Frame-Options" header in the response.

func (*Response) XPermittedCrossDomainPolicies

func (r *Response) XPermittedCrossDomainPolicies(directive string) *Response

XPermittedCrossDomainPolicies sets the "X-Permitted-Cross-Domain-Policies" header in the response.

func (*Response) XPoweredBy

func (r *Response) XPoweredBy(application string) *Response

XPoweredBy sets the "X-Powered-By" header in the response.

type Server

type Server struct {
	MaxMultipartMemory int64
	// contains filtered or unexported fields
}

Server represents an HTTP server that can handle requests and responses.

func NewServer

func NewServer() *Server

NewServer creates a new Server with a new ServeMux.

func (*Server) ANY added in v0.5.0

func (s *Server) ANY(path string, handler Handler, middleware ...Middleware)

ANY adds a new route for all methods with the given path, handler, and middleware.

func (*Server) DELETE

func (s *Server) DELETE(path string, handler Handler, middleware ...Middleware)

DELETE adds a new route for the DELETE method with the given path, handler, and middleware.

func (*Server) GET

func (s *Server) GET(path string, handler Handler, middleware ...Middleware)

GET adds a new route for the GET method with the given path, handler, and middleware.

func (*Server) Group

func (s *Server) Group(path string, middleware ...Middleware) *Group

Group creates a new Group with the given path.

func (*Server) HEAD

func (s *Server) HEAD(path string, handler Handler, middleware ...Middleware)

HEAD adds a new route for the HEAD method with the given path, handler, and middleware.

func (*Server) Handle added in v0.6.0

func (s *Server) Handle(pattern string, handler http.Handler)

Handle adds a raw http.Handler to the Server. Note that no middleware is applied to the handler.

func (*Server) HandleFunc added in v0.5.0

func (s *Server) HandleFunc(pattern string, handler http.HandlerFunc)

HandleFunc adds a raw http.HandlerFunc to the Server. It is useful for handling requests that don't fit into the standard routing patterns. Note that no middleware is applied to the handler.

func (*Server) Handler

func (s *Server) Handler() http.Handler

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(address string) error

ListenAndServe starts the server and listens for incoming requests on the given address.

func (*Server) OPTIONS

func (s *Server) OPTIONS(path string, handler Handler, middleware ...Middleware)

OPTIONS adds a new route for the OPTIONS method with the given path, handler, and middleware.

func (*Server) PATCH added in v0.5.0

func (s *Server) PATCH(path string, handler Handler, middleware ...Middleware)

PATCH adds a new route for the PATCH method with the given path, handler, and middleware.

func (*Server) POST

func (s *Server) POST(path string, handler Handler, middleware ...Middleware)

POST adds a new route for the POST method with the given path, handler, and middleware.

func (*Server) PUT

func (s *Server) PUT(path string, handler Handler, middleware ...Middleware)

PUT adds a new route for the PUT method with the given path, handler, and middleware.

func (*Server) SetMaxMultipartMemory

func (s *Server) SetMaxMultipartMemory(max int64) *Server

func (*Server) SetRemoteIPHeaders

func (s *Server) SetRemoteIPHeaders(headers ...string) *Server

func (*Server) SetTrustRemoteIdHeaders

func (s *Server) SetTrustRemoteIdHeaders(trust bool) *Server

func (*Server) Use

func (s *Server) Use(middleware ...Middleware) *Server

Use adds middleware to the Server.

type Validatable

type Validatable interface {
	// Validate validates the object and returns an error if the object is invalid.
	Validate() error
}

Validatable represents an object that can be validated.

type ValidationError added in v0.2.0

type ValidationError struct {
	Code    string      `json:"code"`
	Message string      `json:"message"`
	Errors  []Violation `json:"errors"`
}

func Require added in v0.2.0

func Require(field, code, message string, cond bool, prev *ValidationError) *ValidationError

Require validates a condition and returns a ValidationError if the condition is false. If the condition is true, it returns the previous ValidationError unchanged. This allows for chaining multiple validation checks together.

func RequireEnumValue added in v0.2.0

func RequireEnumValue[T comparable](field string, value T, allowed []T, prev *ValidationError) *ValidationError

RequireEnumValue validates that a value is in the allowed list. It returns a ValidationError with ValidationCodeInvalid if the value is not in the allowed list. If the value is in the allowed list, it returns the previous ValidationError unchanged.

func RequireEnumValueIndexed added in v0.2.0

func RequireEnumValueIndexed[T comparable](fieldFormat string, index int, value T, allowed []T, prev *ValidationError) *ValidationError

It returns a ValidationError with ValidationCodeInvalid if the value is not in the allowed list. If the value is in the allowed list, it returns the previous ValidationError unchanged.

func RequireIndexed added in v0.2.0

func RequireIndexed(fieldFormat string, index int, code string, messageFormat string, cond bool, prev *ValidationError) *ValidationError

RequireIndexed validates a condition and returns a ValidationError if the condition is false. If the condition is true, it returns the previous ValidationError unchanged. This allows for chaining multiple validation checks together. The field name is formatted using the fieldFormat string and the index. The message is formatted using the messageFormat string and the index.

func RequireMaxLength added in v0.2.0

func RequireMaxLength(field string, max int, value string, prev *ValidationError) *ValidationError

RequireMaxLength validates that a string value has at most the specified maximum length. It returns a ValidationError with ValidationCodeTooLong if the value is longer than max. If the value meets the maximum length, it returns the previous ValidationError unchanged.

func RequireMaxLengthIndexed added in v0.2.0

func RequireMaxLengthIndexed(fieldFormat string, index int, max int, value string, prev *ValidationError) *ValidationError

RequireMaxLengthIndexed validates that a string value has at most the specified maximum length. It returns a ValidationError with ValidationCodeTooLong if the value is longer than max. If the value meets the maximum length, it returns the previous ValidationError unchanged. The field name is formatted using the fieldFormat string and the index. The message is formatted using the fieldFormat string and the index.

func RequireMaxLengthSlice added in v0.2.0

func RequireMaxLengthSlice[T any](field string, max int, value []T, prev *ValidationError) *ValidationError

RequireMaxLengthSlice validates that a slice has at most the specified maximum length. It returns a ValidationError with ValidationCodeTooManyItems if the slice is longer than max. If the slice meets the maximum length, it returns the previous ValidationError unchanged.

func RequireMaxLengthSliceIndexed added in v0.2.0

func RequireMaxLengthSliceIndexed[T any](fieldFormat string, index int, max int, value []T, prev *ValidationError) *ValidationError

It returns a ValidationError with ValidationCodeTooManyItems if the slice is longer than max. If the slice meets the maximum length, it returns the previous ValidationError unchanged.

func RequireMinLength added in v0.2.0

func RequireMinLength(field string, min int, value string, prev *ValidationError) *ValidationError

RequireMinLength validates that a string value has at least the specified minimum length. It returns a ValidationError with ValidationCodeTooShort if the value is shorter than min. If the value meets the minimum length, it returns the previous ValidationError unchanged.

func RequireMinLengthIndexed added in v0.2.0

func RequireMinLengthIndexed(fieldFormat string, index int, min int, value string, prev *ValidationError) *ValidationError

RequireMinLengthIndexed validates that a string value has at least the specified minimum length. It returns a ValidationError with ValidationCodeTooShort if the value is shorter than min. If the value meets the minimum length, it returns the previous ValidationError unchanged. The field name is formatted using the fieldFormat string and the index. The message is formatted using the fieldFormat string and the index.

func RequireMinLengthSlice added in v0.2.0

func RequireMinLengthSlice[T any](field string, min int, value []T, prev *ValidationError) *ValidationError

RequireMinLengthSlice validates that a slice has at least the specified minimum length. It returns a ValidationError with ValidationCodeTooFewItems if the slice is shorter than min. If the slice meets the minimum length, it returns the previous ValidationError unchanged.

func RequireMinLengthSliceIndexed added in v0.2.0

func RequireMinLengthSliceIndexed[T any](fieldFormat string, index int, min int, value []T, prev *ValidationError) *ValidationError

RequireMinLengthSliceIndexed validates that a slice has at least the specified minimum length. It returns a ValidationError with ValidationCodeTooFewItems if the slice is shorter than min. If the slice meets the minimum length, it returns the previous ValidationError unchanged.

func RequireNotEmpty added in v0.2.0

func RequireNotEmpty(field string, value string, prev *ValidationError) *ValidationError

RequireNotEmpty validates that a string value is not empty. It returns a ValidationError with ValidationCodeRequired if the value is empty. If the value is not empty, it returns the previous ValidationError unchanged.

func RequireNotEmptyIndexed added in v0.2.0

func RequireNotEmptyIndexed(fieldFormat string, index int, value string, prev *ValidationError) *ValidationError

RequireNotEmptyIndexed validates that a string value is not empty. It returns a ValidationError with ValidationCodeRequired if the value is empty. If the value is not empty, it returns the previous ValidationError unchanged. The field name is formatted using the fieldFormat string and the index. The message is formatted using the fieldFormat string and the index.

func RequireNotEmptySlice added in v0.2.0

func RequireNotEmptySlice[T any](field string, value []T, prev *ValidationError) *ValidationError

RequireNotEmptySlice validates that a slice is not empty. It returns a ValidationError with ValidationCodeRequired if the slice is empty. If the slice is not empty, it returns the previous ValidationError unchanged.

func RequireNotEmptySliceIndexed added in v0.2.0

func RequireNotEmptySliceIndexed[T any](fieldFormat string, index int, value []T, prev *ValidationError) *ValidationError

RequireNotEmptySliceIndexed validates that a slice is not empty. It returns a ValidationError with ValidationCodeRequired if the slice is empty. If the slice is not empty, it returns the previous ValidationError unchanged.

func RequireRegex added in v0.2.0

func RequireRegex(field string, value string, pattern *regexp.Regexp, prev *ValidationError) *ValidationError

RequireRegex validates that a string value matches the specified regular expression. It returns a ValidationError with ValidationCodeInvalid if the value does not match the pattern. If the value matches the pattern, it returns the previous ValidationError unchanged.

func RequireRegexIndexed added in v0.2.0

func RequireRegexIndexed(fieldFormat string, index int, value string, pattern *regexp.Regexp, prev *ValidationError) *ValidationError

RequireRegexIndexed validates that a string value matches the specified regular expression. It returns a ValidationError with ValidationCodeInvalid if the value does not match the pattern. If the value matches the pattern, it returns the previous ValidationError unchanged.

func (*ValidationError) Error added in v0.2.0

func (e *ValidationError) Error() string

type Violation added in v0.2.0

type Violation struct {
	Field   string `json:"field"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

Directories

Path Synopsis
examples
01_basic_server command
02_groups command
03_middleware command
06_validation command
07_simple_spa command
any command
basic command
head command
raw_handler command
The proxy package is experimental.
The proxy package is experimental.
The spa package is experimental.
The spa package is experimental.

Jump to

Keyboard shortcuts

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