http

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package http re-exports commonly used net/http symbols so that consumers only need a single import: "github.com/CodeSyncr/nimbus/http".

Index

Constants

View Source
const (
	SameSiteDefaultMode = stdlib.SameSiteDefaultMode
	SameSiteLaxMode     = stdlib.SameSiteLaxMode
	SameSiteStrictMode  = stdlib.SameSiteStrictMode
	SameSiteNoneMode    = stdlib.SameSiteNoneMode
)

SameSite mode constants.

View Source
const (
	MethodGet     = stdlib.MethodGet
	MethodHead    = stdlib.MethodHead
	MethodPost    = stdlib.MethodPost
	MethodPut     = stdlib.MethodPut
	MethodPatch   = stdlib.MethodPatch
	MethodDelete  = stdlib.MethodDelete
	MethodConnect = stdlib.MethodConnect
	MethodOptions = stdlib.MethodOptions
	MethodTrace   = stdlib.MethodTrace
)
View Source
const (
	StatusContinue           = stdlib.StatusContinue
	StatusSwitchingProtocols = stdlib.StatusSwitchingProtocols

	StatusOK             = stdlib.StatusOK
	StatusCreated        = stdlib.StatusCreated
	StatusAccepted       = stdlib.StatusAccepted
	StatusNoContent      = stdlib.StatusNoContent
	StatusResetContent   = stdlib.StatusResetContent
	StatusPartialContent = stdlib.StatusPartialContent

	StatusMovedPermanently  = stdlib.StatusMovedPermanently
	StatusFound             = stdlib.StatusFound
	StatusSeeOther          = stdlib.StatusSeeOther
	StatusNotModified       = stdlib.StatusNotModified
	StatusTemporaryRedirect = stdlib.StatusTemporaryRedirect
	StatusPermanentRedirect = stdlib.StatusPermanentRedirect

	StatusBadRequest          = stdlib.StatusBadRequest
	StatusUnauthorized        = stdlib.StatusUnauthorized
	StatusPaymentRequired     = stdlib.StatusPaymentRequired
	StatusForbidden           = stdlib.StatusForbidden
	StatusNotFound            = stdlib.StatusNotFound
	StatusMethodNotAllowed    = stdlib.StatusMethodNotAllowed
	StatusConflict            = stdlib.StatusConflict
	StatusGone                = stdlib.StatusGone
	StatusUnprocessableEntity = stdlib.StatusUnprocessableEntity
	StatusTooManyRequests     = stdlib.StatusTooManyRequests

	StatusInternalServerError = stdlib.StatusInternalServerError
	StatusNotImplemented      = stdlib.StatusNotImplemented
	StatusBadGateway          = stdlib.StatusBadGateway
	StatusServiceUnavailable  = stdlib.StatusServiceUnavailable
	StatusGatewayTimeout      = stdlib.StatusGatewayTimeout
)

Variables

View Source
var Error = stdlib.Error

Error replies to the request with the specified error message and HTTP code.

View Source
var FileServer = stdlib.FileServer

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.

View Source
var ListenAndServe = stdlib.ListenAndServe

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections.

View Source
var MaxBytesReader = stdlib.MaxBytesReader

MaxBytesReader limits the size of an incoming request body.

View Source
var NewServeMux = stdlib.NewServeMux

NewServeMux allocates and returns a new ServeMux.

View Source
var NotFoundHandler = stdlib.NotFoundHandler

NotFoundHandler returns a simple handler that replies with a 404 not found error.

View Source
var ServeFile = stdlib.ServeFile

ServeFile replies to the request with the contents of the named file.

View Source
var SetCookie = stdlib.SetCookie

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.

View Source
var StatusText = stdlib.StatusText

StatusText returns a text for the HTTP status code.

View Source
var StdRedirect = stdlib.Redirect

Redirect replies to the request with a redirect to url.

View Source
var StripPrefix = stdlib.StripPrefix

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path.

Functions

func SPAHandler

