fragments

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2021 License: MIT Imports: 15 Imported by: 0

README

Fragments

main Go Report Card Taylor Swift

Fragments middleware for Fiber enables building microservices for the frontend.

A <fragment> symbolizes a part of a template that can be served by a singular microservice. Thus, making a fragment the contract between different services and teams within a large engineering organization. The middleware concurrently fetches those parts from the service and replaces it in the template. It supports GET and POST HTTP methods to fetcht the content. Related resources like CSS or JavaScript are injected via the HTTP LINK entity header field. A <fragment> can occure in the body element or the header element. See Example to learn more about using fragments.

Tailor by Zalando is prior art for this middleware.

Fragement(s)

A fragment will be hybrid-polymorphic (if this is a thing). On the server it is parsed and evaluate by the middleware. 🦄 In the browser it will be a web component that received data from the middleware (this is still work in progress ⚠️).

Server
  • src The source to fetch for replacement in the DOM
  • method can be of GET (default) or POST.
  • primary denotes a fragment that sets the response code of the page
  • id is an optional unique identifier (optional)
  • refis an optional forward reference to an id (optional)
  • timeout timeout of a fragement to receive in milliseconds (default is 300)
  • deferred is deferring the fetch to the browser
  • fallback is the fallback source in case of timeout/error on the current fragment

Example

Import the middleware package this is part of the Fiber web framework.

package main

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/template/html"

	"github.com/github/fiber-fragments"
)

After you initiate your Fiber app, you can plugin in the fragments middleware. The middleware draws the templates for the fragments to load from the template engine. Thus it supports using all template engines supported by the Fiber team.

// Create a new engine
engine := html.New("./views", ".html")

// Pass the engine to the Views
app := fiber.New(fiber.Config{
	Views: engine,
})

// Associates the route with a specific template with fragments to render
app.Get("/index", fragments.Template(fragments.Config{}, "index", fiber.Map{}, "layouts/main"))

// this would listen to port 8080
app.Listen(":8080")
<html>
<head>
    <script type="fragment" src="assets"></script>
</head>
<body>
    <h1>Example</h1>
    <fragment src="fragment1.html"></fragment>
</body>
</html>

The example folder contains many examples. You can learn how to use a forward reference of content for fetching outer and inner content and replace either one.

Benchmark(s)

This is run on a MacBook Pro 16 inch locally. It is the example run.

  • Parsing a local template with extrapolation with the fragments
  • Parsing the fragments
  • Doing fragments
  • Inlining results and adding Link header resources to the output
echo "GET http://127.0.0.1:8080/index" | vegeta attack -duration=5s -rate 2000 | tee results.bin | vegeta report
  vegeta report -type=json results.bin > metrics.json
  cat results.bin | vegeta plot > plot.html
  cat results.bin | vegeta report -type="hist[0,100ms,200ms,300ms]"

Requests      [total, rate, throughput]         10000, 2000.26, 2000.15
Duration      [total, attack, wait]             5s, 4.999s, 285.172µs
Latencies     [min, mean, 50, 90, 95, 99, max]  183.725µs, 251.517µs, 226.993µs, 310.698µs, 394.601µs, 563.022µs, 1.347ms
Bytes In      [total, mean]                     6240000, 624.00
Bytes Out     [total, mean]                     0, 0.00
Success       [ratio]                           100.00%
Status Codes  [code:count]                      200:10000
Error Set:
Bucket           #      %        Histogram
[0s,     100ms]  10000  100.00%  ###########################################################################
[100ms,  200ms]  0      0.00%
[200ms,  300ms]  0      0.00%
[300ms,  +Inf]   0      0.00%

License

MIT

Documentation

Index

Constants

View Source
const (
	StyleSheet = "stylesheet"
	Script     = "script"
)

Variables

This section is empty.

Functions

func CreateNodes

func CreateNodes(links []Link) []*html.Node

CreateNodes ...

func Do

func Do(c *fiber.Ctx, cfg Config, doc *Document) error

Do represents the core functionality of the middleware. It resolves the fragments from a parsed template.

func Template

func Template(config Config, name string, bind interface{}, layouts ...string) fiber.Handler

Template ...

Types

type Config

type Config struct {
	// Filter defines a function to skip the middleware.
	// Optional. Default: nil
	Filter func(*fiber.Ctx) bool

	// FilterResponse defines a function to filter the responses
	// from the fragment sources.
	FilterResponse func(*fasthttp.Response) *fasthttp.Response

	// FilterRequest defines a function to filter the request
	// to the fragment sources.
	FilterRequest func(*fasthttp.Request) *fasthttp.Request

	// ErrorHandler defines a function which is executed
	// It may be used to define a custom error.
	// Optional. Default: 401 Invalid or expired key
	ErrorHandler fiber.ErrorHandler

	// FilterHead defines a function to filter the new
	// nodes in the <head> of the document passed by the LINK header entity.
	FilterHead func([]*html.Node) []*html.Node

	// DefaultHost defines the host to use,
	// if no host is set on a fragment.
	// Optional. Default: localhost:3000
	DefaultHost string
}

