inertia

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2025 License: MIT Imports: 24 Imported by: 0

README

inertia

gin + inertia, too fast — too complex; no documentation provided.

Documentation

Overview

Package inertia provides a Go web framework for building modern web applications using the Inertia.js approach.

Index

Constants

View Source
const ContextKey = "_inertia/contextkey"

ContextKey is the key that a Context returns itself for.

Variables

View Source
var (
	ErrorHandlerMap = map[int]ErrorHandlerFunc{
		http.StatusNotFound: func(w http.ResponseWriter, r *http.Request, err error) {
			http.NotFound(w, r)
		},
		http.StatusForbidden: func(w http.ResponseWriter, r *http.Request, err error) {
			http.Error(w, "403 Forbidden", http.StatusForbidden)
		},

		http.StatusInternalServerError: func(w http.ResponseWriter, r *http.Request, err error) {
			slog.Error(err.Error(), slog.Int("status", http.StatusInternalServerError), slog.String("method", r.Method), slog.String("path", r.URL.Path))
			http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
		},
	}
)

Functions

func Error

func Error(w http.ResponseWriter, err error, HTTPStatus int)

Error logs the error and sends an internal server error response.

Types

type Context

type Context struct {
	Meta    Meta
	Request *http.Request
	Writer  ResponseWriter
	Params  Params
	// contains filtered or unexported fields
}

func FromContext

func FromContext(ctx context.Context) (*Context, bool)

func MustFromContext

func MustFromContext(ctx context.Context) *Context

func (*Context) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.

func (*Context) AbortWithError

func (c *Context) AbortWithError(code int, err error)

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus calls `Abort()` and writes the headers with the specified status code.

func (*Context) ClientIP

func (c *Context) ClientIP() string

func (*Context) Data

func (c *Context) Data() map[string]any

func (*Context) Deadline

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

Deadline returns that there is no deadline (ok==false) when c.Request has no Context.

func (*Context) DefaultPostForm

func (c *Context) DefaultPostForm(key, defaultValue string) string

DefaultPostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns the specified defaultValue string. See: PostForm() and GetPostForm() for further information.

func (*Context) DefaultQuery

func (c *Context) DefaultQuery(key, defaultValue string) string

DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string. See: Query() and GetQuery() for further information.

GET /?name=Manu&lastname=
c.DefaultQuery("name", "unknown") == "Manu"
c.DefaultQuery("id", "none") == "none"
c.DefaultQuery("lastname", "none") == ""

func (*Context) Done

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

Done returns nil (chan which will wait forever) when c.Request has no Context.

func (*Context) Err

func (c *Context) Err() error

Err returns nil when c.Request has no Context.

func (*Context) Get

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

func (*Context) GetHeader

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

GetHeader returns value from request headers.

func (*Context) GetPostForm

func (c *Context) GetPostForm(key string) (string, bool)

GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded form or multipart form when it exists `(value, true)` (even when the value is an empty string), otherwise it returns ("", false). For example, during a PATCH request to update the user's email:

    [email protected]  -->  ("[email protected]", true) := GetPostForm("email") // set email to "[email protected]"
	   email=                  -->  ("", true) := GetPostForm("email") // set email to ""
                            -->  ("", false) := GetPostForm("email") // do nothing with email

func (*Context) GetPostFormArray

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

GetPostFormArray returns a slice of strings for a given form key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery is like Query(), it returns the keyed url query value if it exists `(value, true)` (even when the value is an empty string), otherwise it returns `("", false)`. It is shortcut for `c.Request.URL.Query().Get(key)`

GET /?name=Manu&lastname=
("Manu", true) == c.GetQuery("name")
("", false) == c.GetQuery("id")
("", true) == c.GetQuery("lastname")

func (*Context) GetQueryArray

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

GetQueryArray returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQueryMap

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

GetQueryMap returns a map for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) Header

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

Header is an intelligent shortcut for c.Writer.Header().Set(key, value). It writes a header in the response. If value == "", this method removes the header `c.Writer.Header().Del(key)`

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) JSON

func (c *Context) JSON(data any) error

func (*Context) Next

func (c *Context) Next()

Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler.

func (*Context) PostForm

func (c *Context) PostForm(key string) (value string)

PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string `("")`.

func (*Context) Query

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

Query returns the keyed url query value if it exists, otherwise it returns an empty string `("")`. It is shortcut for `c.Request.URL.Query().Get(key)`

    GET /path?id=1234&name=Manu&value=
	   c.Query("id") == "1234"
	   c.Query("name") == "Manu"
	   c.Query("value") == ""
	   c.Query("wtf") == ""

func (*Context) QueryArray

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

QueryArray returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.

func (*Context) QueryMap

func (c *Context) QueryMap(key string) (dicts map[string]string)

QueryMap returns a map for a given query key.

func (*Context) Render

func (c *Context) Render(view string) error

func (*Context) Set

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

func (*Context) SetMeta

func (c *Context) SetMeta(meta Meta)

func (*Context) Status

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) Value

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

Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.

func (*Context) Write

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

type ContextKeyType

type ContextKeyType int
const ContextRequestKey ContextKeyType = 0

type Engine

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

func New

func New(options ...Option) (*Engine, error)

func (*Engine) ANY

func (e *Engine) ANY(path string, fn func(c *Context))

func (*Engine) Addr

func (e *Engine) Addr() string

func (*Engine) DELETE

func (e *Engine) DELETE(path string, fn func(c *Context))

func (*Engine) DevAddr

func (e *Engine) DevAddr() string

func (*Engine) GET

func (e *Engine) GET(path string, fn func(c *Context))

func (*Engine) HEAD

func (e *Engine) HEAD(path string, fn func(c *Context))

func (*Engine) IsDevelopentMode