func SPAHandler(dir string) http.HandlerFunc

SPAHandler serves an SPA: serves static files from dir, falls back to index.html.

func ServeStatic

func ServeStatic(dir string) http.Handler

ServeStatic serves static files from the given directory.

func ServeStaticFile

func ServeStaticFile(filePath string) http.HandlerFunc

ServeStaticFile serves a single file.

Types

type Authenticator

type Authenticator interface {
	User() (any, error)
	Login(user any) error
	Logout() error
	Check() bool
}

Authenticator provides AdonisJS-style auth access on the context. Implemented by auth.Accessor so controllers can write c.Auth().User() instead of container.MustMake("auth.guard").(auth.Guard).

type Container

type Container interface {
	Make(key string) (any, error)
	MustMake(key string) any
}

type Context

type Context struct {
	Request   *Request
	Response  ResponseWriter
	Session   Session
	Container Container
	Params    map[string]string
	// contains filtered or unexported fields
}

Context wraps an HTTP request and response with AdonisJS-style helpers.

func New

func New(w ResponseWriter, r *Request, params map[string]string) *Context

New creates a new request context.

func (*Context) Abort

func (c *Context) Abort(code int) error

Abort writes the given status code with no body and returns a generic error.

func (*Context) AbortWithJSON

func (c *Context) AbortWithJSON(code int, body any) error

AbortWithJSON sends a JSON error and returns an error.

func (*Context) Accepted

func (c *Context) Accepted(body any) error

Accepted sends a 202 Accepted JSON response.

func (*Context) All

func (c *Context) All() map[string]string

All returns all form values + query params merged into a map.

func (*Context) Attachment

func (c *Context) Attachment(filename string)

Attachment sets the Content-Disposition header to "attachment".

func (*Context) Auth

func (c *Context) Auth() Authenticator

Auth returns the AdonisJS-style auth accessor for this request. Usage: user, err := c.Auth().User()

func (*Context) BadRequest

func (c *Context) BadRequest(body any) error

BadRequest sends a 400 Bad Request JSON response.

func (*Context) Bind

func (c *Context) Bind(v any) error

Bind decodes the request body (JSON or form) into v. Content-Type is auto-detected.

func (*Context) BindJSON

func (c *Context) BindJSON(v any) error

BindJSON explicitly binds JSON body into v.

func (*Context) CacheControl

func (c *Context) CacheControl(directives string) *Context

CacheControl sets the Cache-Control response header.

func (*Context) ClearCookie

func (c *Context) ClearCookie(name, path, domain string)

ClearCookie removes a cookie by setting MaxAge to -1.

func (*Context) ContentType

func (c *Context) ContentType(ct string) *Context

ContentType sets the Content-Type response header.

func (*Context) Cookie

func (c *Context) Cookie(name string, def ...string) string

Cookie returns a cookie value by name, or the default.

func (*Context) Created

func (c *Context) Created(body any) error

Created sends a 201 Created JSON response.

func (*Context) Ctx

func (c *Context) Ctx() context.Context

Ctx returns the request's context.Context. Use this to pass deadlines, cancellation signals, and request-scoped values to downstream calls (database queries, HTTP clients, etc.).

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte)

Data sends raw bytes with the given content type.

func (*Context) Deadline

func (c *Context) Deadline() (deadline interface{ IsZero() bool }, ok bool)

Deadline returns the deadline from the request context, if any.

func (*Context) Done

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

Done returns the request context's Done channel.

func (*Context) Download

func (c *Context) Download(filePath, fileName string) error

Download sends a file as an attachment with the given filename.

func (*Context) Err

func (c *Context) Err() error

Err returns the request context's error (nil, context.Canceled, or context.DeadlineExceeded).

func (*Context) Except

func (c *Context) Except(keys ...string) map[string]string

Except returns all input except the given keys.

func (*Context) Expires

func (c *Context) Expires(t time.Time) *Context

Expires sets the Expires header.

func (*Context) File

