inertia

package module
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2023 License: MIT Imports: 15 Imported by: 2

README

inertia-echo

test MIT License Go Reference

The Inertia.js server-side adapter for Echo Go web framework.

Inertia.js is a JavaScript library that allows you to build a fully JavaScript-based single-page app without complexity. I assume that you are familiar with Inertia.js and how it works. You also need to familiarize yourself with Echo, a Go web framework. The inertia-echo assists you in developing web applications that leverage both of these technologies.

Installation

go get github.com/kohkimakimoto/inertia-echo

Minimum example

Please see Hello World example.

Usage

Shorthand routes

The inertia-echo provides a helper function for shorthand routes like Official Laravel Adapter.

e.GET("/about", inertia.Handler("About"))

See also the official document: Routing

Responses

Creating responses.

func ShowEventsHandler(c echo.Context) error {
	event := // retrieve a event...
	return inertia.Render(c, http.StatusOK, "Event/Show", map[string]interface{}{
		"Event": event,
	})
}

Root template data.

<meta name="twitter:title" content="{{ .page.Props.Event.Title }}">

Sometimes you may even want to provide data that will not be sent to your JavaScript component.

func ShowEventsHandler(c echo.Context) error {
	event := // retrieve a event...
	return inertia.RenderWithViewData(c, http.StatusOK, "Event/Show", map[string]interface{}{
		"Event": event,
	}, map[string]interface{}{
		"Meta": "Meta data...",
	})
}

You can then access this variable like a regular template variable.

<meta name="twitter:title" content="{{ .Meta }}">

See also the official document: Responses

Redirects

You can use Echo's standard way to redirect.

return c.Redirect(http.StatusFound, "/")

The following is a way to redirect to an external website in Inertia apps.

return inertia.Location(c, "/path/to/external")

See also the official document: Redirects

Shared data

Set shared data via middleware.

e.Use(inertia.MiddlewareWithConfig(inertia.MiddlewareConfig{
	Share: func(c echo.Context) (map[string]interface{}, error) {
		user := // get auth user...
		return map[string]interface{}{
			"AppName":  "App Name",
			"AuthUser": user,
		}, nil
	},
}))

Set shared data manually.

inertia.Share(c, map[string]interface{}{
	"AppName":  "App Name",
	"AuthUser": user,
})

See also the official document: Shared data

Partial reloads
inertia.Render(c, http.StatusOK, "Index", map[string]interface{}{
	// ALWAYS included on first visit
	// OPTIONALLY included on partial reloads
	// ALWAYS evaluated
	"users": users,

	// ALWAYS included on first visit...
	// OPTIONALLY included on partial reloads...
	// ONLY evaluated when needed...
	"users": func() (interface{}, error) {
		users, err := // get users...
		if err != nil {
			return nil, err
		}
		return users
	},

	// NEVER included on first visit
	// OPTIONALLY included on partial reloads
	// ONLY evaluated when needed
	"users": inertia.Lazy(func() (interface{}, error) {
		users, err := // get users...
		if err != nil {
			return nil, err
		}
		return users, nil
	}),
})

See also the official document: Partial reloads

Asset versioning

Configure asset version via middleware.

e.Use(inertia.MiddlewareWithConfig(inertia.MiddlewareConfig{
	VersionFunc: func() string { return version },
}))

Configure asset version manually.

inertia.SetVersion(c, func() string { return version })

See also the official document: Assset versioning

Server-side Rendering (SSR)

The inertia-echo supports SSR. Please see SSR Node.js example.

See also the official document: Server-side Rendering (SSR)

Unsupported features

Validation

The inertia-echo does not support validation, as Echo lacks built-in validation. The implementation of validation is up to you. If you wish to handle validation errors with inertia-echo, you will need to implement it yourself.

See also the official document: Validation

Demo application

Author

Kohki Makimoto kohki.makimoto@gmail.com

License

The MIT License (MIT)

Documentation

Index

Constants

View Source
const (
	HeaderXInertia                 = "X-Inertia"
	HeaderXInertiaVersion          = "X-Inertia-Version"
	HeaderXInertiaLocation         = "X-Inertia-Location"
	HeaderXInertiaPartialData      = "X-Inertia-Partial-Data"
	HeaderXInertiaPartialComponent = "X-Inertia-Partial-Component"
)

Variables

View Source
var (
	ErrNotFound              = errors.New("inertia-echo: context does not have 'Inertia'")
	ErrRendererNotRegistered = errors.New("inertia-echo: renderer not registered")
)
View Source
var DefaultCSRFConfig = CSRFConfig{
	Skipper:        middleware.DefaultSkipper,
	TokenLength:    32,
	TokenLookup:    "header:X-XSRF-TOKEN",
	ContextKey:     "csrf",
	CookieName:     "XSRF-TOKEN",
	CookieMaxAge:   86400,
	CookieSameSite: http.SameSiteDefaultMode,
	CookiePath:     "/",
}
View Source
var DefaultMiddlewareConfig = MiddlewareConfig{
	Skipper:       middleware.DefaultSkipper,
	RootView:      "app.html",
	VersionFunc:   defaultVersionFunc(),
	Share:         nil,
	Renderer:      nil,
	IsSsrDisabled: false,
}

