Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Classy web framework for Go

License

NotificationsYou must be signed in to change notification settings

go-martini/martini

Repository files navigation

NOTE: The martini framework is no longer maintained.

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

Language Translations:

Getting Started

After installing Go and setting up yourGOPATH, create your first.go file. We'll call itserver.go.

package mainimport"github.com/go-martini/martini"funcmain() {m:=martini.Classic()m.Get("/",func()string {return"Hello world!"  })m.Run()}

Then install the Martini package (go 1.1 or greater is required):

go get github.com/go-martini/martini

Then run your server:

go run server.go

You will now have a Martini webserver running onlocalhost:3000.

Getting Help

Join theMailing list

Watch theDemo Video

Ask questions on Stackoverflow using themartini tag

GoDocdocumentation

Features

  • Extremely simple to use.
  • Non-intrusive design.
  • Plays nice with other Golang packages.
  • Awesome path matching and routing.
  • Modular design - Easy to add functionality, easy to rip stuff out.
  • Lots of good handlers/middlewares to use.
  • Great 'out of the box' feature set.
  • Fully compatible with thehttp.HandlerFunc interface.
  • Default document serving (e.g., for serving AngularJS apps in HTML5 mode).

More Middleware

For more middleware and functionality, check out the repositories in themartini-contrib organization.

Table of Contents

Classic Martini

To get up and running quickly,martini.Classic() provides some reasonable defaults that work well for most web applications:

m:=martini.Classic()// ... middleware and routing goes herem.Run()

Below is some of the functionalitymartini.Classic() pulls in automatically:

Handlers

Handlers are the heart and soul of Martini. A handler is basically any kind of callable function:

m.Get("/",func() {println("hello world")})

Return Values

If a handler returns something, Martini will write the result to the currenthttp.ResponseWriter as a string:

m.Get("/",func()string {return"hello world"// HTTP 200 : "hello world"})

You can also optionally return a status code:

m.Get("/",func() (int,string) {return418,"i'm a teapot"// HTTP 418 : "i'm a teapot"})

Service Injection

Handlers are invoked via reflection. Martini makes use ofDependency Injection to resolve dependencies in a Handlers argument list.This makes Martini completely compatible with golang'shttp.HandlerFunc interface.

If you add an argument to your Handler, Martini will search its list of services and attempt to resolve the dependency via type assertion:

m.Get("/",func(res http.ResponseWriter,req*http.Request) {// res and req are injected by Martinires.WriteHeader(200)// HTTP 200})

The following services are included withmartini.Classic():

Routing

In Martini, a route is an HTTP method paired with a URL-matching pattern.Each route can take one or more handler methods:

m.Get("/",func() {// show something})m.Patch("/",func() {// update something})m.Post("/",func() {// create something})m.Put("/",func() {// replace something})m.Delete("/",func() {// destroy something})m.Options("/",func() {// http options})m.NotFound(func() {// handle 404})

Routes are matched in the order they are defined. The first route thatmatches the request is invoked.

Route patterns may include named parameters, accessible via themartini.Params service:

m.Get("/hello/:name",func(params martini.Params)string {return"Hello "+params["name"]})

Routes can be matched with globs:

m.Get("/hello/**",func(params martini.Params)string {return"Hello "+params["_1"]})

Regular expressions can be used as well:

m.Get("/hello/(?P<name>[a-zA-Z]+)",func(params martini.Params)string {returnfmt.Sprintf ("Hello %s",params["name"])})

Take a look at theGo documentation for more info about regular expressions syntax .

Route handlers can be stacked on top of each other, which is useful for things like authentication and authorization:

m.Get("/secret",authorize,func() {// this will execute as long as authorize doesn't write a response})

Route groups can be added too using the Group method.

m.Group("/books",func(r martini.Router) {r.Get("/:id",GetBooks)r.Post("/new",NewBook)r.Put("/update/:id",UpdateBook)r.Delete("/delete/:id",DeleteBook)})

Just like you can pass middlewares to a handler you can pass middlewares to groups.

m.Group("/books",func(r martini.Router) {r.Get("/:id",GetBooks)r.Post("/new",NewBook)r.Put("/update/:id",UpdateBook)r.Delete("/delete/:id",DeleteBook)},MyMiddleware1,MyMiddleware2)

Services

Services are objects that are available to be injected into a Handler's argument list. You can map a service on aGlobal orRequest level.

Global Mapping

A Martini instance implements the inject.Injector interface, so mapping a service is easy:

db:=&MyDatabase{}m:=martini.Classic()m.Map(db)// the service will be available to all handlers as *MyDatabase// ...m.Run()

Request-Level Mapping

Mapping on the request level can be done in a handler viamartini.Context:

funcMyCustomLoggerHandler(c martini.Context,req*http.Request) {logger:=&MyCustomLogger{req}c.Map(logger)// mapped as *MyCustomLogger}

Mapping values to Interfaces

One of the most powerful parts about services is the ability to map a service to an interface. For instance, if you wanted to override thehttp.ResponseWriter with an object that wrapped it and performed extra operations, you can write the following handler:

funcWrapResponseWriter(res http.ResponseWriter,c martini.Context) {rw:=NewSpecialResponseWriter(res)c.MapTo(rw, (*http.ResponseWriter)(nil))// override ResponseWriter with our wrapper ResponseWriter}

Serving Static Files

Amartini.Classic() instance automatically serves static files from the "public" directory in the root of your server.You can serve from more directories by adding moremartini.Static handlers.

m.Use(martini.Static("assets"))// serve from the "assets" directory as well

Serving a Default Document

You can specify the URL of a local file to serve when the requested URL is notfound. You can also specify an exclusion prefix so that certain URLs are ignored.This is useful for servers that serve both static files and have additionalhandlers defined (e.g., REST API). When doing so, it's useful to define thestatic handler as a part of the NotFound chain.

The following example serves the/index.html file whenever any URL isrequested that does not match any local file and does not start with/api/v:

static:=martini.Static("assets", martini.StaticOptions{Fallback:"/index.html",Exclude:"/api/v"})m.NotFound(static,http.NotFound)

Middleware Handlers

Middleware Handlers sit between the incoming http request and the router. In essence they are no different than any other Handler in Martini. You can add a middleware handler to the stack like so:

m.Use(func() {// do some middleware stuff})

You can have full control over the middleware stack with theHandlers function. This will replace any handlers that have been previously set:

m.Handlers(Middleware1,Middleware2,Middleware3,)

Middleware Handlers work really well for things like logging, authorization, authentication, sessions, gzipping, error pages and any other operations that must happen before or after an http request:

// validate an api keym.Use(func(res http.ResponseWriter,req*http.Request) {ifreq.Header.Get("X-API-KEY")!="secret123" {res.WriteHeader(http.StatusUnauthorized)  }})

Next()

Context.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:

// log before and after a requestm.Use(func(c martini.Context,log*log.Logger){log.Println("before a request")c.Next()log.Println("after a request")})

Martini Env

Some Martini handlers make use of themartini.Env global variable to provide special functionality for development environments vs production environments. It is recommended that theMARTINI_ENV=production environment variable to be set when deploying a Martini server into a production environment.

FAQ

Where do I find middleware X?

Start by looking in themartini-contrib projects. If it is not there feel free to contact a martini-contrib team member about adding a new repo to the organization.

  • acceptlang - Handler for parsing theAccept-Language HTTP header.
  • accessflags - Handler to enable Access Control.
  • auth - Handlers for authentication.
  • binding - Handler for mapping/validating a raw request into a structure.
  • cors - Handler that enables CORS support.
  • csrf - CSRF protection for applications
  • encoder - Encoder service for rendering data in several formats and content negotiation.
  • gzip - Handler for adding gzip compress to requests
  • gorelic - NewRelic middleware
  • logstasher - Middleware that prints logstash-compatible JSON
  • method - HTTP method overriding via Header or form fields.
  • oauth2 - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported.
  • permissions2 - Handler for keeping track of users, login states and permissions.
  • render - Handler that provides a service for easily rendering JSON and HTML templates.
  • secure - Implements a few quick security wins.
  • sessions - Handler that provides a Session service.
  • sessionauth - Handler that provides a simple way to make routes require a login, and to handle user logins in the session
  • strict - Strict Mode
  • strip - URL Prefix stripping.
  • staticbin - Handler for serving static files from binary data
  • throttle - Request rate throttling middleware.
  • vauth - Handlers for vender webhook authentication (currently GitHub and TravisCI)
  • web - hoisie web.go's Context

How do I integrate with existing servers?

A Martini instance implementshttp.Handler, so it can easily be used to serve subtreeson existing Go servers. For example this is a working Martini app for Google App Engine:

package helloimport ("net/http""github.com/go-martini/martini")funcinit() {m:=martini.Classic()m.Get("/",func()string {return"Hello world!"  })http.Handle("/",m)}

How do I change the port/host?

Martini'sRun function looks for the PORT and HOST environment variables and uses those. Otherwise Martini will default to localhost:3000.To have more flexibility over port and host, use themartini.RunOnAddr function instead.

m:=martini.Classic()// ...m.RunOnAddr(":8080")

Live code reload?

gin andfresh both live reload martini apps.

Contributing

Martini is meant to be kept tiny and clean. Most contributions should end up in a repository in themartini-contrib organization. If you do have a contribution for the core of Martini feel free to put up a Pull Request.

License

Martini is distributed by The MIT License, see LICENSE

About

Inspired byexpress andsinatra

Martini is obsessively designed by none other than theCode Gangsta


[8]ページ先頭

©2009-2025 Movatter.jp