transplacer

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2018 License: MPL-2.0 Imports: 18 Imported by: 0

README

GoDoc

Features

  • auto http2 push, when available
  • auto watching and updating
  • gzips and sets etags
  • works concurrently, no deadlocks
  • it's a bit of rough magic & ducktape, but, it works

Diy AssetCache for super fast static asset serving straight from the memory

package main

import (
	"log"
	"net/http"
	"time"

	tr "github.com/SaulDoesCode/transplacer"
)

func main() {
	cache, err := tr.Make(&tr.AssetCache{
		Dir:     "./assets",
		Watch:   true,
		Expire:  time.Minute * 30,
		DevMode: true, // extra logs
	})
	if err != nil {
		panic(err.Error())
  }
  defer cache.Close()

	server := &http.Server{
		Addr:    ":http",
		Handler: cache,
	}

	log.Fatal(server.ListenAndServe())
}

With Echo

package main

import (
	"time"

	tr "github.com/SaulDoesCode/transplacer"
	"github.com/labstack/echo"
)

func main() {
	cache, err := tr.Make(&tr.AssetCache{
		Dir:    "./assets",
		Watch:  true,
		Expire: time.Minute * 30,
	})
	if err != nil {
		panic(err.Error())
  }
  defer cache.Close()

	e := echo.New()

	e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			req := c.Request()
			err := next(c)
			if err == nil || req.Method[0] != 'G' {
				return err
			}

			return cache.Serve(c.Response().Writer, req)
		}
	})

	e.Logger.Fatal(e.Start(":http"))
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Compressable - list of compressable file types, append to it if needed
	Compressable = []string{"", ".txt", ".htm", ".html", ".css", ".toml", ".php", ".js", ".json", ".md", ".mdown", ".xml", ".svg", ".go", ".cgi", ".py", ".pl", ".aspx", ".asp"}
)
View Source
var ErrAssetNotFound = errors.New(`no asset/file found, cannot serve`)

ErrAssetNotFound is for when an asset cannot be located/created

Functions

func HTTP2Push

func HTTP2Push(W http.ResponseWriter, target string, headers http.Header) error

HTTP2Push initiates an HTTP/2 server push. This constructs a synthetic request using the target and headers, serializes that request into a PUSH_PROMISE frame, then dispatches that request using the server's request handlec. The target must either be an absolute path (like "/path") or an absolute URL that contains a valid host and the same scheme as the parent request. If the target is a path, it will inherit the scheme and host of the parent request. The headers specifies additional promised request headers. The headers cannot include HTTP/2 pseudo headers like ":path" and ":scheme", which will be added automatically.

func PrepPath

func PrepPath(host, file string) string

PrepPath joins a host path with a clean file path

func StringsContainCI

func StringsContainCI(list []string, match string) bool

StringsContainCI reports whether the lists contains a match regardless of its case.

Types

type Asset

type Asset struct {
	Ext string

	Name string

	ContentType string

	Loaded time.Time

	ModTime time.Time

	Content           *bytes.Reader
	ContentCompressed *bytes.Reader

	CacheControl string

	Etag           string
	EtagCompressed string

	Compressed bool

	PushList []string
}

Asset is an http servable resource

func (*Asset) Serve

func (as *Asset) Serve(res http.ResponseWriter, req *http.Request)

Serve serves the asset via the ussual http ResponseWriter and *Request

type AssetCache

type AssetCache struct {
	Dir string

	Index   string
	NoIndex bool

	Cache *HashMap

	Expire   time.Duration
	Interval time.Duration

	CacheControl string

	Ticker *time.Ticker

	DevMode bool

	Watch   bool
	Watcher *fsnotify.Watcher

	NotFoundHandler func(http.ResponseWriter, *http.Request)
	NotFoundError   error
}

AssetCache is a store for assets

func Make

func Make(a *AssetCache) (*AssetCache, error)

Make prepares a new *AssetCache for use

func (*AssetCache) Close

func (a *AssetCache) Close() error

Close stops and clears the AssetCache

func (*AssetCache) Del

func (a *AssetCache) Del(name string)

Del removes an asset, nb. not the file, the file is fine

func (*AssetCache) Gen

func (a *AssetCache) Gen(name string) (*Asset, error)

Gen generates a new Asset

func (*AssetCache) Get

func (a *AssetCache) Get(name string) (*Asset, bool)

Get fetches an asset

func (*AssetCache) Middleware

func (a *AssetCache) Middleware(h http.HandlerFunc) http.HandlerFunc

Middleware is a generic go handler that sets up AssetCache like any other static file serving solution on your server

func (*AssetCache) Serve

func (a *AssetCache) Serve(res http.ResponseWriter, req *http.Request) error

Serve is the same as ServeHTTP but it returns the error instead of calling .NotFoundHandler, this is useful for echo/air middleware

func (*AssetCache) ServeFile

func (a *AssetCache) ServeFile(res http.ResponseWriter, req *http.Request, file string) error

ServeFile parses a key/filename and serves it if it exists and returns an ErrAssetNotFound if it doesn't

func (*AssetCache) ServeFileDirect

func (a *AssetCache) ServeFileDirect(res http.ResponseWriter, req *http.Request, file string) error

ServeFileDirect takes a key/filename directly and serves it if it exists and returns an ErrAssetNotFound if it doesn't

func (*AssetCache) ServeHTTP

func (a *AssetCache) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface

func (*AssetCache) SetExpiryCheckInterval

func (a *AssetCache) SetExpiryCheckInterval(interval time.Duration)

SetExpiryCheckInterval generates a new ticker with a set interval

func (AssetCache) StopExpiryCheckInterval

func (a AssetCache) StopExpiryCheckInterval()

StopExpiryCheckInterval stops asset expiration checks

func (*AssetCache) Update

func (a *AssetCache) Update(name string) bool

Update first deletes an asset then gets it again, updating it thereby.

type HashMap

type HashMap = hashmap.HashMap

HashMap is an alias of cornelk/hashmap

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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