func (e *Engine) IsDevelopentMode() bool

IsDevelopentMode returns true if the engine is in development mode

func (*Engine) IsSSRMode

func (e *Engine) IsSSRMode() bool

IsSSRMode returns true if the engine is in SSR mode

func (*Engine) OPTIONS

func (e *Engine) OPTIONS(path string, fn func(c *Context))

func (*Engine) PATCH

func (e *Engine) PATCH(path string, fn func(c *Context))

func (*Engine) POST

func (e *Engine) POST(path string, fn func(c *Context))

func (*Engine) PUT

func (e *Engine) PUT(path string, fn func(c *Context))

func (*Engine) Serve

func (e *Engine) Serve() error

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Engine) StaticFS

func (e *Engine) StaticFS(path string, fs fs.FS)

StaticFS serves static assets from the given path

func (*Engine) Use

func (e *Engine) Use(middleware ...HandlerFunc)

Use allows to specify a middleware that should be executed for all the handlers in the group

type ErrorHandlerFunc

type ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)

type HandlerFunc

type HandlerFunc func(c *Context)

func StaticFileServer

func StaticFileServer(prefix string, root fs.FS) HandlerFunc

StaticFileServer returns an inertia.HandlerFunc that serves files from the given fs.FS.

func UseMeta

func UseMeta(defaultMeta *Meta) HandlerFunc

UseMeta creates a middleware that initializes Meta in context

type Meta

type Meta struct {
	Title       string            `json:"title,omitempty"`
	Description string            `json:"description,omitempty"`
	Keywords    string            `json:"keywords,omitempty"`
	Author      string            `json:"author,omitempty"`
	Viewport    string            `json:"viewport,omitempty"`
	Charset     string            `json:"charset,omitempty"`
	Custom      map[string]string `json:"custom,omitempty"`
	OpenGraph   OpenGraph         `json:"og,omitempty"`
	Twitter     TwitterCard       `json:"twitter,omitempty"`
}

Meta represents HTML meta information

func NewMeta

func NewMeta() *Meta

NewMeta creates a new Meta instance with default values

func (*Meta) AddCustom

func (m *Meta) AddCustom(name, content string) *Meta

AddCustom adds a custom meta tag

func (Meta) Clone

func (m Meta) Clone() Meta

func (*Meta) SetAuthor

func (m *Meta) SetAuthor(author string) *Meta

SetAuthor sets the page author

func (*Meta) SetDescription

func (m *Meta) SetDescription(description string) *Meta

SetDescription sets the page description

func (*Meta) SetKeywords

func (m *Meta) SetKeywords(keywords string) *Meta

SetKeywords sets the page keywords

func (*Meta) SetOpenGraph

func (m *Meta) SetOpenGraph(og OpenGraph) *Meta

SetOpenGraph sets Open Graph meta tags

func (*Meta) SetTitle

func (m *Meta) SetTitle(title string) *Meta

SetTitle sets the page title

func (*Meta) SetTwitterCard

func (m *Meta) SetTwitterCard(twitter TwitterCard) *Meta

SetTwitterCard sets Twitter Card meta tags

func (*Meta) ToHTML

func (m *Meta) ToHTML() string

ToHTML converts Meta to HTML meta tags

type Mode

type Mode byte
const (
	ModeProduction Mode = iota
	ModeDevelopment
	ModeSSR
)

type OpenGraph

type OpenGraph struct {
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Image       string `json:"image,omitempty"`
	URL         string `json:"url,omitempty"`
	Type        string `json:"type,omitempty"`
	SiteName    string `json:"site_name,omitempty"`
}

OpenGraph represents Open Graph meta tags

type Option

type Option func(e *Engine) error

Option is an option parameter that modifies Inertia.

func WithDevAddr

func WithDevAddr(addr string) Option

func WithErrorHandler

func WithErrorHandler(status int, errorHandlerFn ErrorHandlerFunc) Option

func WithMode

func WithMode(mode Mode) Option

func WithRootHTML

func WithRootHTML(html string) Option

func WithSSR

func WithSSR(ssr ssr.VM) Option

func WithTags

func WithTags(startTag, endTag string) Option

type Params

type Params []router.Parameter

func (Params) Get

func (p Params) Get(key string) string

func (Params) GetFloat32

func (p Params) GetFloat32(key string) (float32, bool)

func (Params) GetFloat64

func (p Params) GetFloat64(key string) (float64, bool)

func (Params) GetInt

func (p Params) GetInt(key string) (int, bool)

func (Params) GetInt64

func (p Params) GetInt64(key string) (int64, bool)

func (Params) GetUint

func (p Params) GetUint(key string) (uint, bool)

func (Params) GetUint64

func (p Params) GetUint64(key string) (uint64, bool)

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	http.CloseNotifier

	// Status returns the HTTP response status code of the current request.
	Status() int

	// Size returns the number of bytes already written into the response http body.
	// See Written()
	Size() int

	// WriteString writes the string into the response body.
	WriteString(string) (int, error)

	// Written returns true if the response body was already written.
	Written() bool

	// WriteHeaderNow forces to write the http header (status code + headers).
	WriteHeaderNow()

	// Pusher get the http.Pusher for server push
	Pusher() http.Pusher
}

ResponseWriter ...

type TagFunc

type TagFunc func(w io.Writer, tag string) (int, error)

type TwitterCard

type TwitterCard struct {
	Card        string `json:"card,omitempty"`
	Site        string `json:"site,omitempty"`
	Creator     string `json:"creator,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Image       string `json:"image,omitempty"`
}

TwitterCard represents Twitter Card meta tags

Directories

Path Synopsis
gosvel module
middleware module
ssr module
quickjs module

Jump to

Keyboard shortcuts

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