inertia

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2024 License: MIT Imports: 10 Imported by: 0

README

Inertia.js Go Adapter

GitHub Release Go Reference go.mod LICENSE Build Status Go Report Card Codecov

The Inertia.js server-side adapter for Go. Visit inertiajs.com to learn more.

Installation

Install the package using the go get command:

go get github.com/humweb/inertia-go

Usage

1. Create new instance
url := "http://inertia-app.test" // Application URL for redirect
rootTemplate := "./app.gohtml"   // Root template, see the example below
version := ""                    // Asset version

inertiaManager := inertia.New(url, rootTemplate, version)

Or create with embed.FS for root template:

import "embed"

//go:embed template
var templateFS embed.FS

// ...

inertiaManager := inertia.NewWithFS(url, rootTemplate, version, templateFS)
2. Register the middleware
mux := http.NewServeMux()
mux.Handle("/", inertiaManager.Middleware(homeHandler))
3. Render in handlers
func homeHandler(w http.ResponseWriter, r *http.Request) {
    // ...

    err := inertiaManager.Render(w, r, "home/Index", nil)
    if err != nil {
        // Handle server error...
    }
}

Or render with props:

// ...

err := inertiaManager.Render(w, r, "home/Index", inertiaManager.Props{
    "total": 32,
})

//...
4. Server-side Rendering (Optional)

First, enable SSR with the url of the Node server:

inertiaManager.EnableSsrWithDefault() // http://127.0.0.1:13714

Or with custom url:

inertiaManager.EnableSsr("http://ssr-host:13714")

This is a simplified example using Vue 3 and Laravel Mix.

// resources/js/ssr.js

import { createInertiaApp } from '@inertiajs/vue3';
import createServer from '@inertiajs/vue3/server';
import { renderToString } from '@vue/server-renderer';
import { createSSRApp, h } from 'vue';

createServer(page => createInertiaApp({
    page,
    render: renderToString,
    resolve: name => require(`./pages/${name}`),
    setup({ App, props, plugin }) {
        return createSSRApp({
            render: () => h(App, props)
        }).use(plugin);
    }
}));

The following config creates the ssr.js file in the root directory, which should not be embedded in the binary.

// webpack.ssr.mix.js

const mix = require('laravel-mix');
const webpackNodeExternals = require('webpack-node-externals');

mix.options({ manifest: false })
    .js('resources/js/ssr.js', '/')
    .vue({
        version: 3,
        options: {
            optimizeSSR: true
        }
    })
    .webpackConfig({
        target: 'node',
        externals: [
            webpackNodeExternals({
                allowlist: [
                    /^@inertiajs/
                ]
            })
        ]
    });

You can find the example for the SSR based root template below. For more information, please read the official Server-side Rendering documentation on inertiajs.com.

Examples

The following examples show how to use the package.

Share a prop globally
inertiaManager.Share("title", "Inertia App Title")
Share a function with root template
inertiaManager.ShareFunc("asset", assetFunc)
<script src="{{ asset "js/app.js" }}"></script>
Share a prop from middleware
func authenticate(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    
        ctx := inertiaManager.WithProp(r.Context(), "authUserID", user.ID)
        
        // or
        
        ctx := inertiaManager.WithProps(r.Context(), inertiaManager.Props{
            "authUserID": user.ID,
        })
        
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}
Share data with root template
ctx := inertiaManager.WithViewData(r.Context(), "meta", meta)
r = r.WithContext(ctx)
<meta name="description" content="{{ .meta }}">
Root template
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/app.css" rel="stylesheet">
        <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
        <div id="app" data-page="{{ marshal .page }}"></div>
        <script src="js/app.js"></script>
    </body>