func (c *Context) File(name string) (multipart.File, *multipart.FileHeader, error)

File returns the uploaded file for the given form field name.

func (*Context) Files

func (c *Context) Files(name string) []*multipart.FileHeader

Files returns all uploaded files for a form field (e.g. "photos[]").

func (*Context) Filled

func (c *Context) Filled(keys ...string) bool

Filled returns true if all given keys are present and non-empty.

func (*Context) Flush

func (c *Context) Flush()

Flush flushes the response writer if it supports flushing.

func (*Context) Forbidden

func (c *Context) Forbidden(body ...any) error

Forbidden sends a 403 Forbidden JSON response.

func (*Context) FullURL

func (c *Context) FullURL() string

FullURL returns the full request URL including scheme and host. Trusts X-Forwarded-Proto for scheme detection — use middleware.TrustedProxies to strip this header from untrusted sources.

func (*Context) Get

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

Get retrieves a value from the request-scoped store.

func (*Context) HTML

func (c *Context) HTML(code int, html string)

HTML sends an HTML response with the given status code.

func (*Context) Has

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

Has returns true if the input key exists and is non-empty.

func (*Context) HasFile

func (c *Context) HasFile(name string) bool

HasFile returns true if a file was uploaded for the field.

func (*Context) Header

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

Header returns a request header value.

func (*Context) IP

func (c *Context) IP() string

IP returns the client's IP address from forwarding headers or RemoteAddr. This method trusts X-Forwarded-For and X-Real-IP headers. For this to be safe in production, use middleware.TrustedProxies to strip these headers from untrusted sources before they reach your handlers.

func (*Context) Inline

func (c *Context) Inline(filePath, fileName string) error

Inline sends a file to be displayed inline (e.g. PDF in browser).

func (*Context) Input

func (c *Context) Input(key string, def ...string) string

Input returns a form or query parameter by key. Checks POST body first, then query string.

func (*Context) InputBool

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

InputBool returns a form or query parameter as bool. Truthy values: "1", "true", "yes", "on".

func (*Context) InputFloat

func (c *Context) InputFloat(key string, def float64) float64

InputFloat returns a form or query parameter as float64.

func (*Context) InputInt

func (c *Context) InputInt(key string, def int) int

InputInt returns a form or query parameter as int.

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax returns true if the request has X-Requested-With: XMLHttpRequest.

func (*Context) IsJSON

func (c *Context) IsJSON() bool

IsJSON returns true if the Accept header prefers JSON.

func (*Context) JSON

func (c *Context) JSON(code int, body any) error

JSON sends a JSON response.

func (*Context) LastModified

func (c *Context) LastModified(t time.Time) *Context

LastModified sets the Last-Modified header.

func (*Context) Method

func (c *Context) Method() string

Method returns the HTTP method.

func (*Context) MustGet

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

MustGet retrieves a value or panics if not found.

func (*Context) NoCache

func (c *Context) NoCache() *Context

NoCache sets headers to prevent browser caching.

func (*Context) NoContent

func (c *Context) NoContent()

NoContent sends a 204 No Content response.

func (*Context) NotFound

func (c *Context) NotFound(body ...any) error

NotFound sends a 404 Not Found JSON response.

func (*Context) Only

func (c *Context) Only(keys ...string) map[string]string

Only returns a subset of input matching the given keys.

func (*Context) Param

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

Param returns a route parameter by name.

func (*Context) Path

func (c *Context) Path() string

Path returns the request URL path.

func (*Context) Query

func (c *Context) Query(key string, def ...string) string

Query returns a query string parameter. Alias for URL query.

func (*Context) QueryBool

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

QueryBool returns a query parameter as bool.

func (*Context) QueryInt

func (c *Context) QueryInt(key string, def int) int

QueryInt returns a query parameter as an integer, or the default value.

func (*Context) Redirect

func (c *Context) Redirect(code int, url string)

Redirect sends a redirect response.

func (*Context) Require

func (c *Context) Require(key string) (any, error)

