middleware

package module
v0.0.0-...-53a71df Latest Latest
Warning

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

Go to latest
Published: May 25, 2014 License: MIT Imports: 18 Imported by: 9

README

middleware.Context

origin from martini-contrib/web

API Reference

Description

middleware.Context provides a render(forked from martini-contrib/render), beego like ctx.

Usage

ref: https://github.com/martini-contrib/render

package main

import (
	"html/template"
	"strings"

	"github.com/go-martini/martini"
	"github.com/gobuild/middleware"
)

func main() {
	m := martini.Classic()
	var funcMap = template.FuncMap{"title": strings.Title}
	m.Use(middleware.ContextWithCookieSecret("", middleware.Options{
		Funcs: []template.FuncMap{funcMap},
	}))

	m.Post("/hello", func(ctx *middleware.Context) {
		ctx.WriteString("Hello World!")
	})
	m.Get("/home", func(ctx *middleware.Context) {
		ctx.Data["Title"] = "home"
		ctx.HTML(200, "home") // use templates by default
	})
	m.Run()
}

Documentation

Overview

Package web provides a web.go compitable layer for reusing the code written with hoisie's `web.go` framework. Basiclly this package add web.Context to martini's dependency injection system.

Package render is a middleware for Martini that provides easy JSON serialization and HTML template rendering.

package main

import (
  "github.com/go-martini/martini"
  "github.com/martini-contrib/render"
)

func main() {
  m := martini.Classic()
  m.Use(render.Renderer()) // reads "templates" directory by default

  m.Get("/html", func(r render.Render) {
    r.HTML(200, "mytemplate", nil)
  })

  m.Get("/json", func(r render.Render) {
    r.JSON(200, "hello world")
  })

  m.Run()
}

Index

Constants

View Source
const (
	ContentType   = "Content-Type"
	ContentLength = "Content-Length"
	ContentJSON   = "application/json"
	ContentHTML   = "text/html"
	ContentXHTML  = "application/xhtml+xml"
	ContentBinary = "application/octet-stream"
)

Variables

This section is empty.

Functions

func ContextWithCookieSecret

func ContextWithCookieSecret(secret string, options ...Options) martini.Handler

if cookie secret is set to "", then SetSecureCookie would not work

func NewCookie

func NewCookie(name string, value string, age int64) *http.Cookie

NewCookie is a helper method that returns a new http.Cookie object. Duration is specified in seconds. If the duration is zero, the cookie is permanent. This can be used in conjunction with ctx.SetCookie.

func Renderer

func Renderer(options ...Options) martini.Handler

Renderer is a Middleware that maps a render.Render service into the Martini handler chain. An single variadic render.Options struct can be optionally provided to configure HTML rendering. The default directory for templates is "templates" and the default file extension is ".tmpl".

If MARTINI_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the MARTINI_ENV environment variable to "production"

Types

type Context

type Context struct {
	Request *http.Request
	Params  map[string]string

	http.ResponseWriter

	// Flash *Flash
	Data map[string]interface{}
	// contains filtered or unexported fields
}

A Context object is created for every incoming HTTP request, and is passed to handlers as an optional first argument. It provides information about the request, including the http.Request object, the GET and POST params, and acts as a Writer for the response.

func (*Context) Abort

func (ctx *Context) Abort(status int, body string)

Abort is a helper method that sends an HTTP header and an optional body. It is useful for returning 4xx or 5xx errors. Once it has been called, any return value from the handler will not be written to the response.

func (*Context) ContentType

func (ctx *Context) ContentType(val string) string

ContentType sets the Content-Type header for an HTTP response. For example, ctx.ContentType("json") sets the content-type to "application/json" If the supplied value contains a slash (/) it is set as the Content-Type verbatim. The return value is the content type as it was set, or an empty string if none was found.

func (Context) Data

func (r Context) Data(status int, v []byte)

func (Context) Error

func (r Context) Error(status int)

Error writes the given HTTP status to the current ResponseWriter

func (*Context) Forbidden

func (ctx *Context) Forbidden()

Forbidden writes a 403 HTTP response

func (*Context) GetErrMsg

func (ctx *Context) GetErrMsg() string