Functions

func CSRF

func CSRF() echo.MiddlewareFunc

func CSRFWithConfig added in v0.2.0

func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc

func FlushShared added in v0.5.0

func FlushShared(c echo.Context)

func Handler

func Handler(component string, props ...map[string]interface{}) echo.HandlerFunc

Handler is a helper function that makes an inertia route without implementing handler function.

func Has

func Has(c echo.Context) bool

func Location added in v0.5.0

func Location(c echo.Context, url string) error

func Middleware

func Middleware(r Renderer) echo.MiddlewareFunc

func MiddlewareWithConfig

func MiddlewareWithConfig(config MiddlewareConfig) echo.MiddlewareFunc

MiddlewareWithConfig returns an echo middleware that adds the Inertia instance to the context.

func Render added in v0.5.0

func Render(c echo.Context, code int, component string, props map[string]interface{}) error

func RenderWithViewData added in v0.5.0

func RenderWithViewData(c echo.Context, code int, component string, props, viewData map[string]interface{}) error

func RootView added in v0.5.0

func RootView(c echo.Context) string

func SetRootView added in v0.5.0

func SetRootView(c echo.Context, name string)

func SetVersion added in v0.5.0

func SetVersion(c echo.Context, version VersionFunc)

func Share added in v0.5.0

func Share(c echo.Context, props map[string]interface{})

func Shared added in v0.5.0

func Shared(c echo.Context) map[string]interface{}

func Version added in v0.5.0

func Version(c echo.Context) string

Types

type CSRFConfig added in v0.2.0

type CSRFConfig middleware.CSRFConfig

type HTMLRenderer added in v0.7.0

type HTMLRenderer struct {
	Debug       bool
	ContainerId string

	Vite             bool
	ViteDevServerURL string
	ViteBasePath     string
	ViteDisableReact bool
	ViteEntryPoints  []string

	SsrEngine SsrEngine
	// contains filtered or unexported fields
}

HTMLRenderer is a html/template renderer for Echo framework with inertia.js.

func NewRenderer

func NewRenderer() *HTMLRenderer

func (*HTMLRenderer) AddViteEntryPoint added in v0.7.0

func (r *HTMLRenderer) AddViteEntryPoint(entryPoint ...string)

func (*HTMLRenderer) Funcs added in v0.7.0

func (r *HTMLRenderer) Funcs(funcMap template.FuncMap) *HTMLRenderer

func (*HTMLRenderer) MustParse added in v0.7.0

func (r *HTMLRenderer) MustParse(text string) *HTMLRenderer

func (*HTMLRenderer) MustParseFS added in v0.7.0

func (r *HTMLRenderer) MustParseFS(f fs.FS, pattern string) *HTMLRenderer

func (*HTMLRenderer) MustParseGlob added in v0.7.0

func (r *HTMLRenderer) MustParseGlob(pattern string) *HTMLRenderer

func (*HTMLRenderer) MustParseViteManifest added in v0.7.0

func (r *HTMLRenderer) MustParseViteManifest(data []byte)

func (*HTMLRenderer) MustParseViteManifestFS added in v0.7.0

func (r *HTMLRenderer) MustParseViteManifestFS(f fs.FS, name string)

func (*HTMLRenderer) MustParseViteManifestFile added in v0.7.0

func (r *HTMLRenderer) MustParseViteManifestFile(name string)

func (*HTMLRenderer) Parse added in v0.7.0

func (r *HTMLRenderer) Parse(text string) (*HTMLRenderer, error)

func (*HTMLRenderer) ParseFS added in v0.7.0

func (r *HTMLRenderer) ParseFS(f fs.FS, pattern string) (*HTMLRenderer, error)

func (*HTMLRenderer) ParseGlob added in v0.7.0

func (r *HTMLRenderer) ParseGlob(pattern string) (*HTMLRenderer, error)

func (*HTMLRenderer) ParseViteManifest added in v0.7.0

func (r *HTMLRenderer) ParseViteManifest(data []byte) error

func (*HTMLRenderer) ParseViteManifestFS added in v0.7.0

func (r *HTMLRenderer) ParseViteManifestFS(f fs.FS, name string) error

func (*HTMLRenderer) ParseViteManifestFile added in v0.7.0

func (r *HTMLRenderer) ParseViteManifestFile(name string) error

func (*HTMLRenderer) Render added in v0.7.0