Config ...

type Document

type Document struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Document ...

func NewDocument

func NewDocument(root *html.Node) (*Document, error)

NewDocument ...

func (*Document) Fragments

func (d *Document) Fragments() ([]*Fragment, error)

Fragments is returning the selection of fragments from an HTML page.

func (*Document) Html

func (d *Document) Html() (string, error)

Html is returning the final HTML output.

func (*Document) HtmlFragment added in v0.2.0

func (d *Document) HtmlFragment() *HtmlFragment

Fragments is returning the selection of fragments from an HTML page.

func (*Document) SetStatusCode

func (d *Document) SetStatusCode(status int)

SetStatusCode is setting the HTTP status code for the document.

func (*Document) StatusCode

func (d *Document) StatusCode() int

StatusCode is getting the HTTP status code for the document.

type Fragment

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

Fragment is a <fragment> in the <header> or <body> of a HTML page.

func FromSelection

func FromSelection(s *goquery.Selection) *Fragment

FromSelection creates a new fragment from a fragment selection in the DOM.

func (*Fragment) Deferred

func (f *Fragment) Deferred() bool

Deferred is deferring the fetching to the browser.

func (*Fragment) Element

func (f *Fragment) Element() *goquery.Selection

Element is a pointer to the selected element in the DOM.

func (*Fragment) Fallback

func (f *Fragment) Fallback() string

Fallback is the fallback URL for the fragment.

func (*Fragment) HtmlFragment added in v0.2.0

func (f *Fragment) HtmlFragment() *HtmlFragment

HtmlFragment returns embedded fragments of HTML.

func (*Fragment) ID added in v0.2.0

func (f *Fragment) ID() string

ID represents a unique id for the fragment

func (f *Fragment) Links() []*html.Node

Links returns the new nodes that go in the head via the LINK HTTP header entity.

func (*Fragment) Method

func (f *Fragment) Method() string

Method is the HTTP method to use for fetching the fragment.

func (*Fragment) Primary

func (f *Fragment) Primary() bool

Primary denotes a fragment as responsible for setting the response code of the entire HTML page.

func (*Fragment) Ref added in v0.2.0

func (f *Fragment) Ref() string

Ref represents the reference to another fragment

func (*Fragment) Resolve

func (f *Fragment) Resolve() ResolverFunc

Resolve is resolving all needed data, setting headers and the status code.

func (*Fragment) Src

func (f *Fragment) Src() string

Src is the URL for the fragment.

func (*Fragment) Timeout

func (f *Fragment) Timeout() time.Duration

Timeout is the timeout for fetching the fragment.

type Header string

Header ...

func (s Header) Links() []Link

Link ...

type HtmlFragment added in v0.2.0

type HtmlFragment struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

HtmlFragment is representation of HTML fragments.

func NewHtmlFragment added in v0.2.0

func NewHtmlFragment(root *html.Node) (*HtmlFragment, error)

NewHtmlFragment creates a new fragment of HTML.

func (*HtmlFragment) AppendHead added in v0.2.1

func (d *HtmlFragment) AppendHead(ns ...*html.Node)

AppendHead ...

func (*HtmlFragment) Fragment added in v0.2.0

func (h *HtmlFragment) Fragment() *goquery.Document

Document get the full document representation of the HTML fragment.

func (*HtmlFragment) Fragments added in v0.2.0

func (h *HtmlFragment) Fragments() (map[string]*Fragment, error)

Fragments is returning the selection of fragments from an HTML page.

func (*HtmlFragment) Html added in v0.2.0

func (h *HtmlFragment) Html() (string, error)

Html creates the HTML output of the created document.

type Link struct {
	URL    string
	Rel    string
	Params map[string]string
}

Link ...

func FilterByRel

func FilterByRel(links []Link, rel string) []Link

FilterByRel ...

func FilterByScript

func FilterByScript(links ...Link) []Link

FilterByStylesheet ...

func FilterByStylesheet

func FilterByStylesheet(links ...Link) []Link

FilterByStylesheet ...

type Resolver

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

Resolver ...

func NewResolver

func NewResolver() *Resolver

NewResolver ...

func (*Resolver) Resolve

func (r *Resolver) Resolve(c *fiber.Ctx, cfg Config, doc *HtmlFragment) (int, []*html.Node, error)

Resolve blocks until all fragments have been called.

type ResolverFunc

type ResolverFunc func(c *fiber.Ctx, cfg Config) error

ResolverFunc ...

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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