martini

package module
v0.0.0-...-2d0ba5d Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2014 License: MIT Imports: 26 Imported by: 0

README

martini

In a manner suitable for their own use to modify the martini.

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.Cotex to martini's dependency injection system.

Package martini is a powerful package for quickly writing modular web applications/services in Golang.

For a full guide visit http://github.com/go-martini/martini

package main

import "github.com/go-martini/martini"

func main() {
  m := martini.Classic()

  m.Get("/", func() string {
    return "Hello world!"
  })

  m.Run()
}

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

package main

import (
  "encoding/xml"

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

type Greeting struct {
  XMLName xml.Name `xml:"greeting"`
  One     string   `xml:"one,attr"`
  Two     string   `xml:"two,attr"`
}

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.Get("/xml", func(r render.Render) {
    r.XML(200, Greeting{One: "hello", Two: "world"})
  })

  m.Run()
}

Index

Constants

View Source
const (
	Dev  string = "development"
	Prod string = "production"
	Test string = "test"
)

Envs

View Source
const (
	HeaderAcceptEncoding  = "Accept-Encoding"
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLength   = "Content-Length"
	HeaderContentType     = "Content-Type"
	HeaderVary            = "Vary"
)
View Source
const (
	ContentType   = "Content-Type"
	ContentLength = "Content-Length"
	ContentBinary = "application/octet-stream"
	ContentJSON   = "application/json"
	ContentHTML   = "text/html"
	ContentXHTML  = "application/xhtml+xml"
	ContentXML    = "text/xml"
)

Variables

View Source
var (
	Data = map[string]interface{}{} //初始化Data

)
View Source
var Env = Dev

Env is the environment that Martini is executing in. The MARTINI_ENV is read on initialization to set this variable.

View Source
var Root string

Functions

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.

Types

type BeforeFunc

type BeforeFunc func(ResponseWriter)

BeforeFunc is a function that is called before the ResponseWriter has been written to.

type ClassicMartini

type ClassicMartini struct {
	*Martini
	Router
}

ClassicMartini represents a Martini with some reasonable defaults. Embeds the router functions for convenience.

func Classic

func Classic() *ClassicMartini

Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static. Classic also maps martini.Routes as a service.

type Context

type Context interface {
	inject.Injector
	// Next is an optional function that Middleware Handlers can call to yield the until after
	// the other Handlers have been executed. This works really well for any operations that must
	// happen after an http request
	Next()
	// Written returns whether or not the response for this context has been written.
	Written() bool
}

Context represents a request context. Services can be mapped on the request level from this interface.

type Cotex

type Cotex struct {
	Request *http.Request
	Form    map[string]string

	http.ResponseWriter
	*Render
	// contains filtered or unexported fields
}

A Cotex 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 (*Cotex) Abort

func (ctx *Cotex) 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 (*Cotex) ContentType

func (ctx *Cotex) 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 (*Cotex) Forbidden

func (ctx *Cotex) Forbidden()

Forbidden writes a 403 HTTP response

func (*Cotex) GetSecureCookie

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

func (*Cotex) NotFound

func (ctx *Cotex) NotFound(message string)

NotFound writes a 404 HTTP response

func (*Cotex) NotModified

func (ctx *Cotex) NotModified()

Notmodified writes a 304 HTTP response

func (*Cotex) Redirect

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

Redirect is a helper method for 3xx redirects.

func (*Cotex) SetCookie

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

SetCookie adds a cookie header to the response.

func (*Cotex) SetHeader

func (ctx *Cotex) 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 (*Cotex) SetSecureCookie

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

func (*Cotex) Unauthorized

func (ctx *Cotex) Unauthorized()

Unauthorized writes a 401 HTTP response

func (*Cotex) WriteString

func (ctx *Cotex) 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 HTMLRenderOptions

type HTMLRenderOptions struct {
	// Layout template name. Overrides RenderOptions.Layout.
	Layout string
}

HTMLRenderOptions is a struct for overriding some rendering RenderOptions for specific HTML call

type Handler

type Handler interface{}

Handler can be any callable function. Martini attempts to inject services into the handler's argument list. Martini will panic if an argument could not be fullfilled via dependency injection.

func ContextRender

func ContextRender(cookiesecret string, options ...RenderOptions) Handler

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

func Gzip

func Gzip() Handler

All returns a Handler that adds gzip compression to all requests

func Logger

func Logger() Handler

Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.

func Recovery

func Recovery() Handler

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. While Martini is in development mode, Recovery will also output the panic as HTML.

func Renderer

func Renderer(options ...RenderOptions) Handler

func Static

func Static(directory string, staticOpt ...StaticOptions) Handler

Static returns a middleware handler that serves static files in the given directory.

type Martini

type Martini struct {
	inject.Injector
	// contains filtered or unexported fields
}

Martini represents the top level web application. inject.Injector methods can be invoked to map services on a global level.

func New

func New() *Martini

New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.

func (*Martini) Action

func (m *Martini) Action(handler Handler)

Action sets the handler that will be called after all the middleware has been invoked. This is set to martini.Router in a martini.Classic().

func (*Martini) Handlers

func (m *Martini) Handlers(handlers ...Handler)

Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers. Will panic if any of the handlers is not a callable function

func (*Martini) Run

func (m *Martini) Run()

