pt

package module
v0.0.0-...-41c77b6 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2024 License: MIT Imports: 14 Imported by: 2

README

pt -- pt is a helper package for using pongo2 & in-memory tmpl loaders together.

🔗 Table of Contents

❔ Why

pt is a small package with simple helpers for those using pongo2/ricebox + in-memory template loaders together.

$ go get -u github.com/lrstanley/pt@latest

🙋♂ Support & Assistance

  • ❤ Please review the Code of Conduct for guidelines on ensuring everyone has the best experience interacting with the community.
  • 🙋♂ Take a look at the support document on guidelines for tips on how to ask the right questions.
  • 🐞 For all features/bugs/issues/questions/etc, head over here.

🤝 Contributing

  • ❤ Please review the Code of Conduct for guidelines on ensuring everyone has the best experience interacting with the community.
  • 📋 Please review the contributing doc for submitting issues/a guide on submitting pull requests and helping out.
  • 🗝 For anything security related, please review this repositories security policy.

⚖ License

MIT License

Copyright (c) 2017 Liam Stanley <me@liamstanley.io>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Also located here

Documentation

Index

Constants

View Source
const JSONEscapeHTMLKey = "JSONEscapeHTML"

JSONEscapeHTMLKey is a context key which can be used with JSON() to set HTML escaping to true.

Variables

View Source
var NextKey = "next"

NextKey is the query param name used when redirecting.

Functions

func Error

func Error(logger *log.Logger, w http.ResponseWriter, code int, err error, show bool)

Error logs the given error, as well as optionally returns the error back to the connection.

func FileServer

func FileServer(router Router, path string, root http.FileSystem)

FileServer conveniently sets up a http.FileServer handler to serve static files from a http.FileSystem. "router" matches any servemux style router which has a Get() method (e.g. go-chi/chi.Router).

For example, mixing go-chi/chi + go-ricebox:

FileServer(r, "/static", rice.MustFindBox("static").HTTPBox())

func GetNextURL

func GetNextURL(r *http.Request) (next string)

GetNextURL obtains the target url from the intermediary URL, allowing you to pass in a URL parameter (e.g. ?next=/some/authed/page) which you can redirect to after doing some task (e.g. authenticating).

For example:

if isAuthed(r) {
	if next := pt.GetNextURL(r); next != "" {
		pt.RedirectToNextURL(w, r, http.StatusFound)
		return
	}

	http.Redirect(w, r, "/some/home/page", http.StatusFound)
	return
}

func JSON

func JSON(w http.ResponseWriter, r *http.Request, v interface{})

JSON marshals 'v' to JSON, and setting the Content-Type as application/json. Note that this does NOT auto-escape HTML. If you would like to escape HTML, set the JSONEscapeHTMLKey context value to true.

JSON also supports prettification when the origin request has "?pretty=true" or similar.

func RedirectToNextURL

func RedirectToNextURL(w http.ResponseWriter, r *http.Request, statusCode int)

RedirectToNextURL redirects to the url specified within the "next" query parameter. Do this after the task (e.g. after authenticating).

Example:

if auth(user, passwd) {
	pt.RedirectToNextURL(w, r, http.StatusTemporaryRedirect)
	return
}

func RedirectWithNextURL

func RedirectWithNextURL(w http.ResponseWriter, r *http.Request, target string, statusCode int)

RedirectWithNextURL redirects to another page and passes the next url param, (e.g. a login page). target is the target redirect page, and statusCode is the http code used when redirecting.

Example:

if !auth(user, passwd) {
	pt.RedirectWithNextURL(w, r, r.URL.EscapedPath(), http.StatusTemporaryRedirect)
	return
}

Types

type Config

type Config struct {
	// CacheParsed caches the parsed version of the template in memory,
	// which is useful for production when templates aren't being loaded
	// while the application is running (or when you are using ricebox or
	// similar.)
	CacheParsed bool
	// Loader is the template loader to use to load a template. This can
	// be some kind of filesystem loader, or a assetfs/memory-based loader
	// (re: go-ricebox).
	//
	// For example:
	//   rice.MustFindBox("static").Bytes
	Loader func(path string) ([]byte, error)
	FS     fs.FS
	// DefaultCtx is an optional function which you can supply, which is
	// called every time the Render() function is called, which allows you
	// to add additional context variables to the ctx map. Useful if you are
	// adding variables to multiple handlers frequently.
	DefaultCtx func(http.ResponseWriter, *http.Request) (ctx map[string]interface{})
	// NotFoundHandler is an optional handler which you can define when the
	// template cannot be found based on what's returned from the Loader
	// method. If this is not defined, the Render() function will panic, as
	// this indicates the use of an undefined template.
	NotFoundHandler http.HandlerFunc
	// ErrorLogger is an optional io.Writer which errors are written to. Note
	// that these are request-specific errors (e.g. error while writing to the
	// client). Almost all template execution errors will cause a panic.
	ErrorLogger io.Writer
}

Config is the configuration which should be passed to New().

type Loader

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

Loader is a template loader and executor. This should be created as a global variable to execution speed.

func New

func New(set string, conf Config) *Loader

New returns a new loader with initialized template sets and configuration.

func (*Loader) Render

func (ld *Loader) Render(w http.ResponseWriter, r *http.Request, path string, rctx map[string]interface{})

Render is used to render a specific template, where "path" is the path within the provided Config.Loader. "ctx" is the extra context which can be provided and loaded within your template, however it is not required. All ctx keys will be loaded at the base level (in the template, you can just use "{{ yourvar }}"). In addition to this, there are a few predefined ctx keys:

url     -> request.URL
cachets -> The timestamp of when the loader was defined. This is useful
           to append at the end of your css/js/etc as a way of allowing
           the browser to not use the same cache after the application
           has been recompiled/restarted.

ctx keys can be overridden. The priority is:

  1. Context defined via Render().
  2. Context defined via the default context function.
  3. Default defined context by the package, mentioned above.

type M

type M map[string]interface{}

M is a convenience alias for quickly building a map structure that is going out to a responder. Just a short-hand.

type Router

type Router interface {
	Get(pattern string, h http.HandlerFunc)
}

Router is a general interface which many common http routers should fit. See FileServer() for details.

Jump to

Keyboard shortcuts

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