Martini is a powerful package for quickly writing modular web applications/services in Golang.
package main
import "github.com/codegangsta/martini"
func main() {
m := martini.Classic()
m.Get("/", func() string {
return "Hello world!"
})
m.Run()
}
Install the package:
go get github.com/codegangsta/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 here
m.Run()
Below is some of the functionality martini.Classic()
pulls in automatically:
- Request/Response Logging -
martini.Logger()
- Panic Recovery -
martini.Recovery()
- Static File serving -
martini.Static("public")
- Routing -
martini.Router
Handlers are the heart and soul of Martini. A handler is basically any kind of callable function:
m.Get("/", func() {
println("hello world")
}
If a handler returns a string
, Martini will write the result to the current *http.Request
:
m.Get("/", func() string {
return "hello world" // HTTP 200 : "hello world"
})
Handlers are invoked via reflection. Martini makes use of Dependency Injection to resolve dependencies in a Handlers argument list. This makes Martini completely compatible with golang's http.HandlerFunc
interface.
If you add an argument to your Handler, Martini will search it's 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 Martini
res.WriteHead(200) // HTTP 200
})
The following services are included with martini.Classic()
:
- *log.Logger - Global logger for Martini.
- martini.Context - http request context.
- martini.Params -
map[string]string
of named params found by route matching. - http.ResponseWriter - http Response writer interface.
- *http.Request - http Request.
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.Post("/", func() {
// create something
}
m.Put("/", func() {
// replace something
}
m.Delete("/", func() {
// destroy something
}
Routes are matched in the order they are defined. The first route that matches the request is invoked.
Route patterns may include named parameters, accessible via the martini.Params
service:
m.Get("/hello/:name", func(params martini.Params) string {
return "Hello " + params["name"]
})
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
})