[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n\n/.godeps\n/.envrc\n\n# Godeps\nGodeps/_workspace\nGodeps/Readme\n\n### JetBrains template\n# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm\n# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839\n\n.idea/\n\n## File-based project format:\n*.iws\n\n## Plugin-specific files:\n\n# IntelliJ\n/out/\n\n# mpeltonen/sbt-idea plugin\n.idea_modules/\n\n# JIRA plugin\natlassian-ide-plugin.xml\n\n# Crashlytics plugin (for Android Studio and IntelliJ)\ncom_crashlytics_export_strings.xml\ncrashlytics.properties\ncrashlytics-build.properties\nfabric.properties\n"
  },
  {
    "path": "Godeps/Godeps.json",
    "content": "{\n\t\"ImportPath\": \"github.com/go-martini/martini\",\n\t\"GoVersion\": \"go1.4.2\",\n\t\"Deps\": [\n\t\t{\n\t\t\t\"ImportPath\": \"github.com/codegangsta/inject\",\n\t\t\t\"Comment\": \"v1.0-rc1-10-g33e0aa1\",\n\t\t\t\"Rev\": \"33e0aa1cb7c019ccc3fbe049a8262a6403d30504\"\n\t\t}\n\t]\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2015 Jeremy Saenz\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\n### **NOTE:** The martini framework is no longer maintained.\n\nMartini is a powerful package for quickly writing modular web applications/services in Golang.\n\nLanguage Translations:\n* [繁體中文](translations/README_zh_tw.md)\n* [简体中文](translations/README_zh_cn.md)\n* [Português Brasileiro (pt_BR)](translations/README_pt_br.md)\n* [Español](translations/README_es_ES.md)\n* [한국어 번역](translations/README_ko_kr.md)\n* [Русский](translations/README_ru_RU.md)\n* [日本語](translations/README_ja_JP.md)\n* [French](translations/README_fr_FR.md)\n* [Turkish](translations/README_tr_TR.md)\n* [German](translations/README_de_DE.md)\n* [Polski](translations/README_pl_PL.md)\n\n## Getting Started\n\nAfter installing Go and setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH), create your first `.go` file. We'll call it `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nThen install the Martini package (**go 1.1** or greater is required):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nThen run your server:\n~~~\ngo run server.go\n~~~\n\nYou will now have a Martini webserver running on `localhost:3000`.\n\n## Getting Help\n\nJoin the [Mailing list](https://groups.google.com/forum/#!forum/martini-go)\n\nWatch the [Demo Video](http://martini.codegangsta.io/#demo)\n\nAsk questions on Stackoverflow using the [martini tag](http://stackoverflow.com/questions/tagged/martini)\n\nGoDoc [documentation](http://godoc.org/github.com/go-martini/martini)\n\n\n## Features\n* Extremely simple to use.\n* Non-intrusive design.\n* Plays nice with other Golang packages.\n* Awesome path matching and routing.\n* Modular design - Easy to add functionality, easy to rip stuff out.\n* Lots of good handlers/middlewares to use.\n* Great 'out of the box' feature set.\n* **Fully compatible with the [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) interface.**\n* Default document serving (e.g., for serving AngularJS apps in HTML5 mode).\n\n## More Middleware\nFor more middleware and functionality, check out the repositories in the  [martini-contrib](https://github.com/martini-contrib) organization.\n\n## Table of Contents\n* [Classic Martini](#classic-martini)\n  * [Handlers](#handlers)\n  * [Routing](#routing)\n  * [Services](#services)\n  * [Serving Static Files](#serving-static-files)\n* [Middleware Handlers](#middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\nTo get up and running quickly, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) provides some reasonable defaults that work well for most web applications:\n~~~ go\n  m := martini.Classic()\n  // ... middleware and routing goes here\n  m.Run()\n~~~\n\nBelow is some of the functionality [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) pulls in automatically:\n  * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Handlers\nHandlers are the heart and soul of Martini. A handler is basically any kind of callable function:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Return Values\nIf a handler returns something, Martini will write the result to the current [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) as a string:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\nYou can also optionally return a status code:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### Service Injection\nHandlers 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.**\n\nIf you add an argument to your Handler, Martini will search its list of services and attempt to resolve the dependency via type assertion:\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nThe following services are included with [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [*log.Logger](http://godoc.org/log#Logger) - Global logger for Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service.\n  * [martini.Route](http://godoc.org/github.com/go-martini/martini#Route) - Current active route.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request.\n\n### Routing\nIn Martini, a route is an HTTP method paired with a URL-matching pattern.\nEach route can take one or more handler methods:\n~~~ go\nm.Get(\"/\", func() {\n  // show something\n})\n\nm.Patch(\"/\", func() {\n  // update something\n})\n\nm.Post(\"/\", func() {\n  // create something\n})\n\nm.Put(\"/\", func() {\n  // replace something\n})\n\nm.Delete(\"/\", func() {\n  // destroy something\n})\n\nm.Options(\"/\", func() {\n  // http options\n})\n\nm.NotFound(func() {\n  // handle 404\n})\n~~~\n\nRoutes are matched in the order they are defined. The first route that\nmatches the request is invoked.\n\nRoute patterns may include named parameters, accessible via the [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nRoutes can be matched with globs:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\nRegular expressions can be used as well:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nTake a look at the [Go documentation](http://golang.org/pkg/regexp/syntax/) for more info about regular expressions syntax .\n\nRoute handlers can be stacked on top of each other, which is useful for things like authentication and authorization:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // this will execute as long as authorize doesn't write a response\n})\n~~~\n\nRoute groups can be added too using the Group method.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nJust like you can pass middlewares to a handler you can pass middlewares to groups.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Services\nServices are objects that are available to be injected into a Handler's argument list. You can map a service on a *Global* or *Request* level.\n\n#### Global Mapping\nA Martini instance implements the inject.Injector interface, so mapping a service is easy:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // the service will be available to all handlers as *MyDatabase\n// ...\nm.Run()\n~~~\n\n#### Request-Level Mapping\nMapping on the request level can be done in a handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context):\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // mapped as *MyCustomLogger\n}\n~~~\n\n#### Mapping values to Interfaces\nOne of the most powerful parts about services is the ability to map a service to an interface. For instance, if you wanted to override the [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) with an object that wrapped it and performed extra operations, you can write the following handler:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter\n}\n~~~\n\n### Serving Static Files\nA [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) instance automatically serves static files from the \"public\" directory in the root of your server.\nYou can serve from more directories by adding more [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers.\n~~~ go\nm.Use(martini.Static(\"assets\")) // serve from the \"assets\" directory as well\n~~~\n\n#### Serving a Default Document\nYou can specify the URL of a local file to serve when the requested URL is not\nfound. You can also specify an exclusion prefix so that certain URLs are ignored.\nThis is useful for servers that serve both static files and have additional\nhandlers defined (e.g., REST API). When doing so, it's useful to define the\nstatic handler as a part of the NotFound chain.\n\nThe following example serves the `/index.html` file whenever any URL is\nrequested that does not match any local file and does not start with `/api/v`:\n~~~ go\nstatic := martini.Static(\"assets\", martini.StaticOptions{Fallback: \"/index.html\", Exclude: \"/api/v\"})\nm.NotFound(static, http.NotFound)\n~~~\n\n## Middleware Handlers\nMiddleware 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:\n~~~ go\nm.Use(func() {\n  // do some middleware stuff\n})\n~~~\n\nYou can have full control over the middleware stack with the `Handlers` function. This will replace any handlers that have been previously set:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nMiddleware 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:\n~~~ go\n// validate an api key\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) 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:\n~~~ go\n// log before and after a request\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"before a request\")\n\n  c.Next()\n\n  log.Println(\"after a request\")\n})\n~~~\n\n## Martini Env\n\nSome Martini handlers make use of the `martini.Env` global variable to provide special functionality for development environments vs production environments. It is recommended that the `MARTINI_ENV=production` environment variable to be set when deploying a Martini server into a production environment.\n\n## FAQ\n\n### Where do I find middleware X?\n\nStart by looking in the [martini-contrib](https://github.com/martini-contrib) projects. If it is not there feel free to contact a martini-contrib team member about adding a new repo to the organization.\n\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header.\n* [accessflags](https://github.com/martini-contrib/accessflags) - Handler to enable Access Control.\n* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication.\n* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure.\n* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support.\n* [csrf](https://github.com/martini-contrib/csrf) - CSRF protection for applications\n* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation.\n* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests\n* [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic middleware\n* [logstasher](https://github.com/martini-contrib/logstasher) - Middleware that prints logstash-compatible JSON \n* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported.\n* [permissions2](https://github.com/xyproto/permissions2) - Handler for keeping track of users, login states and permissions.\n* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates.\n* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins.\n* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service.\n* [sessionauth](https://github.com/martini-contrib/sessionauth) - Handler that provides a simple way to make routes require a login, and to handle user logins in the session\n* [strict](https://github.com/martini-contrib/strict) - Strict Mode \n* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping.\n* [staticbin](https://github.com/martini-contrib/staticbin) - Handler for serving static files from binary data\n* [throttle](https://github.com/martini-contrib/throttle) - Request rate throttling middleware.\n* [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI)\n* [web](https://github.com/martini-contrib/web) - hoisie web.go's Context\n\n### How do I integrate with existing servers?\n\nA Martini instance implements `http.Handler`, so it can easily be used to serve subtrees\non existing Go servers. For example this is a working Martini app for Google App Engine:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### How do I change the port/host?\n\nMartini's `Run` function looks for the PORT and HOST environment variables and uses those. Otherwise Martini will default to localhost:3000.\nTo have more flexibility over port and host, use the `martini.RunOnAddr` function instead.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  m.RunOnAddr(\":8080\")\n~~~\n\n### Live code reload?\n\n[gin](https://github.com/codegangsta/gin) and [fresh](https://github.com/pilu/fresh) both live reload martini apps.\n\n## Contributing\nMartini is meant to be kept tiny and clean. Most contributions should end up in a repository in the [martini-contrib](https://github.com/martini-contrib) organization. If you do have a contribution for the core of Martini feel free to put up a Pull Request.\n\n## License\nMartini is distributed by The MIT License, see LICENSE\n\n## About\n\nInspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra)\n\nMartini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/)\n"
  },
  {
    "path": "env.go",
    "content": "package martini\n\nimport (\n\t\"os\"\n)\n\n// Envs\nconst (\n\tDev  string = \"development\"\n\tProd string = \"production\"\n\tTest string = \"test\"\n)\n\n// Env is the environment that Martini is executing in. The MARTINI_ENV is read on initialization to set this variable.\nvar Env = Dev\nvar Root string\n\nfunc setENV(e string) {\n\tif len(e) > 0 {\n\t\tEnv = e\n\t}\n}\n\nfunc init() {\n\tsetENV(os.Getenv(\"MARTINI_ENV\"))\n\tvar err error\n\tRoot, err = os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"
  },
  {
    "path": "env_test.go",
    "content": "package martini\n\nimport (\n\t\"testing\"\n)\n\nfunc Test_SetENV(t *testing.T) {\n\ttests := []struct {\n\t\tin  string\n\t\tout string\n\t}{\n\t\t{\"\", \"development\"},\n\t\t{\"not_development\", \"not_development\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tsetENV(test.in)\n\t\tif Env != test.out {\n\t\t\texpect(t, Env, test.out)\n\t\t}\n\t}\n}\n\nfunc Test_Root(t *testing.T) {\n\tif len(Root) == 0 {\n\t\tt.Errorf(\"Expected root path will be set\")\n\t}\n}\n"
  },
  {
    "path": "go_version.go",
    "content": "// +build !go1.1\n\npackage martini\n\nfunc MartiniDoesNotSupportGo1Point0() {\n\t\"Martini requires Go 1.1 or greater.\"\n}\n"
  },
  {
    "path": "logger.go",
    "content": "package martini\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\n// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.\nfunc Logger() Handler {\n\treturn func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) {\n\t\tstart := time.Now()\n\n\t\taddr := req.Header.Get(\"X-Real-IP\")\n\t\tif addr == \"\" {\n\t\t\taddr = req.Header.Get(\"X-Forwarded-For\")\n\t\t\tif addr == \"\" {\n\t\t\t\taddr = req.RemoteAddr\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"Started %s %s for %s\", req.Method, req.URL.Path, addr)\n\n\t\trw := res.(ResponseWriter)\n\t\tc.Next()\n\n\t\tlog.Printf(\"Completed %v %s in %v\\n\", rw.Status(), http.StatusText(rw.Status()), time.Since(start))\n\t}\n}\n"
  },
  {
    "path": "logger_test.go",
    "content": "package martini\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc Test_Logger(t *testing.T) {\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\n\tm := New()\n\t// replace log for testing\n\tm.Map(log.New(buff, \"[martini] \", 0))\n\tm.Use(Logger())\n\tm.Use(func(res http.ResponseWriter) {\n\t\tres.WriteHeader(http.StatusNotFound)\n\t})\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/foobar\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(recorder, req)\n\texpect(t, recorder.Code, http.StatusNotFound)\n\trefute(t, len(buff.String()), 0)\n}\n"
  },
  {
    "path": "martini.go",
    "content": "// Package martini is a powerful package for quickly writing modular web applications/services in Golang.\n//\n// For a full guide visit http://github.com/go-martini/martini\n//\n//  package main\n//\n//  import \"github.com/go-martini/martini\"\n//\n//  func main() {\n//    m := martini.Classic()\n//\n//    m.Get(\"/\", func() string {\n//      return \"Hello world!\"\n//    })\n//\n//    m.Run()\n//  }\npackage martini\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"reflect\"\n\n\t\"github.com/codegangsta/inject\"\n)\n\n// Martini represents the top level web application. inject.Injector methods can be invoked to map services on a global level.\ntype Martini struct {\n\tinject.Injector\n\thandlers []Handler\n\taction   Handler\n\tlogger   *log.Logger\n}\n\n// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.\nfunc New() *Martini {\n\tm := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, \"[martini] \", 0)}\n\tm.Map(m.logger)\n\tm.Map(defaultReturnHandler())\n\treturn m\n}\n\n// Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers.\n// Will panic if any of the handlers is not a callable function\nfunc (m *Martini) Handlers(handlers ...Handler) {\n\tm.handlers = make([]Handler, 0)\n\tfor _, handler := range handlers {\n\t\tm.Use(handler)\n\t}\n}\n\n// 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().\nfunc (m *Martini) Action(handler Handler) {\n\tvalidateHandler(handler)\n\tm.action = handler\n}\n\n// Logger sets the logger\nfunc (m *Martini) Logger(logger *log.Logger) {\n\tm.logger = logger\n\tm.Map(m.logger)\n}\n\n// 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.\nfunc (m *Martini) Use(handler Handler) {\n\tvalidateHandler(handler)\n\n\tm.handlers = append(m.handlers, handler)\n}\n\n// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.\nfunc (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n\tm.createContext(res, req).run()\n}\n\n// Run the http server on a given host and port.\nfunc (m *Martini) RunOnAddr(addr string) {\n\t// TODO: Should probably be implemented using a new instance of http.Server in place of\n\t// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.\n\t// This would also allow to improve testing when a custom host and port are passed.\n\n\tlogger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)\n\tlogger.Printf(\"listening on %s (%s)\\n\", addr, Env)\n\tlogger.Fatalln(http.ListenAndServe(addr, m))\n}\n\n// Run the http server. Listening on os.GetEnv(\"PORT\") or 3000 by default.\nfunc (m *Martini) Run() {\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tport = \"3000\"\n\t}\n\n\thost := os.Getenv(\"HOST\")\n\n\tm.RunOnAddr(host + \":\" + port)\n}\n\nfunc (m *Martini) createContext(res http.ResponseWriter, req *http.Request) *context {\n\tc := &context{inject.New(), m.handlers, m.action, NewResponseWriter(res), 0}\n\tc.SetParent(m)\n\tc.MapTo(c, (*Context)(nil))\n\tc.MapTo(c.rw, (*http.ResponseWriter)(nil))\n\tc.Map(req)\n\treturn c\n}\n\n// ClassicMartini represents a Martini with some reasonable defaults. Embeds the router functions for convenience.\ntype ClassicMartini struct {\n\t*Martini\n\tRouter\n}\n\n// Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static.\n// Classic also maps martini.Routes as a service.\nfunc Classic() *ClassicMartini {\n\tr := NewRouter()\n\tm := New()\n\tm.Use(Logger())\n\tm.Use(Recovery())\n\tm.Use(Static(\"public\"))\n\tm.MapTo(r, (*Routes)(nil))\n\tm.Action(r.Handle)\n\treturn &ClassicMartini{m, r}\n}\n\n// Handler can be any callable function. Martini attempts to inject services into the handler's argument list.\n// Martini will panic if an argument could not be fullfilled via dependency injection.\ntype Handler interface{}\n\nfunc validateHandler(handler Handler) {\n\tif reflect.TypeOf(handler).Kind() != reflect.Func {\n\t\tpanic(\"martini handler must be a callable func\")\n\t}\n}\n\n// Context represents a request context. Services can be mapped on the request level from this interface.\ntype Context interface {\n\tinject.Injector\n\t// Next is an optional function that Middleware Handlers can call to yield the until after\n\t// the other Handlers have been executed. This works really well for any operations that must\n\t// happen after an http request\n\tNext()\n\t// Written returns whether or not the response for this context has been written.\n\tWritten() bool\n}\n\ntype context struct {\n\tinject.Injector\n\thandlers []Handler\n\taction   Handler\n\trw       ResponseWriter\n\tindex    int\n}\n\nfunc (c *context) handler() Handler {\n\tif c.index < len(c.handlers) {\n\t\treturn c.handlers[c.index]\n\t}\n\tif c.index == len(c.handlers) {\n\t\treturn c.action\n\t}\n\tpanic(\"invalid index for context handler\")\n}\n\nfunc (c *context) Next() {\n\tc.index += 1\n\tc.run()\n}\n\nfunc (c *context) Written() bool {\n\treturn c.rw.Written()\n}\n\nfunc (c *context) run() {\n\tfor c.index <= len(c.handlers) {\n\t\t_, err := c.Invoke(c.handler())\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tc.index += 1\n\n\t\tif c.Written() {\n\t\t\treturn\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "martini_test.go",
    "content": "package martini\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n/* Test Helpers */\nfunc expect(t *testing.T, a interface{}, b interface{}) {\n\tif a != b {\n\t\tt.Errorf(\"Expected %v (type %v) - Got %v (type %v)\", b, reflect.TypeOf(b), a, reflect.TypeOf(a))\n\t}\n}\n\nfunc refute(t *testing.T, a interface{}, b interface{}) {\n\tif a == b {\n\t\tt.Errorf(\"Did not expect %v (type %v) - Got %v (type %v)\", b, reflect.TypeOf(b), a, reflect.TypeOf(a))\n\t}\n}\n\nfunc Test_New(t *testing.T) {\n\tm := New()\n\tif m == nil {\n\t\tt.Error(\"martini.New() cannot return nil\")\n\t}\n}\n\nfunc Test_Martini_RunOnAddr(t *testing.T) {\n\t// just test that Run doesn't bomb\n\tgo New().RunOnAddr(\"127.0.0.1:8080\")\n}\n\nfunc Test_Martini_Run(t *testing.T) {\n\tgo New().Run()\n}\n\nfunc Test_Martini_ServeHTTP(t *testing.T) {\n\tresult := \"\"\n\tresponse := httptest.NewRecorder()\n\n\tm := New()\n\tm.Use(func(c Context) {\n\t\tresult += \"foo\"\n\t\tc.Next()\n\t\tresult += \"ban\"\n\t})\n\tm.Use(func(c Context) {\n\t\tresult += \"bar\"\n\t\tc.Next()\n\t\tresult += \"baz\"\n\t})\n\tm.Action(func(res http.ResponseWriter, req *http.Request) {\n\t\tresult += \"bat\"\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t})\n\n\tm.ServeHTTP(response, (*http.Request)(nil))\n\n\texpect(t, result, \"foobarbatbazban\")\n\texpect(t, response.Code, http.StatusBadRequest)\n}\n\nfunc Test_Martini_Handlers(t *testing.T) {\n\tresult := \"\"\n\tresponse := httptest.NewRecorder()\n\n\tbatman := func(c Context) {\n\t\tresult += \"batman!\"\n\t}\n\n\tm := New()\n\tm.Use(func(c Context) {\n\t\tresult += \"foo\"\n\t\tc.Next()\n\t\tresult += \"ban\"\n\t})\n\tm.Handlers(\n\t\tbatman,\n\t\tbatman,\n\t\tbatman,\n\t)\n\tm.Action(func(res http.ResponseWriter, req *http.Request) {\n\t\tresult += \"bat\"\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t})\n\n\tm.ServeHTTP(response, (*http.Request)(nil))\n\n\texpect(t, result, \"batman!batman!batman!bat\")\n\texpect(t, response.Code, http.StatusBadRequest)\n}\n\nfunc Test_Martini_EarlyWrite(t *testing.T) {\n\tresult := \"\"\n\tresponse := httptest.NewRecorder()\n\n\tm := New()\n\tm.Use(func(res http.ResponseWriter) {\n\t\tresult += \"foobar\"\n\t\tres.Write([]byte(\"Hello world\"))\n\t})\n\tm.Use(func() {\n\t\tresult += \"bat\"\n\t})\n\tm.Action(func(res http.ResponseWriter) {\n\t\tresult += \"baz\"\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t})\n\n\tm.ServeHTTP(response, (*http.Request)(nil))\n\n\texpect(t, result, \"foobar\")\n\texpect(t, response.Code, http.StatusOK)\n}\n\nfunc Test_Martini_Written(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tm := New()\n\tm.Handlers(func(res http.ResponseWriter) {\n\t\tres.WriteHeader(http.StatusOK)\n\t})\n\n\tctx := m.createContext(response, (*http.Request)(nil))\n\texpect(t, ctx.Written(), false)\n\n\tctx.run()\n\texpect(t, ctx.Written(), true)\n}\n\nfunc Test_Martini_Basic_NoRace(t *testing.T) {\n\tm := New()\n\thandlers := []Handler{func() {}, func() {}}\n\t// Ensure append will not realloc to trigger the race condition\n\tm.handlers = handlers[:1]\n\treq, _ := http.NewRequest(\"GET\", \"/\", nil)\n\tfor i := 0; i < 2; i++ {\n\t\tgo func() {\n\t\t\tresponse := httptest.NewRecorder()\n\t\t\tm.ServeHTTP(response, req)\n\t\t}()\n\t}\n}\n"
  },
  {
    "path": "recovery.go",
    "content": "package martini\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"runtime\"\n\n\t\"github.com/codegangsta/inject\"\n)\n\nconst (\n\tpanicHtml = `<html>\n<head><title>PANIC: %s</title>\n<style type=\"text/css\">\nhtml, body {\n\tfont-family: \"Roboto\", sans-serif;\n\tcolor: #333333;\n\tbackground-color: #ea5343;\n\tmargin: 0px;\n}\nh1 {\n\tcolor: #d04526;\n\tbackground-color: #ffffff;\n\tpadding: 20px;\n\tborder-bottom: 1px dashed #2b3848;\n}\npre {\n\tmargin: 20px;\n\tpadding: 20px;\n\tborder: 2px solid #2b3848;\n\tbackground-color: #ffffff;\n}\n</style>\n</head><body>\n<h1>PANIC</h1>\n<pre style=\"font-weight: bold;\">%s</pre>\n<pre>%s</pre>\n</body>\n</html>`\n)\n\nvar (\n\tdunno     = []byte(\"???\")\n\tcenterDot = []byte(\"·\")\n\tdot       = []byte(\".\")\n\tslash     = []byte(\"/\")\n)\n\n// stack returns a nicely formated stack frame, skipping skip frames\nfunc stack(skip int) []byte {\n\tbuf := new(bytes.Buffer) // the returned data\n\t// As we loop, we open files and read them. These variables record the currently\n\t// loaded file.\n\tvar lines [][]byte\n\tvar lastFile string\n\tfor i := skip; ; i++ { // Skip the expected number of frames\n\t\tpc, file, line, ok := runtime.Caller(i)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\t// Print this much at least.  If we can't find the source, it won't show.\n\t\tfmt.Fprintf(buf, \"%s:%d (0x%x)\\n\", file, line, pc)\n\t\tif file != lastFile {\n\t\t\tdata, err := ioutil.ReadFile(file)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlines = bytes.Split(data, []byte{'\\n'})\n\t\t\tlastFile = file\n\t\t}\n\t\tfmt.Fprintf(buf, \"\\t%s: %s\\n\", function(pc), source(lines, line))\n\t}\n\treturn buf.Bytes()\n}\n\n// source returns a space-trimmed slice of the n'th line.\nfunc source(lines [][]byte, n int) []byte {\n\tn-- // in stack trace, lines are 1-indexed but our array is 0-indexed\n\tif n < 0 || n >= len(lines) {\n\t\treturn dunno\n\t}\n\treturn bytes.TrimSpace(lines[n])\n}\n\n// function returns, if possible, the name of the function containing the PC.\nfunc function(pc uintptr) []byte {\n\tfn := runtime.FuncForPC(pc)\n\tif fn == nil {\n\t\treturn dunno\n\t}\n\tname := []byte(fn.Name())\n\t// The name includes the path name to the package, which is unnecessary\n\t// since the file name is already included.  Plus, it has center dots.\n\t// That is, we see\n\t//\truntime/debug.*T·ptrmethod\n\t// and want\n\t//\t*T.ptrmethod\n\t// Also the package path might contains dot (e.g. code.google.com/...),\n\t// so first eliminate the path prefix\n\tif lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {\n\t\tname = name[lastslash+1:]\n\t}\n\tif period := bytes.Index(name, dot); period >= 0 {\n\t\tname = name[period+1:]\n\t}\n\tname = bytes.Replace(name, centerDot, dot, -1)\n\treturn name\n}\n\n// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.\n// While Martini is in development mode, Recovery will also output the panic as HTML.\nfunc Recovery() Handler {\n\treturn func(c Context, log *log.Logger) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tstack := stack(3)\n\t\t\t\tlog.Printf(\"PANIC: %s\\n%s\", err, stack)\n\n\t\t\t\t// Lookup the current responsewriter\n\t\t\t\tval := c.Get(inject.InterfaceOf((*http.ResponseWriter)(nil)))\n\t\t\t\tres := val.Interface().(http.ResponseWriter)\n\n\t\t\t\t// respond with panic message while in development mode\n\t\t\t\tvar body []byte\n\t\t\t\tif Env == Dev {\n\t\t\t\t\tres.Header().Set(\"Content-Type\", \"text/html\")\n\t\t\t\t\tbody = []byte(fmt.Sprintf(panicHtml, err, err, stack))\n\t\t\t\t} else {\n\t\t\t\t\tbody = []byte(\"500 Internal Server Error\")\n\t\t\t\t}\n\n\t\t\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tif nil != body {\n\t\t\t\t\tres.Write(body)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tc.Next()\n\t}\n}\n"
  },
  {
    "path": "recovery_test.go",
    "content": "package martini\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc Test_Recovery(t *testing.T) {\n\tbuff := bytes.NewBufferString(\"\")\n\trecorder := httptest.NewRecorder()\n\n\tsetENV(Dev)\n\tm := New()\n\t// replace log for testing\n\tm.Map(log.New(buff, \"[martini] \", 0))\n\tm.Use(func(res http.ResponseWriter, req *http.Request) {\n\t\tres.Header().Set(\"Content-Type\", \"unpredictable\")\n\t})\n\tm.Use(Recovery())\n\tm.Use(func(res http.ResponseWriter, req *http.Request) {\n\t\tpanic(\"here is a panic!\")\n\t})\n\tm.ServeHTTP(recorder, (*http.Request)(nil))\n\texpect(t, recorder.Code, http.StatusInternalServerError)\n\texpect(t, recorder.HeaderMap.Get(\"Content-Type\"), \"text/html\")\n\trefute(t, recorder.Body.Len(), 0)\n\trefute(t, len(buff.String()), 0)\n}\n\nfunc Test_Recovery_ResponseWriter(t *testing.T) {\n\trecorder := httptest.NewRecorder()\n\trecorder2 := httptest.NewRecorder()\n\n\tsetENV(Dev)\n\tm := New()\n\tm.Use(Recovery())\n\tm.Use(func(c Context) {\n\t\tc.MapTo(recorder2, (*http.ResponseWriter)(nil))\n\t\tpanic(\"here is a panic!\")\n\t})\n\tm.ServeHTTP(recorder, (*http.Request)(nil))\n\n\texpect(t, recorder2.Code, http.StatusInternalServerError)\n\texpect(t, recorder2.HeaderMap.Get(\"Content-Type\"), \"text/html\")\n\trefute(t, recorder2.Body.Len(), 0)\n}\n"
  },
  {
    "path": "response_writer.go",
    "content": "package martini\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n)\n\n// ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about\n// the response. It is recommended that middleware handlers use this construct to wrap a responsewriter\n// if the functionality calls for it.\ntype ResponseWriter interface {\n\thttp.ResponseWriter\n\thttp.Flusher\n\thttp.Hijacker\n\t// Status returns the status code of the response or 0 if the response has not been written.\n\tStatus() int\n\t// Written returns whether or not the ResponseWriter has been written.\n\tWritten() bool\n\t// Size returns the size of the response body.\n\tSize() int\n\t// Before allows for a function to be called before the ResponseWriter has been written to. This is\n\t// useful for setting headers or any other operations that must happen before a response has been written.\n\tBefore(BeforeFunc)\n}\n\n// BeforeFunc is a function that is called before the ResponseWriter has been written to.\ntype BeforeFunc func(ResponseWriter)\n\n// NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter\nfunc NewResponseWriter(rw http.ResponseWriter) ResponseWriter {\n\tnewRw := responseWriter{rw, 0, 0, nil}\n\tif cn, ok := rw.(http.CloseNotifier); ok {\n\t\treturn &closeNotifyResponseWriter{newRw, cn}\n\t}\n\treturn &newRw\n}\n\ntype responseWriter struct {\n\thttp.ResponseWriter\n\tstatus      int\n\tsize        int\n\tbeforeFuncs []BeforeFunc\n}\n\nfunc (rw *responseWriter) WriteHeader(s int) {\n\trw.callBefore()\n\trw.ResponseWriter.WriteHeader(s)\n\trw.status = s\n}\n\nfunc (rw *responseWriter) Write(b []byte) (int, error) {\n\tif !rw.Written() {\n\t\t// The status will be StatusOK if WriteHeader has not been called yet\n\t\trw.WriteHeader(http.StatusOK)\n\t}\n\tsize, err := rw.ResponseWriter.Write(b)\n\trw.size += size\n\treturn size, err\n}\n\nfunc (rw *responseWriter) Status() int {\n\treturn rw.status\n}\n\nfunc (rw *responseWriter) Size() int {\n\treturn rw.size\n}\n\nfunc (rw *responseWriter) Written() bool {\n\treturn rw.status != 0\n}\n\nfunc (rw *responseWriter) Before(before BeforeFunc) {\n\trw.beforeFuncs = append(rw.beforeFuncs, before)\n}\n\nfunc (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\thijacker, ok := rw.ResponseWriter.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"the ResponseWriter doesn't support the Hijacker interface\")\n\t}\n\treturn hijacker.Hijack()\n}\n\nfunc (rw *responseWriter) callBefore() {\n\tfor i := len(rw.beforeFuncs) - 1; i >= 0; i-- {\n\t\trw.beforeFuncs[i](rw)\n\t}\n}\n\nfunc (rw *responseWriter) Flush() {\n\tflusher, ok := rw.ResponseWriter.(http.Flusher)\n\tif ok {\n\t\tflusher.Flush()\n\t}\n}\n\ntype closeNotifyResponseWriter struct {\n\tresponseWriter\n\tcloseNotifier http.CloseNotifier\n}\n\nfunc (rw *closeNotifyResponseWriter) CloseNotify() <-chan bool {\n\treturn rw.closeNotifier.CloseNotify()\n}\n"
  },
  {
    "path": "response_writer_test.go",
    "content": "package martini\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype closeNotifyingRecorder struct {\n\t*httptest.ResponseRecorder\n\tclosed chan bool\n}\n\nfunc newCloseNotifyingRecorder() *closeNotifyingRecorder {\n\treturn &closeNotifyingRecorder{\n\t\thttptest.NewRecorder(),\n\t\tmake(chan bool, 1),\n\t}\n}\n\nfunc (c *closeNotifyingRecorder) close() {\n\tc.closed <- true\n}\n\nfunc (c *closeNotifyingRecorder) CloseNotify() <-chan bool {\n\treturn c.closed\n}\n\ntype hijackableResponse struct {\n\tHijacked bool\n}\n\nfunc newHijackableResponse() *hijackableResponse {\n\treturn &hijackableResponse{}\n}\n\nfunc (h *hijackableResponse) Header() http.Header           { return nil }\nfunc (h *hijackableResponse) Write(buf []byte) (int, error) { return 0, nil }\nfunc (h *hijackableResponse) WriteHeader(code int)          {}\nfunc (h *hijackableResponse) Flush()                        {}\nfunc (h *hijackableResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\th.Hijacked = true\n\treturn nil, nil, nil\n}\n\nfunc Test_ResponseWriter_WritingString(t *testing.T) {\n\trec := httptest.NewRecorder()\n\trw := NewResponseWriter(rec)\n\n\trw.Write([]byte(\"Hello world\"))\n\n\texpect(t, rec.Code, rw.Status())\n\texpect(t, rec.Body.String(), \"Hello world\")\n\texpect(t, rw.Status(), http.StatusOK)\n\texpect(t, rw.Size(), 11)\n\texpect(t, rw.Written(), true)\n}\n\nfunc Test_ResponseWriter_WritingStrings(t *testing.T) {\n\trec := httptest.NewRecorder()\n\trw := NewResponseWriter(rec)\n\n\trw.Write([]byte(\"Hello world\"))\n\trw.Write([]byte(\"foo bar bat baz\"))\n\n\texpect(t, rec.Code, rw.Status())\n\texpect(t, rec.Body.String(), \"Hello worldfoo bar bat baz\")\n\texpect(t, rw.Status(), http.StatusOK)\n\texpect(t, rw.Size(), 26)\n}\n\nfunc Test_ResponseWriter_WritingHeader(t *testing.T) {\n\trec := httptest.NewRecorder()\n\trw := NewResponseWriter(rec)\n\n\trw.WriteHeader(http.StatusNotFound)\n\n\texpect(t, rec.Code, rw.Status())\n\texpect(t, rec.Body.String(), \"\")\n\texpect(t, rw.Status(), http.StatusNotFound)\n\texpect(t, rw.Size(), 0)\n}\n\nfunc Test_ResponseWriter_Before(t *testing.T) {\n\trec := httptest.NewRecorder()\n\trw := NewResponseWriter(rec)\n\tresult := \"\"\n\n\trw.Before(func(ResponseWriter) {\n\t\tresult += \"foo\"\n\t})\n\trw.Before(func(ResponseWriter) {\n\t\tresult += \"bar\"\n\t})\n\n\trw.WriteHeader(http.StatusNotFound)\n\n\texpect(t, rec.Code, rw.Status())\n\texpect(t, rec.Body.String(), \"\")\n\texpect(t, rw.Status(), http.StatusNotFound)\n\texpect(t, rw.Size(), 0)\n\texpect(t, result, \"barfoo\")\n}\n\nfunc Test_ResponseWriter_Hijack(t *testing.T) {\n\thijackable := newHijackableResponse()\n\trw := NewResponseWriter(hijackable)\n\thijacker, ok := rw.(http.Hijacker)\n\texpect(t, ok, true)\n\t_, _, err := hijacker.Hijack()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\texpect(t, hijackable.Hijacked, true)\n}\n\nfunc Test_ResponseWrite_Hijack_NotOK(t *testing.T) {\n\thijackable := new(http.ResponseWriter)\n\trw := NewResponseWriter(*hijackable)\n\thijacker, ok := rw.(http.Hijacker)\n\texpect(t, ok, true)\n\t_, _, err := hijacker.Hijack()\n\n\trefute(t, err, nil)\n}\n\nfunc Test_ResponseWriter_CloseNotify(t *testing.T) {\n\trec := newCloseNotifyingRecorder()\n\trw := NewResponseWriter(rec)\n\tclosed := false\n\tnotifier := rw.(http.CloseNotifier).CloseNotify()\n\trec.close()\n\tselect {\n\tcase <-notifier:\n\t\tclosed = true\n\tcase <-time.After(time.Second):\n\t}\n\texpect(t, closed, true)\n}\n\nfunc Test_ResponseWriter_Flusher(t *testing.T) {\n\n\trec := httptest.NewRecorder()\n\trw := NewResponseWriter(rec)\n\n\t_, ok := rw.(http.Flusher)\n\texpect(t, ok, true)\n}\n\nfunc Test_ResponseWriter_FlusherHandler(t *testing.T) {\n\n\t// New martini instance\n\tm := Classic()\n\n\tm.Get(\"/events\", func(w http.ResponseWriter, r *http.Request) {\n\n\t\tf, ok := w.(http.Flusher)\n\t\texpect(t, ok, true)\n\n\t\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\t\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\t\tw.Header().Set(\"Connection\", \"keep-alive\")\n\n\t\tfor i := 0; i < 2; i++ {\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\tio.WriteString(w, \"data: Hello\\n\\n\")\n\t\t\tf.Flush()\n\t\t}\n\n\t})\n\n\trecorder := httptest.NewRecorder()\n\tr, _ := http.NewRequest(\"GET\", \"/events\", nil)\n\tm.ServeHTTP(recorder, r)\n\n\tif recorder.Code != 200 {\n\t\tt.Error(\"Response not 200\")\n\t}\n\n\tif recorder.Body.String() != \"data: Hello\\n\\ndata: Hello\\n\\n\" {\n\t\tt.Error(\"Didn't receive correct body, got:\", recorder.Body.String())\n\t}\n\n}\n"
  },
  {
    "path": "return_handler.go",
    "content": "package martini\n\nimport (\n\t\"github.com/codegangsta/inject\"\n\t\"net/http\"\n\t\"reflect\"\n)\n\n// ReturnHandler is a service that Martini provides that is called\n// when a route handler returns something. The ReturnHandler is\n// responsible for writing to the ResponseWriter based on the values\n// that are passed into this function.\ntype ReturnHandler func(Context, []reflect.Value)\n\nfunc defaultReturnHandler() ReturnHandler {\n\treturn func(ctx Context, vals []reflect.Value) {\n\t\trv := ctx.Get(inject.InterfaceOf((*http.ResponseWriter)(nil)))\n\t\tres := rv.Interface().(http.ResponseWriter)\n\t\tvar responseVal reflect.Value\n\t\tif len(vals) > 1 && vals[0].Kind() == reflect.Int {\n\t\t\tres.WriteHeader(int(vals[0].Int()))\n\t\t\tresponseVal = vals[1]\n\t\t} else if len(vals) > 0 {\n\t\t\tresponseVal = vals[0]\n\t\t}\n\t\tif canDeref(responseVal) {\n\t\t\tresponseVal = responseVal.Elem()\n\t\t}\n\t\tif isByteSlice(responseVal) {\n\t\t\tres.Write(responseVal.Bytes())\n\t\t} else {\n\t\t\tres.Write([]byte(responseVal.String()))\n\t\t}\n\t}\n}\n\nfunc isByteSlice(val reflect.Value) bool {\n\treturn val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8\n}\n\nfunc canDeref(val reflect.Value) bool {\n\treturn val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr\n}\n"
  },
  {
    "path": "router.go",
    "content": "package martini\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"sync\"\n)\n\n// 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.\ntype Params map[string]string\n\n// Router is Martini's de-facto routing interface. Supports HTTP verbs, stacked handlers, and dependency injection.\ntype Router interface {\n\tRoutes\n\n\t// Group adds a group where related routes can be added.\n\tGroup(string, func(Router), ...Handler)\n\t// Get adds a route for a HTTP GET request to the specified matching pattern.\n\tGet(string, ...Handler) Route\n\t// Patch adds a route for a HTTP PATCH request to the specified matching pattern.\n\tPatch(string, ...Handler) Route\n\t// Post adds a route for a HTTP POST request to the specified matching pattern.\n\tPost(string, ...Handler) Route\n\t// Put adds a route for a HTTP PUT request to the specified matching pattern.\n\tPut(string, ...Handler) Route\n\t// Delete adds a route for a HTTP DELETE request to the specified matching pattern.\n\tDelete(string, ...Handler) Route\n\t// Options adds a route for a HTTP OPTIONS request to the specified matching pattern.\n\tOptions(string, ...Handler) Route\n\t// Head adds a route for a HTTP HEAD request to the specified matching pattern.\n\tHead(string, ...Handler) Route\n\t// Any adds a route for any HTTP method request to the specified matching pattern.\n\tAny(string, ...Handler) Route\n\t// AddRoute adds a route for a given HTTP method request to the specified matching pattern.\n\tAddRoute(string, string, ...Handler) Route\n\n\t// NotFound sets the handlers that are called when a no route matches a request. Throws a basic 404 by default.\n\tNotFound(...Handler)\n\n\t// Handle is the entry point for routing. This is used as a martini.Handler\n\tHandle(http.ResponseWriter, *http.Request, Context)\n}\n\ntype router struct {\n\troutes     []*route\n\tnotFounds  []Handler\n\tgroups     []group\n\troutesLock sync.RWMutex\n}\n\ntype group struct {\n\tpattern  string\n\thandlers []Handler\n}\n\n// NewRouter creates a new Router instance.\n// If you aren't using ClassicMartini, then you can add Routes as a\n// service with:\n//\n//\tm := martini.New()\n//\tr := martini.NewRouter()\n//\tm.MapTo(r, (*martini.Routes)(nil))\n//\n// If you are using ClassicMartini, then this is done for you.\nfunc NewRouter() Router {\n\treturn &router{notFounds: []Handler{http.NotFound}, groups: make([]group, 0)}\n}\n\nfunc (r *router) Group(pattern string, fn func(Router), h ...Handler) {\n\tr.groups = append(r.groups, group{pattern, h})\n\tfn(r)\n\tr.groups = r.groups[:len(r.groups)-1]\n}\n\nfunc (r *router) Get(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"GET\", pattern, h)\n}\n\nfunc (r *router) Patch(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"PATCH\", pattern, h)\n}\n\nfunc (r *router) Post(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"POST\", pattern, h)\n}\n\nfunc (r *router) Put(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"PUT\", pattern, h)\n}\n\nfunc (r *router) Delete(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"DELETE\", pattern, h)\n}\n\nfunc (r *router) Options(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"OPTIONS\", pattern, h)\n}\n\nfunc (r *router) Head(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"HEAD\", pattern, h)\n}\n\nfunc (r *router) Any(pattern string, h ...Handler) Route {\n\treturn r.addRoute(\"*\", pattern, h)\n}\n\nfunc (r *router) AddRoute(method, pattern string, h ...Handler) Route {\n\treturn r.addRoute(method, pattern, h)\n}\n\nfunc (r *router) Handle(res http.ResponseWriter, req *http.Request, context Context) {\n\tbestMatch := NoMatch\n\tvar bestVals map[string]string\n\tvar bestRoute *route\n\tfor _, route := range r.getRoutes() {\n\t\tmatch, vals := route.Match(req.Method, req.URL.Path)\n\t\tif match.BetterThan(bestMatch) {\n\t\t\tbestMatch = match\n\t\t\tbestVals = vals\n\t\t\tbestRoute = route\n\t\t\tif match == ExactMatch {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif bestMatch != NoMatch {\n\t\tparams := Params(bestVals)\n\t\tcontext.Map(params)\n\t\tbestRoute.Handle(context, res)\n\t\treturn\n\t}\n\n\t// no routes exist, 404\n\tc := &routeContext{context, 0, r.notFounds}\n\tcontext.MapTo(c, (*Context)(nil))\n\tc.run()\n}\n\nfunc (r *router) NotFound(handler ...Handler) {\n\tr.notFounds = handler\n}\n\nfunc (r *router) addRoute(method string, pattern string, handlers []Handler) *route {\n\tif len(r.groups) > 0 {\n\t\tgroupPattern := \"\"\n\t\th := make([]Handler, 0)\n\t\tfor _, g := range r.groups {\n\t\t\tgroupPattern += g.pattern\n\t\t\th = append(h, g.handlers...)\n\t\t}\n\n\t\tpattern = groupPattern + pattern\n\t\th = append(h, handlers...)\n\t\thandlers = h\n\t}\n\n\troute := newRoute(method, pattern, handlers)\n\troute.Validate()\n\tr.appendRoute(route)\n\treturn route\n}\n\nfunc (r *router) appendRoute(rt *route) {\n\tr.routesLock.Lock()\n\tdefer r.routesLock.Unlock()\n\tr.routes = append(r.routes, rt)\n}\n\nfunc (r *router) getRoutes() []*route {\n\tr.routesLock.RLock()\n\tdefer r.routesLock.RUnlock()\n\treturn r.routes[:]\n}\n\nfunc (r *router) findRoute(name string) *route {\n\tfor _, route := range r.getRoutes() {\n\t\tif route.name == name {\n\t\t\treturn route\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Route is an interface representing a Route in Martini's routing layer.\ntype Route interface {\n\t// URLWith returns a rendering of the Route's url with the given string params.\n\tURLWith([]string) string\n\t// Name sets a name for the route.\n\tName(string)\n\t// GetName returns the name of the route.\n\tGetName() string\n\t// Pattern returns the pattern of the route.\n\tPattern() string\n\t// Method returns the method of the route.\n\tMethod() string\n}\n\ntype route struct {\n\tmethod   string\n\tregex    *regexp.Regexp\n\thandlers []Handler\n\tpattern  string\n\tname     string\n}\n\nvar routeReg1 = regexp.MustCompile(`:[^/#?()\\.\\\\]+`)\nvar routeReg2 = regexp.MustCompile(`\\*\\*`)\n\nfunc newRoute(method string, pattern string, handlers []Handler) *route {\n\troute := route{method, nil, handlers, pattern, \"\"}\n\tpattern = routeReg1.ReplaceAllStringFunc(pattern, func(m string) string {\n\t\treturn fmt.Sprintf(`(?P<%s>[^/#?]+)`, m[1:])\n\t})\n\tvar index int\n\tpattern = routeReg2.ReplaceAllStringFunc(pattern, func(m string) string {\n\t\tindex++\n\t\treturn fmt.Sprintf(`(?P<_%d>[^#?]*)`, index)\n\t})\n\tpattern += `\\/?`\n\troute.regex = regexp.MustCompile(pattern)\n\treturn &route\n}\n\ntype RouteMatch int\n\nconst (\n\tNoMatch RouteMatch = iota\n\tStarMatch\n\tOverloadMatch\n\tExactMatch\n)\n\n//Higher number = better match\nfunc (r RouteMatch) BetterThan(o RouteMatch) bool {\n\treturn r > o\n}\n\nfunc (r route) MatchMethod(method string) RouteMatch {\n\tswitch {\n\tcase method == r.method:\n\t\treturn ExactMatch\n\tcase method == \"HEAD\" && r.method == \"GET\":\n\t\treturn OverloadMatch\n\tcase r.method == \"*\":\n\t\treturn StarMatch\n\tdefault:\n\t\treturn NoMatch\n\t}\n}\n\nfunc (r route) Match(method string, path string) (RouteMatch, map[string]string) {\n\t// add Any method matching support\n\tmatch := r.MatchMethod(method)\n\tif match == NoMatch {\n\t\treturn match, nil\n\t}\n\n\tmatches := r.regex.FindStringSubmatch(path)\n\tif len(matches) > 0 && matches[0] == path {\n\t\tparams := make(map[string]string)\n\t\tfor i, name := range r.regex.SubexpNames() {\n\t\t\tif len(name) > 0 {\n\t\t\t\tparams[name] = matches[i]\n\t\t\t}\n\t\t}\n\t\treturn match, params\n\t}\n\treturn NoMatch, nil\n}\n\nfunc (r *route) Validate() {\n\tfor _, handler := range r.handlers {\n\t\tvalidateHandler(handler)\n\t}\n}\n\nfunc (r *route) Handle(c Context, res http.ResponseWriter) {\n\tcontext := &routeContext{c, 0, r.handlers}\n\tc.MapTo(context, (*Context)(nil))\n\tc.MapTo(r, (*Route)(nil))\n\tcontext.run()\n}\n\nvar urlReg = regexp.MustCompile(`:[^/#?()\\.\\\\]+|\\(\\?P<[a-zA-Z0-9]+>.*\\)`)\n\n// URLWith returns the url pattern replacing the parameters for its values\nfunc (r *route) URLWith(args []string) string {\n\tif len(args) > 0 {\n\t\targCount := len(args)\n\t\ti := 0\n\t\turl := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string {\n\t\t\tvar val interface{}\n\t\t\tif i < argCount {\n\t\t\t\tval = args[i]\n\t\t\t} else {\n\t\t\t\tval = m\n\t\t\t}\n\t\t\ti += 1\n\t\t\treturn fmt.Sprintf(`%v`, val)\n\t\t})\n\n\t\treturn url\n\t}\n\treturn r.pattern\n}\n\nfunc (r *route) Name(name string) {\n\tr.name = name\n}\n\nfunc (r *route) GetName() string {\n\treturn r.name\n}\n\nfunc (r *route) Pattern() string {\n\treturn r.pattern\n}\n\nfunc (r *route) Method() string {\n\treturn r.method\n}\n\n// Routes is a helper service for Martini's routing layer.\ntype Routes interface {\n\t// URLFor returns a rendered URL for the given route. Optional params can be passed to fulfill named parameters in the route.\n\tURLFor(name string, params ...interface{}) string\n\t// MethodsFor returns an array of methods available for the path\n\tMethodsFor(path string) []string\n\t// All returns an array with all the routes in the router.\n\tAll() []Route\n}\n\n// URLFor returns the url for the given route name.\nfunc (r *router) URLFor(name string, params ...interface{}) string {\n\troute := r.findRoute(name)\n\n\tif route == nil {\n\t\tpanic(\"route not found\")\n\t}\n\n\tvar args []string\n\tfor _, param := range params {\n\t\tswitch v := param.(type) {\n\t\tcase int:\n\t\t\targs = append(args, strconv.FormatInt(int64(v), 10))\n\t\tcase string:\n\t\t\targs = append(args, v)\n\t\tdefault:\n\t\t\tif v != nil {\n\t\t\t\tpanic(\"Arguments passed to URLFor must be integers or strings\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn route.URLWith(args)\n}\n\nfunc (r *router) All() []Route {\n\troutes := r.getRoutes()\n\tvar ri = make([]Route, len(routes))\n\n\tfor i, route := range routes {\n\t\tri[i] = Route(route)\n\t}\n\n\treturn ri\n}\n\nfunc hasMethod(methods []string, method string) bool {\n\tfor _, v := range methods {\n\t\tif v == method {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// MethodsFor returns all methods available for path\nfunc (r *router) MethodsFor(path string) []string {\n\tmethods := []string{}\n\tfor _, route := range r.getRoutes() {\n\t\tmatches := route.regex.FindStringSubmatch(path)\n\t\tif len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) {\n\t\t\tmethods = append(methods, route.method)\n\t\t}\n\t}\n\treturn methods\n}\n\ntype routeContext struct {\n\tContext\n\tindex    int\n\thandlers []Handler\n}\n\nfunc (r *routeContext) Next() {\n\tr.index += 1\n\tr.run()\n}\n\nfunc (r *routeContext) run() {\n\tfor r.index < len(r.handlers) {\n\t\thandler := r.handlers[r.index]\n\t\tvals, err := r.Invoke(handler)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.index += 1\n\n\t\t// if the handler returned something, write it to the http response\n\t\tif len(vals) > 0 {\n\t\t\tev := r.Get(reflect.TypeOf(ReturnHandler(nil)))\n\t\t\thandleReturn := ev.Interface().(ReturnHandler)\n\t\t\thandleReturn(r, vals)\n\t\t}\n\n\t\tif r.Written() {\n\t\t\treturn\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "router_test.go",
    "content": "package martini\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc Test_Routing(t *testing.T) {\n\trouter := NewRouter()\n\trecorder := httptest.NewRecorder()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\n\treq2, _ := http.NewRequest(\"POST\", \"http://localhost:3000/bar/bat\", nil)\n\tcontext2 := New().createContext(recorder, req2)\n\n\treq3, _ := http.NewRequest(\"DELETE\", \"http://localhost:3000/baz\", nil)\n\tcontext3 := New().createContext(recorder, req3)\n\n\treq4, _ := http.NewRequest(\"PATCH\", \"http://localhost:3000/bar/foo\", nil)\n\tcontext4 := New().createContext(recorder, req4)\n\n\treq5, _ := http.NewRequest(\"GET\", \"http://localhost:3000/fez/this/should/match\", nil)\n\tcontext5 := New().createContext(recorder, req5)\n\n\treq6, _ := http.NewRequest(\"PUT\", \"http://localhost:3000/pop/blah/blah/blah/bap/foo/\", nil)\n\tcontext6 := New().createContext(recorder, req6)\n\n\treq7, _ := http.NewRequest(\"DELETE\", \"http://localhost:3000/wap//pow\", nil)\n\tcontext7 := New().createContext(recorder, req7)\n\n\treq8, _ := http.NewRequest(\"HEAD\", \"http://localhost:3000/wap//pow\", nil)\n\tcontext8 := New().createContext(recorder, req8)\n\n\treq9, _ := http.NewRequest(\"OPTIONS\", \"http://localhost:3000/opts\", nil)\n\tcontext9 := New().createContext(recorder, req9)\n\n\treq10, _ := http.NewRequest(\"HEAD\", \"http://localhost:3000/foo\", nil)\n\tcontext10 := New().createContext(recorder, req10)\n\n\treq11, _ := http.NewRequest(\"GET\", \"http://localhost:3000/bazz/inga\", nil)\n\tcontext11 := New().createContext(recorder, req11)\n\n\treq12, _ := http.NewRequest(\"POST\", \"http://localhost:3000/bazz/inga\", nil)\n\tcontext12 := New().createContext(recorder, req12)\n\n\treq13, _ := http.NewRequest(\"GET\", \"http://localhost:3000/bazz/in/ga\", nil)\n\tcontext13 := New().createContext(recorder, req13)\n\n\treq14, _ := http.NewRequest(\"GET\", \"http://localhost:3000/bzz\", nil)\n\tcontext14 := New().createContext(recorder, req14)\n\n\tresult := \"\"\n\trouter.Get(\"/foo\", func(req *http.Request) {\n\t\tresult += \"foo\"\n\t})\n\trouter.Patch(\"/bar/:id\", func(params Params) {\n\t\texpect(t, params[\"id\"], \"foo\")\n\t\tresult += \"barfoo\"\n\t})\n\trouter.Post(\"/bar/:id\", func(params Params) {\n\t\texpect(t, params[\"id\"], \"bat\")\n\t\tresult += \"barbat\"\n\t})\n\trouter.Put(\"/fizzbuzz\", func() {\n\t\tresult += \"fizzbuzz\"\n\t})\n\trouter.Delete(\"/bazzer\", func(c Context) {\n\t\tresult += \"baz\"\n\t})\n\trouter.Get(\"/fez/**\", func(params Params) {\n\t\texpect(t, params[\"_1\"], \"this/should/match\")\n\t\tresult += \"fez\"\n\t})\n\trouter.Put(\"/pop/**/bap/:id/**\", func(params Params) {\n\t\texpect(t, params[\"id\"], \"foo\")\n\t\texpect(t, params[\"_1\"], \"blah/blah/blah\")\n\t\texpect(t, params[\"_2\"], \"\")\n\t\tresult += \"popbap\"\n\t})\n\trouter.Delete(\"/wap/**/pow\", func(params Params) {\n\t\texpect(t, params[\"_1\"], \"\")\n\t\tresult += \"wappow\"\n\t})\n\trouter.Options(\"/opts\", func() {\n\t\tresult += \"opts\"\n\t})\n\trouter.Head(\"/wap/**/pow\", func(params Params) {\n\t\texpect(t, params[\"_1\"], \"\")\n\t\tresult += \"wappow\"\n\t})\n\trouter.Group(\"/bazz\", func(r Router) {\n\t\tr.Get(\"/inga\", func() {\n\t\t\tresult += \"get\"\n\t\t})\n\n\t\tr.Post(\"/inga\", func() {\n\t\t\tresult += \"post\"\n\t\t})\n\n\t\tr.Group(\"/in\", func(r Router) {\n\t\t\tr.Get(\"/ga\", func() {\n\t\t\t\tresult += \"ception\"\n\t\t\t})\n\t\t}, func() {\n\t\t\tresult += \"group\"\n\t\t})\n\t}, func() {\n\t\tresult += \"bazz\"\n\t}, func() {\n\t\tresult += \"inga\"\n\t})\n\trouter.AddRoute(\"GET\", \"/bzz\", func(c Context) {\n\t\tresult += \"bzz\"\n\t})\n\n\trouter.Handle(recorder, req, context)\n\trouter.Handle(recorder, req2, context2)\n\trouter.Handle(recorder, req3, context3)\n\trouter.Handle(recorder, req4, context4)\n\trouter.Handle(recorder, req5, context5)\n\trouter.Handle(recorder, req6, context6)\n\trouter.Handle(recorder, req7, context7)\n\trouter.Handle(recorder, req8, context8)\n\trouter.Handle(recorder, req9, context9)\n\trouter.Handle(recorder, req10, context10)\n\trouter.Handle(recorder, req11, context11)\n\trouter.Handle(recorder, req12, context12)\n\trouter.Handle(recorder, req13, context13)\n\trouter.Handle(recorder, req14, context14)\n\texpect(t, result, \"foobarbatbarfoofezpopbapwappowwappowoptsfoobazzingagetbazzingapostbazzingagroupceptionbzz\")\n\texpect(t, recorder.Code, http.StatusNotFound)\n\texpect(t, recorder.Body.String(), \"404 page not found\\n\")\n}\n\nfunc Test_RouterHandlerStatusCode(t *testing.T) {\n\trouter := NewRouter()\n\trouter.Get(\"/foo\", func() string {\n\t\treturn \"foo\"\n\t})\n\trouter.Get(\"/bar\", func() (int, string) {\n\t\treturn http.StatusForbidden, \"bar\"\n\t})\n\trouter.Get(\"/baz\", func() (string, string) {\n\t\treturn \"baz\", \"BAZ!\"\n\t})\n\trouter.Get(\"/bytes\", func() []byte {\n\t\treturn []byte(\"Bytes!\")\n\t})\n\trouter.Get(\"/interface\", func() interface{} {\n\t\treturn \"Interface!\"\n\t})\n\n\t// code should be 200 if none is returned from the handler\n\trecorder := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusOK)\n\texpect(t, recorder.Body.String(), \"foo\")\n\n\t// if a status code is returned, it should be used\n\trecorder = httptest.NewRecorder()\n\treq, _ = http.NewRequest(\"GET\", \"http://localhost:3000/bar\", nil)\n\tcontext = New().createContext(recorder, req)\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusForbidden)\n\texpect(t, recorder.Body.String(), \"bar\")\n\n\t// shouldn't use the first returned value as a status code if not an integer\n\trecorder = httptest.NewRecorder()\n\treq, _ = http.NewRequest(\"GET\", \"http://localhost:3000/baz\", nil)\n\tcontext = New().createContext(recorder, req)\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusOK)\n\texpect(t, recorder.Body.String(), \"baz\")\n\n\t// Should render bytes as a return value as well.\n\trecorder = httptest.NewRecorder()\n\treq, _ = http.NewRequest(\"GET\", \"http://localhost:3000/bytes\", nil)\n\tcontext = New().createContext(recorder, req)\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusOK)\n\texpect(t, recorder.Body.String(), \"Bytes!\")\n\n\t// Should render interface{} values.\n\trecorder = httptest.NewRecorder()\n\treq, _ = http.NewRequest(\"GET\", \"http://localhost:3000/interface\", nil)\n\tcontext = New().createContext(recorder, req)\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusOK)\n\texpect(t, recorder.Body.String(), \"Interface!\")\n}\n\nfunc Test_RouterHandlerStacking(t *testing.T) {\n\trouter := NewRouter()\n\trecorder := httptest.NewRecorder()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\n\tresult := \"\"\n\n\tf1 := func() {\n\t\tresult += \"foo\"\n\t}\n\n\tf2 := func(c Context) {\n\t\tresult += \"bar\"\n\t\tc.Next()\n\t\tresult += \"bing\"\n\t}\n\n\tf3 := func() string {\n\t\tresult += \"bat\"\n\t\treturn \"Hello world\"\n\t}\n\n\tf4 := func() {\n\t\tresult += \"baz\"\n\t}\n\n\trouter.Get(\"/foo\", f1, f2, f3, f4)\n\n\trouter.Handle(recorder, req, context)\n\texpect(t, result, \"foobarbatbing\")\n\texpect(t, recorder.Body.String(), \"Hello world\")\n}\n\nvar routeTests = []struct {\n\t// in\n\tmethod string\n\tpath   string\n\n\t// out\n\tmatch  RouteMatch\n\tparams map[string]string\n}{\n\t{\"GET\", \"/foo/123/bat/321\", ExactMatch, map[string]string{\"bar\": \"123\", \"baz\": \"321\"}},\n\t{\"POST\", \"/foo/123/bat/321\", NoMatch, map[string]string{}},\n\t{\"GET\", \"/foo/hello/bat/world\", ExactMatch, map[string]string{\"bar\": \"hello\", \"baz\": \"world\"}},\n\t{\"GET\", \"foo/hello/bat/world\", NoMatch, map[string]string{}},\n\t{\"GET\", \"/foo/123/bat/321/\", ExactMatch, map[string]string{\"bar\": \"123\", \"baz\": \"321\"}},\n\t{\"GET\", \"/foo/123/bat/321//\", NoMatch, map[string]string{}},\n\t{\"GET\", \"/foo/123//bat/321/\", NoMatch, map[string]string{}},\n\t{\"HEAD\", \"/foo/123/bat/321/\", OverloadMatch, map[string]string{\"bar\": \"123\", \"baz\": \"321\"}},\n}\n\nfunc Test_RouteMatching(t *testing.T) {\n\troute := newRoute(\"GET\", \"/foo/:bar/bat/:baz\", nil)\n\tfor _, tt := range routeTests {\n\t\tmatch, params := route.Match(tt.method, tt.path)\n\t\tif match != tt.match || params[\"bar\"] != tt.params[\"bar\"] || params[\"baz\"] != tt.params[\"baz\"] {\n\t\t\tt.Errorf(\"expected: (%v, %v) got: (%v, %v)\", tt.match, tt.params, match, params)\n\t\t}\n\t}\n}\n\nfunc Test_MethodsFor(t *testing.T) {\n\trouter := NewRouter()\n\trecorder := httptest.NewRecorder()\n\n\treq, _ := http.NewRequest(\"POST\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\tcontext.MapTo(router, (*Routes)(nil))\n\trouter.Post(\"/foo/bar\", func() {\n\t})\n\n\trouter.Post(\"/fo\", func() {\n\t})\n\n\trouter.Get(\"/foo\", func() {\n\t})\n\n\trouter.Put(\"/foo\", func() {\n\t})\n\n\trouter.NotFound(func(routes Routes, w http.ResponseWriter, r *http.Request) {\n\t\tmethods := routes.MethodsFor(r.URL.Path)\n\t\tif len(methods) != 0 {\n\t\t\tw.Header().Set(\"Allow\", strings.Join(methods, \",\"))\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t}\n\t})\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusMethodNotAllowed)\n\texpect(t, recorder.Header().Get(\"Allow\"), \"GET,PUT\")\n}\n\nfunc Test_NotFound(t *testing.T) {\n\trouter := NewRouter()\n\trecorder := httptest.NewRecorder()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\n\trouter.NotFound(func(res http.ResponseWriter) {\n\t\thttp.Error(res, \"Nope\", http.StatusNotFound)\n\t})\n\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusNotFound)\n\texpect(t, recorder.Body.String(), \"Nope\\n\")\n}\n\nfunc Test_NotFoundAsHandler(t *testing.T) {\n\trouter := NewRouter()\n\trecorder := httptest.NewRecorder()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\n\trouter.NotFound(func() string {\n\t\treturn \"not found\"\n\t})\n\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusOK)\n\texpect(t, recorder.Body.String(), \"not found\")\n\n\trecorder = httptest.NewRecorder()\n\n\tcontext = New().createContext(recorder, req)\n\n\trouter.NotFound(func() (int, string) {\n\t\treturn 404, \"not found\"\n\t})\n\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusNotFound)\n\texpect(t, recorder.Body.String(), \"not found\")\n\n\trecorder = httptest.NewRecorder()\n\n\tcontext = New().createContext(recorder, req)\n\n\trouter.NotFound(func() (int, string) {\n\t\treturn 200, \"\"\n\t})\n\n\trouter.Handle(recorder, req, context)\n\texpect(t, recorder.Code, http.StatusOK)\n\texpect(t, recorder.Body.String(), \"\")\n}\n\nfunc Test_NotFoundStacking(t *testing.T) {\n\trouter := NewRouter()\n\trecorder := httptest.NewRecorder()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\n\tresult := \"\"\n\n\tf1 := func() {\n\t\tresult += \"foo\"\n\t}\n\n\tf2 := func(c Context) {\n\t\tresult += \"bar\"\n\t\tc.Next()\n\t\tresult += \"bing\"\n\t}\n\n\tf3 := func() string {\n\t\tresult += \"bat\"\n\t\treturn \"Not Found\"\n\t}\n\n\tf4 := func() {\n\t\tresult += \"baz\"\n\t}\n\n\trouter.NotFound(f1, f2, f3, f4)\n\n\trouter.Handle(recorder, req, context)\n\texpect(t, result, \"foobarbatbing\")\n\texpect(t, recorder.Body.String(), \"Not Found\")\n}\n\nfunc Test_Any(t *testing.T) {\n\trouter := NewRouter()\n\trouter.Any(\"/foo\", func(res http.ResponseWriter) {\n\t\thttp.Error(res, \"Nope\", http.StatusNotFound)\n\t})\n\n\trecorder := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\trouter.Handle(recorder, req, context)\n\n\texpect(t, recorder.Code, http.StatusNotFound)\n\texpect(t, recorder.Body.String(), \"Nope\\n\")\n\n\trecorder = httptest.NewRecorder()\n\treq, _ = http.NewRequest(\"PUT\", \"http://localhost:3000/foo\", nil)\n\tcontext = New().createContext(recorder, req)\n\trouter.Handle(recorder, req, context)\n\n\texpect(t, recorder.Code, http.StatusNotFound)\n\texpect(t, recorder.Body.String(), \"Nope\\n\")\n}\n\nfunc Test_URLFor(t *testing.T) {\n\trouter := NewRouter()\n\n\trouter.Get(\"/foo\", func() {\n\t\t// Nothing\n\t}).Name(\"foo\")\n\n\trouter.Post(\"/bar/:id\", func(params Params) {\n\t\t// Nothing\n\t}).Name(\"bar\")\n\n\trouter.Get(\"/baz/:id/(?P<name>[a-z]*)\", func(params Params, routes Routes) {\n\t\t// Nothing\n\t}).Name(\"baz_id\")\n\n\trouter.Get(\"/bar/:id/:name\", func(params Params, routes Routes) {\n\t\texpect(t, routes.URLFor(\"foo\", nil), \"/foo\")\n\t\texpect(t, routes.URLFor(\"bar\", 5), \"/bar/5\")\n\t\texpect(t, routes.URLFor(\"baz_id\", 5, \"john\"), \"/baz/5/john\")\n\t\texpect(t, routes.URLFor(\"bar_id\", 5, \"john\"), \"/bar/5/john\")\n\t}).Name(\"bar_id\")\n\n\t// code should be 200 if none is returned from the handler\n\trecorder := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/bar/foo/bar\", nil)\n\tcontext := New().createContext(recorder, req)\n\tcontext.MapTo(router, (*Routes)(nil))\n\trouter.Handle(recorder, req, context)\n}\n\nfunc Test_AllRoutes(t *testing.T) {\n\trouter := NewRouter()\n\n\tpatterns := []string{\"/foo\", \"/fee\", \"/fii\"}\n\tmethods := []string{\"GET\", \"POST\", \"DELETE\"}\n\tnames := []string{\"foo\", \"fee\", \"fii\"}\n\n\trouter.Get(\"/foo\", func() {}).Name(\"foo\")\n\trouter.Post(\"/fee\", func() {}).Name(\"fee\")\n\trouter.Delete(\"/fii\", func() {}).Name(\"fii\")\n\n\tfor i, r := range router.All() {\n\t\texpect(t, r.Pattern(), patterns[i])\n\t\texpect(t, r.Method(), methods[i])\n\t\texpect(t, r.GetName(), names[i])\n\t}\n}\n\nfunc Test_ActiveRoute(t *testing.T) {\n\trouter := NewRouter()\n\n\trouter.Get(\"/foo\", func(r Route) {\n\t\texpect(t, r.Pattern(), \"/foo\")\n\t\texpect(t, r.GetName(), \"foo\")\n\t}).Name(\"foo\")\n\n\t// code should be 200 if none is returned from the handler\n\trecorder := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"http://localhost:3000/foo\", nil)\n\tcontext := New().createContext(recorder, req)\n\tcontext.MapTo(router, (*Routes)(nil))\n\trouter.Handle(recorder, req, context)\n}\n"
  },
  {
    "path": "static.go",
    "content": "package martini\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n// StaticOptions is a struct for specifying configuration options for the martini.Static middleware.\ntype StaticOptions struct {\n\t// Prefix is the optional prefix used to serve the static directory content\n\tPrefix string\n\t// SkipLogging will disable [Static] log messages when a static file is served.\n\tSkipLogging bool\n\t// IndexFile defines which file to serve as index if it exists.\n\tIndexFile string\n\t// Expires defines which user-defined function to use for producing a HTTP Expires Header\n\t// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching\n\tExpires func() string\n\t// Fallback defines a default URL to serve when the requested resource was\n\t// not found.\n\tFallback string\n\t// Exclude defines a pattern for URLs this handler should never process.\n\tExclude string\n}\n\nfunc prepareStaticOptions(options []StaticOptions) StaticOptions {\n\tvar opt StaticOptions\n\tif len(options) > 0 {\n\t\topt = options[0]\n\t}\n\n\t// Defaults\n\tif len(opt.IndexFile) == 0 {\n\t\topt.IndexFile = \"index.html\"\n\t}\n\t// Normalize the prefix if provided\n\tif opt.Prefix != \"\" {\n\t\t// Ensure we have a leading '/'\n\t\tif opt.Prefix[0] != '/' {\n\t\t\topt.Prefix = \"/\" + opt.Prefix\n\t\t}\n\t\t// Remove any trailing '/'\n\t\topt.Prefix = strings.TrimRight(opt.Prefix, \"/\")\n\t}\n\treturn opt\n}\n\n// Static returns a middleware handler that serves static files in the given directory.\nfunc Static(directory string, staticOpt ...StaticOptions) Handler {\n\tif !filepath.IsAbs(directory) {\n\t\tdirectory = filepath.Join(Root, directory)\n\t}\n\tdir := http.Dir(directory)\n\topt := prepareStaticOptions(staticOpt)\n\n\treturn func(res http.ResponseWriter, req *http.Request, log *log.Logger) {\n\t\tif req.Method != \"GET\" && req.Method != \"HEAD\" {\n\t\t\treturn\n\t\t}\n\t\tif opt.Exclude != \"\" && strings.HasPrefix(req.URL.Path, opt.Exclude) {\n\t\t\treturn\n\t\t}\n\t\tfile := req.URL.Path\n\t\t// if we have a prefix, filter requests by stripping the prefix\n\t\tif opt.Prefix != \"\" {\n\t\t\tif !strings.HasPrefix(file, opt.Prefix) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfile = file[len(opt.Prefix):]\n\t\t\tif file != \"\" && file[0] != '/' {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tf, err := dir.Open(file)\n\t\tif err != nil {\n\t\t\t// try any fallback before giving up\n\t\t\tif opt.Fallback != \"\" {\n\t\t\t\tfile = opt.Fallback // so that logging stays true\n\t\t\t\tf, err = dir.Open(opt.Fallback)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\t// discard the error?\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tdefer f.Close()\n\n\t\tfi, err := f.Stat()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// try to serve index file\n\t\tif fi.IsDir() {\n\t\t\t// redirect if missing trailing slash\n\t\t\tif !strings.HasSuffix(req.URL.Path, \"/\") {\n\t\t\t\tdest := url.URL{\n\t\t\t\t\tPath:     req.URL.Path + \"/\",\n\t\t\t\t\tRawQuery: req.URL.RawQuery,\n\t\t\t\t\tFragment: req.URL.Fragment,\n\t\t\t\t}\n\t\t\t\thttp.Redirect(res, req, dest.String(), http.StatusFound)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfile = path.Join(file, opt.IndexFile)\n\t\t\tf, err = dir.Open(file)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer f.Close()\n\n\t\t\tfi, err = f.Stat()\n\t\t\tif err != nil || fi.IsDir() {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif !opt.SkipLogging {\n\t\t\tlog.Println(\"[Static] Serving \" + file)\n\t\t}\n\n\t\t// Add an Expires header to the static content\n\t\tif opt.Expires != nil {\n\t\t\tres.Header().Set(\"Expires\", opt.Expires())\n\t\t}\n\n\t\thttp.ServeContent(res, req, file, fi.ModTime(), f)\n\t}\n}\n"
  },
  {
    "path": "static_test.go",
    "content": "package martini\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\n\t\"github.com/codegangsta/inject\"\n)\n\nvar currentRoot, _ = os.Getwd()\n\nfunc Test_Static(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\tresponse.Body = new(bytes.Buffer)\n\n\tm := New()\n\tr := NewRouter()\n\n\tm.Use(Static(currentRoot))\n\tm.Action(r.Handle)\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/martini.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\texpect(t, response.Header().Get(\"Expires\"), \"\")\n\tif response.Body.Len() == 0 {\n\t\tt.Errorf(\"Got empty body for GET request\")\n\t}\n}\n\nfunc Test_Static_Local_Path(t *testing.T) {\n\tRoot = os.TempDir()\n\tresponse := httptest.NewRecorder()\n\tresponse.Body = new(bytes.Buffer)\n\n\tm := New()\n\tr := NewRouter()\n\n\tm.Use(Static(\".\"))\n\tf, err := ioutil.TempFile(Root, \"static_content\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tf.WriteString(\"Expected Content\")\n\tf.Close()\n\tm.Action(r.Handle)\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/\"+path.Base(f.Name()), nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\texpect(t, response.Header().Get(\"Expires\"), \"\")\n\texpect(t, response.Body.String(), \"Expected Content\")\n}\n\nfunc Test_Static_Head(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\tresponse.Body = new(bytes.Buffer)\n\n\tm := New()\n\tr := NewRouter()\n\n\tm.Use(Static(currentRoot))\n\tm.Action(r.Handle)\n\n\treq, err := http.NewRequest(\"HEAD\", \"http://localhost:3000/martini.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\tif response.Body.Len() != 0 {\n\t\tt.Errorf(\"Got non-empty body for HEAD request\")\n\t}\n}\n\nfunc Test_Static_As_Post(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tm := New()\n\tr := NewRouter()\n\n\tm.Use(Static(currentRoot))\n\tm.Action(r.Handle)\n\n\treq, err := http.NewRequest(\"POST\", \"http://localhost:3000/martini.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusNotFound)\n}\n\nfunc Test_Static_BadDir(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tm := Classic()\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/martini.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\trefute(t, response.Code, http.StatusOK)\n}\n\nfunc Test_Static_Options_Logging(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tvar buffer bytes.Buffer\n\tm := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, \"[martini] \", 0)}\n\tm.Map(m.logger)\n\tm.Map(defaultReturnHandler())\n\n\topt := StaticOptions{}\n\tm.Use(Static(currentRoot, opt))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/martini.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\texpect(t, buffer.String(), \"[martini] [Static] Serving /martini.go\\n\")\n\n\t// Now without logging\n\tm.Handlers()\n\tbuffer.Reset()\n\n\t// This should disable logging\n\topt.SkipLogging = true\n\tm.Use(Static(currentRoot, opt))\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\texpect(t, buffer.String(), \"\")\n}\n\nfunc Test_Static_Options_ServeIndex(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tvar buffer bytes.Buffer\n\tm := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, \"[martini] \", 0)}\n\tm.Map(m.logger)\n\tm.Map(defaultReturnHandler())\n\n\topt := StaticOptions{IndexFile: \"martini.go\"} // Define martini.go as index file\n\tm.Use(Static(currentRoot, opt))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\texpect(t, buffer.String(), \"[martini] [Static] Serving /martini.go\\n\")\n}\n\nfunc Test_Static_Options_Prefix(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tvar buffer bytes.Buffer\n\tm := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, \"[martini] \", 0)}\n\tm.Map(m.logger)\n\tm.Map(defaultReturnHandler())\n\n\t// Serve current directory under /public\n\tm.Use(Static(currentRoot, StaticOptions{Prefix: \"/public\"}))\n\n\t// Check file content behaviour\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/public/martini.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\texpect(t, buffer.String(), \"[martini] [Static] Serving /martini.go\\n\")\n}\n\nfunc Test_Static_Options_Expires(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tvar buffer bytes.Buffer\n\tm := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, \"[martini] \", 0)}\n\tm.Map(m.logger)\n\tm.Map(defaultReturnHandler())\n\n\t// Serve current directory under /public\n\tm.Use(Static(currentRoot, StaticOptions{Expires: func() string { return \"46\" }}))\n\n\t// Check file content behaviour\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/martini.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Header().Get(\"Expires\"), \"46\")\n}\n\nfunc Test_Static_Options_Fallback(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tvar buffer bytes.Buffer\n\tm := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, \"[martini] \", 0)}\n\tm.Map(m.logger)\n\tm.Map(defaultReturnHandler())\n\n\t// Serve current directory under /public\n\tm.Use(Static(currentRoot, StaticOptions{Fallback: \"/martini.go\"}))\n\n\t// Check file content behaviour\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/initram.go\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusOK)\n\texpect(t, buffer.String(), \"[martini] [Static] Serving /martini.go\\n\")\n}\n\nfunc Test_Static_Redirect(t *testing.T) {\n\tresponse := httptest.NewRecorder()\n\n\tm := New()\n\tm.Use(Static(currentRoot, StaticOptions{Prefix: \"/public\"}))\n\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:3000/public?param=foo#bar\", nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tm.ServeHTTP(response, req)\n\texpect(t, response.Code, http.StatusFound)\n\texpect(t, response.Header().Get(\"Location\"), \"/public/?param=foo#bar\")\n}\n"
  },
  {
    "path": "translations/README_de_DE.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini ist ein mächtiges Package zur schnellen Entwicklung von modularen Webanwendungen und -services in Golang. \n\n## Ein Projekt starten\n\nNach der Installation von Go und dem Einrichten des [GOPATH](http://golang.org/doc/code.html#GOPATH), erstelle Deine erste `.go`-Datei. Speichere sie unter `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hallo Welt!\"\n  })\n  m.Run()\n}\n~~~\n\nInstalliere anschließend das Martini Package (**Go 1.1** oder höher wird vorausgesetzt):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nStarte den Server:\n~~~\ngo run server.go\n~~~\n\nDer Martini-Webserver ist nun unter `localhost:3000` erreichbar.\n\n## Hilfe\n\nAbonniere den [Emailverteiler](https://groups.google.com/forum/#!forum/martini-go)\n\nSchaue das [Demovideo](http://martini.codegangsta.io/#demo)\n\nStelle Fragen auf Stackoverflow mit dem [Martini-Tag](http://stackoverflow.com/questions/tagged/martini)\n\nGoDoc [Dokumentation](http://godoc.org/github.com/go-martini/martini)\n\n\n## Eigenschaften\n* Sehr einfach nutzbar\n* Nicht-intrusives Design\n* Leicht kombinierbar mit anderen Golang Packages\n* Ausgezeichnetes Path Matching und Routing\n* Modulares Design - einfaches Hinzufügen und Entfernen von Funktionen\n* Eine Vielzahl von guten Handlern/Middlewares nutzbar\n* Großer Funktionsumfang mitgeliefert\n* **Voll kompatibel mit dem [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) Interface.**\n* Standardmäßiges Ausliefern von Dateien (z.B. von AngularJS-Apps im HTML5-Modus)\n\n## Mehr Middleware\nMehr Informationen zur Middleware und Funktionalität findest Du in den Repositories der [martini-contrib](https://github.com/martini-contrib) Gruppe.\n\n## Inhaltsverzeichnis\n* [Classic Martini](#classic-martini)\n  * [Handler](#handler)\n  * [Routing](#routing)\n  * [Services](#services)\n  * [Statische Dateien bereitstellen](#statische-dateien-bereitstellen)\n* [Middleware Handler](#middleware-handler)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\nEinen schnellen Start in ein Projekt ermöglicht [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic), dessen Voreinstellungen sich für die meisten Webanwendungen eignen:\n~~~ go\n  m := martini.Classic()\n  // ... Middleware und Routing hier einfügen\n  m.Run()\n~~~\n\nAufgelistet findest Du einige Aspekte, die [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) automatich berücksichtigt:\n\n  * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Handler\nHandler sind das Herz und die Seele von Martini. Ein Handler ist grundsätzlich jede Art von aufrufbaren Funktionen:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"Hallo Welt\")\n})\n~~~\n\n#### Rückgabewerte\nWenn ein Handler Rückgabewerte beinhaltet, übergibt Martini diese an den aktuellen [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) in Form eines String:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"Hallo Welt\" // HTTP 200 : \"Hallo Welt\"\n})\n~~~\n\nDie Rückgabe eines Statuscode ist optional:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"Ich bin eine Teekanne\" // HTTP 418 : \"Ich bin eine Teekanne\"\n})\n~~~\n\n#### Service Injection\nHandler werden per Reflection aufgerufen. Martini macht Gebrauch von *Dependency Injection*, um Abhängigkeiten in der Argumentliste von Handlern aufzulösen. **Dies macht Martini komplett kompatibel mit Golangs `http.HandlerFunc` Interface.**\n\nFügst Du einem Handler ein Argument hinzu, sucht Martini in seiner Liste von Services und versucht, die Abhängigkeiten via Type Assertion aufzulösen. \n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res und req wurden von Martini injiziert\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nDie Folgenden Services sind Bestandteil von [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n\n  * [*log.Logger](http://godoc.org/log#Logger) - Globaler Logger für Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` von benannten Parametern, welche durch Route Matching gefunden wurden.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Routen Hilfeservice.\n  * [martini.Route](http://godoc.org/github.com/go-martini/martini#Route) - Aktuelle, aktive Route.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request.\n\n### Routing\nEine Route ist in Martini eine HTTP-Methode gepaart mit einem URL-Matching-Pattern. Jede Route kann eine oder mehrere Handler-Methoden übernehmen:\n~~~ go\nm.Get(\"/\", func() {\n  // zeige etwas an\n})\n\nm.Patch(\"/\", func() {\n  // aktualisiere etwas\n})\n\nm.Post(\"/\", func() {\n  // erstelle etwas\n})\n\nm.Put(\"/\", func() {\n  // ersetze etwas\n})\n\nm.Delete(\"/\", func() {\n  // lösche etwas\n})\n\nm.Options(\"/\", func() {\n  // HTTP-Optionen\n})\n\nm.NotFound(func() {\n  // bearbeite 404-Fehler\n})\n~~~\n\nRouten werden in der Reihenfolge, in welcher sie definiert wurden, zugeordnet. Die bei einer Anfrage zuerst zugeordnete Route wird daraufhin aufgerufen.  \n\nRoutenmuster enthalten ggf. benannte Parameter, die über den [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) Service abrufbar sind:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hallo \" + params[\"name\"]\n})\n~~~\n\nRouten können mit Globs versehen werden:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hallo \" + params[\"_1\"]\n})\n~~~\n\nReguläre Ausdrücke sind ebenfalls möglich:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hallo %s\", params[\"name\"])\n})\n~~~\nWeitere Informationen zum Syntax regulärer Ausdrücke findest Du in der [Go Dokumentation](http://golang.org/pkg/regexp/syntax/).\n\nRouten-Handler können auch ineinander verschachtelt werden. Dies ist bei der Authentifizierung und den Berechtigungen nützlich.\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // wird ausgeführt, solange authorize nichts zurückgibt\n})\n~~~\n\nRoutengruppen können durch die Group-Methode hinzugefügt werden.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nSowohl Handlern als auch Middlewares können Gruppen übergeben werden.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Services\nServices sind Objekte, welche der Argumentliste von Handlern beigefügt werden können.\nDu kannst einem Service der *Global* oder *Request* Ebene zuordnen.\n\n#### Global Mapping\nEine Martini-Instanz implementiert das inject.Injector Interface, sodass ein Service leicht zugeordnet werden kann:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // der Service ist allen Handlern unter *MyDatabase verfügbar\n// ...\nm.Run()\n~~~\n\n#### Request-Level Mapping\nDas Zuordnen auf der Request-Ebene kann in einem Handler via  [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) realisiert werden:\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // zugeordnet als *MyCustomLogger\n}\n~~~\n\n#### Werten einem Interface zuordnen\nEiner der mächtigsten Aspekte von Services ist dessen Fähigkeit, einen Service einem Interface zuzuordnen. Möchtest Du den [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) mit einem Decorator (Objekt) und dessen Zusatzfunktionen überschreiben, definiere den Handler wie folgt:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // überschribe ResponseWriter mit dem  ResponseWriter Decorator\n}\n~~~\n\n### Statische Dateien bereitstellen\nEine [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) Instanz übertragt automatisch statische Dateien aus dem \"public\"-Ordner im Stammverzeichnis Deines Servers. Dieses Verhalten lässt sich durch weitere [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) Handler auf andere Verzeichnisse übertragen.\n~~~ go\nm.Use(martini.Static(\"assets\")) // überträgt auch vom \"assets\"-Verzeichnis\n~~~\n\n#### Eine voreingestelle Datei übertragen\nDu kannst die URL zu einer lokalen Datei angeben, sollte die URL einer Anfrage nicht gefunden werden. Durch einen Präfix können bestimmte URLs ignoriert werden.\nDies ist für Server nützlich, welche statische Dateien übertragen und ggf. zusätzliche Handler defineren (z.B. eine REST-API). Ist dies der Fall, so ist das Anlegen eines Handlers in der NotFound-Reihe nützlich.\n\nDas gezeigte Beispiel zeigt die `/index.html` immer an, wenn die angefrage URL keiner lokalen Datei zugeordnet werden kann bzw. wenn sie nicht mit `/api/v` beginnt:\n~~~ go\nstatic := martini.Static(\"assets\", martini.StaticOptions{Fallback: \"/index.html\", Exclude: \"/api/v\"})\nm.NotFound(static, http.NotFound)\n~~~\n\n## Middleware Handler\nMiddleware-Handler befinden sich logisch zwischen einer Anfrage via HTTP und dem Router. Im wesentlichen unterscheiden sie sich nicht von anderen Handlern in Martini.\nDu kannst einen Middleware-Handler dem Stack folgendermaßen anfügen:\n~~~ go\nm.Use(func() {\n  // durchlaufe die Middleware\n})\n~~~\n\nVolle Kontrolle über den Middleware Stack erlangst Du mit der `Handlers`-Funktion.\nSie ersetzt jeden zuvor definierten Handler:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nMiddleware Handler arbeiten gut mit Aspekten wie Logging, Berechtigungen, Authentifizierung, Sessions, Komprimierung durch gzip, Fehlerseiten und anderen Operationen zusammen, die vor oder nach einer Anfrage passieren.\n~~~ go\n// überprüfe einen API-Schlüssel\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) ist eine optionale Funktion, die Middleware-Handler aufrufen können, um sie nach dem Beenden der anderen Handler auszuführen. Dies funktioniert besonders gut, wenn Operationen nach einer HTTP-Anfrage ausgeführt werden müssen.\n~~~ go\n// protokolliere vor und nach einer Anfrage\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"vor einer Anfrage\")\n\n  c.Next()\n\n  log.Println(\"nach einer Anfrage\")\n})\n~~~\n\n## Martini Env\n\nEinige Martini-Handler machen von der globalen `martini.Env` Variable gebrauch, die der Entwicklungsumgebung erweiterte Funktionen bietet, welche die Produktivumgebung nicht enthält. Es wird empfohlen, die `MARTINI_ENV=production` Umgebungsvariable zu setzen, sobald der Martini-Server in den Live-Betrieb übergeht.\n\n## FAQ\n\n### Wo finde ich eine bestimmte Middleware?\n\nStarte die Suche mit einem Blick in die Projekte von [martini-contrib](https://github.com/martini-contrib). Solltest Du nicht fündig werden, kontaktiere ein Mitglied des martini-contrib Teams, um eine neue Repository anzulegen.\n\n * [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler zum Parsen des `Accept-Language` HTTP-Header.\n * [accessflags](https://github.com/martini-contrib/accessflags) - Handler zur Ermöglichung von Zugriffskontrollen.\n * [auth](https://github.com/martini-contrib/auth) - Handler zur Authentifizierung.\n * [binding](https://github.com/martini-contrib/binding) - Handler zum Zuordnen/Validieren einer Anfrage zu einem Struct.\n * [cors](https://github.com/martini-contrib/cors) - Handler für CORS-Support.\n * [csrf](https://github.com/martini-contrib/csrf) - CSRF-Schutz für Applikationen\n * [encoder](https://github.com/martini-contrib/encoder) - Enkodierungsservice zum Datenrendering in den verschiedensten Formaten.\n * [gzip](https://github.com/martini-contrib/gzip) - Handler zum Ermöglichen von gzip-Kompression bei HTTP-Anfragen.\n * [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic Middleware\n * [logstasher](https://github.com/martini-contrib/logstasher) - Middlewaredie Logstashkompatibles JSON ausgibt\n * [method](https://github.com/martini-contrib/method) - Überschreibe eine HTTP-Method via Header oder Formularfelder.\n * [oauth2](https://github.com/martini-contrib/oauth2) - Handler der den Login mit OAuth 2.0 in Martinianwendungen ermöglicht. Google Sign-in, Facebook Connect und Github werden ebenfalls unterstützt.\n * [permissions2](https://github.com/xyproto/permissions2) - Handler zum Mitverfolgen von Benutzern, Loginstatus und Berechtigungen.\n * [render](https://github.com/martini-contrib/render) - Handler, der einen einfachen Service zum Rendern von JSON und HTML-Templates bereitstellt.\n * [secure](https://github.com/martini-contrib/secure) - Implementation von Sicherheitsfunktionen\n * [sessions](https://github.com/martini-contrib/sessions) - Handler mit einem Session service.\n * [sessionauth](https://github.com/martini-contrib/sessionauth) - Handler zur einfachen Aufforderung eines Logins für Routes und zur Bearbeitung von Benutzerlogins in der Sitzung\n * [strict](https://github.com/martini-contrib/strict) - Strikter Modus.\n * [strip](https://github.com/martini-contrib/strip) - URL-Prefix Stripping.\n * [staticbin](https://github.com/martini-contrib/staticbin) - Handler for serving static files from binary data\n * [throttle](https://github.com/martini-contrib/throttle) - Middleware zum Drosseln von HTTP-Anfragen.\n * [vauth](https://github.com/rafecolton/vauth) - Handler zur Webhook-Authentifizierung (momentan nur GitHub und TravisCI)\n * [web](https://github.com/martini-contrib/web) - hoisie web.go's Kontext\n\n### Wie integriere ich in bestehende Systeme?\n\nEine Martiniinstanz implementiert `http.Handler`, sodass Subrouten in bestehenden Servern einfach genutzt werden können. Hier ist eine funktionierende Martinianwendungen für die Google App Engine:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hallo Welt!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### Wie ändere ich den Port/Host?\n\nMartinis `Run` Funktion sucht automatisch nach den PORT und HOST Umgebungsvariablen, um diese zu nutzen. Andernfalls ist localhost:3000 voreingestellt.\nFür mehr Flexibilität über den Port und den Host nutze stattdessen die `martini.RunOnAddr` Funktion.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### Automatisches Aktualisieren?\n\n[Gin](https://github.com/codegangsta/gin) und [Fresh](https://github.com/pilu/fresh) aktualisieren Martini-Apps live.\n\n## Bei Martini mitwirken\n\nMartinis Maxime ist Minimalismus und sauberer Code. Die meisten Beiträge sollten sich in den Repositories der [martini-contrib](https://github.com/martini-contrib) Gruppe wiederfinden. Beinhaltet Dein Beitrag Veränderungen am Kern von Martini, zögere nicht, einen Pull Request zu machen.\n\n## Über das Projekt\n\nInspiriert von [Express](https://github.com/visionmedia/express) und [Sinatra](https://github.com/sinatra/sinatra)\n\nMartini wird leidenschaftlich von niemand Geringerem als dem [Code Gangsta](http://codegangsta.io/) entwickelt\n"
  },
  {
    "path": "translations/README_es_ES.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini es un poderoso paquete para escribir rápidamente aplicaciones/servicios web modulares en Golang.\n\n\n## Vamos a iniciar\n\nDespués de instalar Go y de configurar su [GOPATH](http://golang.org/doc/code.html#GOPATH), cree su primer archivo `.go`. Vamos a llamar a este `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hola Mundo!\"\n  })\n  m.Run()\n}\n~~~\n\nLuego instale el paquete Martini (Es necesario **go 1.1** o superior):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nDespués corra su servidor:\n~~~\ngo run server.go\n~~~\n\nAhora tendrá un webserver Martini corriendo en el puerto `localhost:3000`.\n\n## Obtenga ayuda\n\nSuscribase a la [Lista de email](https://groups.google.com/forum/#!forum/martini-go)\n\nObserve el [Video demostrativo](http://martini.codegangsta.io/#demo)\n\nUse la etiqueta [martini](http://stackoverflow.com/questions/tagged/martini) para preguntas en Stackoverflow\n\nDocumentación [GoDoc](http://godoc.org/github.com/go-martini/martini)\n\n\n## Caracteríticas\n* Extremadamente simple de usar.\n* Diseño no intrusivo.\n* Buena integración con otros paquetes Golang.\n* Enrutamiento impresionante.\n* Diseño modular - Fácil de añadir y remover funcionalidades.\n* Muy buen uso de handlers/middlewares.\n* Grandes características innovadoras.\n* **Compatibilidad total con la interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).**\n* Sirviendo documentos por defecto (e.g. para servir aplicaciones AngularJS en modo HTML5).\n\n## Más Middlewares\nPara más middlewares y funcionalidades, revisar los repositorios en [martini-contrib](https://github.com/martini-contrib).\n\n## Lista de contenidos\n* [Classic Martini](#classic-martini)\n  * [Handlers](#handlers)\n  * [Routing](#routing)\n  * [Services](#services)\n  * [Serving Static Files](#serving-static-files)\n* [Middleware Handlers](#middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\nPara iniciar rápidamente, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) prevee algunas herramientas que funcionan bien para la mayoría de aplicaciones web:\n~~~ go\n  m := martini.Classic()\n  // middlewares y rutas aquí\n  m.Run()\n~~~\n\nAlgunas funcionalidades que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) ofrece automáticamente son:\n  * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Handlers\nHandlers son el corazón y el alma de Martini. Un handler es básicamente cualquier tipo de función que puede ser llamada.\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hola mundo\")\n})\n~~~\n\n#### Retorno de Valores\nSi un handler retorna cualquier cosa, Martini escribirá el valor retornado como una cadena [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter):\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hola mundo\" // HTTP 200 : \"hola mundo\"\n})\n~~~\n\nUsted también puede retornar un código de estado:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"soy una tetera\" // HTTP 418 : \"soy una tetera\"\n})\n~~~\n\n#### Inyección de Servicios\nHandlers son invocados vía reflexión. Martini utiliza *Inyección de Dependencia* para resolver dependencias en la lista de argumentos Handlers. **Esto hace que Martini sea completamente compatible con  la interface `http.HandlerFunc` de golang.**\n\nSi agrega un argumento a su Handler, Martini buscará en su lista de servicios e intentará resolver su dependencia vía su tipo de aserción:\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res y req son inyectados por Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nLos siguientes servicios son incluidos con [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nombres de los parámetros buscados por la ruta.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Servicio de ayuda para las Rutas.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escribe la interfaz.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request.\n\n### Rutas\nEn Martini, una ruta es un método HTTP emparejado con un patrón URL. Cada ruta puede tener uno o más métodos handler:\n~~~ go\nm.Get(\"/\", func() {\n  // mostrar algo\n})\n\nm.Patch(\"/\", func() {\n  // actualizar algo\n})\n\nm.Post(\"/\", func() {\n  // crear algo\n})\n\nm.Put(\"/\", func() {\n  // reemplazar algo\n})\n\nm.Delete(\"/\", func() {\n  // destruir algo\n})\n\nm.Options(\"/\", func() {\n  // opciones HTTP\n})\n\nm.NotFound(func() {\n  // manipula 404\n})\n~~~\n\nLas rutas son emparejadas en el orden en que son definidas. La primera ruta que coincide con la solicitud es invocada.\n\nLos patrones de rutas puede incluir nombres como parámetros accesibles vía el servicio [martini.Params](http://godoc.org/github.com/go-martini/martini#Params):\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nLas rutas se pueden combinar con globs:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\nLas expresiones regulares pueden ser usadas también:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nObserve la [documentación](http://golang.org/pkg/regexp/syntax/) para mayor información sobre la sintaxis de expresiones regulares.\n\n\nHandlers de ruta pueden ser apilados encima de otros, lo cual es útil para cosas como autenticación y autorización:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // será ejecutado cuando autorice escribir una respuesta\n})\n~~~\n\nGrupos de rutas puede ser añadidas usando el método Group.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nAl igual que usted puede pasar middlewares a un handler, puede pasar middlewares a grupos.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Servicios\nLo servicios son objetos que están disponibles para ser inyectados en una lista de argumentos Handler. Usted puede mapear un servicio a nivel *Global* o *Request*.\n\n#### Mapeo Global\nUna instancia de Martini implementa la interface `inject.Injector`, asi que el mapeo de un servicio es sencillo:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // el servicio estará disponible para todos los handlers como *MyDatabase.\n// ...\nm.Run()\n~~~\n\n#### Mapeo por Request\nEl mapeo a nivel de request puede ser hecho en un handler via  [martini.Context](http://godoc.org/github.com/go-martini/martini#Context):\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // mapeado como *MyCustomLogger\n}\n~~~\n\n#### Valores de Mapeo para Interfaces\nUna de las partes más poderosas sobre servicios es la capacidad de mapear un servicio para una interface. Por ejemplo, si desea sobreescribir [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) con un objeto que envuelva y realice operaciones extra, puede escribir el siguiente handler:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // sobreescribir ResponseWriter con nuestro ResponseWriter\n}\n~~~\n\n### Sirviendo Archivos Estáticos\nUna instancia de [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) sirve automáticamente archivos estáticos del directorio \"public\" en la raíz de su servidor.\nUsted puede servir más directorios, añadiendo más [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers.\n~~~ go\nm.Use(martini.Static(\"assets\")) // sirviendo los archivos del directorio \"assets\"\n~~~\n\n## Middleware Handlers\nLos Middleware Handlers se sitúan entre una solicitud HTTP y un router. En esencia, ellos no son diferentes de cualquier otro Handler en Martini. Usted puede añadir un handler de middleware para la pila de la siguiente forma:\n~~~ go\nm.Use(func() {\n  // Hacer algo con middleware\n})\n~~~\n\nPuede tener el control total sobre la pila del Middleware con la función `Handlers`. Esto reemplazará a cualquier handler que haya sido establecido previamente:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nMiddleware Handlers trabaja realmente bien como logging, autorización, autenticación, sesión, gzipping, páginas de errores y una serie de otras operaciones que deben suceder antes o después de una solicitud http:\n~~~ go\n// Valida una llave de api\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) es una función opcional que Middleware Handlers puede llamar para entregar hasta después de que una solicitud http haya sido ejecutada. Esto trabaja muy bien para calquier operación que debe suceder luego de una solicitud http:\n~~~ go\n// log antes y después de una solicitud\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"antes de una solicitud\")\n\n  c.Next()\n\n  log.Println(\"luego de una solicitud\")\n})\n~~~\n\n## Martini Env\n\nMartini handlers hace uso de `martini.Env`, una variable global para proveer funcionalidad especial en ambientes de desarrollo y ambientes de producción. Es recomendado que una variable `MARTINI_ENV=production` sea definida cuando se despliegue en un ambiente de producción.\n\n## FAQ\n\n### ¿Dónde puedo encontrar una middleware X?\n\nInicie su búsqueda en los proyectos [martini-contrib](https://github.com/martini-contrib). Si no esta allí, no dude en contactar a algún miembro del equipo martini-contrib para adicionar un nuevo repositorio para la organización.\n\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para analizar el `Accept-Language` HTTP header.\n* [accessflags](https://github.com/martini-contrib/accessflags) - Handler para habilitar Access Control.\n* [auth](https://github.com/martini-contrib/auth) - Handlers para autenticación.\n* [binding](https://github.com/martini-contrib/binding) - Handler para mapeo/validación de un request en una estructura.\n* [cors](https://github.com/martini-contrib/cors) - Handler habilita soporte para CORS.\n* [csrf](https://github.com/martini-contrib/csrf) - CSRF protección para aplicaciones.\n* [encoder](https://github.com/martini-contrib/encoder) - Servicio de codificador para renderizado de datos en varios formatos y gestión de contenidos.\n* [gzip](https://github.com/martini-contrib/gzip) - Handler para agregar compresión gzip para los requests.\n* [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic middleware\n* [logstasher](https://github.com/martini-contrib/logstasher) - Middleware que imprime logstash-compatiable JSON.\n* [method](https://github.com/martini-contrib/method) - HTTP method overriding via cabecera o campos de formulario.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Handler que provee OAuth 2.0 login para Martini apps. Google Sign-in, Facebook Connect y Github login son soportados.\n* [permissions2](https://github.com/xyproto/permissions2) - Handler para hacer seguimiento de usuarios, estados de login y permisos.\n* [render](https://github.com/martini-contrib/render) - Handler que provee un servicio para fácil renderizado de plantillas HTML y JSON.\n* [secure](https://github.com/martini-contrib/secure) - Implementa un par de rápidos triunfos de seguridad.\n* [sessions](https://github.com/martini-contrib/sessions) - Handler que provee un servicio de sesiones.\n* [sessionauth](https://github.com/martini-contrib/sessionauth) - Handler que provee una simple forma de hacer routes, requerir un login y manejar login de usuarios en la sesión.\n* [strict](https://github.com/martini-contrib/strict) - Modo estricto (Strict Mode)\n* [strip](https://github.com/martini-contrib/strip) - Prefijo de extracción de URL.\n* [staticbin](https://github.com/martini-contrib/staticbin) - Handler para servir archivos estáticos desde datos binarios.\n* [throttle](https://github.com/martini-contrib/throttle) - Request rate throttling middleware.\n* [vauth](https://github.com/rafecolton/vauth) - Handlers para expender autenticación con webhooks (actualmente GitHub y TravisCI)\n* [web](https://github.com/martini-contrib/web) - Contexto hoisie web.go's\n\n### ¿Cómo se integra con los servidores existentes?\n\nUna instancia de Martini implementa `http.Handler`, de modo que puede ser fácilmente utilizado para servir sub-rutas y directorios en servidores Go existentes. Por ejemplo, este es un aplicativo Martini trabajando para Google App Engine:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hola Mundo!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### ¿Cómo cambiar el puerto/host?\n\nLa función `Run` de Martini observa las variables de entorno `PORT` y `HOST` para utilizarlas. De lo contrário, Martini asume por defecto `localhost:3000`. Para tener mayor flexibilidad sobre el puerto y host, use la función `martini.RunOnAddr`.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### ¿Servidor con autoreload?\n\n[gin](https://github.com/codegangsta/gin) y [fresh](https://github.com/pilu/fresh) son ambas aplicaciones para autorecarga de Martini.\n\n## Contribuyendo\nMartini se desea mantener pequeño y limpio. La mayoría de contribuciones deben realizarse en el repositorio [martini-contrib](https://github.com/martini-contrib). Si desea hacer una contribución al core de Martini es libre de realizar un Pull Request.\n\n## Sobre\n\nInspirado por [Express](https://github.com/visionmedia/express) y [Sinatra](https://github.com/sinatra/sinatra)\n\nMartini está diseñado obsesivamente por nada menos que [Code Gangsta](http://codegangsta.io/)\n\n"
  },
  {
    "path": "translations/README_fr_FR.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini est une puissante bibliothèque pour développer rapidement des applications et services web en Golang.\n\n\n## Pour commencer\n\nAprès avoir installé Go et configuré le chemin d'accès pour [GOPATH](http://golang.org/doc/code.html#GOPATH), créez votre premier fichier '.go'. Nous l'appellerons 'server.go'.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nInstallez ensuite le paquet Martini (**go 1.1** ou supérieur est requis) :\n\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nLa commande suivante vous permettra de lancer votre serveur :\n~~~\ngo run server.go\n~~~\n\nVous avez à présent un serveur web Martini à l'écoute sur l'adresse et le port suivants : `localhost:3000`.\n\n## Besoin d'aide\n- Souscrivez à la [Liste d'emails](https://groups.google.com/forum/#!forum/martini-go)\n- Regardez les vidéos [Demo en vidéo](http://martini.codegangsta.io/#demo)\n- Posez vos questions sur StackOverflow.com en utilisant le tag [martini](http://stackoverflow.com/questions/tagged/martini)\n- La documentation GoDoc [documentation](http://godoc.org/github.com/go-martini/martini)\n\n\n## Caractéristiques\n* Simple d'utilisation\n* Design non-intrusif\n* Compatible avec les autres paquets Golang\n* Gestionnaire d'URL et routeur disponibles\n* Modulable, permettant l'ajout et le retrait de fonctionnalités\n* Un grand nombre de handlers/middlewares disponibles\n* Prêt pour une utilisation immédiate\n* **Entièrement compatible avec l'interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).**\n\n## Plus de Middleware\nPour plus de middlewares et de fonctionnalités, consultez le dépôt [martini-contrib](https://github.com/martini-contrib).\n\n## Table des matières\n* [Classic Martini](#classic-martini)\n  * [Handlers](#handlers)\n  * [Routage](#routing)\n  * [Services](#services)\n  * [Serveur de fichiers statiques](#serving-static-files)\n* [Middleware Handlers](#middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\nPour vous faire gagner un temps précieux, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) est configuré avec des paramètres qui devraient couvrir les besoins de la plupart des applications web :\n\n~~~ go\n  m := martini.Classic()\n  // ... les middlewares and le routage sont insérés ici...\n  m.Run()\n~~~\n\nVoici quelques handlers/middlewares que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) intègre par défault :\n  * Logging des requêtes/réponses - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Récupération sur erreur - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Serveur de fichiers statiques - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routage - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Handlers\nLes Handlers sont le coeur et l'âme de Martini. N'importe quelle fonction peut être utilisée comme un handler.\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Valeurs retournées\nSi un handler retourne une valeur, Martini écrira le résultat dans l'instance [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) courante sous forme de ```string```:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\nVous pouvez aussi optionnellement renvoyer un code de statut HTTP :\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### Injection de services\nLes handlers sont appelés via réflexion. Martini utilise \"l'injection par dépendance\" pour résoudre les dépendances des handlers dans la liste d'arguments. **Cela permet à Martini d'être parfaitement compatible avec l'interface golang ```http.HandlerFunc```.**\n\nSi vous ajoutez un argument à votre Handler, Martini parcourera la liste des services et essayera de déterminer ses dépendances selon son type :\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\nLes services suivants sont inclus avec [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [log.Logger](http://godoc.org/log#Logger) - Global logger for Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - Contexte d'une requête HTTP.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` contenant les paramètres retrouvés par correspondance des routes.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Service d'aide au routage.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - Interface d'écriture de réponses HTTP.\n  * [*http.Request](http://godoc.org/net/http/#Request) - Requête HTTP.\n\n### Routeur\nDans Martini, un chemin est une méthode HTTP liée à un modèle d'adresse URL.\nChaque chemin peut avoir un seul ou plusieurs méthodes *handler* :\n~~~ go\nm.Get(\"/\", func() {\n  // show something\n})\n\nm.Patch(\"/\", func() {\n  // update something\n})\n\nm.Post(\"/\", func() {\n  // create something\n})\n\nm.Put(\"/\", func() {\n  // replace something\n})\n\nm.Delete(\"/\", func() {\n  // destroy something\n})\n\nm.Options(\"/\", func() {\n  // http options\n})\n\nm.NotFound(func() {\n  // handle 404\n})\n~~~\nLes chemins seront traités dans l'ordre dans lequel ils auront été définis. Le *handler* du premier chemin trouvé qui correspondra à la requête sera invoqué.\n\n\nLes chemins peuvent inclure des paramètres nommés, accessibles avec le service [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) :\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nLes chemins peuvent correspondre à des globs :\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\nLes expressions régulières peuvent aussi être utilisées :\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nJetez un oeil à la documentation [Go documentation](http://golang.org/pkg/regexp/syntax/) pour plus d'informations sur la syntaxe des expressions régulières.\n\nLes handlers d'un chemins peuvent être superposés, ce qui s'avère particulièrement pratique pour des tâches comme la gestion de l'authentification et des autorisations :\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // this will execute as long as authorize doesn't write a response\n})\n~~~\n\nUn groupe de chemins peut aussi être ajouté en utilisant la méthode ```Group``` :\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nComme vous pouvez passer des middlewares à un handler, vous pouvez également passer des middlewares à des groupes :\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Services\nLes services sont des objets injectés dans la liste d'arguments d'un handler. Un service peut être défini pour une *requête*, ou de manière *globale*.\n\n\n#### Global Mapping\nLes instances Martini implémentent l'interace inject.Injector, ce qui facilite grandement le mapping de services :\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // the service will be available to all handlers as *MyDatabase\n// ...\nm.Run()\n~~~\n\n#### Requête-Level Mapping\nPour une déclaration au niveau d'une requête, il suffit d'utiliser un handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) :\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // mapped as *MyCustomLogger\n}\n~~~\n\n#### Mapping de valeurs à des interfaces\nL'un des aspects les plus intéressants des services réside dans le fait qu'ils peuvent être liés à des interfaces. Par exemple, pour surcharger [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) avec un objet qui l'enveloppe et étend ses fonctionnalités, vous pouvez utiliser le handler suivant :\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter\n}\n~~~\n\n### Serveur de fichiers statiques\nUne instance [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) est déjà capable de servir les fichiers statiques qu'elle trouvera dans le dossier *public* à la racine de votre serveur.\nVous pouvez indiquer d'autres dossiers sources à l'aide du handler  [martini.Static](http://godoc.org/github.com/go-martini/martini#Static).\n~~~ go\nm.Use(martini.Static(\"assets\")) // serve from the \"assets\" directory as well\n~~~\n\n## Les middleware Handlers\nLes *middleware handlers* sont placés entre la requête HTTP entrante et le routeur. Ils ne sont aucunement différents des autres handlers présents dans Martini. Vous pouvez ajouter un middleware handler comme ceci :\n~~~ go\nm.Use(func() {\n  // do some middleware stuff\n})\n~~~\nVous avez un contrôle total sur la structure middleware avec la fonction ```Handlers```. Son exécution écrasera tous les handlers configurés précédemment :\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\nMiddleware Handlers est très pratique pour automatiser des fonctions comme le logging, l'autorisation, l'authentification, sessions, gzipping, pages d'erreur, et toutes les opérations qui se font avant ou après chaque requête HTTP :\n~~~ go\n// validate an api key\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next() (Suivant)\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) est une fonction optionnelle que les Middleware Handlers peuvent appeler pour patienter jusqu'à ce que tous les autres handlers aient été exécutés. Cela fonctionne très bien pour toutes opérations qui interviennent après une requête HTTP :\n~~~ go\n// log before and after a request\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"avant la requête\")\n\n  c.Next()\n\n  log.Println(\"après la requête\")\n})\n~~~\n\n## Martini Env\nPlusieurs Martini handlers utilisent 'martini.Env' comme variable globale pour fournir des fonctionnalités particulières qui diffèrent entre l'environnement de développement et l'environnement de production. Il est recommandé que la variable 'MARTINI_ENV=production' soit définie pour déployer un serveur Martini en environnement de production.\n\n## FAQ (Foire aux questions)\n\n### Où puis-je trouver des middleware ?\nCommencer par regarder dans le [martini-contrib](https://github.com/martini-contrib) projet. S'il n'y est pas, n'hésitez pas à contacter un membre de l'équipe martini-contrib pour ajouter un nouveau dépôt à l'organisation.\n\n* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication.\n* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure.\n* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests\n* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates.\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header.\n* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service.\n* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping.\n* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields.\n* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins.\n* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation.\n* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported.\n* [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI)\n\n### Comment puis-je m'intègrer avec des serveurs existants ?\nUne instance Martini implémente ```http.Handler```. Elle peut donc utilisée pour alimenter des sous-arbres sur des serveurs Go existants. Voici l'exemple d'une application Martini pour Google App Engine :\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### Comment changer le port/adresse ?\n\nLa fonction ```Run``` de Martini utilise le port et l'adresse spécifiés dans les variables d'environnement. Si elles ne peuvent y être trouvées, Martini utilisera *localhost:3000* par default.\nPour avoir plus de flexibilité sur le port et l'adresse, utilisez la fonction `martini.RunOnAddr` à la place.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### Rechargement du code en direct ?\n\n[gin](https://github.com/codegangsta/gin) et [fresh](https://github.com/pilu/fresh) sont tous les capables de recharger le code des applications martini chaque fois qu'il est modifié.\n\n## Contribuer\nMartini est destiné à rester restreint et épuré. Toutes les contributions doivent finir dans un dépot dans l'organisation [martini-contrib](https://github.com/martini-contrib). Si vous avez une contribution pour le noyau de Martini, n'hésitez pas à envoyer une Pull Request.\n\n## A propos de Martini\n\nInspiré par [express](https://github.com/visionmedia/express) et [Sinatra](https://github.com/sinatra/sinatra), Martini est l'oeuvre de nul d'autre que [Code Gangsta](http://codegangsta.io/), votre serviteur.\n"
  },
  {
    "path": "translations/README_ja_JP.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartiniはGolangによる、モジュール形式のウェブアプリケーション/サービスを作成するパワフルなパッケージです。\n\n## はじめに\n\nGoをインストールし、[GOPATH](http://golang.org/doc/code.html#GOPATH)を設定した後、Martiniを始める最初の`.go`ファイルを作りましょう。これを`server.go`とします。\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nそのあとで、Martini パッケージをインストールします。(**go 1.1**か、それ以上のバーションが必要です。)\n\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nインストールが完了したら、サーバを起動しましょう。\n~~~\ngo run server.go\n~~~\n\nそうすれば`localhost:3000`でMartiniのサーバが起動します。\n\n## 分からないことがあったら？\n\n[メーリングリスト](https://groups.google.com/forum/#!forum/martini-go)に入る\n\n[デモビデオ](http://martini.codegangsta.io/#demo)をみる\n\nStackoverflowで[martini tag](http://stackoverflow.com/questions/tagged/martini)を使い質問する\n\nGoDoc [documentation](http://godoc.org/github.com/go-martini/martini)\n\n\n## 特徴\n* 非常にシンプルに使用できる\n* 押し付けがましくないデザイン\n* 他のGolangパッケージとの協調性\n* 素晴らしいパスマッチングとルーティング\n* モジュラーデザイン - 機能性の付け外しが簡単\n* たくさんの良いハンドラ/ミドルウェア\n* 優れた 'すぐに使える' 機能たち\n* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)との完全な互換性**\n\n## もっとミドルウェアについて知るには？\nさらに多くのミドルウェアとその機能について知りたいときは、[martini-contrib](https://github.com/martini-contrib) オーガナイゼーションにあるリポジトリを確認してください。\n\n## 目次(Table of Contents)\n* [Classic Martini](#classic-martini)\n  * [ハンドラ](#handlers)\n  * [ルーティング](#routing)\n  * [サービス](#services)\n  * [静的ファイル配信](#serving-static-files)\n* [ミドルウェアハンドラ](#middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\n立ち上げ、すぐ実行できるように、[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) はほとんどのウェブアプリケーションで機能する、標準的な機能を提供します。\n~~~ go\n  m := martini.Classic()\n  // ... middleware and routing goes here\n  m.Run()\n~~~\n\n下記が[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)が自動的に読み込む機能の一覧です。\n  * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### ハンドラ\nハンドラはMartiniのコアであり、存在意義でもあります。ハンドラには基本的に、呼び出し可能な全ての関数が適応できます。\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Return Values\nもしハンドラが何かを返す場合、Martiniはその結果を現在の[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)にstringとして書き込みます。\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\n任意でステータスコードを返すこともできます。\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### Service Injection\nハンドラはリフレクションによって実行されます。Martiniはハンドラの引数内の依存関係を**依存性の注入(Dependency Injection)**を使って解決しています。**これによって、Martiniはgolangの`http.HandlerFunc`と完全な互換性を備えています。**\n\nハンドラに引数を追加すると、Martiniは内部のサービスを検索し、依存性をtype assertionによって解決しようと試みます。\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)にはこれらのサービスが内包されています:\n  * [*log.Logger](http://godoc.org/log#Logger) - Martiniのためのグローバルなlogger.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string`型の、ルートマッチングによって検出されたパラメータ\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request.\n\n### ルーティング\nMartiniでは、ルーティングはHTTPメソッドとURL-matching patternによって対になっており、それぞれが一つ以上のハンドラメソッドを持つことができます。\n~~~ go\nm.Get(\"/\", func() {\n  // show something\n})\n\nm.Patch(\"/\", func() {\n  // update something\n})\n\nm.Post(\"/\", func() {\n  // create something\n})\n\nm.Put(\"/\", func() {\n  // replace something\n})\n\nm.Delete(\"/\", func() {\n  // destroy something\n})\n\nm.Options(\"/\", func() {\n  // http options\n})\n\nm.NotFound(func() {\n  // handle 404\n})\n~~~\n\nルーティングはそれらの定義された順番に検索され、最初にマッチしたルーティングが呼ばれます。\n\n名前付きパラメータを定義することもできます。これらのパラメータは[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)サービスを通じてアクセスすることができます:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nワイルドカードを使用することができます:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\n正規表現も、このように使うことができます:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\n\nもっと正規表現の構文をしりたい場合は、[Go documentation](http://golang.org/pkg/regexp/syntax/) を見てください。\n\n\nハンドラは互いの上に積み重ねてることができます。これは、認証や承認処理の際に便利です:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // this will execute as long as authorize doesn't write a response\n})\n~~~\n\nルーティンググループも、Groupメソッドを使用することで追加できます。\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nハンドラにミドルウェアを渡せるのと同じように、グループにもミドルウェアを渡すことができます:\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### サービス\nサービスはハンドラの引数として注入されることで利用可能になるオブジェクトです。これらは*グローバル*、または*リクエスト*のレベルでマッピングすることができます。\n\n#### Global Mapping\nMartiniのインスタンスはinject.Injectorのインターフェースを実装しています。なので、サービスをマッピングすることは簡単です:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // the service will be available to all handlers as *MyDatabase\n// ...\nm.Run()\n~~~\n\n#### Request-Level Mapping\nリクエストレベルでのマッピングは[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)を使い、ハンドラ内で行うことができます:\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // mapped as *MyCustomLogger\n}\n~~~\n\n#### Mapping values to Interfaces\nサービスの最も強力なことの一つは、インターフェースにサービスをマッピングできる機能です。例えば、[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)を機能を追加して上書きしたい場合、このようにハンドラを書くことができます:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter\n}\n~~~\n\n### 静的ファイル配信\n\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) インスタンスは、自動的にルート直下の \"public\" ディレクトリ以下の静的ファイルを配信します。[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)を追加することで、もっと多くのディレクトリを配信することもできます:\n~~~ go\nm.Use(martini.Static(\"assets\")) // serve from the \"assets\" directory as well\n~~~\n\n## ミドルウェア　ハンドラ\nミドルウェア ハンドラは次に来るhttpリクエストとルーターの間に位置します。本質的には、その他のハンドラとの違いはありません。ミドルウェア　ハンドラの追加はこのように行います:\n~~~ go\nm.Use(func() {\n  // do some middleware stuff\n})\n~~~\n\n`Handlers`関数を使えば、ミドルウェアスタックを完全に制御できます。これは以前に設定されている全てのハンドラを置き換えます:\n\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nミドルウェア ハンドラはロギング、認証、承認プロセス、セッション、gzipping、エラーページの表示、その他httpリクエストの前後で怒らなければならないような場合に素晴らしく効果を発揮します。\n~~~ go\n// validate an api key\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) は他のハンドラが実行されたことを取得するために使用する機能です。これはhttpリクエストのあとに実行したい任意の関数があるときに素晴らしく機能します:\n~~~ go\n// log before and after a request\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"before a request\")\n\n  c.Next()\n\n  log.Println(\"after a request\")\n})\n~~~\n\n## Martini Env\n\nいくつかのMartiniのハンドラはdevelopment環境とproduction環境で別々の動作を提供するために`martini.Env`グローバル変数を使用しています。Martiniサーバを本番環境にデプロイする際には、`MARTINI_ENV=production`環境変数をセットすることをおすすめします。\n\n## FAQ\n\n### Middlewareを見つけるには?\n\n[martini-contrib](https://github.com/martini-contrib)プロジェクトをみることから始めてください。もし望みのものがなければ、新しいリポジトリをオーガナイゼーションに追加するために、martini-contribチームのメンバーにコンタクトを取ってみてください。\n\n* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication.\n* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure.\n* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests\n* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates.\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header.\n* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service.\n* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping.\n* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields.\n* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins.\n* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation.\n* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported.\n\n### 既存のサーバに組み込むには?\n\nMartiniのインスタンスは`http.Handler`を実装しているので、既存のGoサーバ上でサブツリーを提供するのは簡単です。例えばこれは、Google App Engine上で動くMartiniアプリです:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### どうやってポート/ホストをかえるの?\n\nMartiniの`Run`関数はPORTとHOSTという環境変数を探し、その値を使用します。見つからない場合はlocalhost:3000がデフォルトで使用されます。もっと柔軟性をもとめるなら、`martini.RunOnAddr`関数が役に立ちます:\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### Live code reload?\n\n[gin](https://github.com/codegangsta/gin) と [fresh](https://github.com/pilu/fresh) 両方がMartiniアプリケーションを自動リロードできます。\n\n## Contributing\nMartini本体は小さく、クリーンであるべきであり、ほとんどのコントリビューションは[martini-contrib](https://github.com/martini-contrib) オーガナイゼーション内で完結すべきですが、もしMartiniのコアにコントリビュートすることがあるなら、自由に行ってください。\n\n## About\n\nInspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra)\n\nMartini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/)\n"
  },
  {
    "path": "translations/README_ko_kr.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\n마티니(Martini)는 강력하고 손쉬운 웹애플리케이션 / 웹서비스개발을 위한 Golang 패키지입니다.\n\n## 시작하기\n\nGo 인스톨 및 [GOPATH](http://golang.org/doc/code.html#GOPATH) 환경변수 설정 이후에, `.go` 파일 하나를 만들어 보죠..흠... 일단 `server.go`라고 부르겠습니다.\n~~~go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello, 세계!\"\n  })\n  m.Run()\n}\n~~~\n\n마티니 패키지를 인스톨 합니다. (**go 1.1** 혹은 그 이상 버젼 필요):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\n이제 서버를 돌려 봅시다:\n~~~\ngo run server.go\n~~~\n\n마티니 웹서버가 `localhost:3000`에서 돌아가고 있는 것을 확인하실 수 있을 겁니다.\n\n## 도움이 필요하다면?\n\n[메일링 리스트](https://groups.google.com/forum/#!forum/martini-go)에 가입해 주세요\n\n[데모 비디오](http://martini.codegangsta.io/#demo)도 있어요.\n\n혹은 Stackoverflow에 [마티니 태크](http://stackoverflow.com/questions/tagged/martini)를 이용해서 물어봐 주세요\n\nGoDoc [문서(documentation)](http://godoc.org/github.com/go-martini/martini)\n\n문제는 전부다 영어로 되어 있다는 건데요 -_-;;;\n나는 한글 아니면 보기 싫다! 하는 분들은 아래 링크를 참조하세요\n- [golang-korea](https://code.google.com/p/golang-korea/)\n- 혹은 ([RexK](http://github.com/RexK))의 이메일로 연락주세요.\n\n## 주요기능\n* 사용하기 엄청 쉽습니다.\n* 비간섭(Non-intrusive) 디자인\n* 다른 Golang 패키지들과 잘 어울립니다.\n* 끝내주는 경로 매칭과 라우팅.\n* 모듈형 디자인 - 기능추가가 쉽고, 코드 꺼내오기도 쉬움.\n* 유용한 핸들러와 미들웨어가 많음.\n* 훌륭한 패키지화(out of the box) 기능들\n* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 인터페이스와 호환율 100%**\n\n## 미들웨어(Middleware)\n미들웨어들과 추가기능들은 [martini-contrib](https://github.com/martini-contrib)에서 확인해 주세요.\n\n## 목차\n* [Classic Martini](#classic-martini)\n  * [핸들러](#핸들러handlers)\n  * [라우팅](#라우팅routing)\n  * [서비스](#서비스services)\n  * [정적파일 서빙](#정적파일-서빙serving-static-files)\n* [미들웨어 핸들러](#미들웨어-핸들러middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\n마티니를 쉽고 빠르게 이용하시려면, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)를 이용해 보세요. 보통 웹애플리케이션에서 사용하는 설정들이 이미 포함되어 있습니다.\n~~~ go\n  m := martini.Classic()\n  // ... 미들웨어와 라우팅 설정은 이곳에 오면 작성하면 됩니다.\n  m.Run()\n~~~\n\n아래는 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)에 자동으로 제공되는 기본 기능들 입니다.\n\n  * Request/Response 로그 기능 - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * 패닉 리커버리 (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * 정적 파일 서빙 - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * 라우팅(Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### 핸들러(Handlers)\n\n핸들러(Handlers)는 마티니의 핵심입니다. 핸들러는 기본적으로 실행 가능한 모든 형태의 함수들입니다.\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello 세계\")\n})\n~~~\n\n#### 반환 값 (Return Values)\n핸들러가 반환을 하는 함수라면, 마티니는 반환 값을 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)에 스트링으로 입력 할 것입니다.\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello 세계\" // HTTP 200 : \"hello 세계\"\n})\n~~~\n\n원하신다면, 선택적으로 상태코드도 함께 반환 할 수 있습니다.\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"난 주전자야!\" // HTTP 418 : \"난 주전자야!\"\n})\n~~~\n\n#### 서비스 주입(Service Injection)\n핸들러들은 리플렉션을 통해 호출됩니다. 마티니는 *의존성 주입*을 이용해서 핸들러의 인수들을 주입합니다. **이것이 마티니를 `http.HandlerFunc` 인터페이스와 100% 호환할 수 있게 해줍니다.**\n\n핸들러의 인수를 입력했다면, 마티니가 서비스 목록들을 살펴본 후 타입확인(type assertion)을 통해 의존성문제 해결을 시도 할 것입니다.\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res와 req는 마티니에 의해 주입되었다.\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\n아래 서비스들은 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):에 포함되어 있습니다.\n  * [*log.Logger](http://godoc.org/log#Logger) - 마티니의 글로벌(전역) 로그.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http 요청 컨텍스트.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - 루트 매칭으로 찾은 인자를 `map[string]string`으로 변형.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - 루트 도우미 서비스.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer 인터페이스.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http 리퀘스트.\n\n### 라우팅(Routing)\n마티니에서 루트는 HTTP 메소드와 URL매칭 패턴의 페어입니다.\n각 루트는 하나 혹은 그 이상의 핸들러 메소드를 가질 수 있습니다.\n~~~ go\nm.Get(\"/\", func() {\n  // 보여줘 봐\n})\n\nm.Patch(\"/\", func() {\n  // 업데이트 좀 해\n})\n\nm.Post(\"/\", func() {\n  // 만들어봐\n})\n\nm.Put(\"/\", func() {\n  // 변경해봐\n})\n\nm.Delete(\"/\", func() {\n  // 없애버려!\n})\n\nm.Options(\"/\", func() {\n  // http 옵션 메소드\n})\n\nm.NotFound(func() {\n  // 404 해결하기\n})\n~~~\n\n루트들은 정의된 순서대로 매칭된다. 들어온 요구에 처음으로 매칭된 루트가 호출된다.\n\n루트 패턴은 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service로 액세스 가능한 인자들을 포함하기도 한다:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\t\t\t// :name을 Params인자에서 추출\n})\n~~~\n\n루트는 별표식(\\*)으로 매칭 될 수도 있습니다:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\n정규식도 사용가능합니다:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\n정규식에 관하여 더 자세히 알고 싶다면 [Go documentation](http://golang.org/pkg/regexp/syntax/)을 참조해 주세요.\n\n루트 핸들러는 스택을 쌓아 올릴 수 있습니다. 특히 유저 인증작업이나, 허가작업에 유용히 쓰일 수 있죠.\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // 이 함수는 authorize 함수가 resopnse에 결과를 쓰지 않는이상 실행 될 거에요.\n})\n~~~\n\n```RootGroup```은 루트들을 한 곳에 모아 정리하는데 유용합니다.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\n핸들러에 미들웨어를 집어넣을 수 있는것과 같이, 그룹에도 미들웨어를 집어넣는 것이 가능합니다.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### 서비스(Services)\n서비스는 핸들러의 인수목록에 주입 될 수 있는 오브젝트들을 말합니다. 서비스는 *글로벌* 혹은 *리퀘스트* 레벨단위로 주입이 가능합니다.\n\n#### 글로벌 맵핑(Global Mapping)\n마타니 인스턴스는 서비스 맵핑을 쉽게 하기 위해서 inject.Injector 인터페이스를 반형합니다:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // 서비스가 모든 핸들러에서 *MyDatabase로서 사용될 수 있습니다.\n// ...\nm.Run()\n~~~\n\n#### 리퀘스트 레벨 맵핑(Request-Level Mapping)\n리퀘스트 레벨 맵핑은 핸들러안에서 [martini.Context](http://godoc.org/github.com/go-martini/martini#Context)를 사용하면 됩니다:\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // *MyCustomLogger로서 맵핑 됨\n}\n~~~\n\n#### 인터페이스로 값들 맵핑(Mapping values to Interfaces)\n서비스의 강력한 기능중 하나는 서비스를 인터페이스로 맵핑이 가능하다는 것입니다. 예를들어, [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)를 재정의(override)해서 부가 기능들을 수행하게 하고 싶으시다면, 아래와 같이 핸들러를 작성 하시면 됩니다.\n\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // ResponseWriter를 NewResponseWriter로 치환(override)\n}\n~~~\n\n### 정적파일 서빙(Serving Static Files)\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 인스턴스는 \"public\" 폴더안에 있는 파일들을 정적파일로써 자동으로 서빙합니다. 더 많은 폴더들은 정적파일 폴더에 포함시키시려면 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 핸들러를 이용하시면 됩니다.\n\n~~~ go\nm.Use(martini.Static(\"assets\")) // \"assets\" 폴더에서도 정적파일 서빙.\n~~~\n\n## 미들웨어 핸들러(Middleware Handlers)\n미들웨어 핸들러는 http request와 라우팅 사이에서 작동합니다. 미들웨어 핸들러는 근본적으로 다른 핸들러들과는 다릅니다. 사용방법은 아래와 같습니다:\n~~~ go\nm.Use(func() {\n  // 미들웨어 임무 수행!\n})\n~~~\n\n`Handlers`를 이용하여 미들웨어 스택들의 완전 컨트롤이 가능합니다. 다만, 이렇게 설정하시면 이전에 `Handlers`를 이용하여 설정한 핸들러들은 사라집니다:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\n미들웨어 핸들러는 로깅(logging), 허가(authorization), 인가(authentication), 세션, 압축(gzipping), 에러 페이지 등 등, http request의 전후로 실행되어야 할 일들을 처리하기 아주 좋습니다:\n~~~ go\n// API 키 확인작업\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"비밀암호!!!\" {\n    res.WriteHeader(http.StatusUnauthorized)\t// HTTP 401\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)는  선택적 함수입니다. 이 함수는 http request가 다 작동 될때까지 기다립니다.따라서 http request 이후에 실행 되어야 할 업무들을 수행하기 좋은 함수입니다.\n~~~ go\n// log before and after a request\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"request전입니다.\")\n\n  c.Next()\n\n  log.Println(\"request후 입니다.\")\n})\n~~~\n\n## Martini Env\n마티니 핸들러들은 `martini.Env` 글로벌 변수를 사용하여 개발환경에서는 프로덕션 환경과는 다르게 작동하기도 합니다. 따라서, 프로덕션 서버로 마티니 서버를 배포하시게 된다면 꼭 환경변수 `MARTINI_ENV=production`를 세팅해주시기 바랍니다.\n\n## FAQ\n\n### 미들웨어들을 어디서 찾아야 하나요?\n\n깃헙에서 [martini-contrib](https://github.com/martini-contrib) 프로젝트들을 찾아보세요. 만약에 못 찾으시겠으면, martini-contrib 팀원들에게 연락해서 하나 만들어 달라고 해보세요.\n* [auth](https://github.com/martini-contrib/auth) - 인증작업을 도와주는 핸들러.\n* [binding](https://github.com/martini-contrib/binding) - request를 맵핑하고 검사하는 핸들러.\n* [gzip](https://github.com/martini-contrib/gzip) - gzip 핸들러.\n* [render](https://github.com/martini-contrib/render) - HTML 템플레이트들과 JSON를 사용하기 편하게 해주는 핸들러.\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - `Accept-Language` HTTP 해더를 파싱 할 때 유용한 핸들러.\n* [sessions](https://github.com/martini-contrib/sessions) - 세션 서비스를 제공하는 핸들러.\n* [strip](https://github.com/martini-contrib/strip) - URL 프리틱스를 없애주는 핸들러.\n* [method](https://github.com/martini-contrib/method) - 해더나 폼필드를 이용한 HTTP 메소드 치환.\n* [secure](https://github.com/martini-contrib/secure) - 몇몇 보안설정을 위한 핸들러.\n* [encoder](https://github.com/martini-contrib/encoder) - 데이터 렌더링과 컨텐트 타입을위한 인코딩 서비스.\n* [cors](https://github.com/martini-contrib/cors) - CORS 서포트를 위한 핸들러.\n* [oauth2](https://github.com/martini-contrib/oauth2) - OAuth2.0 로그인 핸들러. 페이스북, 구글, 깃헙 지원.\n\n### 현재 작동중인 서버에 마티니를 적용하려면?\n\n마티니 인스턴스는 `http.Handler` 인터페이스를 차용합니다. 따라서 Go 서버 서브트리로 쉽게 사용될 수 있습니다. 아래 코드는 구글 앱 엔진에서 작동하는 마티니 앱입니다:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello 세계!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### 포트와 호스트는 어떻게 바꾸나요?\n\n마티니의 `Run` 함수는 PORT와 HOST 환경변수를 이용하는데, 설정이 안되어 있다면 localhost:3000으로 설정 되어 집니다.\n좀더 유연하게 설정을 하고 싶다면, `martini.RunOnAddr`를 활용해 주세요.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### 라이브 코드 리로드?\n\n[gin](https://github.com/codegangsta/gin) 과 [fresh](https://github.com/pilu/fresh) 가 마티니 앱의 라이브 리로드를 도와줍니다.\n\n## 공헌하기(Contributing)\n\n마티니는 간단하고 가벼운 패키지로 남을 것입니다. 따라서 보통 대부분의 공헌들은 [martini-contrib](https://github.com/martini-contrib) 그룹의 저장소로 가게 됩니다. 만약 마티니 코어에 기여하고 싶으시다면 주저없이 Pull Request를 해주세요.\n\n## About\n\n[express](https://github.com/visionmedia/express) 와 [sinatra](https://github.com/sinatra/sinatra)의 영향을 받았습니다.\n\n마티니는 [Code Gangsta](http://codegangsta.io/)가 디자인 했습니다.\n"
  },
  {
    "path": "translations/README_pl_PL.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini to solidny framework umożliwiający sprawne tworzenie modularnych aplikacji internetowych i usług sieciowych w języku Go.\n\n## Pierwsze kroki\n\nPo zakończonej instalacji Go i ustawieniu zmiennej [GOPATH](http://golang.org/doc/code.html#GOPATH), utwórz swój pierwszy plik `.go`. Nazwijmy go `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nNastępnie zainstaluj pakiet Martini (środowisko **go** w wersji **1.1** lub nowszej jest wymagane):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nUruchom serwer:\n~~~\ngo run server.go\n~~~\n\nW tym momencie webserwer Martini jest uruchomiony na `localhost:3000`.\n\n## Uzyskiwanie pomocy\n\nDołącz do [grup dyskusyjnych](https://groups.google.com/forum/#!forum/martini-go)\n\nObejrzyj przygotowane [demo](http://martini.codegangsta.io/#demo)\n\nZadawaj pytania na Stackoverflow dodając [tag martini](http://stackoverflow.com/questions/tagged/martini)\n\nGoDoc [dokumentacja](http://godoc.org/github.com/go-martini/martini)\n\n\n## Cechy frameworka\n* Bardzo prosty w użyciu.\n* Posiada niewymagającą ingerencji budowę.\n* Łatwo integruje się z innymi pakietami w języku Go.\n* Sprawnie dopasowuje ścieżki i routing.\n* Modularny projekt - łatwo dodać funkcję i łatwo usunąć.\n* Bogate zasoby handlerów i middleware'ów do wykorzystania.\n* Spora część funkcji działa 'z paczki'.\n* **W pełni kompatybilny z interfejsem [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).**\n* Umożliwia serwowanie domyślnych stron (np. przy serwowaniu aplikacji napisanych w AngularJS w trybie HTML5).\n\n## Więcej middleware'ów\nW celu uzyskania więcej informacji o middleware'ach i ich możliwościach, przejrzyj repozytoria należące do organizacji [martini-contrib](https://github.com/martini-contrib).\n\n## Spis treści\n* [Domyślna konfiguracja (Martini Classic)](#domyślna-konfiguracja-martini-classic))\n  * [Handlery](#handlery)\n  * [Routing](#routing)\n  * [Usługi](#usługi)\n  * [Serwowanie plików statycznych](#serwowanie-plików-statycznych)\n* [Handlery middleware'ów](#handlery-middlewareów)\n  * [Next()](#next)\n* [Zmienne środowiskowe Martini](#zmienne-środowiskowe-martini)\n* [FAQ](#faq)\n\n## Domyślna konfiguracja (Martini Classic)\nMartini pozwala bardzo szybko uruchomić webserver korzystając przy tym z [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic). Standardowo Classic dostarcza domyślne ustawienia, które z powodzeniem pozwolą nam uruchomić wiele aplikacji internetowych:\n~~~ go\n  m := martini.Classic()\n  // ... miejsce na middleware'y i routing\n  m.Run()\n~~~\n\nPoniżej wymieniono kilka funkcji [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) dostarczanych automatycznie:\n  * Logowanie żądań/odpowiedzi - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Serwowanie plików statycznych - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Handlery\nHandlery to serce i dusza Martini. Handlerem można nazwać każdą funkcję postaci:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Wartości zwracane\nJeśli handler zwróci wartość, Martini przekaże ją do bieżącego [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) jako łańcuch znaków:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\nOpcjonalnie można zwrócić także status HTTP:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### Wstrzykiwanie usług\nHandlery są wywoływane przez refleksję. Martini korzysta z *wstrzykiwania zależności* w celu rozwiązania tych, które występują na liście argumentów handlera. **To sprawia, że Martini jest w pełni zgodny z interfejsem `http.HandlerFunc`.**\n\nJeśli dodasz argument do handlera, Martini przeszuka swoja listę usług i spróbuje dopasować zależność na podstawie asercji typów:\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res i req są wstrzykiwane przez Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nNastępujące usługi są dostarczane razem z [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [*log.Logger](http://godoc.org/log#Logger) - globalny logger dla Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - kontekst żądania HTTP.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` przechowująca nazwane parametry, znalezione podczas dopasowywania _routes_.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - usługa wspierająca _route'y_.\n  * [martini.Route](http://godoc.org/github.com/go-martini/martini#Route) - bieżacy aktywny _route_.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - interfejs zapisu odpowiedzi HTTP.\n  * [*http.Request](http://godoc.org/net/http/#Request) - żądanie HTTP.\n\n### Routing\nW Martini, jako _route_ należy rozumieć metodę HTTP skojarzoną ze wzorcem dopasowującym adres URL.\nKażdy wzorzec może być skojarzony z jedną lub więcej metod handlera:\n~~~ go\nm.Get(\"/\", func() {\n  // wyświetl coś\n})\n\nm.Patch(\"/\", func() {\n  // zaaktualizuj coś\n})\n\nm.Post(\"/\", func() {\n  // utwórz coś\n})\n\nm.Put(\"/\", func() {\n  // zamień coś\n})\n\nm.Delete(\"/\", func() {\n  // zniszcz coś\n})\n\nm.Options(\"/\", func() {\n  // opcje HTTP\n})\n\nm.NotFound(func() {\n  // obsłuż 404\n})\n~~~\n\n_Route'y_ są dopasowywane w kolejności ich definiowania. Pierwszy dopasowany _route_ zostanie wywołany. \n\nWzorce ścieżek _route'ów_ mogą zawierać nazwane paremetry, dostępne poprzez usługę  [martini.Params](http://godoc.org/github.com/go-martini/martini#Params):\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\n_Route'y_ mogą zostać dopasowane z wartościami globalnymi:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\nRównież wyrażenia regularne mogą zostać użyte:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nWięcej informacji o budowie wyrażeń regularnych znajdziesz w [dokumentacji Go](http://golang.org/pkg/regexp/syntax/).\n\nHandlery można organizować w stosy wywołań, co przydaje się przy mechanizmach takich jak uwierzytelnianie i autoryzacja:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // funkcja będzie wywoływana dopóty, dopóki authorize nie zwróci odpowiedzi\n})\n~~~\n\nGrupy _route'ów_ mogą zostać dodane przy pomocy metody Group.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nW taki sam sposób jak przekazujesz middleware'y do handlerów, to możesz przekazywać middleware'y do grup.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Usługi\nUsługi są obiektami możliwymi do wstrzyknięcia poprzez listę argumentów danego handlera i mogą być mapowane na poziomie *globalnym* lub *żądania*.\n\n#### Mapowanie globalne\nInstancja Martini implementuje interfejs inject.Injector interface, więc mapowanie jest bardzo proste:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // usługa będzie dostępna dla wszystkich handlerów jako *MyDatabase\n// ...\nm.Run()\n~~~\n\n#### Mapowanie na poziomie żądania\nMapowanie na poziomie żądania może być wykonane w handlerze poprzez [martini.Context](http://godoc.org/github.com/go-martini/martini#Context):\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // zmapowany jako *MyCustomLogger\n}\n~~~\n\n#### Mapowanie wartości na interfejsy\nJedną z mocnych stron usług jest możliwość zmapowania konkretnej usługi na interfejs. Dla przykładu, jeśli chcesz nadpisać [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) obiektem, który go opakowuje i wykonuje dodatkowe operacje, to możesz napisać następujący handler:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // nadpisz oryginalny ResponseWriter naszym ResponseWriterem\n}\n~~~\n\n### Serwowanie plików statycznych\nInstancja [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) automatycznie serwuje statyczne pliki z katalogu \"public\" znajdującym się bezpośrednio w głównym katalogu serwera. Możliwe jest serwowanie dodatkowych katalogów poprzez dodanie handlerów [martini.Static](http://godoc.org/github.com/go-martini/martini#Static).\n~~~ go\nm.Use(martini.Static(\"assets\")) // serwuj zasoby z katalogu \"assets\"\n~~~\n\n#### Serwowanie domyślnej strony\nMożesz zdefiniować adres URL lokalnego pliku, który będzie serwowany gdy żądany adres URL nie zostanie znaleziony. Dodatkowo możesz zdefiniować prefiks wykluczający, który spowoduje, że niektórze adresy URL zostaną zignorowane. Jest to przydatna opcja dla serwerów, które jednocześnie serwują statyczne pliki i mają zdefiniowane handlery (np. REST API). Warto także rozważyć zdefiniowanie statycznych handlerów jako części łańcucha NotFound.\n\nW poniższym przykładzie aplikacja serwuje plik `/index.html`, gdy tylko adres URL nie zostanie dopasowany do istniejącego lokalnego pliku i nie zaczyna się prefiksem `/api/v`:\n~~~ go\nstatic := martini.Static(\"assets\", martini.StaticOptions{Fallback: \"/index.html\", Exclude: \"/api/v\"})\nm.NotFound(static, http.NotFound)\n~~~\n\n## Handlery middleware'ów\nHandlery middleware'ów są uruchamiane po otrzymaniu żądania HTTP a przed przekazaniem go do routera. W zasadzie nie ma różnicy między nimi a handlerami Martini. Handler middleware'a można dodać do stosu wywołań w następujący sposób:\n~~~ go\nm.Use(func() {\n  // wykonaj operacje zdefiniowane przez middleware\n})\n~~~\n\nPełną kontrolę na stosem middleware'owym zapewnia funkcja `Handlers`. Poniższy przykład prezentuje, jak można zamienić poprzednio skonfigurowane handlery:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nHandlery middleware'ów sprawdzają się doskonale dla mechanizmów takich jak logowanie, autoryzacja, uwierzytelnianie, obsługa sesji, kompresja odpowiedzi, strony błędów i innych, których operacje muszą zostać wykonane przed i po obsłudze żądania HTTP:\n~~~ go\n// validate an api key\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) jest opcjonalną funkcją, którą handlery middleware'ów wywołują, żeby przekazać tymczasowo obsługę żadania do kolejnych handlerów, a później do niej wrócić. Mechanizm sprawdza się doskonale w przypadku wykonywania operacji po obsłudze żądania HTTP:\n~~~ go\n// zaloguj przed i po żądaniu\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"before a request\")\n\n  c.Next()\n\n  log.Println(\"after a request\")\n})\n~~~\n\n## Zmienne środowiskowe Martini\n\nNiektóre handlery Martini wykorzystują globalną zmienną `martini.Env` by dostarczać specjalne funkcje dla środowisk deweloperskich i produkcyjnych. Zaleca się ustawienie zmiennej `MARTINI_ENV=production` w środowisku produkcyjnym.\n\n## FAQ\n\n### Gdzie mam szukać middleware'u X?\n\nProponujemy zacząć poszukiwania od projektów należących do [martini-contrib](https://github.com/martini-contrib). Jeśli dany middleware się tam nie znajduje, skontaktuj się z członkiem zespołu martini-contrib i poproś go o dodanie nowego repozytorium do organizacji.\n\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler umożliwiający parsowanie nagłówka HTTP `Accept-Language`.\n* [accessflags](https://github.com/martini-contrib/accessflags) - Handler dołączający obsługę kontroli dostępu.\n* [auth](https://github.com/martini-contrib/auth) - Handlery uwierzytelniające.\n* [binding](https://github.com/martini-contrib/binding) - Handler mapujący/walidujący żądanie na strukturę.\n* [cors](https://github.com/martini-contrib/cors) - Handler dostarcza wsparcie dla CORS.\n* [csrf](https://github.com/martini-contrib/csrf) - Ochrona CSRF dla aplikacji.\n* [encoder](https://github.com/martini-contrib/encoder) - Usługa enkodująca treść odpowiedzi w różnych formatach, wspiera negocjacje formatu.\n* [gzip](https://github.com/martini-contrib/gzip) - Handler dla kompresji GZIP żądań.\n* [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic middleware.\n* [logstasher](https://github.com/martini-contrib/logstasher) - Middleware zwracający odpowiedź formacie kompatybilnym z logstash JSONem.\n* [method](https://github.com/martini-contrib/method) - Nadpisywanie metod HTTP poprzez nagłówek.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Handler dostarczający logowanie OAuth 2.0 dla aplikacji Martini. Logowanie Google Sign-in, Facebook Connect i Github wspierane.\n* [permissions2](https://github.com/xyproto/permissions2) - Handler śledzący użytkowników, ich logowania i uprawnienia.\n* [render](https://github.com/martini-contrib/render) - Handler dostarczający usługę łatwo renderującą odpowiedź do formatu JSON i szablonów HTML.\n* [secure](https://github.com/martini-contrib/secure) - Implementuje kilka szybkich \"quick-wins\" związanych z bezpieczeństwem.\n* [sessions](https://github.com/martini-contrib/sessions) - Handler dostarcza usługę sesji.\n* [sessionauth](https://github.com/martini-contrib/sessionauth) - Handler, który umożliwia w prosty sposób nałożenie reguły wymagania logowania dla konkretnych adresów oraz obsługę zalogowanych użytkowników w sesji. \n* [strict](https://github.com/martini-contrib/strict) - Strict Mode \n* [strip](https://github.com/martini-contrib/strip) - Pomijanie prefiksu URL.\n* [staticbin](https://github.com/martini-contrib/staticbin) - Handler umożliwia serwowanie statycznych plików z zasobów binarnych.\n* [throttle](https://github.com/martini-contrib/throttle) - Middleware kontrolujący przepustowość handlerów.\n* [vauth](https://github.com/rafecolton/vauth) - Handlery wspierające vendorowe uwierzytelnianie (obecnie GitHub i TravisCI).\n* [web](https://github.com/martini-contrib/web) - Kontekst znany z web.go.\n\n### Jak mogę zintegrować Martini z istniejącymi serwerami?\n\nInstacja Martini implementuje `http.Handler`, więc może być łatwo wykorzystana do serwowania całych drzew zasobów na istniejących serwerach Go. Przykład przedstawia działającą aplikację Martini dla Google App Engine:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### Jak mogę zmienić host/port?\n\nFunkcja `Run` sprawdza, czy są zdefiniowane zmienne środowiskowe HOST i PORT, i jeśli są to ich używa. W przeciwnym wypadku Martini uruchomi się z domyślnymi ustawieniami localhost:3000.\nW celu uzyskania większej kontroli nad hostem i portem, skorzystaj z funkcji `martini.RunOnAddr`.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### Automatyczne przeładowywanie kodu aplikacji (Live code reload)\n\n[gin](https://github.com/codegangsta/gin) i [fresh](https://github.com/pilu/fresh) wspierają przeładowywanie kodu aplikacji.\n\n## Rozwijanie\nMartini w założeniu ma pozostać czysty i uporządkowany. Większość kontrybucji powinna trafić jako repozytorium organizacji [martini-contrib](https://github.com/martini-contrib). Jeśli masz kontrybucję do core'a projektu Martini, zgłoś Pull Requesta.\n\n## O projekcie\n\nInspirowany [expressem](https://github.com/visionmedia/express) i [sinatrą](https://github.com/sinatra/sinatra)\n\nMartini został obsesyjnie zaprojektowany przez nikogo innego jak przez [Code Gangsta](http://codegangsta.io/)\n"
  },
  {
    "path": "translations/README_pt_br.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\n**NOTA:** O martini framework não é mais mantido.\n\nMartini é um poderoso pacote para escrever aplicações/serviços modulares em Golang..\n\n\n## Vamos começar\n\nApós a instalação do Go e de configurar o [GOPATH](http://golang.org/doc/code.html#GOPATH), crie seu primeiro arquivo `.go`. Vamos chamá-lo de `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nEntão instale o pacote do Martini (É necessário **go 1.1** ou superior):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nEntão rode o servidor:\n~~~\ngo run server.go\n~~~\n\nAgora você tem um webserver Martini rodando na porta `localhost:3000`.\n\n## Obtenha ajuda\n\nAssine a [Lista de email](https://groups.google.com/forum/#!forum/martini-go)\n\nVeja o [Vídeo demonstrativo](http://martini.codegangsta.io/#demo)\n\nUse a tag [martini](http://stackoverflow.com/questions/tagged/martini) para perguntas no Stackoverflow\n\n\n\n## Caracteríticas\n* Extrema simplicidade de uso.\n* Design não intrusivo.\n* Boa integração com outros pacotes Golang.\n* Router impressionante.\n* Design modular - Fácil para adicionar e remover funcionalidades.\n* Muito bom no uso handlers/middlewares.\n* Grandes caracteríticas inovadoras.\n* **Completa compatibilidade com a interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).**\n\n## Mais Middleware\nPara mais middleware e funcionalidades, veja os repositórios em [martini-contrib](https://github.com/martini-contrib).\n\n## Tabela de Conteudos\n* [Classic Martini](#classic-martini)\n  * [Handlers](#handlers)\n  * [Routing](#routing)\n  * [Services](#services)\n  * [Serving Static Files](#serving-static-files)\n* [Middleware Handlers](#middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\nPara iniciar rapidamente, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) provê algumas ferramentas razoáveis para maioria das aplicações web:\n~~~ go\n  m := martini.Classic()\n  // ... middleware e rota aqui\n  m.Run()\n~~~\n\nAlgumas das funcionalidade que o [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) oferece automaticamente são:\n  * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Servidor de arquivos státicos - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Rotas - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Handlers\nHandlers são o coração e a alma do Martini. Um handler é basicamente qualquer função que pode ser chamada:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Retorno de Valores\nSe um handler retornar alguma coisa, Martini irá escrever o valor retornado como uma string ao [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter):\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\nVocê também pode retornar o código de status:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"Eu sou um bule\" // HTTP 418 : \"Eu sou um bule\"\n})\n~~~\n\n#### Injeção de Serviços\nHandlers são chamados via reflexão. Martini utiliza *Injeção de Dependencia* para resolver as dependencias nas listas de argumentos dos Handlers . **Isso faz Martini ser completamente compatível com a interface `http.HandlerFunc` do golang.**\n\nSe você adicionar um argumento ao seu Handler, Martini ira procurar na sua lista de serviços e tentar resolver sua dependencia pelo seu tipo:\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res e req são injetados pelo Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nOs seguintes serviços são incluídos com [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nomes dos parâmetros buscados pela rota.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Serviço de auxílio as rotas.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escreve a interface.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request.\n\n### Rotas\nNo Martini, uma rota é um método HTTP emparelhado com um padrão de URL de correspondência.\nCada rota pode ter um ou mais métodos handler:\n~~~ go\nm.Get(\"/\", func() {\n  // mostra alguma coisa\n})\n\nm.Patch(\"/\", func() {\n  // altera alguma coisa\n})\n\nm.Post(\"/\", func() {\n  // cria alguma coisa\n})\n\nm.Put(\"/\", func() {\n  // sobrescreve alguma coisa\n})\n\nm.Delete(\"/\", func() {\n  // destrói alguma coisa\n})\n\nm.Options(\"/\", func() {\n  // opções do HTTP\n})\n\nm.NotFound(func() {\n  // manipula 404\n})\n~~~\n\nAs rotas são combinadas na ordem em que são definidas. A primeira rota que corresponde a solicitação é chamada.\n\nO padrão de rotas pode incluir parâmetros que podem ser acessados via [martini.Params](http://godoc.org/github.com/go-martini/martini#Params):\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nAs rotas podem ser combinados com expressões regulares e globs:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\nExpressões regulares podem ser bem usadas:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nDê uma olhada na [documentação](http://golang.org/pkg/regexp/syntax/) para mais informações sobre expressões regulares.\n\n\nHandlers de rota podem ser empilhados em cima uns dos outros, o que é útil para coisas como autenticação e autorização:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // Será executado quando authorize não escrever uma resposta\n})\n~~~\n\nGrupos de rota podem ser adicionados usando o método Group.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nAssim como você pode passar middlewares para um manipulador você pode passar middlewares para grupos.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Serviços\nServiços são objetos que estão disponíveis para ser injetado em uma lista de argumentos de Handler. Você pode mapear um serviço num nível *Global* ou *Request*.\n\n#### Mapeamento Global\nUm exemplo onde o Martini implementa a interface inject.Injector, então o mapeamento de um serviço é fácil:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // o serviço estará disponível para todos os handlers *MyDatabase.\n// ...\nm.Run()\n~~~\n\n#### Mapeamento por requisição\nMapeamento do nível de request pode ser feito via handler através [martini.Context](http://godoc.org/github.com/go-martini/martini#Context):\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // mapeamento é *MyCustomLogger\n}\n~~~\n\n#### Valores de Mapeamento para Interfaces\nUma das partes mais poderosas sobre os serviços é a capacidade para mapear um serviço de uma interface. Por exemplo, se você quiser substituir o [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) com um objeto que envolveu-o e realizou operações extras, você pode escrever o seguinte handler:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // substituir ResponseWriter com nosso ResponseWriter invólucro\n}\n~~~\n\n### Servindo Arquivos Estáticos\nUma instância de [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) serve automaticamente arquivos estáticos do diretório \"public\" na raiz do seu servidor.\nVocê pode servir de mais diretórios, adicionando mais [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers.\n~~~ go\nm.Use(martini.Static(\"assets\")) // servindo os arquivos do diretório \"assets\"\n~~~\n\n## Middleware Handlers\nMiddleware Handlers ficam entre a solicitação HTTP e o roteador. Em essência, eles não são diferentes de qualquer outro Handler no Martini. Você pode adicionar um handler de middleware para a pilha assim:\n~~~ go\nm.Use(func() {\n  // faz algo com middleware\n})\n~~~\n\nVocê pode ter o controle total sobre a pilha de middleware com a função `Handlers`. Isso irá substituir quaisquer manipuladores que foram previamente definidos:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nMiddleware Handlers trabalham muito bem com princípios com logging, autorização, autenticação, sessão, gzipping, páginas de erros e uma série de outras operações que devem acontecer antes ou depois de uma solicitação HTTP:\n~~~ go\n// Valida uma chave de API\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) é uma função opcional que Middleware Handlers podem chamar para aguardar a execução de outros Handlers. Isso funciona muito bem para operações que devem acontecer após uma requisição:\n~~~ go\n// log antes e depois do request\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"antes do request\")\n\n  c.Next()\n\n  log.Println(\"depois do request\")\n})\n~~~\n\n## Martini Env\n\nMartini handlers fazem uso do `martini.Env`, uma variável global para fornecer funcionalidade especial para ambientes de desenvolvimento e ambientes de produção. É recomendado que a variável `MARTINI_ENV=production` seja definida quando a implementação estiver em um ambiente de produção.\n\n## FAQ\n\n### Onde posso encontrar o middleware X?\n\nInicie sua busca nos projetos [martini-contrib](https://github.com/martini-contrib). Se ele não estiver lá não hesite em contactar um membro da equipe martini-contrib sobre como adicionar um novo repo para a organização.\n\n* [auth](https://github.com/martini-contrib/auth) - Handlers para autenticação.\n* [binding](https://github.com/martini-contrib/binding) - Handler para mapeamento/validação de um request a estrutura.\n* [gzip](https://github.com/martini-contrib/gzip) - Handler para adicionar compreção gzip para o requests\n* [render](https://github.com/martini-contrib/render) - Handler que providencia uma rederização simples para JSON e templates HTML.\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para parsing do `Accept-Language` no header HTTP.\n* [sessions](https://github.com/martini-contrib/sessions) - Handler que prove o serviço de sessão.\n* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping.\n* [method](https://github.com/martini-contrib/method) - HTTP método de substituição via cabeçalho ou campos do formulário.\n* [secure](https://github.com/martini-contrib/secure) - Implementa rapidamente itens de segurança.\n* [encoder](https://github.com/martini-contrib/encoder) - Serviço Encoder para renderização de dados em vários formatos e negociação de conteúdo.\n* [cors](https://github.com/martini-contrib/cors) - Handler que habilita suporte a CORS.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Handler que prove sistema de login OAuth 2.0 para aplicações Martini. Google Sign-in, Facebook Connect e Github login são suportados.\n\n### Como faço para integrar com os servidores existentes?\n\nUma instância do Martini implementa `http.Handler`, de modo que pode ser facilmente utilizado para servir sub-rotas e diretórios\nem servidores Go existentes. Por exemplo, este é um aplicativo Martini trabalhando para Google App Engine:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### Como faço para alterar a porta/host?\n\nA função `Run` do Martini olha para as variáveis PORT e HOST para utilizá-las. Caso contrário o Martini assume como padrão localhost:3000.\nPara ter mais flexibilidade sobre a porta e host use a função `martini.RunOnAddr`.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### Servidor com autoreload?\n\n[gin](https://github.com/codegangsta/gin) e [fresh](https://github.com/pilu/fresh) são aplicativos para autoreload do Martini.\n\n## Contribuindo\nMartini é feito para ser mantido pequeno e limpo. A maioria das contribuições devem ser feitas no repositório [martini-contrib](https://github.com/martini-contrib). Se quiser contribuir com o core do Martini fique livre para fazer um Pull Request.\n\n## Sobre\n\nInspirado por [express](https://github.com/visionmedia/express) e [sinatra](https://github.com/sinatra/sinatra)\n\nMartini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/)\n"
  },
  {
    "path": "translations/README_ru_RU.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini - мощный пакет для быстрой разработки веб приложений и сервисов на Golang.\n\n## Начало работы\n\nПосле установки Golang и настройки вашего [GOPATH](http://golang.org/doc/code.html#GOPATH), создайте ваш первый `.go` файл. Назовем его `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nПотом установите пакет Martini (требуется **go 1.1** или выше):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nПотом запустите ваш сервер:\n~~~\ngo run server.go\n~~~\n\nИ вы получите запущенный Martini сервер на `localhost:3000`.\n\n## Помощь\n\nПрисоединяйтесь к [рассылке](https://groups.google.com/forum/#!forum/martini-go)\n\nЗадавайте вопросы на Stackoverflow используя [тэг martini](http://stackoverflow.com/questions/tagged/martini)\n\nGoDoc [документация](http://godoc.org/github.com/go-martini/martini)\n\n\n## Возможности\n* Очень прост в использовании.\n* Ненавязчивый дизайн.\n* Хорошо сочетается с другими пакетами.\n* Потрясающий роутинг и маршрутизация.\n* Модульный дизайн - легко добавлять и исключать функциональность.\n* Большое количество хороших обработчиков/middlewares, готовых к использованию.\n* Отличный набор 'из коробки'.\n* **Полностью совместим с интерфейсом [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).**\n\n## Больше Middleware\nСмотрите репозитории организации [martini-contrib](https://github.com/martini-contrib), для большей информации о функциональности и middleware.\n\n## Содержание\n* [Classic Martini](#classic-martini)\n  * [Обработчики](#%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8)\n  * [Роутинг](#%D0%A0%D0%BE%D1%83%D1%82%D0%B8%D0%BD%D0%B3)\n  * [Сервисы](#%D0%A1%D0%B5%D1%80%D0%B2%D0%B8%D1%81%D1%8B)\n  * [Отдача статических файлов](#%D0%9E%D1%82%D0%B4%D0%B0%D1%87%D0%B0-%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D1%85-%D1%84%D0%B0%D0%B9%D0%BB%D0%BE%D0%B2)\n* [Middleware обработчики](#middleware-%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8)\n  * [Next()](#next)\n* [Окружение](#%D0%9E%D0%BA%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5)\n* [FAQ](#faq)\n\n## Classic Martini\nДля быстрого старта [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) предлагает несколько предустановок, это используется для большинства веб приложений:\n~~~ go\n  m := martini.Classic()\n  // ... middleware и роутинг здесь\n  m.Run()\n~~~\n\nНиже представлена уже подключенная [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) функциональность:  \n\n  * Request/Response логгирование - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Отдача статики - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Роутинг - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Обработчики\nОбработчики - это сердце и душа Martini. Обработчик - любая функция, которая может быть вызвана:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Возвращаемые значения\nЕсли обработчик возвращает что-либо, Martini запишет это как результат в текущий [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), в виде строки:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\nТак же вы можете возвращать код статуса, опционально:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### Внедрение сервисов\nОбработчики вызываются посредством рефлексии. Martini использует **Внедрение зависимости** для разрешения зависимостей в списке аргумента обработчика. **Это делает Martini полностью совместимым с интерфейсом `http.HandlerFunc`.**\n\nЕсли вы добавите аргументы в ваш обработчик, Martini будет пытаться найти этот список сервисов за счет проверки типов(type assertion):\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res и req будут внедрены  Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nСледующие сервисы включены в [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n\n  * [*log.Logger](http://godoc.org/log#Logger) - Глобальный логгер для Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request контекст.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` именованных аргументов из роутера.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Хэлпер роутеров.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer интерфейс.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request.\n\n### Роутинг\nВ Martini, роут - это объединенные паттерн и HTTP метод.\nКаждый роут может принимать один или несколько обработчиков:\n~~~ go\nm.Get(\"/\", func() {\n  // показать что-то\n})\n\nm.Patch(\"/\", func() {\n  // обновить что-то\n})\n\nm.Post(\"/\", func() {\n  // создать что-то\n})\n\nm.Put(\"/\", func() {\n  // изменить что-то\n})\n\nm.Delete(\"/\", func() {\n  // удалить что-то\n})\n\nm.Options(\"/\", func() {\n  // http опции\n})\n\nm.NotFound(func() {\n  // обработчик 404\n})\n~~~\n\nРоуты могут сопоставляться с http запросами только в порядке объявления. Вызывается первый роут, который соответствует запросу.\n\nПаттерны роутов могут включать именованные параметры, доступные через [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) сервис:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nРоуты можно объявлять как glob'ы:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\nТак же могут использоваться регулярные выражения:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nСинтаксис регулярных выражений смотрите [Go documentation](http://golang.org/pkg/regexp/syntax/).\n\nОбработчики роутов так же могут быть выстроены в стек, друг перед другом. Это очень удобно для таких задач как авторизация и аутентификация:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // будет вызываться, в случае если authorize ничего не записал в ответ\n})\n~~~\n\nРоуты так же могут быть объединены в группы, посредством метода Group:\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nТак же как вы можете добавить middleware для обычного обработчика, вы можете добавить middleware и для группы.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Сервисы\nСервисы - это объекты, которые доступны для внедрения в аргументы обработчиков. Вы можете замапить сервисы на уровне всего приложения либо на уровне запроса.\n\n#### Глобальный маппинг\nЭкземпляр Martini реализует интерфейс inject.Injector, поэтому замаппить сервис легко:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // сервис будет доступен для всех обработчиков как *MyDatabase\n// ...\nm.Run()\n~~~\n\n#### Маппинг уровня запроса\nМаппинг на уровне запроса можно сделать при помощи [martini.Context](http://godoc.org/github.com/go-martini/martini#Context):\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // как *MyCustomLogger\n}\n~~~\n\n#### Маппинг на определенный интерфейс\nОдна из мощных частей, того что касается сервисов - маппинг сервиса на определенный интерфейс. Например, если вы хотите переопределить [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) объектом, который оборачивает и добавляет новые операции, вы можете написать следующее:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // переопределить ResponseWriter нашей оберткой\n}\n~~~\n\n### Отдача статических файлов\nЭкземпляр [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) автоматически отдает статические файлы из директории \"public\" в корне, рядом с вашим файлом `server.go`.\nВы можете добавить еще директорий, добавляя [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) обработчики.  \n~~~ go\nm.Use(martini.Static(\"assets\")) // отдача файлов из \"assets\" директории\n~~~\n\n## Middleware Обработчики\nMiddleware обработчики находятся между входящим http запросом и роутом. По сути, они ничем не отличаются от любого другого обработчика Martini. Вы можете добавить middleware обработчик в стек следующим образом:\n~~~ go\nm.Use(func() {\n  // делать какую то middleware работу\n})\n~~~\n\nДля полного контроля над стеком middleware существует метод `Handlers`. В этом примере будут заменены все обработчики, которые были до этого:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nMiddleware обработчики очень хорошо работают для таких вещей как логгирование, авторизация, аутентификация, сессии, сжатие, страницы ошибок и любые другие операции, которые должны быть выполнены до или после http запроса:\n~~~ go\n// валидация api ключа\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) опциональная функция, которая может быть вызвана в Middleware обработчике, для выхода из контекста, и возврата в него, после вызова всего стека обработчиков. Это можно использовать для операций, которые должны быть выполнены после http запроса:\n~~~ go\n// логгирование до и после http запроса\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"до запроса\")\n\n  c.Next()\n\n  log.Println(\"после запроса\")\n})\n~~~\n\n## Окружение\nНекоторые Martini обработчики используют глобальную переменную `martini.Env` для того, чтоб предоставить специальную функциональность для девелопмент и продакшн окружения. Рекомендуется устанавливать `MARTINI_ENV=production`, когда вы деплоите приложение на продакшн.\n\n## FAQ\n\n### Где найти готовые middleware?\n\nНачните поиск с [martini-contrib](https://github.com/martini-contrib) проектов. Если нет ничего подходящего, без колебаний пишите члену команды martini-contrib о добавлении нового репозитория в организацию.\n\n* [auth](https://github.com/martini-contrib/auth) - Обработчики для аутентификации.\n* [binding](https://github.com/martini-contrib/binding) - Обработчик для маппинга/валидации сырого запроса в определенную структуру(struct).\n* [gzip](https://github.com/martini-contrib/gzip) - Обработчик, добавляющий gzip сжатие для запросов.\n* [render](https://github.com/martini-contrib/render) - Обработчик, которые предоставляет сервис для легкого рендеринга JSON и HTML шаблонов.\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Обработчик для парсинга `Accept-Language` HTTP заголовка.\n* [sessions](https://github.com/martini-contrib/sessions) - Сервис сессий.\n* [strip](https://github.com/martini-contrib/strip) - Удаление префиксов из URL.\n* [method](https://github.com/martini-contrib/method) - Подмена HTTP метода через заголовок.\n* [secure](https://github.com/martini-contrib/secure) - Набор для безопасности.\n* [encoder](https://github.com/martini-contrib/encoder) - Сервис для представления данных в нескольких форматах и взаимодействия с контентом.\n* [cors](https://github.com/martini-contrib/cors) - Поддержка CORS.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Обработчик, предоставляющий OAuth 2.0 логин для Martini приложений. Вход через Google, Facebook и через Github поддерживаются.\n\n### Как интегрироваться с существуюшими серверами?\n\nЭкземпляр Martini реализует интерфейс `http.Handler`, потому - это очень просто использовать вместе с существующим Go проектом. Например, это работает для платформы Google App Engine:\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### Как изменить порт и/или хост?\nФункция `Run` смотрит переменные окружиения PORT и HOST, и использует их.\nВ противном случае Martini по умолчанию будет использовать `localhost:3000`.\nДля большей гибкости используйте вместо этого функцию `martini.RunOnAddr`.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### Живая перезагрузка кода?\n\n[gin](https://github.com/codegangsta/gin) и [fresh](https://github.com/pilu/fresh) могут работать вместе с Martini.\n\n## Вклад в общее дело\n\nПодразумевается что Martini чистый и маленький. Большинство улучшений должны быть в организации [martini-contrib](https://github.com/martini-contrib). Но если вы хотите улучшить ядро Martini, отправляйте пулл реквесты.\n\n## О проекте\n\nВдохновлен [express](https://github.com/visionmedia/express) и [sinatra](https://github.com/sinatra/sinatra)\n\nMartini создан [Code Gangsta](http://codegangsta.io/)\n"
  },
  {
    "path": "translations/README_tr_TR.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini Go dilinde hızlı ve modüler web uygulamaları ve servisleri için güçlü bir pakettir.\n\n\n## Başlangıç\n\nGo kurulumu ve [GOPATH](http://golang.org/doc/code.html#GOPATH) ayarını yaptıktan sonra, ilk `.go` uzantılı dosyamızı oluşturuyoruz. Bu oluşturduğumuz dosyayı `server.go` olarak adlandıracağız.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nMartini paketini kurduktan sonra (**go 1.1** ve daha üst go sürümü gerekmektedir.):\n\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nDaha sonra server'ımızı çalıştırıyoruz:\n\n~~~\ngo run server.go\n~~~\n\nŞimdi elimizde çalışan bir adet Martini webserver `localhost:3000`  adresinde bulunmaktadır.\n\n\n## Yardım Almak İçin \n\n[Mail Listesi](https://groups.google.com/forum/#!forum/martini-go)\n\n[Örnek Video](http://martini.codegangsta.io/#demo)\n\nStackoverflow üzerinde [martini etiketine](http://stackoverflow.com/questions/tagged/martini) sahip sorular\n\n[GO Diline ait Dökümantasyonlar](http://godoc.org/github.com/go-martini/martini)\n\n\n## Özellikler \n* Oldukça basit bir kullanıma sahip.\n* Kısıtlama yok.\n* Golang paketleri ile rahat bir şekilde kullanılıyor.\n* Müthiş bir şekilde path eşleştirme ve yönlendirme.\n* Modüler dizayn - Kolay eklenen fonksiyonellik.\n* handlers/middlewares kullanımı çok iyi.\n* Büyük 'kutu dışarı' özellik seti.\n* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) arayüzü ile tam uyumludur.**\n* Varsayılan belgelendirme işlemleri (örnek olarak, AngularJS uygulamalarının HTML5 modunda servis edilmesi).\n\n## Daha Fazla Middleware(Ara Katman)\n\nDaha fazla ara katman ve fonksiyonellik için, şu repoları inceleyin [martini-contrib](https://github.com/martini-contrib).\n\n## Tablo İçerikleri\n* [Classic Martini](#classic-martini)\n  * [İşleyiciler / Handlers](#handlers)\n  * [Yönlendirmeler / Routing](#routing)\n  * [Servisler](#services)\n  * [Statik Dosyaların Sunumu](#serving-static-files)\n* [Katman İşleyiciler / Middleware Handlers](#middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) hızlıca projeyi çalıştırır ve çoğu web uygulaması için iyi çalışan bazı makul varsayılanlar sağlar:\n\n~~~ go\n  m := martini.Classic()\n  // ... middleware and routing goes here\n  m.Run()\n~~~\n\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) aşağıdaki bazı fonsiyonelleri  otomatik olarak çeker:\n\n  * İstek/Yanıt Kayıtları (Request/Response Logging) - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Hataların Düzeltilmesi (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Statik Dosyaların Sunumu (Static File serving) - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Yönlendirmeler (Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### İşleyiciler (Handlers)\nİşleyiciler Martini'nin ruhu ve kalbidir. Bir işleyici temel olarak her türlü fonksiyonu çağırabilir:\n\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Geriye Dönen Değerler\n\nEğer bir işleyici geriye bir şey dönderiyorsa, Martini string olarak sonucu [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) ile yazacaktır:\n\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\nAyrıca isteğe bağlı bir durum kodu dönderebilir:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### Service Injection\nİşlemciler yansıma yoluyla çağrılır. Martini *Dependency Injection* kullanarak arguman listesindeki bağımlıkları giderir.**Bu sayede Martini go programlama dilinin `http.HandlerFunc` arayüzü ile tamamen uyumlu hale getirilir.**\n\nEğer işleyiciye bir arguman eklersek, Martini \"type assertion\" ile servis listesinde arayacak ve bağımlılıkları çözmek için girişimde bulunacaktır:\n\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nAşağıdaki servislerin içerikleri\n\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [*log.Logger](http://godoc.org/log#Logger) - Martini için Global loglayıcı.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request içereği.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` ile yol eşleme tarafından params olarak isimlendirilen yapılar bulundu.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Yönledirilme için yardımcı olan yapıdır.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http yanıtlarını yazacak olan yapıdır.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request(http isteği yapar).\n\n### Yönlendirme - Routing\nMartini'de bir yol HTTP metodu URL-matching pattern'i ile eşleştirilir.\nHer bir yol bir veya daha fazla işleyici metod alabilir:\n~~~ go\nm.Get(\"/\", func() {\n  // show something\n})\n\nm.Patch(\"/\", func() {\n  // update something\n})\n\nm.Post(\"/\", func() {\n  // create something\n})\n\nm.Put(\"/\", func() {\n  // replace something\n})\n\nm.Delete(\"/\", func() {\n  // destroy something\n})\n\nm.Options(\"/\", func() {\n  // http options\n})\n\nm.NotFound(func() {\n  // handle 404\n})\n~~~\n\nYollar sırayla tanımlandıkları şekilde eşleştirilir.Request ile eşleşen ilk rota çağrılır.\n\nYol patternleri [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) servisi tarafından adlandırılan parametreleri içerebilir:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nYollar globaller ile eşleşebilir:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\nDüzenli ifadeler kullanılabilir:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nDüzenli ifadeler hakkında daha fazla bilgiyi [Go dökümanlarından](http://golang.org/pkg/regexp/syntax/) elde edebilirsiniz.\n\nYol işleyicileri birbirlerinin üstüne istiflenebilir. Bu durum doğrulama ve yetkilendirme(authentication and authorization) işlemleri için iyi bir yöntemdir: \n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // this will execute as long as authorize doesn't write a response\n})\n~~~\n\nYol grupları Grup metodlar kullanılarak eklenebilir.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nTıpkı ara katmanların işleyiciler için bazı ara katman işlemlerini atlayabileceği gibi gruplar içinde atlayabilir.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Servisler\n\nServisler işleyicilerin arguman listesine enjekte edilecek kullanılabilir nesnelerdir. İstenildiği taktirde bir servis *Global* ve *Request* seviyesinde eşlenebilir.\n\n#### Global Eşleme - Global Mapping\n\nBir martini örneği(instance) projeye enjekte edilir. \nA Martini instance implements the inject.Enjekte arayüzü, çok kolay bir şekilde servis eşlemesi yapar:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // the service will be available to all handlers as *MyDatabase\n// ...\nm.Run()\n~~~\n\n#### Request-Level Mapping\nRequest düzeyinde eşleme yapmak üzere işleyici [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) ile oluşturulabilir:\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // mapped as *MyCustomLogger\n}\n~~~\n\n#### Arayüz Eşleme Değerleri\nServisler hakkındaki en güçlü şeylerden birisi bir arabirim ile bir servis eşleşmektedir. Örneğin, istenirse [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) yapısı paketlenmiş ve ekstra işlemleri gerçekleştirilen bir nesne ile  override edilebilir. Şu işleyici yazılabilir:\n\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter\n}\n~~~\n\n### Statik Dosyaların Sunumu\n\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) örneği otomatik olarak statik dosyaları serverda root içinde yer alan \"public\" dizininden servis edilir.\n\nEğer istenirse daha fazla [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) işleyicisi eklenerek daha fazla dizin servis edilebilir.\n~~~ go\nm.Use(martini.Static(\"assets\")) // serve from the \"assets\" directory as well\n~~~\n\n#### Standart Dökümanların Sunulması - Serving a Default Document\n\nEğer istenilen URL bulunamaz ise özel bir URL dönderilebilir. Ayrıca bir dışlama(exclusion) ön eki ile bazı URL'ler göz ardı edilir. Bu durum statik dosyaların ve ilave işleyiciler için kullanışlıdır(Örneğin, REST API). Bunu yaparken, bu işlem ile NotFound zincirinin bir parçası olan statik işleyiciyi tanımlamak kolaydır.\n\nHerhangi bir URL isteği bir local dosya ile eşleşmediği ve `/api/v` ile başlamadığı zaman aşağıdaki örnek `/index.html` dosyasını sonuç olarak geriye döndürecektir.\n~~~ go\nstatic := martini.Static(\"assets\", martini.StaticOptions{Fallback: \"/index.html\", Exclude: \"/api/v\"})\nm.NotFound(static, http.NotFound)\n~~~\n\n## Ara Katman İşleyicileri\nAra katmana ait işleyiciler http isteği ve yönlendirici arasında bulunmaktadır. Özünde onlar diğer Martini işleyicilerinden farklı değildirler. İstenildiği taktirde bir yığına ara katman işleyicisi şu şekilde eklenebilir:\n~~~ go\nm.Use(func() {\n  // do some middleware stuff\n})\n~~~\n\n`Handlers` fonksiyonu ile ara katman yığını üzerinde tüm kontrole sahip olunabilir. Bu daha önceden ayarlanmış herhangi bir işleyicinin yerini alacaktır:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nOrta katman işleyicileri loglama, giriş , yetkilendirme , sessionlar, sıkıştırma(gzipping) , hata sayfaları ve HTTP isteklerinden önce ve sonra herhangi bir olay sonucu oluşan durumlar için gerçekten iyi bir yapıya sahiptir:\n\n~~~ go\n// validate an api key\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) orta katman işleyicilerinin diğer işleyiciler yok edilmeden çağrılmasını sağlayan opsiyonel bir fonksiyondur.Bu iş http işlemlerinden sonra gerçekleşecek işlemler için gerçekten iyidir:\n~~~ go\n// log before and after a request\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"before a request\")\n\n  c.Next()\n\n  log.Println(\"after a request\")\n})\n~~~\n\n## Martini Env\n\nBazı Martini işleyicileri `martini.Env` yapısının özel fonksiyonlarını kullanmak için geliştirici ortamları, üretici ortamları vs. kullanır.Bu üretim ortamına Martini sunucu kurulurken `MARTINI_ENV=production` şeklinde ortam değişkeninin ayarlanması gerekir.\n\n## FAQ\n\n### Ara Katmanda X'i Nerede Bulurum?\n\n[martini-contrib](https://github.com/martini-contrib) projelerine bakarak başlayın. Eğer aradığınız şey orada mevcut değil ise yeni bir repo eklemek için martini-contrib takım üyeleri ile iletişime geçin.\n\n* [auth](https://github.com/martini-contrib/auth) - Kimlik doğrulama için işleyiciler.\n* [binding](https://github.com/martini-contrib/binding) - Mapping/Validating yapısı içinde ham request'i doğrulamak için kullanılan işleyici(handler)\n* [gzip](https://github.com/martini-contrib/gzip) - İstekleri gzip sıkışıtırıp eklemek için kullanılan işleyici\n* [render](https://github.com/martini-contrib/render) - Kolay bir şekilde JSON ve HTML şablonları oluşturmak için kullanılan işleyici.\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - `Kabul edilen dile` göre HTTP başlığını oluşturmak için kullanılan işleyici.\n* [sessions](https://github.com/martini-contrib/sessions) - Oturum hizmeti vermek için kullanılır.\n* [strip](https://github.com/martini-contrib/strip) - İşleyicilere gitmeden önce URL'ye ait ön şeriti değiştirme işlemini yapar.\n* [method](https://github.com/martini-contrib/method) - Formlar ve başlık için http metodunu override eder.\n* [secure](https://github.com/martini-contrib/secure) - Birkaç hızlı güvenlik uygulaması ile kazanımda bulundurur.\n* [encoder](https://github.com/martini-contrib/encoder) - Encoder servis veri işlemleri için çeşitli format ve içerik sağlar.\n* [cors](https://github.com/martini-contrib/cors) - İşleyicilerin CORS desteği bulunur.\n* [oauth2](https://github.com/martini-contrib/oauth2) - İşleyiciler OAuth 2.0 için Martini uygulamalarına giriş sağlar. Google , Facebook ve Github için desteği mevcuttur.\n* [vauth](https://github.com/rafecolton/vauth) - Webhook için giriş izni sağlar. (şimdilik sadece GitHub ve TravisCI ile)\n\n### Mevcut Sunucular ile Nasıl Entegre Edilir?\n\nBir martini örneği `http.Handler`'ı projeye dahil eder, bu sayde kolay bir şekilde mevcut olan Go sunucularında  bulunan alt ağaçlarda kullanabilir. Örnek olarak, bu olay Google App Engine için hazırlanmış Martini uygulamalarında kullanılmaktadır:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### port/hostu nasıl değiştiririm?\n\nMartini'ye ait `Run` fonksiyounu PORT ve HOST'a ait ortam değişkenlerini arar ve bunları kullanır. Aksi taktirde standart olarak localhost:3000 adresini port ve host olarak kullanacaktır.\n\nPort ve host için daha fazla esneklik isteniyorsa `martini.RunOnAddr` fonksiyonunu kullanın.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### Anlık Kod Yüklemesi?\n\n[gin](https://github.com/codegangsta/gin) ve [fresh](https://github.com/pilu/fresh) anlık kod yüklemeleri yapan martini uygulamalarıdır.\n\n## Katkıda Bulunmak\nMartini'nin temiz ve düzenli olaması gerekiyordu. \nMartini is meant to be kept tiny and clean. Tüm kullanıcılar katkı yapmak için [martini-contrib](https://github.com/martini-contrib) organizasyonunda yer alan repoları bitirmelidirler. Eğer martini core için katkıda bulunacaksanız fork işlemini yaparak başlayabilirsiniz.\n\n## Hakkında \n\n[express](https://github.com/visionmedia/express) ve [sinatra](https://github.com/sinatra/sinatra) projelerinden esinlenmiştir.\n\nMartini [Code Gangsta](http://codegangsta.io/) tarafından tasarlanılmıştır.\n"
  },
  {
    "path": "translations/README_zh_cn.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/174bef7e3c999e103cacfe2770102266 \"wercker status\")](https://app.wercker.com/project/bykey/174bef7e3c999e103cacfe2770102266) [![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini是一个强大为了编写模块化Web应用而生的GO语言框架.\n\n## 第一个应用\n\n在你安装了GO语言和设置了你的[GOPATH](http://golang.org/doc/code.html#GOPATH)之后, 创建你的自己的`.go`文件, 这里我们假设它的名字叫做 `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\n然后安装Martini的包. (注意Martini需要Go语言1.1或者以上的版本支持):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\n最后运行你的服务:\n~~~\ngo run server.go\n~~~\n\n这时你将会有一个Martini的服务监听了, 地址是: `localhost:3000`.\n\n## 获得帮助\n\n请加入: [邮件列表](https://groups.google.com/forum/#!forum/martini-go)\n\n或者可以查看在线演示地址: [演示视频](http://martini.codegangsta.io/#demo)\n\n## 功能列表\n* 使用极其简单.\n* 无侵入式的设计.\n* 很好的与其他的Go语言包协同使用.\n* 超赞的路径匹配和路由.\n* 模块化的设计 - 容易插入功能件，也容易将其拔出来.\n* 已有很多的中间件可以直接使用.\n* 框架内已拥有很好的开箱即用的功能支持.\n* **完全兼容[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)接口.**\n\n## 更多中间件\n更多的中间件和功能组件, 请查看代码仓库: [martini-contrib](https://github.com/martini-contrib).\n\n## 目录\n* [核心 Martini](#classic-martini)\n  * [处理器](#handlers)\n  * [路由](#routing)\n  * [服务](#services)\n  * [服务静态文件](#serving-static-files)\n* [中间件处理器](#middleware-handlers)\n  * [Next()](#next)\n* [常见问答](#faq)\n\n## 核心 Martini\n为了更快速的启用Martini, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 提供了一些默认的方便Web开发的工具:\n~~~ go\n  m := martini.Classic()\n  // ... middleware and routing goes here\n  m.Run()\n~~~\n\n下面是Martini核心已经包含的功能 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * Request/Response Logging （请求/响应日志） - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery （容错） - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Static File serving （静态文件服务） - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routing （路由） - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### 处理器\n处理器是Martini的灵魂和核心所在. 一个处理器基本上可以是任何的函数:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### 返回值\n当一个处理器返回结果的时候, Martini将会把返回值作为字符串写入到当前的[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)里面:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\n另外你也可以选择性的返回多一个状态码:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### 服务的注入\n处理器是通过反射来调用的. Martini 通过*Dependency Injection* *（依赖注入）* 来为处理器注入参数列表. **这样使得Martini与Go语言的`http.HandlerFunc`接口完全兼容.**\n\n如果你加入一个参数到你的处理器, Martini将会搜索它参数列表中的服务，并且通过类型判断来解决依赖关系:\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是通过Martini注入的\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\n下面的这些服务已经被包含在核心Martini中: [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [*log.Logger](http://godoc.org/log#Logger) - Martini的全局日志.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context （请求上下文）.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. （名字和参数键值对的参数列表）\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. （路由协助处理）\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. (响应结果的流接口)\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request. （http请求)\n\n### 路由\n在Martini中, 路由是一个HTTP方法配对一个URL匹配模型. 每一个路由可以对应一个或多个处理器方法:\n~~~ go\nm.Get(\"/\", func() {\n  // 显示\n})\n\nm.Patch(\"/\", func() {\n  // 更新\n})\n\nm.Post(\"/\", func() {\n  // 创建\n})\n\nm.Put(\"/\", func() {\n  // 替换\n})\n\nm.Delete(\"/\", func() {\n  // 删除\n})\n\nm.Options(\"/\", func() {\n  // http 选项\n})\n\nm.NotFound(func() {\n  // 处理 404\n})\n~~~\n\n路由匹配的顺序是按照他们被定义的顺序执行的. 最先被定义的路由将会首先被用户请求匹配并调用.\n\n路由模型可能包含参数列表, 可以通过[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)服务来获取:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\n路由匹配可以通过正则表达式或者glob的形式:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\n也可以这样使用正则表达式:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\n有关正则表达式的更多信息请参见[Go官方文档](http://golang.org/pkg/regexp/syntax/).\n\n\n路由处理器可以被相互叠加使用, 例如很有用的地方可以是在验证和授权的时候:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // 该方法将会在authorize方法没有输出结果的时候执行.\n})\n~~~\n\n也可以通过 Group 方法, 将 route 编成一組.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\n就像为 handler 增加 middleware 方法一样, 你也可以为一组 routes 增加 middleware.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### 服务\n服务即是被注入到处理器中的参数. 你可以映射一个服务到 *全局* 或者 *请求* 的级别.\n\n\n#### 全局映射\n如果一个Martini实现了inject.Injector的接口, 那么映射成为一个服务就非常简单:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // *MyDatabase 这个服务将可以在所有的处理器中被使用到.\n// ...\nm.Run()\n~~~\n\n#### 请求级别的映射\n映射在请求级别的服务可以用[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)来完成:\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // 映射成为了 *MyCustomLogger\n}\n~~~\n\n#### 映射值到接口\n关于服务最强悍的地方之一就是它能够映射服务到接口. 例如说, 假设你想要覆盖[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)成为一个对象, 那么你可以封装它并包含你自己的额外操作, 你可以如下这样来编写你的处理器:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // 覆盖 ResponseWriter 成为我们封装过的 ResponseWriter\n}\n~~~\n\n### 服务静态文件\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 默认会服务位于你服务器环境根目录下的\"public\"文件夹.\n你可以通过加入[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)的处理器来加入更多的静态文件服务的文件夹.\n~~~ go\nm.Use(martini.Static(\"assets\")) // 也会服务静态文件于\"assets\"的文件夹\n~~~\n\n## 中间件处理器\n中间件处理器是工作于请求和路由之间的. 本质上来说和Martini其他的处理器没有分别. 你可以像如下这样添加一个中间件处理器到它的堆中:\n~~~ go\nm.Use(func() {\n  // 做一些中间件该做的事情\n})\n~~~\n\n你可以通过`Handlers`函数对中间件堆有完全的控制. 它将会替换掉之前的任何设置过的处理器:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\n中间件处理器可以非常好处理一些功能，像logging(日志), authorization(授权), authentication(认证), sessions(会话), error pages(错误页面), 以及任何其他的操作需要在http请求发生之前或者之后的:\n\n~~~ go\n// 验证api密匙\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)是一个可选的函数用于中间件处理器暂时放弃执行直到其他的处理器都执行完毕. 这样就可以很好的处理在http请求完成后需要做的操作.\n~~~ go\n// log 记录请求完成前后  (*译者注: 很巧妙，掌声鼓励.)\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"before a request\")\n\n  c.Next()\n\n  log.Println(\"after a request\")\n})\n~~~\n\n## Martini Env\n一些handler使用环境变量 `martini.Env` 对开发环境和生产环境提供特殊功能. 推荐在生产环境设置环境变量 `MARTINI_ENV=production`.\n\n\n## 常见问答\n\n### 我在哪里可以找到中间件资源?\n\n可以查看 [martini-contrib](https://github.com/martini-contrib) 项目. 如果看了觉得没有什么好货色, 可以联系martini-contrib的团队成员为你创建一个新的代码资源库.\n\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析`Accept-Language` HTTP报头的处理器。\n* [accessflags](https://github.com/martini-contrib/accessflags) - 启用访问控制处理器.\n* [auth](https://github.com/martini-contrib/auth) - 认证处理器。\n* [binding](https://github.com/martini-contrib/binding) - 映射/验证raw请求到结构体(structure)里的处理器。\n* [cors](https://github.com/martini-contrib/cors) - 提供支持 CORS 的处理器。\n* [csrf](https://github.com/martini-contrib/csrf) - 为应用提供CSRF防护。\n* [encoder](https://github.com/martini-contrib/encoder) - 提供用于多种格式的数据渲染或内容协商的编码服务。\n* [gzip](https://github.com/martini-contrib/gzip) - 通过giz方式压缩请求信息的处理器。\n* [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic 中间件\n* [logstasher](https://github.com/martini-contrib/logstasher) - logstash日志兼容JSON中间件 \n* [method](https://github.com/martini-contrib/method) - 通过请求头或表单域覆盖HTTP方法。\n* [oauth2](https://github.com/martini-contrib/oauth2) - 基于 OAuth 2.0 的应用登录处理器。支持谷歌、Facebook和Github的登录。\n* [permissions2](https://github.com/xyproto/permissions2) - 跟踪用户，登录状态和权限控制器\n* [render](https://github.com/martini-contrib/render) - 渲染JSON和HTML模板的处理器。\n* [secure](https://github.com/martini-contrib/secure) - 提供一些安全方面的速效方案。\n* [sessions](https://github.com/martini-contrib/sessions) - 提供`Session`服务支持的处理器。\n* [sessionauth](https://github.com/martini-contrib/sessionauth) - 提供简单的方式使得路由需要登录, 并在Session中处理用户登录\n* [strip](https://github.com/martini-contrib/strip) - 用于过滤指定的URL前缀。\n* [strip](https://github.com/martini-contrib/strip) - URL前缀剥离。\n* [staticbin](https://github.com/martini-contrib/staticbin) - 从二进制数据中提供静态文件服务的处理器。\n* [throttle](https://github.com/martini-contrib/throttle) - 请求速率调节中间件.\n* [vauth](https://github.com/rafecolton/vauth) - 负责webhook认证的处理器(目前支持GitHub和TravisCI)。\n* [web](https://github.com/martini-contrib/web) - hoisie web.go's Context\n\n### 我如何整合到我现有的服务器中?\n\n由于Martini实现了 `http.Handler`, 所以它可以很简单的应用到现有Go服务器的子集中. 例如说这是一段在Google App Engine中的示例:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### 我如何修改port/host?\n\nMartini的`Run`函数会检查PORT和HOST的环境变量并使用它们. 否则Martini将会默认使用localhost:3000\n如果想要自定义PORT和HOST, 使用`martini.RunOnAddr`函数来代替.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  m.RunOnAddr(\":8080\")\n~~~\n\n## 贡献\nMartini项目想要保持简单且干净的代码. 大部分的代码应该贡献到[martini-contrib](https://github.com/martini-contrib)组织中作为一个项目. 如果你想要贡献Martini的核心代码也可以发起一个Pull Request.\n\n## 关于\n\n灵感来自于 [express](https://github.com/visionmedia/express) 和 [sinatra](https://github.com/sinatra/sinatra)\n\nMartini作者 [Code Gangsta](http://codegangsta.io/)\n译者: [Leon](http://github.com/leonli)\n"
  },
  {
    "path": "translations/README_zh_tw.md",
    "content": "# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\nMartini 是一個使用 Go 語言來快速開發模組化 Web 應用程式或服務的強大套件\n\n## 開始\n\n在您安裝Go語言以及設定好\n[GOPATH](http://golang.org/doc/code.html#GOPATH)環境變數後,\n開始寫您第一支`.go`檔, 我們將稱它為`server.go`\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello 世界!\"\n  })\n  m.Run()\n}\n~~~\n\n然後安裝Martini套件 (**go 1.1**以上的版本是必要的)\n~~~\ngo get github.com/go-martini/martini\n~~~\n\n然後利用以下指令執行你的程式:\n~~~\ngo run server.go\n~~~\n\n此時, 您將會看到一個 Martini Web 伺服器在`localhost:3000`上執行\n\n## 尋求幫助\n\n可以加入 [Mailing list](https://groups.google.com/forum/#!forum/martini-go)\n\n觀看 [Demo Video](http://martini.codegangsta.io/#demo)\n\n## 功能\n\n* 超容易使用\n* 非侵入式設計\n* 很容易跟其他Go套件同時使用\n* 很棒的路徑matching和routing方式\n* 模組化設計 - 容易增加或移除功能\n* 有很多handlers或middlewares可以直接使用\n* 已經提供很多內建功能\n* **跟[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 介面**完全相容\n* 預設document服務 (例如, 提供AngularJS在HTML5模式的服務)\n\n## 其他Middleware\n尋找更多的middleware或功能, 請到  [martini-contrib](https://github.com/martini-contrib)程式集搜尋\n\n## 目錄\n* [Classic Martini](#classic-martini)\n* [Handlers](#handlers)\n* [Routing](#routing)\n* [Services (服務)](#services)\n* [Serving Static Files (伺服靜態檔案)](#serving-static-files)\n* [Middleware Handlers](#middleware-handlers)\n* [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ (常見問題與答案)](#faq)\n\n## Classic Martini\n\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)\n提供大部份web應用程式所需要的基本預設功能:\n\n~~~ go\n  m := martini.Classic()\n  // ... middleware 或 routing 寫在這裡\n  m.Run()\n~~~\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)\n 會自動提供以下功能\n* Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n* Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n* Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n* Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n\n### Handlers\nHandlers 是 Martini 的核心, 每個 handler 就是一個基本的呼叫函式, 例如:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello 世界\")\n})\n~~~\n\n#### 回傳值\n如果一個 handler 有回傳值, Martini就會用字串的方式將結果寫回現在的\n[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 例如:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello 世界\" // HTTP 200 : \"hello 世界\"\n})\n~~~\n\n你也可以選擇回傳狀態碼, 例如:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"我是一個茶壺\" // HTTP 418 : \"我是一個茶壺\"\n})\n~~~\n\n#### 注入服務 (Service Injection)\nHandlers 是透過 reflection 方式被喚起, Martini 使用 *Dependency Injection* 的方法\n載入 Handler 變數所需要的相關物件 **這也是 Martini 跟 Go 語言`http.HandlerFunc`介面\n完全相容的原因**\n\n如果你在 Handler 裡加入一個變數, Martini 會嘗試著從它的服務清單裡透過 type assertion\n方式將相關物件載入\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是由 Martini 注入\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\n[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 包含以下物件:\n  * [*log.Logger](http://godoc.org/log#Logger) - Martini 的全區域 Logger.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request 內文.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper 服務.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http 回應 writer 介面.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http 請求.\n\n### Routing\n在 Martini 裡, 一個 route 就是一個 HTTP 方法與其 URL 的比對模式.\n每個 route 可以有ㄧ或多個 handler 方法:\n~~~ go\nm.Get(\"/\", func() {\n  // 顯示（值）\n})\n\nm.Patch(\"/\", func() {\n  // 更新\n})\n\nm.Post(\"/\", func() {\n  // 產生\n})\n\nm.Put(\"/\", func() {\n  // 取代\n})\n\nm.Delete(\"/\", func() {\n  // 刪除\n})\n\nm.Options(\"/\", func() {\n  // http 選項\n})\n\nm.NotFound(func() {\n  // handle 404\n})\n~~~\n\nRoutes 依照它們被定義時的順序做比對. 第一個跟請求 (request) 相同的 route 就被執行.\n\nRoute 比對模式可以包含變數部分, 可以透過 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) 物件來取值:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nRoutes 也可以用 \"**\" 來配對, 例如:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\n也可以用正規表示法 (regular expressions) 來做比對, 例如:\n~~~go\nm.Get(\"/hello/(?P<name>[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\n更多有關正規表示法文法的資訊, 請參考 [Go 文件](http://golang.org/pkg/regexp/syntax/).\n\nRoute handlers 也可以相互堆疊, 尤其是認證與授權相當好用:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // 這裏開始處理授權問題, 而非寫出回應\n})\n~~~\n\n也可以用 Group 方法, 將 route 編成一組.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\n跟對 handler 增加 middleware 方法一樣, 你也可以為一組 routes 增加 middleware.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Services\n服務是一些物件可以被注入 Handler 變數裡的東西, 可以分對應到 *Global* 或 *Request* 兩種等級.\n\n#### Global Mapping (全域級對應)\n一個 Martini 實體 (instance) 實現了 inject.Injector 介面, 所以非常容易對應到所需要的服務, 例如:\n~~~ go\ndb := &MyDatabase{}\nm := martini.Classic()\nm.Map(db) // 所以 *MyDatabase 就可以被所有的 handlers 使用\n// ...\nm.Run()\n~~~\n\n#### Request-Level Mapping (請求級對應)\n如果只在一個 handler 裡定義, 透由  [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) 獲得一個請求 (request) 級的對應:\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := &MyCustomLogger{req}\n  c.Map(logger) // 對應到 *MyCustomLogger\n}\n~~~\n\n#### 透由介面對應\n有關服務, 最強的部分是它還能對應到一個介面 (interface), 例如,\n如果你想要包裹並增加一個變數而改寫 (override) 原有的 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 你的 handler 可以寫成:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // 我們包裹的 ResponseWriter 蓋掉原始的 ResponseWrite\n}\n~~~\n\n### Serving Static Files\n一個[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 實體會將伺服器根目錄下 public 子目錄裡的檔案自動當成靜態檔案處理. 你也可以手動用 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 增加其他目錄, 例如.\n~~~ go\nm.Use(martini.Static(\"assets\")) // \"assets\" 子目錄裡, 也視為靜態檔案\n~~~\n\n#### Serving a Default Document\n當某些 URL 找不到時, 你也可以指定本地檔案的 URL 來顯示.\n你也可以用開頭除外 (exclusion prefix) 的方式, 來忽略某些 URLs,\n它尤其在某些伺服器同時伺服靜態檔案, 而且還有額外 handlers 處理 (例如 REST API) 時, 特別好用.\n比如說, 在比對找不到之後, 想要用靜態檔來處理特別好用.\n\n以下範例, 就是在 URL 開頭不是`/api/v`而且也不是本地檔案的情況下, 顯示`/index.html`檔:\n~~~ go\nstatic := martini.Static(\"assets\", martini.StaticOptions{Fallback: \"/index.html\", Exclude: \"/api/v\"})\nm.NotFound(static, http.NotFound)\n~~~\n\n## Middleware Handlers\nMiddleware Handlers 位於進來的 http 請求與 router 之間, 在 Martini 裡, 本質上它跟其他\n Handler 沒有什麼不同, 例如, 你可加入一個 middleware 方法如下\n~~~ go\nm.Use(func() {\n  // 做 middleware 的事\n})\n~~~\n\n你也可以用`Handlers`完全控制 middelware 層, 把先前設定的 handlers 都替換掉, 例如:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nMiddleware Handlers 成被拿來處理 http 請求之前和之後的事, 尤其是用來紀錄logs, 授權, 認證,\nsessions, 壓縮 （gzipping), 顯示錯誤頁面等等, 都非常好用, 例如:\n~~~ go\n// validate an api key\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) 是 Middleware Handlers 可以呼叫的選項功能, 用來等到其他 handlers 處理完再開始執行.\n它常常被用來處理那些必須在 http 請求之後才能發生的事件, 例如:\n~~~ go\n// 在請求前後加 logs\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"before a request\")\n\n  c.Next()\n\n  log.Println(\"after a request\")\n})\n~~~\n\n## Martini Env\n\n有些 Martini handlers 使用 `martini.Env` 全區域變數, 來當成開發環境或是上架 (production)\n環境的設定判斷. 建議用 `MARTINI_ENV=production` 環境變數來設定 Martini 伺服器是上架與否.\n\n## FAQ\n\n### 我去哪可以找到 middleware X?\n\n可以從 [martini-contrib](https://github.com/martini-contrib) 裡的專案找起.\n如果那裡沒有, 請與 martini-contrib 團隊聯絡, 將它加入.\n\n* [auth](https://github.com/martini-contrib/auth) - 處理認證的 Handler.\n* [binding](https://github.com/martini-contrib/binding) -\n處理一個單純的請求對應到一個結構體與確認內容正確與否的 Handler.\n* [gzip](https://github.com/martini-contrib/gzip) - 對請求加 gzip 壓縮的 Handler.\n* [render](https://github.com/martini-contrib/render) - 提供簡單處理 JSON 和\nHTML 樣板成形 (rendering) 的 Handler.\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析 `Accept-Language` HTTP 檔頭的 Handler.\n* [sessions](https://github.com/martini-contrib/sessions) - 提供 Session 服務的 Handler.\n* [strip](https://github.com/martini-contrib/strip) - URL 字頭處理 (Prefix stripping).\n* [method](https://github.com/martini-contrib/method) - 透過 Header 或表格 (form) 欄位蓋過 HTTP 方法 (method).\n* [secure](https://github.com/martini-contrib/secure) - 提供一些簡單的安全機制.\n* [encoder](https://github.com/martini-contrib/encoder) - 轉換資料格式之 Encoder 服務.\n* [cors](https://github.com/martini-contrib/cors) - 啟動支援 CORS 之 Handler.\n* [oauth2](https://github.com/martini-contrib/oauth2) - 讓 Martini 應用程式能提供 OAuth 2.0 登入的 Handler. 其中支援 Google 登錄, Facebook Connect 與 Github 的登入等.\n* [vauth](https://github.com/rafecolton/vauth) - 處理 vender webhook 認證的 Handler (目前支援 GitHub 以及 TravisCI)\n\n### 我如何整合到現有的伺服器?\n\nMartini 實作 `http.Handler`,所以可以非常容易整合到現有的 Go 伺服器裡.\n以下寫法, 是一個能在 Google App Engine 上運行的 Martini 應用程式:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### 我要如何改變 port/host?\n\nMartini 的 `Run` 功能會看 PORT 及 HOST 當時的環境變數, 否則 Martini 會用 localhost:3000\n當預設值. 讓 port 及 host 更有彈性, 可以用 `martini.RunOnAddr` 取代.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  log.Fatal(m.RunOnAddr(\":8080\"))\n~~~\n\n### 可以線上更新 (live reload) 嗎?\n\n[gin](https://github.com/codegangsta/gin) 和 [fresh](https://github.com/pilu/fresh) 可以幫 Martini 程式做到線上更新.\n\n## 貢獻\nMartini 盡量保持小而美的精神, 大多數的程式貢獻者可以在 [martini-contrib](https://github.com/martini-contrib) 組織提供代碼. 如果你想要對 Martini 核心提出貢獻, 請丟出 Pull Request.\n\n## 關於\n\n靈感來自與 [express](https://github.com/visionmedia/express) 以及 [sinatra](https://github.com/sinatra/sinatra)\n\nMartini 由 [Code Gangsta](http://codegangsta.io/) 公司設計出品 (著魔地)\n"
  },
  {
    "path": "wercker.yml",
    "content": "box: wercker/golang@1.1.1"
  }
]