func (*Context) GetSecureCookie

func (ctx *Context) GetSecureCookie(name string) (string, bool)

func (*Context) HTML

func (ctx *Context) HTML(status int, name string, htmlOpt ...HTMLOptions)

HTML calls render.HTML underlying but reduce one argument.

func (*Context) Handle

func (ctx *Context) Handle(status int, desc string, err error)

Handle handles and logs error by given status.

func (*Context) HasApiError

func (ctx *Context) HasApiError() bool

HasError returns true if error occurs in form validation.

func (*Context) HasError

func (ctx *Context) HasError() bool

HasError returns true if error occurs in form validation.

func (Context) JSON

func (r Context) JSON(status int, v interface{})

func (*Context) NotFound

func (ctx *Context) NotFound(message string)

NotFound writes a 404 HTTP response

func (*Context) NotModified

func (ctx *Context) NotModified()

Notmodified writes a 304 HTTP response

func (*Context) Query

func (ctx *Context) Query(name string) string

new func added Query querys form parameter.

func (*Context) Redirect

func (ctx *Context) Redirect(status int, url_ string)

Redirect is a helper method for 3xx redirects.

func (*Context) ServeContent

func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{})

func (*Context) ServeFile

func (ctx *Context) ServeFile(file string, names ...string)

func (*Context) SetCookie

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie adds a cookie header to the response.

func (*Context) SetHeader

func (ctx *Context) SetHeader(hdr string, val string, unique bool)

SetHeader sets a response header. If `unique` is true, the current value of that header will be overwritten . If false, it will be appended.

func (*Context) SetSecureCookie

func (ctx *Context) SetSecureCookie(name string, val string, age int64)

func (Context) Status

func (r Context) Status(status int)

func (Context) Template

func (r Context) Template() *template.Template

func (*Context) Unauthorized

func (ctx *Context) Unauthorized()

Unauthorized writes a 401 HTTP response

func (*Context) WriteString

func (ctx *Context) WriteString(content string)

WriteString writes string data into the response object.

type Delims

type Delims struct {
	// Left delimiter, defaults to {{
	Left string
	// Right delimiter, defaults to }}
	Right string
}

Delims represents a set of Left and Right delimiters for HTML template rendering

type HTMLOptions

type HTMLOptions struct {
	// Layout template name. Overrides Options.Layout.
	Layout string
}

HTMLOptions is a struct for overriding some rendering Options for specific HTML call

type Options

type Options struct {
	// Directory to load templates. Default is "templates"
	Directory string
	// Layout template name. Will not render a layout if "". Defaults to "".
	Layout string
	// Extensions to parse template files from. Defaults to [".tmpl"]
	Extensions []string
	// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
	Funcs []template.FuncMap
	// Delims sets the action delimiters to the specified strings in the Delims struct.
	Delims Delims
	// Appends the given charset to the Content-Type header. Default is "UTF-8".
	Charset string
	// Outputs human readable JSON
	IndentJSON bool
	// Allows changing of output to XHTML instead of HTML. Default is "text/html"
	HTMLContentType string
}

Options is a struct for specifying configuration options for the render.Renderer middleware

type Render

type Render interface {
	// JSON writes the given status and JSON serialized version of the given value to the http.ResponseWriter.
	JSON(status int, v interface{})
	// HTML renders a html template specified by the name and writes the result and given status to the http.ResponseWriter.
	HTML(status int, name string, v interface{}, htmlOpt ...HTMLOptions)
	// Data writes the raw byte array to the http.ResponseWriter.
	Data(status int, v []byte)
	// Error is a convenience function that writes an http status to the http.ResponseWriter.
	Error(status int)
	// Status is an alias for Error (writes an http status to the http.ResponseWriter)
	Status(status int)
	// Redirect is a convienience function that sends an HTTP redirect. If status is omitted, uses 302 (Found)
	Redirect(location string, status ...int)
	// Template returns the internal *template.Template used to render the HTML
	Template() *template.Template
	// Header exposes the header struct from http.ResponseWriter.
	Header() http.Header
}

Render is a service that can be injected into a Martini handler. Render provides functions for easily writing JSON and HTML templates out to a http Response.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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