func (r *HTMLRenderer) Render(w io.Writer, name string, data map[string]interface{}, in *Inertia) error

Render renders HTML by using templates.

type Inertia

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

func Get

func Get(c echo.Context) (*Inertia, error)

func MustGet

func MustGet(c echo.Context) *Inertia

func (*Inertia) DisableSsr added in v0.7.0

func (i *Inertia) DisableSsr()

func (*Inertia) EnableSsr added in v0.7.0

func (i *Inertia) EnableSsr()

func (*Inertia) FlushShared

func (i *Inertia) FlushShared()

func (*Inertia) IsSsrDisabled added in v0.7.0

func (i *Inertia) IsSsrDisabled() bool

func (*Inertia) IsSsrEnabled added in v0.7.0

func (i *Inertia) IsSsrEnabled() bool

func (*Inertia) Location

func (i *Inertia) Location(url string) error

Location generates 409 response for external redirects see https://inertiajs.com/redirects#external-redirects

func (*Inertia) Render

func (i *Inertia) Render(code int, component string, props map[string]interface{}) error

func (*Inertia) RenderWithViewData

func (i *Inertia) RenderWithViewData(code int, component string, props, viewData map[string]interface{}) error

func (*Inertia) Renderer added in v0.6.0

func (i *Inertia) Renderer() Renderer

func (*Inertia) RootView added in v0.4.0

func (i *Inertia) RootView() string

func (*Inertia) SetRenderer added in v0.6.0

func (i *Inertia) SetRenderer(r Renderer)

func (*Inertia) SetRootView

func (i *Inertia) SetRootView(name string)

func (*Inertia) SetVersion

func (i *Inertia) SetVersion(version VersionFunc)

func (*Inertia) Share

func (i *Inertia) Share(props map[string]interface{})

func (*Inertia) Shared

func (i *Inertia) Shared() map[string]interface{}

func (*Inertia) Version

func (i *Inertia) Version() string

type LazyProp

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

func Lazy

func Lazy(callback LazyPropFunc) *LazyProp

Lazy defines a lazy evaluated data. see https://inertiajs.com/partial-reloads#lazy-data-evaluation

type LazyPropFunc added in v0.12.0

type LazyPropFunc func() (interface{}, error)

type MiddlewareConfig

type MiddlewareConfig struct {
	Skipper middleware.Skipper
	// The root template that's loaded on the first page visit.
	// see https://inertiajs.com/server-side-setup#root-template
	RootView string
	// Determines the current asset version.
	// see https://inertiajs.com/asset-versioning
	VersionFunc func() string
	// Defines the props that are shared by default.
	// see https://inertiajs.com/shared-data
	Share SharedDataFunc
	// Renderer is a renderer that is used for rendering the root view.
	Renderer Renderer
	// IsSsrDisabled is a flag that determines whether server-side rendering is disabled.
	IsSsrDisabled bool
}

type Page

type Page struct {
	Component string                 `json:"component"`
	Props     map[string]interface{} `json:"props"`
	URL       string                 `json:"url"`
	Version   string                 `json:"version"`
}

type Renderer

type Renderer interface {
	// Render renders a HTML for inertia.
	Render(io.Writer, string, map[string]interface{}, *Inertia) error
}

type ResponseWriterWrapper

type ResponseWriterWrapper struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseWriterWrapper is a wrapper of http.ResponseWriter for buffering a response status code. Inertia.js adapter needs to change the response status code in a middleware. For example, if a request has X-Inertia, the adapter change the response code to 303 from 302. see https://inertiajs.com/redirects

func NewResponseWriterWrapper

func NewResponseWriterWrapper(w http.ResponseWriter) *ResponseWriterWrapper

func (*ResponseWriterWrapper) FlushHeader

func (w *ResponseWriterWrapper) FlushHeader()

func (*ResponseWriterWrapper) WriteHeader

func (w *ResponseWriterWrapper) WriteHeader(statusCode int)

WriteHeader stores header instead of sending it, if it is not 200

type SharedDataFunc

type SharedDataFunc func(c echo.Context) (map[string]interface{}, error)

type SsrEngine added in v0.7.0

type SsrEngine interface {
	Render(*Page) (*SsrResponse, error)
}

type SsrResponse added in v0.7.0

type SsrResponse struct {
	Head []string `json:"head"`
	Body string   `json:"body"`
}

func (*SsrResponse) BodyHTML added in v0.7.0

func (r *SsrResponse) BodyHTML() template.HTML

func (*SsrResponse) HeadHTML added in v0.7.0

func (r *SsrResponse) HeadHTML() template.HTML

type VersionFunc

type VersionFunc func() string

type ViteManifest

type ViteManifest map[string]interface{}

Directories

Path Synopsis
examples
helloworld Module
ssr

Jump to

Keyboard shortcuts

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