Run the http server. Listening on os.GetEnv("PORT") or 3000 by default.

func (*Martini) ServeHTTP

func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.

func (*Martini) Use

func (m *Martini) Use(handler Handler)

Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.

type Params

type Params map[string]string

Params is a map of name/value pairs for named routes. An instance of martini.Params is available to be injected into any route handler.

type Render

type Render struct {
	http.ResponseWriter

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

func Renderor

func Renderor(res http.ResponseWriter, req *http.Request, c Context, options ...RenderOptions) *Render

func (*Render) Error

func (r *Render) Error(status int, message ...string)

Error writes the given HTTP status to the current ResponseWriter

func (*Render) HTML

func (r *Render) HTML(status int, name string, binding interface{}, htmlOpt ...HTMLRenderOptions)

func (*Render) HTMLString

func (r *Render) HTMLString(name string, binding interface{}, htmlOpt ...HTMLRenderOptions) (string, error)

func (*Render) JSON

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

func (*Render) JSONString

func (r *Render) JSONString(v interface{}) (string, error)

func (*Render) Redirect

func (r *Render) Redirect(location string, status ...int)

func (*Render) Status

func (r *Render) Status(status int)

func (*Render) Template

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

func (*Render) WriteData

func (r *Render) WriteData(status int, v []byte)

func (*Render) XML

func (r *Render) XML(status int, v interface{})

type RenderOptions

type RenderOptions 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
	// Outputs human readable XML
	IndentXML bool
	// Prefixes the JSON output with the given bytes.
	PrefixJSON []byte
	// Prefixes the XML output with the given bytes.
	PrefixXML []byte
	// Allows changing of output to XHTML instead of HTML. Default is "text/html"
	HTMLContentType string
}

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

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Written returns whether or not the ResponseWriter has been written.
	Written() bool
	// Size returns the size of the response body.
	Size() int
	// Before allows for a function to be called before the ResponseWriter has been written to. This is
	// useful for setting headers or any other operations that must happen before a response has been written.
	Before(BeforeFunc)
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type ReturnHandler

type ReturnHandler func(Context, []reflect.Value)

ReturnHandler is a service that Martini provides that is called when a route handler returns something. The ReturnHandler is responsible for writing to the ResponseWriter based on the values that are passed into this function.

type Route

type Route interface {
	// URLWith returns a rendering of the Route's url with the given string params.
	URLWith([]string) string
	// Name sets a name for the route.
	Name(string)
	// GetName returns the name of the route.
	GetName() string
	// Pattern returns the pattern of the route.
	Pattern() string
	// Method returns the method of the route.
	Method() string
}

Route is an interface representing a Route in Martini's routing layer.

type Router

type Router interface {
	Routes

	// Group adds a group where related routes can be added.
	Group(string, func(Router), ...Handler)
	// Get adds a route for a HTTP GET request to the specified matching pattern.
	Get(string, ...Handler) Route
	// Patch adds a route for a HTTP PATCH request to the specified matching pattern.
	Patch(string, ...Handler) Route
	// Post adds a route for a HTTP POST request to the specified matching pattern.
	Post(string, ...Handler) Route
	// Put adds a route for a HTTP PUT request to the specified matching pattern.
	Put(string, ...Handler) Route
	// Delete adds a route for a HTTP DELETE request to the specified matching pattern.
	Delete(string, ...Handler) Route
	// Options adds a route for a HTTP OPTIONS request to the specified matching pattern.
	Options(string, ...Handler) Route
	// Head adds a route for a HTTP HEAD request to the specified matching pattern.
	Head(string, ...Handler) Route
	// Any adds a route for any HTTP method request to the specified matching pattern.
	Any(string, ...Handler) Route

	// NotFound sets the handlers that are called when a no route matches a request. Throws a basic 404 by default.
	NotFound(...Handler)

	// Handle is the entry point for routing. This is used as a martini.Handler
	Handle(http.ResponseWriter, *http.Request, Context)
}

Router is Martini's de-facto routing interface. Supports HTTP verbs, stacked handlers, and dependency injection.

func NewRouter

func NewRouter() Router

NewRouter creates a new Router instance. If you aren't using ClassicMartini, then you can add Routes as a service with:

m := martini.New()
r := martini.NewRouter()
m.MapTo(r, (*martini.Routes)(nil))

If you are using ClassicMartini, then this is done for you.

type Routes

type Routes interface {
	// URLFor returns a rendered URL for the given route. Optional params can be passed to fulfill named parameters in the route.
	URLFor(name string, params ...interface{}) string
	// MethodsFor returns an array of methods available for the path
	MethodsFor(path string) []string
	// All returns an array with all the routes in the router.
	All() []Route
}

Routes is a helper service for Martini's routing layer.

type StaticOptions

type StaticOptions struct {
	// Prefix is the optional prefix used to serve the static directory content
	Prefix string
	// SkipLogging will disable [Static] log messages when a static file is served.
	SkipLogging bool
	// IndexFile defines which file to serve as index if it exists.
	IndexFile string
	// Expires defines which user-defined function to use for producing a HTTP Expires Header
	// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
	Expires func() string
}

StaticOptions is a struct for specifying configuration options for the martini.Static middleware.

Directories

Path Synopsis
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides utilities for mapping and injecting dependencies in various ways.

Jump to

Keyboard shortcuts

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