Require retrieves a stored value or returns an error when missing. Prefer this in runtime code paths where panics are undesirable.

func (*Context) SSE

func (c *Context) SSE(event, data string) error

SSE sends a Server-Sent Event. Call multiple times for streaming.

func (*Context) SendFile

func (c *Context) SendFile(dir, file string)

SendFile serves a file from the filesystem.

func (*Context) ServerError

func (c *Context) ServerError(body ...any) error

ServerError sends a 500 Internal Server Error JSON response.

func (*Context) Set

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

Set stores a key-value pair in the request-scoped store.

func (*Context) SetAuth

func (c *Context) SetAuth(a Authenticator)

SetAuth sets the auth accessor (called by auth.Init middleware).

func (*Context) SetCookie

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie sets a response cookie with the given parameters.

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader sets a response header.

func (*Context) Status

func (c *Context) Status(code int) *Context

Status sets the HTTP status code for the next response write. Does NOT flush headers immediately — the actual WriteHeader call happens when JSON/View/String/HTML writes the response body.

func (*Context) StatusCode

func (c *Context) StatusCode() int

StatusCode returns the current HTTP status code.

func (*Context) Stream

func (c *Context) Stream(code int, contentType string, fn func(w io.Writer) error) error

Stream sends a streaming response. The callback writes directly to the response.

func (*Context) StreamJSON

func (c *Context) StreamJSON(code int, fn func(enc *json.Encoder) error) error

StreamJSON sends a streaming JSON response (useful for large datasets).

func (*Context) String

func (c *Context) String(code int, s string)

String sends a plain text response.

func (*Context) Unauthorized

func (c *Context) Unauthorized(body ...any) error

Unauthorized sends a 401 Unauthorized JSON response.

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent returns the User-Agent header.

func (*Context) View

func (c *Context) View(name string, data any) error

View renders a .nimbus template and sends HTML response. When Shield CSRF is enabled, csrfField is auto-injected so templates can use {{ .csrfField }}.

func (*Context) WithContext

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

WithContext returns a shallow copy of Context with the request's context replaced by ctx. Use this to attach deadlines or values:

ctx, cancel := context.WithTimeout(c.Ctx(), 5*time.Second)
defer cancel()
c = c.WithContext(ctx)

func (*Context) Write

func (c *Context) Write(data []byte) (int, error)

Write implements io.Writer on the response.

func (*Context) WriteString

func (c *Context) WriteString(s string) (int, error)

WriteString writes a string to the response.

type Cookie = stdlib.Cookie

Cookie is a re-export of net/http.Cookie.

type Dir

type Dir = stdlib.Dir

Dir is a re-export of net/http.Dir.

type FileSystem

type FileSystem = stdlib.FileSystem

FileSystem is a re-export of net/http.FileSystem.

type Flusher

type Flusher = stdlib.Flusher

Flusher is implemented by ResponseWriters that allow flushing buffered data.

type Handler

type Handler = stdlib.Handler

Handler is a re-export of net/http.Handler.

type Header = stdlib.Header

Header is a re-export of net/http.Header.

type Request

type Request = stdlib.Request

Request is a re-export of net/http.Request.

type ResponseWriter

type ResponseWriter = stdlib.ResponseWriter

ResponseWriter is a re-export of net/http.ResponseWriter.

type SameSite

type SameSite = stdlib.SameSite

SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests.

type ServeMux

type ServeMux = stdlib.ServeMux

ServeMux is a re-export of net/http.ServeMux.

type Session

type Session interface {
	Get(key string) any
	Set(key string, val any)
	Delete(key string)
	GetFlash(key string) any
	SetFlash(key string, val any)
	Regenerate()
}

type StdHandlerFunc

type StdHandlerFunc = stdlib.HandlerFunc

HandlerFunc is a re-export of net/http.HandlerFunc. Note: renamed to StdHandlerFunc to avoid conflict with router.HandlerFunc.

Jump to

Keyboard shortcuts

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