</html>
Root template with Server-side Rendering (SSR)
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/app.css" rel="stylesheet">
        <link rel="icon" type="image/x-icon" href="favicon.ico">
        {{ if .ssr }}
            {{ raw .ssr.Head }}
        {{ end }}
    </head>
    <body>
        {{ if not .ssr }}
            <div id="app" data-page="{{ marshal .page }}"></div>
        {{ else }}
            {{ raw .ssr.Body }}
        {{ end }}
    </body>
</html>

Reporting Issues

If you are facing a problem with this package or found any bug, please open an issue on GitHub.

License

The MIT License (MIT). Please see License File for more information.

Documentation

Index

Constants

View Source
const ContextKeyProps contextKey = "props"

ContextKeyProps key.

View Source
const ContextKeyViewData contextKey = "viewData"

ContextKeyViewData key.

Variables

View Source
var (
	// ErrInvalidContextProps error.
	ErrInvalidContextProps = errors.New("inertia: could not convert context props to map")

	// ErrInvalidContextViewData error.
	ErrInvalidContextViewData = errors.New("inertia: could not convert context view data to map")

	// ErrBadSsrStatusCode error.
	ErrBadSsrStatusCode = errors.New("inertia: bad ssr status code >= 400")

	// ErrBadSsrStatusCode error.
	ErrRawTemplateFunc = errors.New("inertia: error with raw template func")
)

Functions

func Marshal

func Marshal(v any) (template.JS, error)

func Raw

func Raw(v any) (template.HTML, error)

func ResolvePropVal

func ResolvePropVal(val any) (any, error)

Types

type Inertia

type Inertia struct {
	Url string

	SharedProps   Props
	SharedFuncMap template.FuncMap

	SsrURL    string
	SsrClient *http.Client
	// contains filtered or unexported fields
}

Inertia type.

func New

func New(url, rootTemplate, version string) *Inertia

New function.

func NewWithFS

func NewWithFS(url, rootTemplate, version string, templateFS fs.FS) *Inertia

NewWithFS function.

func (*Inertia) Back

func (i *Inertia) Back(w http.ResponseWriter, r *http.Request)

func (*Inertia) DisableSsr

func (i *Inertia) DisableSsr()

DisableSsr function.

func (*Inertia) EnableSsr

func (i *Inertia) EnableSsr(ssrURL string)

EnableSsr function.

func (*Inertia) EnableSsrWithDefault

func (i *Inertia) EnableSsrWithDefault()

EnableSsrWithDefault function.

func (*Inertia) IsSsrEnabled

func (i *Inertia) IsSsrEnabled() bool

IsSsrEnabled function.

func (*Inertia) Location

func (i *Inertia) Location(w http.ResponseWriter, r *http.Request, url string)

Location function.

func (*Inertia) Middleware

func (i *Inertia) Middleware(next http.Handler) http.Handler

Middleware function.

func (*Inertia) PrepareProps

func (i *Inertia) PrepareProps(r *http.Request, component string, props Props) (Props, error)

func (*Inertia) Render

func (i *Inertia) Render(w http.ResponseWriter, r *http.Request, component string, props Props) error

Render function.

func (*Inertia) Share

func (i *Inertia) Share(key string, value any)

Share function.

func (*Inertia) ShareFunc

func (i *Inertia) ShareFunc(key string, value any)

ShareFunc function.

func (*Inertia) WithProp

func (i *Inertia) WithProp(ctx context.Context, key string, value any) context.Context

WithProp function.

func (*Inertia) WithProps

func (i *Inertia) WithProps(ctx context.Context, props Props) context.Context

WithProps appends props values to the passed context.Context.

func (*Inertia) WithViewData

func (i *Inertia) WithViewData(ctx context.Context, key string, value any) context.Context

WithViewData function.

type LazyProp

type LazyProp func() (any, error)

LazyProp is a property value that will only evaluate when needed.

https://inertiajs.com/partial-reloads

type Page

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

Page type.

type Props

type Props = map[string]any

type Ssr

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

Ssr type.

Jump to

Keyboard shortcuts

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