├── .gitignore ├── Godeps └── Godeps.json ├── LICENSE ├── README.md ├── env.go ├── env_test.go ├── go_version.go ├── logger.go ├── logger_test.go ├── martini.go ├── martini_test.go ├── recovery.go ├── recovery_test.go ├── response_writer.go ├── response_writer_test.go ├── return_handler.go ├── router.go ├── router_test.go ├── static.go ├── static_test.go ├── translations ├── README_de_DE.md ├── README_es_ES.md ├── README_fr_FR.md ├── README_ja_JP.md ├── README_ko_kr.md ├── README_pl_PL.md ├── README_pt_br.md ├── README_ru_RU.md ├── README_tr_TR.md ├── README_zh_cn.md └── README_zh_tw.md └── wercker.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | 25 | /.godeps 26 | /.envrc 27 | 28 | # Godeps 29 | Godeps/_workspace 30 | Godeps/Readme 31 | 32 | ### JetBrains template 33 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 34 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 35 | 36 | .idea/ 37 | 38 | ## File-based project format: 39 | *.iws 40 | 41 | ## Plugin-specific files: 42 | 43 | # IntelliJ 44 | /out/ 45 | 46 | # mpeltonen/sbt-idea plugin 47 | .idea_modules/ 48 | 49 | # JIRA plugin 50 | atlassian-ide-plugin.xml 51 | 52 | # Crashlytics plugin (for Android Studio and IntelliJ) 53 | com_crashlytics_export_strings.xml 54 | crashlytics.properties 55 | crashlytics-build.properties 56 | fabric.properties 57 | -------------------------------------------------------------------------------- /Godeps/Godeps.json: -------------------------------------------------------------------------------- 1 | { 2 | "ImportPath": "github.com/go-martini/martini", 3 | "GoVersion": "go1.4.2", 4 | "Deps": [ 5 | { 6 | "ImportPath": "github.com/codegangsta/inject", 7 | "Comment": "v1.0-rc1-10-g33e0aa1", 8 | "Rev": "33e0aa1cb7c019ccc3fbe049a8262a6403d30504" 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Jeremy Saenz 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | ### **NOTE:** The martini framework is no longer maintained. 4 | 5 | Martini is a powerful package for quickly writing modular web applications/services in Golang. 6 | 7 | Language Translations: 8 | * [繁體中文](translations/README_zh_tw.md) 9 | * [简体中文](translations/README_zh_cn.md) 10 | * [Português Brasileiro (pt_BR)](translations/README_pt_br.md) 11 | * [Español](translations/README_es_ES.md) 12 | * [한국어 번역](translations/README_ko_kr.md) 13 | * [Русский](translations/README_ru_RU.md) 14 | * [日本語](translations/README_ja_JP.md) 15 | * [French](translations/README_fr_FR.md) 16 | * [Turkish](translations/README_tr_TR.md) 17 | * [German](translations/README_de_DE.md) 18 | * [Polski](translations/README_pl_PL.md) 19 | 20 | ## Getting Started 21 | 22 | After 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`. 23 | 24 | ~~~ go 25 | package main 26 | 27 | import "github.com/go-martini/martini" 28 | 29 | func main() { 30 | m := martini.Classic() 31 | m.Get("/", func() string { 32 | return "Hello world!" 33 | }) 34 | m.Run() 35 | } 36 | ~~~ 37 | 38 | Then install the Martini package (**go 1.1** or greater is required): 39 | ~~~ 40 | go get github.com/go-martini/martini 41 | ~~~ 42 | 43 | Then run your server: 44 | ~~~ 45 | go run server.go 46 | ~~~ 47 | 48 | You will now have a Martini webserver running on `localhost:3000`. 49 | 50 | ## Getting Help 51 | 52 | Join the [Mailing list](https://groups.google.com/forum/#!forum/martini-go) 53 | 54 | Watch the [Demo Video](http://martini.codegangsta.io/#demo) 55 | 56 | Ask questions on Stackoverflow using the [martini tag](http://stackoverflow.com/questions/tagged/martini) 57 | 58 | GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) 59 | 60 | 61 | ## Features 62 | * Extremely simple to use. 63 | * Non-intrusive design. 64 | * Plays nice with other Golang packages. 65 | * Awesome path matching and routing. 66 | * Modular design - Easy to add functionality, easy to rip stuff out. 67 | * Lots of good handlers/middlewares to use. 68 | * Great 'out of the box' feature set. 69 | * **Fully compatible with the [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) interface.** 70 | * Default document serving (e.g., for serving AngularJS apps in HTML5 mode). 71 | 72 | ## More Middleware 73 | For more middleware and functionality, check out the repositories in the [martini-contrib](https://github.com/martini-contrib) organization. 74 | 75 | ## Table of Contents 76 | * [Classic Martini](#classic-martini) 77 | * [Handlers](#handlers) 78 | * [Routing](#routing) 79 | * [Services](#services) 80 | * [Serving Static Files](#serving-static-files) 81 | * [Middleware Handlers](#middleware-handlers) 82 | * [Next()](#next) 83 | * [Martini Env](#martini-env) 84 | * [FAQ](#faq) 85 | 86 | ## Classic Martini 87 | To 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: 88 | ~~~ go 89 | m := martini.Classic() 90 | // ... middleware and routing goes here 91 | m.Run() 92 | ~~~ 93 | 94 | Below is some of the functionality [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) pulls in automatically: 95 | * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 96 | * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 97 | * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 98 | * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 99 | 100 | ### Handlers 101 | Handlers are the heart and soul of Martini. A handler is basically any kind of callable function: 102 | ~~~ go 103 | m.Get("/", func() { 104 | println("hello world") 105 | }) 106 | ~~~ 107 | 108 | #### Return Values 109 | If a handler returns something, Martini will write the result to the current [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) as a string: 110 | ~~~ go 111 | m.Get("/", func() string { 112 | return "hello world" // HTTP 200 : "hello world" 113 | }) 114 | ~~~ 115 | 116 | You can also optionally return a status code: 117 | ~~~ go 118 | m.Get("/", func() (int, string) { 119 | return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" 120 | }) 121 | ~~~ 122 | 123 | #### Service Injection 124 | Handlers are invoked via reflection. Martini makes use of *Dependency Injection* to resolve dependencies in a Handlers argument list. **This makes Martini completely compatible with golang's `http.HandlerFunc` interface.** 125 | 126 | If you add an argument to your Handler, Martini will search its list of services and attempt to resolve the dependency via type assertion: 127 | ~~~ go 128 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini 129 | res.WriteHeader(200) // HTTP 200 130 | }) 131 | ~~~ 132 | 133 | The following services are included with [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 134 | * [*log.Logger](http://godoc.org/log#Logger) - Global logger for Martini. 135 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. 136 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. 137 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. 138 | * [martini.Route](http://godoc.org/github.com/go-martini/martini#Route) - Current active route. 139 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. 140 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request. 141 | 142 | ### Routing 143 | In Martini, a route is an HTTP method paired with a URL-matching pattern. 144 | Each route can take one or more handler methods: 145 | ~~~ go 146 | m.Get("/", func() { 147 | // show something 148 | }) 149 | 150 | m.Patch("/", func() { 151 | // update something 152 | }) 153 | 154 | m.Post("/", func() { 155 | // create something 156 | }) 157 | 158 | m.Put("/", func() { 159 | // replace something 160 | }) 161 | 162 | m.Delete("/", func() { 163 | // destroy something 164 | }) 165 | 166 | m.Options("/", func() { 167 | // http options 168 | }) 169 | 170 | m.NotFound(func() { 171 | // handle 404 172 | }) 173 | ~~~ 174 | 175 | Routes are matched in the order they are defined. The first route that 176 | matches the request is invoked. 177 | 178 | Route patterns may include named parameters, accessible via the [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service: 179 | ~~~ go 180 | m.Get("/hello/:name", func(params martini.Params) string { 181 | return "Hello " + params["name"] 182 | }) 183 | ~~~ 184 | 185 | Routes can be matched with globs: 186 | ~~~ go 187 | m.Get("/hello/**", func(params martini.Params) string { 188 | return "Hello " + params["_1"] 189 | }) 190 | ~~~ 191 | 192 | Regular expressions can be used as well: 193 | ~~~go 194 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 195 | return fmt.Sprintf ("Hello %s", params["name"]) 196 | }) 197 | ~~~ 198 | Take a look at the [Go documentation](http://golang.org/pkg/regexp/syntax/) for more info about regular expressions syntax . 199 | 200 | Route handlers can be stacked on top of each other, which is useful for things like authentication and authorization: 201 | ~~~ go 202 | m.Get("/secret", authorize, func() { 203 | // this will execute as long as authorize doesn't write a response 204 | }) 205 | ~~~ 206 | 207 | Route groups can be added too using the Group method. 208 | ~~~ go 209 | m.Group("/books", func(r martini.Router) { 210 | r.Get("/:id", GetBooks) 211 | r.Post("/new", NewBook) 212 | r.Put("/update/:id", UpdateBook) 213 | r.Delete("/delete/:id", DeleteBook) 214 | }) 215 | ~~~ 216 | 217 | Just like you can pass middlewares to a handler you can pass middlewares to groups. 218 | ~~~ go 219 | m.Group("/books", func(r martini.Router) { 220 | r.Get("/:id", GetBooks) 221 | r.Post("/new", NewBook) 222 | r.Put("/update/:id", UpdateBook) 223 | r.Delete("/delete/:id", DeleteBook) 224 | }, MyMiddleware1, MyMiddleware2) 225 | ~~~ 226 | 227 | ### Services 228 | Services 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. 229 | 230 | #### Global Mapping 231 | A Martini instance implements the inject.Injector interface, so mapping a service is easy: 232 | ~~~ go 233 | db := &MyDatabase{} 234 | m := martini.Classic() 235 | m.Map(db) // the service will be available to all handlers as *MyDatabase 236 | // ... 237 | m.Run() 238 | ~~~ 239 | 240 | #### Request-Level Mapping 241 | Mapping on the request level can be done in a handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): 242 | ~~~ go 243 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 244 | logger := &MyCustomLogger{req} 245 | c.Map(logger) // mapped as *MyCustomLogger 246 | } 247 | ~~~ 248 | 249 | #### Mapping values to Interfaces 250 | One of the most powerful parts about services is the ability to map a service to an interface. For instance, if you wanted to override 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: 251 | ~~~ go 252 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 253 | rw := NewSpecialResponseWriter(res) 254 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter 255 | } 256 | ~~~ 257 | 258 | ### Serving Static Files 259 | A [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. 260 | You can serve from more directories by adding more [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. 261 | ~~~ go 262 | m.Use(martini.Static("assets")) // serve from the "assets" directory as well 263 | ~~~ 264 | 265 | #### Serving a Default Document 266 | You can specify the URL of a local file to serve when the requested URL is not 267 | found. You can also specify an exclusion prefix so that certain URLs are ignored. 268 | This is useful for servers that serve both static files and have additional 269 | handlers defined (e.g., REST API). When doing so, it's useful to define the 270 | static handler as a part of the NotFound chain. 271 | 272 | The following example serves the `/index.html` file whenever any URL is 273 | requested that does not match any local file and does not start with `/api/v`: 274 | ~~~ go 275 | static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) 276 | m.NotFound(static, http.NotFound) 277 | ~~~ 278 | 279 | ## Middleware Handlers 280 | Middleware Handlers sit between the incoming http request and the router. In essence they are no different than any other Handler in Martini. You can add a middleware handler to the stack like so: 281 | ~~~ go 282 | m.Use(func() { 283 | // do some middleware stuff 284 | }) 285 | ~~~ 286 | 287 | You can have full control over the middleware stack with the `Handlers` function. This will replace any handlers that have been previously set: 288 | ~~~ go 289 | m.Handlers( 290 | Middleware1, 291 | Middleware2, 292 | Middleware3, 293 | ) 294 | ~~~ 295 | 296 | Middleware Handlers work really well for things like logging, authorization, authentication, sessions, gzipping, error pages and any other operations that must happen before or after an http request: 297 | ~~~ go 298 | // validate an api key 299 | m.Use(func(res http.ResponseWriter, req *http.Request) { 300 | if req.Header.Get("X-API-KEY") != "secret123" { 301 | res.WriteHeader(http.StatusUnauthorized) 302 | } 303 | }) 304 | ~~~ 305 | 306 | ### Next() 307 | [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: 308 | ~~~ go 309 | // log before and after a request 310 | m.Use(func(c martini.Context, log *log.Logger){ 311 | log.Println("before a request") 312 | 313 | c.Next() 314 | 315 | log.Println("after a request") 316 | }) 317 | ~~~ 318 | 319 | ## Martini Env 320 | 321 | Some 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. 322 | 323 | ## FAQ 324 | 325 | ### Where do I find middleware X? 326 | 327 | Start 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. 328 | 329 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. 330 | * [accessflags](https://github.com/martini-contrib/accessflags) - Handler to enable Access Control. 331 | * [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. 332 | * [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. 333 | * [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. 334 | * [csrf](https://github.com/martini-contrib/csrf) - CSRF protection for applications 335 | * [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. 336 | * [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests 337 | * [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic middleware 338 | * [logstasher](https://github.com/martini-contrib/logstasher) - Middleware that prints logstash-compatible JSON 339 | * [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. 340 | * [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. 341 | * [permissions2](https://github.com/xyproto/permissions2) - Handler for keeping track of users, login states and permissions. 342 | * [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. 343 | * [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. 344 | * [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. 345 | * [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 346 | * [strict](https://github.com/martini-contrib/strict) - Strict Mode 347 | * [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. 348 | * [staticbin](https://github.com/martini-contrib/staticbin) - Handler for serving static files from binary data 349 | * [throttle](https://github.com/martini-contrib/throttle) - Request rate throttling middleware. 350 | * [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI) 351 | * [web](https://github.com/martini-contrib/web) - hoisie web.go's Context 352 | 353 | ### How do I integrate with existing servers? 354 | 355 | A Martini instance implements `http.Handler`, so it can easily be used to serve subtrees 356 | on existing Go servers. For example this is a working Martini app for Google App Engine: 357 | 358 | ~~~ go 359 | package hello 360 | 361 | import ( 362 | "net/http" 363 | "github.com/go-martini/martini" 364 | ) 365 | 366 | func init() { 367 | m := martini.Classic() 368 | m.Get("/", func() string { 369 | return "Hello world!" 370 | }) 371 | http.Handle("/", m) 372 | } 373 | ~~~ 374 | 375 | ### How do I change the port/host? 376 | 377 | Martini's `Run` function looks for the PORT and HOST environment variables and uses those. Otherwise Martini will default to localhost:3000. 378 | To have more flexibility over port and host, use the `martini.RunOnAddr` function instead. 379 | 380 | ~~~ go 381 | m := martini.Classic() 382 | // ... 383 | m.RunOnAddr(":8080") 384 | ~~~ 385 | 386 | ### Live code reload? 387 | 388 | [gin](https://github.com/codegangsta/gin) and [fresh](https://github.com/pilu/fresh) both live reload martini apps. 389 | 390 | ## Contributing 391 | Martini 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. 392 | 393 | ## License 394 | Martini is distributed by The MIT License, see LICENSE 395 | 396 | ## About 397 | 398 | Inspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra) 399 | 400 | Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) 401 | -------------------------------------------------------------------------------- /env.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "os" 5 | ) 6 | 7 | // Envs 8 | const ( 9 | Dev string = "development" 10 | Prod string = "production" 11 | Test string = "test" 12 | ) 13 | 14 | // Env is the environment that Martini is executing in. The MARTINI_ENV is read on initialization to set this variable. 15 | var Env = Dev 16 | var Root string 17 | 18 | func setENV(e string) { 19 | if len(e) > 0 { 20 | Env = e 21 | } 22 | } 23 | 24 | func init() { 25 | setENV(os.Getenv("MARTINI_ENV")) 26 | var err error 27 | Root, err = os.Getwd() 28 | if err != nil { 29 | panic(err) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /env_test.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_SetENV(t *testing.T) { 8 | tests := []struct { 9 | in string 10 | out string 11 | }{ 12 | {"", "development"}, 13 | {"not_development", "not_development"}, 14 | } 15 | 16 | for _, test := range tests { 17 | setENV(test.in) 18 | if Env != test.out { 19 | expect(t, Env, test.out) 20 | } 21 | } 22 | } 23 | 24 | func Test_Root(t *testing.T) { 25 | if len(Root) == 0 { 26 | t.Errorf("Expected root path will be set") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /go_version.go: -------------------------------------------------------------------------------- 1 | // +build !go1.1 2 | 3 | package martini 4 | 5 | func MartiniDoesNotSupportGo1Point0() { 6 | "Martini requires Go 1.1 or greater." 7 | } 8 | -------------------------------------------------------------------------------- /logger.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "time" 7 | ) 8 | 9 | // Logger returns a middleware handler that logs the request as it goes in and the response as it goes out. 10 | func Logger() Handler { 11 | return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) { 12 | start := time.Now() 13 | 14 | addr := req.Header.Get("X-Real-IP") 15 | if addr == "" { 16 | addr = req.Header.Get("X-Forwarded-For") 17 | if addr == "" { 18 | addr = req.RemoteAddr 19 | } 20 | } 21 | 22 | log.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr) 23 | 24 | rw := res.(ResponseWriter) 25 | c.Next() 26 | 27 | log.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start)) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /logger_test.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "bytes" 5 | "log" 6 | "net/http" 7 | "net/http/httptest" 8 | "testing" 9 | ) 10 | 11 | func Test_Logger(t *testing.T) { 12 | buff := bytes.NewBufferString("") 13 | recorder := httptest.NewRecorder() 14 | 15 | m := New() 16 | // replace log for testing 17 | m.Map(log.New(buff, "[martini] ", 0)) 18 | m.Use(Logger()) 19 | m.Use(func(res http.ResponseWriter) { 20 | res.WriteHeader(http.StatusNotFound) 21 | }) 22 | 23 | req, err := http.NewRequest("GET", "http://localhost:3000/foobar", nil) 24 | if err != nil { 25 | t.Error(err) 26 | } 27 | 28 | m.ServeHTTP(recorder, req) 29 | expect(t, recorder.Code, http.StatusNotFound) 30 | refute(t, len(buff.String()), 0) 31 | } 32 | -------------------------------------------------------------------------------- /martini.go: -------------------------------------------------------------------------------- 1 | // Package martini is a powerful package for quickly writing modular web applications/services in Golang. 2 | // 3 | // For a full guide visit http://github.com/go-martini/martini 4 | // 5 | // package main 6 | // 7 | // import "github.com/go-martini/martini" 8 | // 9 | // func main() { 10 | // m := martini.Classic() 11 | // 12 | // m.Get("/", func() string { 13 | // return "Hello world!" 14 | // }) 15 | // 16 | // m.Run() 17 | // } 18 | package martini 19 | 20 | import ( 21 | "log" 22 | "net/http" 23 | "os" 24 | "reflect" 25 | 26 | "github.com/codegangsta/inject" 27 | ) 28 | 29 | // Martini represents the top level web application. inject.Injector methods can be invoked to map services on a global level. 30 | type Martini struct { 31 | inject.Injector 32 | handlers []Handler 33 | action Handler 34 | logger *log.Logger 35 | } 36 | 37 | // New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used. 38 | func New() *Martini { 39 | m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)} 40 | m.Map(m.logger) 41 | m.Map(defaultReturnHandler()) 42 | return m 43 | } 44 | 45 | // Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers. 46 | // Will panic if any of the handlers is not a callable function 47 | func (m *Martini) Handlers(handlers ...Handler) { 48 | m.handlers = make([]Handler, 0) 49 | for _, handler := range handlers { 50 | m.Use(handler) 51 | } 52 | } 53 | 54 | // 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(). 55 | func (m *Martini) Action(handler Handler) { 56 | validateHandler(handler) 57 | m.action = handler 58 | } 59 | 60 | // Logger sets the logger 61 | func (m *Martini) Logger(logger *log.Logger) { 62 | m.logger = logger 63 | m.Map(m.logger) 64 | } 65 | 66 | // 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. 67 | func (m *Martini) Use(handler Handler) { 68 | validateHandler(handler) 69 | 70 | m.handlers = append(m.handlers, handler) 71 | } 72 | 73 | // ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server. 74 | func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) { 75 | m.createContext(res, req).run() 76 | } 77 | 78 | // Run the http server on a given host and port. 79 | func (m *Martini) RunOnAddr(addr string) { 80 | // TODO: Should probably be implemented using a new instance of http.Server in place of 81 | // calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use. 82 | // This would also allow to improve testing when a custom host and port are passed. 83 | 84 | logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger) 85 | logger.Printf("listening on %s (%s)\n", addr, Env) 86 | logger.Fatalln(http.ListenAndServe(addr, m)) 87 | } 88 | 89 | // Run the http server. Listening on os.GetEnv("PORT") or 3000 by default. 90 | func (m *Martini) Run() { 91 | port := os.Getenv("PORT") 92 | if len(port) == 0 { 93 | port = "3000" 94 | } 95 | 96 | host := os.Getenv("HOST") 97 | 98 | m.RunOnAddr(host + ":" + port) 99 | } 100 | 101 | func (m *Martini) createContext(res http.ResponseWriter, req *http.Request) *context { 102 | c := &context{inject.New(), m.handlers, m.action, NewResponseWriter(res), 0} 103 | c.SetParent(m) 104 | c.MapTo(c, (*Context)(nil)) 105 | c.MapTo(c.rw, (*http.ResponseWriter)(nil)) 106 | c.Map(req) 107 | return c 108 | } 109 | 110 | // ClassicMartini represents a Martini with some reasonable defaults. Embeds the router functions for convenience. 111 | type ClassicMartini struct { 112 | *Martini 113 | Router 114 | } 115 | 116 | // Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static. 117 | // Classic also maps martini.Routes as a service. 118 | func Classic() *ClassicMartini { 119 | r := NewRouter() 120 | m := New() 121 | m.Use(Logger()) 122 | m.Use(Recovery()) 123 | m.Use(Static("public")) 124 | m.MapTo(r, (*Routes)(nil)) 125 | m.Action(r.Handle) 126 | return &ClassicMartini{m, r} 127 | } 128 | 129 | // Handler can be any callable function. Martini attempts to inject services into the handler's argument list. 130 | // Martini will panic if an argument could not be fullfilled via dependency injection. 131 | type Handler interface{} 132 | 133 | func validateHandler(handler Handler) { 134 | if reflect.TypeOf(handler).Kind() != reflect.Func { 135 | panic("martini handler must be a callable func") 136 | } 137 | } 138 | 139 | // Context represents a request context. Services can be mapped on the request level from this interface. 140 | type Context interface { 141 | inject.Injector 142 | // Next is an optional function that Middleware Handlers can call to yield the until after 143 | // the other Handlers have been executed. This works really well for any operations that must 144 | // happen after an http request 145 | Next() 146 | // Written returns whether or not the response for this context has been written. 147 | Written() bool 148 | } 149 | 150 | type context struct { 151 | inject.Injector 152 | handlers []Handler 153 | action Handler 154 | rw ResponseWriter 155 | index int 156 | } 157 | 158 | func (c *context) handler() Handler { 159 | if c.index < len(c.handlers) { 160 | return c.handlers[c.index] 161 | } 162 | if c.index == len(c.handlers) { 163 | return c.action 164 | } 165 | panic("invalid index for context handler") 166 | } 167 | 168 | func (c *context) Next() { 169 | c.index += 1 170 | c.run() 171 | } 172 | 173 | func (c *context) Written() bool { 174 | return c.rw.Written() 175 | } 176 | 177 | func (c *context) run() { 178 | for c.index <= len(c.handlers) { 179 | _, err := c.Invoke(c.handler()) 180 | if err != nil { 181 | panic(err) 182 | } 183 | c.index += 1 184 | 185 | if c.Written() { 186 | return 187 | } 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /martini_test.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "net/http" 5 | "net/http/httptest" 6 | "reflect" 7 | "testing" 8 | ) 9 | 10 | /* Test Helpers */ 11 | func expect(t *testing.T, a interface{}, b interface{}) { 12 | if a != b { 13 | t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) 14 | } 15 | } 16 | 17 | func refute(t *testing.T, a interface{}, b interface{}) { 18 | if a == b { 19 | t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) 20 | } 21 | } 22 | 23 | func Test_New(t *testing.T) { 24 | m := New() 25 | if m == nil { 26 | t.Error("martini.New() cannot return nil") 27 | } 28 | } 29 | 30 | func Test_Martini_RunOnAddr(t *testing.T) { 31 | // just test that Run doesn't bomb 32 | go New().RunOnAddr("127.0.0.1:8080") 33 | } 34 | 35 | func Test_Martini_Run(t *testing.T) { 36 | go New().Run() 37 | } 38 | 39 | func Test_Martini_ServeHTTP(t *testing.T) { 40 | result := "" 41 | response := httptest.NewRecorder() 42 | 43 | m := New() 44 | m.Use(func(c Context) { 45 | result += "foo" 46 | c.Next() 47 | result += "ban" 48 | }) 49 | m.Use(func(c Context) { 50 | result += "bar" 51 | c.Next() 52 | result += "baz" 53 | }) 54 | m.Action(func(res http.ResponseWriter, req *http.Request) { 55 | result += "bat" 56 | res.WriteHeader(http.StatusBadRequest) 57 | }) 58 | 59 | m.ServeHTTP(response, (*http.Request)(nil)) 60 | 61 | expect(t, result, "foobarbatbazban") 62 | expect(t, response.Code, http.StatusBadRequest) 63 | } 64 | 65 | func Test_Martini_Handlers(t *testing.T) { 66 | result := "" 67 | response := httptest.NewRecorder() 68 | 69 | batman := func(c Context) { 70 | result += "batman!" 71 | } 72 | 73 | m := New() 74 | m.Use(func(c Context) { 75 | result += "foo" 76 | c.Next() 77 | result += "ban" 78 | }) 79 | m.Handlers( 80 | batman, 81 | batman, 82 | batman, 83 | ) 84 | m.Action(func(res http.ResponseWriter, req *http.Request) { 85 | result += "bat" 86 | res.WriteHeader(http.StatusBadRequest) 87 | }) 88 | 89 | m.ServeHTTP(response, (*http.Request)(nil)) 90 | 91 | expect(t, result, "batman!batman!batman!bat") 92 | expect(t, response.Code, http.StatusBadRequest) 93 | } 94 | 95 | func Test_Martini_EarlyWrite(t *testing.T) { 96 | result := "" 97 | response := httptest.NewRecorder() 98 | 99 | m := New() 100 | m.Use(func(res http.ResponseWriter) { 101 | result += "foobar" 102 | res.Write([]byte("Hello world")) 103 | }) 104 | m.Use(func() { 105 | result += "bat" 106 | }) 107 | m.Action(func(res http.ResponseWriter) { 108 | result += "baz" 109 | res.WriteHeader(http.StatusBadRequest) 110 | }) 111 | 112 | m.ServeHTTP(response, (*http.Request)(nil)) 113 | 114 | expect(t, result, "foobar") 115 | expect(t, response.Code, http.StatusOK) 116 | } 117 | 118 | func Test_Martini_Written(t *testing.T) { 119 | response := httptest.NewRecorder() 120 | 121 | m := New() 122 | m.Handlers(func(res http.ResponseWriter) { 123 | res.WriteHeader(http.StatusOK) 124 | }) 125 | 126 | ctx := m.createContext(response, (*http.Request)(nil)) 127 | expect(t, ctx.Written(), false) 128 | 129 | ctx.run() 130 | expect(t, ctx.Written(), true) 131 | } 132 | 133 | func Test_Martini_Basic_NoRace(t *testing.T) { 134 | m := New() 135 | handlers := []Handler{func() {}, func() {}} 136 | // Ensure append will not realloc to trigger the race condition 137 | m.handlers = handlers[:1] 138 | req, _ := http.NewRequest("GET", "/", nil) 139 | for i := 0; i < 2; i++ { 140 | go func() { 141 | response := httptest.NewRecorder() 142 | m.ServeHTTP(response, req) 143 | }() 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /recovery.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io/ioutil" 7 | "log" 8 | "net/http" 9 | "runtime" 10 | 11 | "github.com/codegangsta/inject" 12 | ) 13 | 14 | const ( 15 | panicHtml = ` 16 | PANIC: %s 17 | 37 | 38 |

PANIC

39 |
%s
40 |
%s
41 | 42 | ` 43 | ) 44 | 45 | var ( 46 | dunno = []byte("???") 47 | centerDot = []byte("·") 48 | dot = []byte(".") 49 | slash = []byte("/") 50 | ) 51 | 52 | // stack returns a nicely formated stack frame, skipping skip frames 53 | func stack(skip int) []byte { 54 | buf := new(bytes.Buffer) // the returned data 55 | // As we loop, we open files and read them. These variables record the currently 56 | // loaded file. 57 | var lines [][]byte 58 | var lastFile string 59 | for i := skip; ; i++ { // Skip the expected number of frames 60 | pc, file, line, ok := runtime.Caller(i) 61 | if !ok { 62 | break 63 | } 64 | // Print this much at least. If we can't find the source, it won't show. 65 | fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) 66 | if file != lastFile { 67 | data, err := ioutil.ReadFile(file) 68 | if err != nil { 69 | continue 70 | } 71 | lines = bytes.Split(data, []byte{'\n'}) 72 | lastFile = file 73 | } 74 | fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) 75 | } 76 | return buf.Bytes() 77 | } 78 | 79 | // source returns a space-trimmed slice of the n'th line. 80 | func source(lines [][]byte, n int) []byte { 81 | n-- // in stack trace, lines are 1-indexed but our array is 0-indexed 82 | if n < 0 || n >= len(lines) { 83 | return dunno 84 | } 85 | return bytes.TrimSpace(lines[n]) 86 | } 87 | 88 | // function returns, if possible, the name of the function containing the PC. 89 | func function(pc uintptr) []byte { 90 | fn := runtime.FuncForPC(pc) 91 | if fn == nil { 92 | return dunno 93 | } 94 | name := []byte(fn.Name()) 95 | // The name includes the path name to the package, which is unnecessary 96 | // since the file name is already included. Plus, it has center dots. 97 | // That is, we see 98 | // runtime/debug.*T·ptrmethod 99 | // and want 100 | // *T.ptrmethod 101 | // Also the package path might contains dot (e.g. code.google.com/...), 102 | // so first eliminate the path prefix 103 | if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 { 104 | name = name[lastslash+1:] 105 | } 106 | if period := bytes.Index(name, dot); period >= 0 { 107 | name = name[period+1:] 108 | } 109 | name = bytes.Replace(name, centerDot, dot, -1) 110 | return name 111 | } 112 | 113 | // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. 114 | // While Martini is in development mode, Recovery will also output the panic as HTML. 115 | func Recovery() Handler { 116 | return func(c Context, log *log.Logger) { 117 | defer func() { 118 | if err := recover(); err != nil { 119 | stack := stack(3) 120 | log.Printf("PANIC: %s\n%s", err, stack) 121 | 122 | // Lookup the current responsewriter 123 | val := c.Get(inject.InterfaceOf((*http.ResponseWriter)(nil))) 124 | res := val.Interface().(http.ResponseWriter) 125 | 126 | // respond with panic message while in development mode 127 | var body []byte 128 | if Env == Dev { 129 | res.Header().Set("Content-Type", "text/html") 130 | body = []byte(fmt.Sprintf(panicHtml, err, err, stack)) 131 | } else { 132 | body = []byte("500 Internal Server Error") 133 | } 134 | 135 | res.WriteHeader(http.StatusInternalServerError) 136 | if nil != body { 137 | res.Write(body) 138 | } 139 | } 140 | }() 141 | 142 | c.Next() 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /recovery_test.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "bytes" 5 | "log" 6 | "net/http" 7 | "net/http/httptest" 8 | "testing" 9 | ) 10 | 11 | func Test_Recovery(t *testing.T) { 12 | buff := bytes.NewBufferString("") 13 | recorder := httptest.NewRecorder() 14 | 15 | setENV(Dev) 16 | m := New() 17 | // replace log for testing 18 | m.Map(log.New(buff, "[martini] ", 0)) 19 | m.Use(func(res http.ResponseWriter, req *http.Request) { 20 | res.Header().Set("Content-Type", "unpredictable") 21 | }) 22 | m.Use(Recovery()) 23 | m.Use(func(res http.ResponseWriter, req *http.Request) { 24 | panic("here is a panic!") 25 | }) 26 | m.ServeHTTP(recorder, (*http.Request)(nil)) 27 | expect(t, recorder.Code, http.StatusInternalServerError) 28 | expect(t, recorder.HeaderMap.Get("Content-Type"), "text/html") 29 | refute(t, recorder.Body.Len(), 0) 30 | refute(t, len(buff.String()), 0) 31 | } 32 | 33 | func Test_Recovery_ResponseWriter(t *testing.T) { 34 | recorder := httptest.NewRecorder() 35 | recorder2 := httptest.NewRecorder() 36 | 37 | setENV(Dev) 38 | m := New() 39 | m.Use(Recovery()) 40 | m.Use(func(c Context) { 41 | c.MapTo(recorder2, (*http.ResponseWriter)(nil)) 42 | panic("here is a panic!") 43 | }) 44 | m.ServeHTTP(recorder, (*http.Request)(nil)) 45 | 46 | expect(t, recorder2.Code, http.StatusInternalServerError) 47 | expect(t, recorder2.HeaderMap.Get("Content-Type"), "text/html") 48 | refute(t, recorder2.Body.Len(), 0) 49 | } 50 | -------------------------------------------------------------------------------- /response_writer.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "net" 7 | "net/http" 8 | ) 9 | 10 | // ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about 11 | // the response. It is recommended that middleware handlers use this construct to wrap a responsewriter 12 | // if the functionality calls for it. 13 | type ResponseWriter interface { 14 | http.ResponseWriter 15 | http.Flusher 16 | http.Hijacker 17 | // Status returns the status code of the response or 0 if the response has not been written. 18 | Status() int 19 | // Written returns whether or not the ResponseWriter has been written. 20 | Written() bool 21 | // Size returns the size of the response body. 22 | Size() int 23 | // Before allows for a function to be called before the ResponseWriter has been written to. This is 24 | // useful for setting headers or any other operations that must happen before a response has been written. 25 | Before(BeforeFunc) 26 | } 27 | 28 | // BeforeFunc is a function that is called before the ResponseWriter has been written to. 29 | type BeforeFunc func(ResponseWriter) 30 | 31 | // NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter 32 | func NewResponseWriter(rw http.ResponseWriter) ResponseWriter { 33 | newRw := responseWriter{rw, 0, 0, nil} 34 | if cn, ok := rw.(http.CloseNotifier); ok { 35 | return &closeNotifyResponseWriter{newRw, cn} 36 | } 37 | return &newRw 38 | } 39 | 40 | type responseWriter struct { 41 | http.ResponseWriter 42 | status int 43 | size int 44 | beforeFuncs []BeforeFunc 45 | } 46 | 47 | func (rw *responseWriter) WriteHeader(s int) { 48 | rw.callBefore() 49 | rw.ResponseWriter.WriteHeader(s) 50 | rw.status = s 51 | } 52 | 53 | func (rw *responseWriter) Write(b []byte) (int, error) { 54 | if !rw.Written() { 55 | // The status will be StatusOK if WriteHeader has not been called yet 56 | rw.WriteHeader(http.StatusOK) 57 | } 58 | size, err := rw.ResponseWriter.Write(b) 59 | rw.size += size 60 | return size, err 61 | } 62 | 63 | func (rw *responseWriter) Status() int { 64 | return rw.status 65 | } 66 | 67 | func (rw *responseWriter) Size() int { 68 | return rw.size 69 | } 70 | 71 | func (rw *responseWriter) Written() bool { 72 | return rw.status != 0 73 | } 74 | 75 | func (rw *responseWriter) Before(before BeforeFunc) { 76 | rw.beforeFuncs = append(rw.beforeFuncs, before) 77 | } 78 | 79 | func (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { 80 | hijacker, ok := rw.ResponseWriter.(http.Hijacker) 81 | if !ok { 82 | return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface") 83 | } 84 | return hijacker.Hijack() 85 | } 86 | 87 | func (rw *responseWriter) callBefore() { 88 | for i := len(rw.beforeFuncs) - 1; i >= 0; i-- { 89 | rw.beforeFuncs[i](rw) 90 | } 91 | } 92 | 93 | func (rw *responseWriter) Flush() { 94 | flusher, ok := rw.ResponseWriter.(http.Flusher) 95 | if ok { 96 | flusher.Flush() 97 | } 98 | } 99 | 100 | type closeNotifyResponseWriter struct { 101 | responseWriter 102 | closeNotifier http.CloseNotifier 103 | } 104 | 105 | func (rw *closeNotifyResponseWriter) CloseNotify() <-chan bool { 106 | return rw.closeNotifier.CloseNotify() 107 | } 108 | -------------------------------------------------------------------------------- /response_writer_test.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | "net" 7 | "net/http" 8 | "net/http/httptest" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | type closeNotifyingRecorder struct { 14 | *httptest.ResponseRecorder 15 | closed chan bool 16 | } 17 | 18 | func newCloseNotifyingRecorder() *closeNotifyingRecorder { 19 | return &closeNotifyingRecorder{ 20 | httptest.NewRecorder(), 21 | make(chan bool, 1), 22 | } 23 | } 24 | 25 | func (c *closeNotifyingRecorder) close() { 26 | c.closed <- true 27 | } 28 | 29 | func (c *closeNotifyingRecorder) CloseNotify() <-chan bool { 30 | return c.closed 31 | } 32 | 33 | type hijackableResponse struct { 34 | Hijacked bool 35 | } 36 | 37 | func newHijackableResponse() *hijackableResponse { 38 | return &hijackableResponse{} 39 | } 40 | 41 | func (h *hijackableResponse) Header() http.Header { return nil } 42 | func (h *hijackableResponse) Write(buf []byte) (int, error) { return 0, nil } 43 | func (h *hijackableResponse) WriteHeader(code int) {} 44 | func (h *hijackableResponse) Flush() {} 45 | func (h *hijackableResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) { 46 | h.Hijacked = true 47 | return nil, nil, nil 48 | } 49 | 50 | func Test_ResponseWriter_WritingString(t *testing.T) { 51 | rec := httptest.NewRecorder() 52 | rw := NewResponseWriter(rec) 53 | 54 | rw.Write([]byte("Hello world")) 55 | 56 | expect(t, rec.Code, rw.Status()) 57 | expect(t, rec.Body.String(), "Hello world") 58 | expect(t, rw.Status(), http.StatusOK) 59 | expect(t, rw.Size(), 11) 60 | expect(t, rw.Written(), true) 61 | } 62 | 63 | func Test_ResponseWriter_WritingStrings(t *testing.T) { 64 | rec := httptest.NewRecorder() 65 | rw := NewResponseWriter(rec) 66 | 67 | rw.Write([]byte("Hello world")) 68 | rw.Write([]byte("foo bar bat baz")) 69 | 70 | expect(t, rec.Code, rw.Status()) 71 | expect(t, rec.Body.String(), "Hello worldfoo bar bat baz") 72 | expect(t, rw.Status(), http.StatusOK) 73 | expect(t, rw.Size(), 26) 74 | } 75 | 76 | func Test_ResponseWriter_WritingHeader(t *testing.T) { 77 | rec := httptest.NewRecorder() 78 | rw := NewResponseWriter(rec) 79 | 80 | rw.WriteHeader(http.StatusNotFound) 81 | 82 | expect(t, rec.Code, rw.Status()) 83 | expect(t, rec.Body.String(), "") 84 | expect(t, rw.Status(), http.StatusNotFound) 85 | expect(t, rw.Size(), 0) 86 | } 87 | 88 | func Test_ResponseWriter_Before(t *testing.T) { 89 | rec := httptest.NewRecorder() 90 | rw := NewResponseWriter(rec) 91 | result := "" 92 | 93 | rw.Before(func(ResponseWriter) { 94 | result += "foo" 95 | }) 96 | rw.Before(func(ResponseWriter) { 97 | result += "bar" 98 | }) 99 | 100 | rw.WriteHeader(http.StatusNotFound) 101 | 102 | expect(t, rec.Code, rw.Status()) 103 | expect(t, rec.Body.String(), "") 104 | expect(t, rw.Status(), http.StatusNotFound) 105 | expect(t, rw.Size(), 0) 106 | expect(t, result, "barfoo") 107 | } 108 | 109 | func Test_ResponseWriter_Hijack(t *testing.T) { 110 | hijackable := newHijackableResponse() 111 | rw := NewResponseWriter(hijackable) 112 | hijacker, ok := rw.(http.Hijacker) 113 | expect(t, ok, true) 114 | _, _, err := hijacker.Hijack() 115 | if err != nil { 116 | t.Error(err) 117 | } 118 | expect(t, hijackable.Hijacked, true) 119 | } 120 | 121 | func Test_ResponseWrite_Hijack_NotOK(t *testing.T) { 122 | hijackable := new(http.ResponseWriter) 123 | rw := NewResponseWriter(*hijackable) 124 | hijacker, ok := rw.(http.Hijacker) 125 | expect(t, ok, true) 126 | _, _, err := hijacker.Hijack() 127 | 128 | refute(t, err, nil) 129 | } 130 | 131 | func Test_ResponseWriter_CloseNotify(t *testing.T) { 132 | rec := newCloseNotifyingRecorder() 133 | rw := NewResponseWriter(rec) 134 | closed := false 135 | notifier := rw.(http.CloseNotifier).CloseNotify() 136 | rec.close() 137 | select { 138 | case <-notifier: 139 | closed = true 140 | case <-time.After(time.Second): 141 | } 142 | expect(t, closed, true) 143 | } 144 | 145 | func Test_ResponseWriter_Flusher(t *testing.T) { 146 | 147 | rec := httptest.NewRecorder() 148 | rw := NewResponseWriter(rec) 149 | 150 | _, ok := rw.(http.Flusher) 151 | expect(t, ok, true) 152 | } 153 | 154 | func Test_ResponseWriter_FlusherHandler(t *testing.T) { 155 | 156 | // New martini instance 157 | m := Classic() 158 | 159 | m.Get("/events", func(w http.ResponseWriter, r *http.Request) { 160 | 161 | f, ok := w.(http.Flusher) 162 | expect(t, ok, true) 163 | 164 | w.Header().Set("Content-Type", "text/event-stream") 165 | w.Header().Set("Cache-Control", "no-cache") 166 | w.Header().Set("Connection", "keep-alive") 167 | 168 | for i := 0; i < 2; i++ { 169 | time.Sleep(10 * time.Millisecond) 170 | io.WriteString(w, "data: Hello\n\n") 171 | f.Flush() 172 | } 173 | 174 | }) 175 | 176 | recorder := httptest.NewRecorder() 177 | r, _ := http.NewRequest("GET", "/events", nil) 178 | m.ServeHTTP(recorder, r) 179 | 180 | if recorder.Code != 200 { 181 | t.Error("Response not 200") 182 | } 183 | 184 | if recorder.Body.String() != "data: Hello\n\ndata: Hello\n\n" { 185 | t.Error("Didn't receive correct body, got:", recorder.Body.String()) 186 | } 187 | 188 | } 189 | -------------------------------------------------------------------------------- /return_handler.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "github.com/codegangsta/inject" 5 | "net/http" 6 | "reflect" 7 | ) 8 | 9 | // ReturnHandler is a service that Martini provides that is called 10 | // when a route handler returns something. The ReturnHandler is 11 | // responsible for writing to the ResponseWriter based on the values 12 | // that are passed into this function. 13 | type ReturnHandler func(Context, []reflect.Value) 14 | 15 | func defaultReturnHandler() ReturnHandler { 16 | return func(ctx Context, vals []reflect.Value) { 17 | rv := ctx.Get(inject.InterfaceOf((*http.ResponseWriter)(nil))) 18 | res := rv.Interface().(http.ResponseWriter) 19 | var responseVal reflect.Value 20 | if len(vals) > 1 && vals[0].Kind() == reflect.Int { 21 | res.WriteHeader(int(vals[0].Int())) 22 | responseVal = vals[1] 23 | } else if len(vals) > 0 { 24 | responseVal = vals[0] 25 | } 26 | if canDeref(responseVal) { 27 | responseVal = responseVal.Elem() 28 | } 29 | if isByteSlice(responseVal) { 30 | res.Write(responseVal.Bytes()) 31 | } else { 32 | res.Write([]byte(responseVal.String())) 33 | } 34 | } 35 | } 36 | 37 | func isByteSlice(val reflect.Value) bool { 38 | return val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8 39 | } 40 | 41 | func canDeref(val reflect.Value) bool { 42 | return val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr 43 | } 44 | -------------------------------------------------------------------------------- /router.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "reflect" 7 | "regexp" 8 | "strconv" 9 | "sync" 10 | ) 11 | 12 | // 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. 13 | type Params map[string]string 14 | 15 | // Router is Martini's de-facto routing interface. Supports HTTP verbs, stacked handlers, and dependency injection. 16 | type Router interface { 17 | Routes 18 | 19 | // Group adds a group where related routes can be added. 20 | Group(string, func(Router), ...Handler) 21 | // Get adds a route for a HTTP GET request to the specified matching pattern. 22 | Get(string, ...Handler) Route 23 | // Patch adds a route for a HTTP PATCH request to the specified matching pattern. 24 | Patch(string, ...Handler) Route 25 | // Post adds a route for a HTTP POST request to the specified matching pattern. 26 | Post(string, ...Handler) Route 27 | // Put adds a route for a HTTP PUT request to the specified matching pattern. 28 | Put(string, ...Handler) Route 29 | // Delete adds a route for a HTTP DELETE request to the specified matching pattern. 30 | Delete(string, ...Handler) Route 31 | // Options adds a route for a HTTP OPTIONS request to the specified matching pattern. 32 | Options(string, ...Handler) Route 33 | // Head adds a route for a HTTP HEAD request to the specified matching pattern. 34 | Head(string, ...Handler) Route 35 | // Any adds a route for any HTTP method request to the specified matching pattern. 36 | Any(string, ...Handler) Route 37 | // AddRoute adds a route for a given HTTP method request to the specified matching pattern. 38 | AddRoute(string, string, ...Handler) Route 39 | 40 | // NotFound sets the handlers that are called when a no route matches a request. Throws a basic 404 by default. 41 | NotFound(...Handler) 42 | 43 | // Handle is the entry point for routing. This is used as a martini.Handler 44 | Handle(http.ResponseWriter, *http.Request, Context) 45 | } 46 | 47 | type router struct { 48 | routes []*route 49 | notFounds []Handler 50 | groups []group 51 | routesLock sync.RWMutex 52 | } 53 | 54 | type group struct { 55 | pattern string 56 | handlers []Handler 57 | } 58 | 59 | // NewRouter creates a new Router instance. 60 | // If you aren't using ClassicMartini, then you can add Routes as a 61 | // service with: 62 | // 63 | // m := martini.New() 64 | // r := martini.NewRouter() 65 | // m.MapTo(r, (*martini.Routes)(nil)) 66 | // 67 | // If you are using ClassicMartini, then this is done for you. 68 | func NewRouter() Router { 69 | return &router{notFounds: []Handler{http.NotFound}, groups: make([]group, 0)} 70 | } 71 | 72 | func (r *router) Group(pattern string, fn func(Router), h ...Handler) { 73 | r.groups = append(r.groups, group{pattern, h}) 74 | fn(r) 75 | r.groups = r.groups[:len(r.groups)-1] 76 | } 77 | 78 | func (r *router) Get(pattern string, h ...Handler) Route { 79 | return r.addRoute("GET", pattern, h) 80 | } 81 | 82 | func (r *router) Patch(pattern string, h ...Handler) Route { 83 | return r.addRoute("PATCH", pattern, h) 84 | } 85 | 86 | func (r *router) Post(pattern string, h ...Handler) Route { 87 | return r.addRoute("POST", pattern, h) 88 | } 89 | 90 | func (r *router) Put(pattern string, h ...Handler) Route { 91 | return r.addRoute("PUT", pattern, h) 92 | } 93 | 94 | func (r *router) Delete(pattern string, h ...Handler) Route { 95 | return r.addRoute("DELETE", pattern, h) 96 | } 97 | 98 | func (r *router) Options(pattern string, h ...Handler) Route { 99 | return r.addRoute("OPTIONS", pattern, h) 100 | } 101 | 102 | func (r *router) Head(pattern string, h ...Handler) Route { 103 | return r.addRoute("HEAD", pattern, h) 104 | } 105 | 106 | func (r *router) Any(pattern string, h ...Handler) Route { 107 | return r.addRoute("*", pattern, h) 108 | } 109 | 110 | func (r *router) AddRoute(method, pattern string, h ...Handler) Route { 111 | return r.addRoute(method, pattern, h) 112 | } 113 | 114 | func (r *router) Handle(res http.ResponseWriter, req *http.Request, context Context) { 115 | bestMatch := NoMatch 116 | var bestVals map[string]string 117 | var bestRoute *route 118 | for _, route := range r.getRoutes() { 119 | match, vals := route.Match(req.Method, req.URL.Path) 120 | if match.BetterThan(bestMatch) { 121 | bestMatch = match 122 | bestVals = vals 123 | bestRoute = route 124 | if match == ExactMatch { 125 | break 126 | } 127 | } 128 | } 129 | if bestMatch != NoMatch { 130 | params := Params(bestVals) 131 | context.Map(params) 132 | bestRoute.Handle(context, res) 133 | return 134 | } 135 | 136 | // no routes exist, 404 137 | c := &routeContext{context, 0, r.notFounds} 138 | context.MapTo(c, (*Context)(nil)) 139 | c.run() 140 | } 141 | 142 | func (r *router) NotFound(handler ...Handler) { 143 | r.notFounds = handler 144 | } 145 | 146 | func (r *router) addRoute(method string, pattern string, handlers []Handler) *route { 147 | if len(r.groups) > 0 { 148 | groupPattern := "" 149 | h := make([]Handler, 0) 150 | for _, g := range r.groups { 151 | groupPattern += g.pattern 152 | h = append(h, g.handlers...) 153 | } 154 | 155 | pattern = groupPattern + pattern 156 | h = append(h, handlers...) 157 | handlers = h 158 | } 159 | 160 | route := newRoute(method, pattern, handlers) 161 | route.Validate() 162 | r.appendRoute(route) 163 | return route 164 | } 165 | 166 | func (r *router) appendRoute(rt *route) { 167 | r.routesLock.Lock() 168 | defer r.routesLock.Unlock() 169 | r.routes = append(r.routes, rt) 170 | } 171 | 172 | func (r *router) getRoutes() []*route { 173 | r.routesLock.RLock() 174 | defer r.routesLock.RUnlock() 175 | return r.routes[:] 176 | } 177 | 178 | func (r *router) findRoute(name string) *route { 179 | for _, route := range r.getRoutes() { 180 | if route.name == name { 181 | return route 182 | } 183 | } 184 | 185 | return nil 186 | } 187 | 188 | // Route is an interface representing a Route in Martini's routing layer. 189 | type Route interface { 190 | // URLWith returns a rendering of the Route's url with the given string params. 191 | URLWith([]string) string 192 | // Name sets a name for the route. 193 | Name(string) 194 | // GetName returns the name of the route. 195 | GetName() string 196 | // Pattern returns the pattern of the route. 197 | Pattern() string 198 | // Method returns the method of the route. 199 | Method() string 200 | } 201 | 202 | type route struct { 203 | method string 204 | regex *regexp.Regexp 205 | handlers []Handler 206 | pattern string 207 | name string 208 | } 209 | 210 | var routeReg1 = regexp.MustCompile(`:[^/#?()\.\\]+`) 211 | var routeReg2 = regexp.MustCompile(`\*\*`) 212 | 213 | func newRoute(method string, pattern string, handlers []Handler) *route { 214 | route := route{method, nil, handlers, pattern, ""} 215 | pattern = routeReg1.ReplaceAllStringFunc(pattern, func(m string) string { 216 | return fmt.Sprintf(`(?P<%s>[^/#?]+)`, m[1:]) 217 | }) 218 | var index int 219 | pattern = routeReg2.ReplaceAllStringFunc(pattern, func(m string) string { 220 | index++ 221 | return fmt.Sprintf(`(?P<_%d>[^#?]*)`, index) 222 | }) 223 | pattern += `\/?` 224 | route.regex = regexp.MustCompile(pattern) 225 | return &route 226 | } 227 | 228 | type RouteMatch int 229 | 230 | const ( 231 | NoMatch RouteMatch = iota 232 | StarMatch 233 | OverloadMatch 234 | ExactMatch 235 | ) 236 | 237 | //Higher number = better match 238 | func (r RouteMatch) BetterThan(o RouteMatch) bool { 239 | return r > o 240 | } 241 | 242 | func (r route) MatchMethod(method string) RouteMatch { 243 | switch { 244 | case method == r.method: 245 | return ExactMatch 246 | case method == "HEAD" && r.method == "GET": 247 | return OverloadMatch 248 | case r.method == "*": 249 | return StarMatch 250 | default: 251 | return NoMatch 252 | } 253 | } 254 | 255 | func (r route) Match(method string, path string) (RouteMatch, map[string]string) { 256 | // add Any method matching support 257 | match := r.MatchMethod(method) 258 | if match == NoMatch { 259 | return match, nil 260 | } 261 | 262 | matches := r.regex.FindStringSubmatch(path) 263 | if len(matches) > 0 && matches[0] == path { 264 | params := make(map[string]string) 265 | for i, name := range r.regex.SubexpNames() { 266 | if len(name) > 0 { 267 | params[name] = matches[i] 268 | } 269 | } 270 | return match, params 271 | } 272 | return NoMatch, nil 273 | } 274 | 275 | func (r *route) Validate() { 276 | for _, handler := range r.handlers { 277 | validateHandler(handler) 278 | } 279 | } 280 | 281 | func (r *route) Handle(c Context, res http.ResponseWriter) { 282 | context := &routeContext{c, 0, r.handlers} 283 | c.MapTo(context, (*Context)(nil)) 284 | c.MapTo(r, (*Route)(nil)) 285 | context.run() 286 | } 287 | 288 | var urlReg = regexp.MustCompile(`:[^/#?()\.\\]+|\(\?P<[a-zA-Z0-9]+>.*\)`) 289 | 290 | // URLWith returns the url pattern replacing the parameters for its values 291 | func (r *route) URLWith(args []string) string { 292 | if len(args) > 0 { 293 | argCount := len(args) 294 | i := 0 295 | url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string { 296 | var val interface{} 297 | if i < argCount { 298 | val = args[i] 299 | } else { 300 | val = m 301 | } 302 | i += 1 303 | return fmt.Sprintf(`%v`, val) 304 | }) 305 | 306 | return url 307 | } 308 | return r.pattern 309 | } 310 | 311 | func (r *route) Name(name string) { 312 | r.name = name 313 | } 314 | 315 | func (r *route) GetName() string { 316 | return r.name 317 | } 318 | 319 | func (r *route) Pattern() string { 320 | return r.pattern 321 | } 322 | 323 | func (r *route) Method() string { 324 | return r.method 325 | } 326 | 327 | // Routes is a helper service for Martini's routing layer. 328 | type Routes interface { 329 | // URLFor returns a rendered URL for the given route. Optional params can be passed to fulfill named parameters in the route. 330 | URLFor(name string, params ...interface{}) string 331 | // MethodsFor returns an array of methods available for the path 332 | MethodsFor(path string) []string 333 | // All returns an array with all the routes in the router. 334 | All() []Route 335 | } 336 | 337 | // URLFor returns the url for the given route name. 338 | func (r *router) URLFor(name string, params ...interface{}) string { 339 | route := r.findRoute(name) 340 | 341 | if route == nil { 342 | panic("route not found") 343 | } 344 | 345 | var args []string 346 | for _, param := range params { 347 | switch v := param.(type) { 348 | case int: 349 | args = append(args, strconv.FormatInt(int64(v), 10)) 350 | case string: 351 | args = append(args, v) 352 | default: 353 | if v != nil { 354 | panic("Arguments passed to URLFor must be integers or strings") 355 | } 356 | } 357 | } 358 | 359 | return route.URLWith(args) 360 | } 361 | 362 | func (r *router) All() []Route { 363 | routes := r.getRoutes() 364 | var ri = make([]Route, len(routes)) 365 | 366 | for i, route := range routes { 367 | ri[i] = Route(route) 368 | } 369 | 370 | return ri 371 | } 372 | 373 | func hasMethod(methods []string, method string) bool { 374 | for _, v := range methods { 375 | if v == method { 376 | return true 377 | } 378 | } 379 | return false 380 | } 381 | 382 | // MethodsFor returns all methods available for path 383 | func (r *router) MethodsFor(path string) []string { 384 | methods := []string{} 385 | for _, route := range r.getRoutes() { 386 | matches := route.regex.FindStringSubmatch(path) 387 | if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) { 388 | methods = append(methods, route.method) 389 | } 390 | } 391 | return methods 392 | } 393 | 394 | type routeContext struct { 395 | Context 396 | index int 397 | handlers []Handler 398 | } 399 | 400 | func (r *routeContext) Next() { 401 | r.index += 1 402 | r.run() 403 | } 404 | 405 | func (r *routeContext) run() { 406 | for r.index < len(r.handlers) { 407 | handler := r.handlers[r.index] 408 | vals, err := r.Invoke(handler) 409 | if err != nil { 410 | panic(err) 411 | } 412 | r.index += 1 413 | 414 | // if the handler returned something, write it to the http response 415 | if len(vals) > 0 { 416 | ev := r.Get(reflect.TypeOf(ReturnHandler(nil))) 417 | handleReturn := ev.Interface().(ReturnHandler) 418 | handleReturn(r, vals) 419 | } 420 | 421 | if r.Written() { 422 | return 423 | } 424 | } 425 | } 426 | -------------------------------------------------------------------------------- /router_test.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "net/http" 5 | "net/http/httptest" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | func Test_Routing(t *testing.T) { 11 | router := NewRouter() 12 | recorder := httptest.NewRecorder() 13 | 14 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 15 | context := New().createContext(recorder, req) 16 | 17 | req2, _ := http.NewRequest("POST", "http://localhost:3000/bar/bat", nil) 18 | context2 := New().createContext(recorder, req2) 19 | 20 | req3, _ := http.NewRequest("DELETE", "http://localhost:3000/baz", nil) 21 | context3 := New().createContext(recorder, req3) 22 | 23 | req4, _ := http.NewRequest("PATCH", "http://localhost:3000/bar/foo", nil) 24 | context4 := New().createContext(recorder, req4) 25 | 26 | req5, _ := http.NewRequest("GET", "http://localhost:3000/fez/this/should/match", nil) 27 | context5 := New().createContext(recorder, req5) 28 | 29 | req6, _ := http.NewRequest("PUT", "http://localhost:3000/pop/blah/blah/blah/bap/foo/", nil) 30 | context6 := New().createContext(recorder, req6) 31 | 32 | req7, _ := http.NewRequest("DELETE", "http://localhost:3000/wap//pow", nil) 33 | context7 := New().createContext(recorder, req7) 34 | 35 | req8, _ := http.NewRequest("HEAD", "http://localhost:3000/wap//pow", nil) 36 | context8 := New().createContext(recorder, req8) 37 | 38 | req9, _ := http.NewRequest("OPTIONS", "http://localhost:3000/opts", nil) 39 | context9 := New().createContext(recorder, req9) 40 | 41 | req10, _ := http.NewRequest("HEAD", "http://localhost:3000/foo", nil) 42 | context10 := New().createContext(recorder, req10) 43 | 44 | req11, _ := http.NewRequest("GET", "http://localhost:3000/bazz/inga", nil) 45 | context11 := New().createContext(recorder, req11) 46 | 47 | req12, _ := http.NewRequest("POST", "http://localhost:3000/bazz/inga", nil) 48 | context12 := New().createContext(recorder, req12) 49 | 50 | req13, _ := http.NewRequest("GET", "http://localhost:3000/bazz/in/ga", nil) 51 | context13 := New().createContext(recorder, req13) 52 | 53 | req14, _ := http.NewRequest("GET", "http://localhost:3000/bzz", nil) 54 | context14 := New().createContext(recorder, req14) 55 | 56 | result := "" 57 | router.Get("/foo", func(req *http.Request) { 58 | result += "foo" 59 | }) 60 | router.Patch("/bar/:id", func(params Params) { 61 | expect(t, params["id"], "foo") 62 | result += "barfoo" 63 | }) 64 | router.Post("/bar/:id", func(params Params) { 65 | expect(t, params["id"], "bat") 66 | result += "barbat" 67 | }) 68 | router.Put("/fizzbuzz", func() { 69 | result += "fizzbuzz" 70 | }) 71 | router.Delete("/bazzer", func(c Context) { 72 | result += "baz" 73 | }) 74 | router.Get("/fez/**", func(params Params) { 75 | expect(t, params["_1"], "this/should/match") 76 | result += "fez" 77 | }) 78 | router.Put("/pop/**/bap/:id/**", func(params Params) { 79 | expect(t, params["id"], "foo") 80 | expect(t, params["_1"], "blah/blah/blah") 81 | expect(t, params["_2"], "") 82 | result += "popbap" 83 | }) 84 | router.Delete("/wap/**/pow", func(params Params) { 85 | expect(t, params["_1"], "") 86 | result += "wappow" 87 | }) 88 | router.Options("/opts", func() { 89 | result += "opts" 90 | }) 91 | router.Head("/wap/**/pow", func(params Params) { 92 | expect(t, params["_1"], "") 93 | result += "wappow" 94 | }) 95 | router.Group("/bazz", func(r Router) { 96 | r.Get("/inga", func() { 97 | result += "get" 98 | }) 99 | 100 | r.Post("/inga", func() { 101 | result += "post" 102 | }) 103 | 104 | r.Group("/in", func(r Router) { 105 | r.Get("/ga", func() { 106 | result += "ception" 107 | }) 108 | }, func() { 109 | result += "group" 110 | }) 111 | }, func() { 112 | result += "bazz" 113 | }, func() { 114 | result += "inga" 115 | }) 116 | router.AddRoute("GET", "/bzz", func(c Context) { 117 | result += "bzz" 118 | }) 119 | 120 | router.Handle(recorder, req, context) 121 | router.Handle(recorder, req2, context2) 122 | router.Handle(recorder, req3, context3) 123 | router.Handle(recorder, req4, context4) 124 | router.Handle(recorder, req5, context5) 125 | router.Handle(recorder, req6, context6) 126 | router.Handle(recorder, req7, context7) 127 | router.Handle(recorder, req8, context8) 128 | router.Handle(recorder, req9, context9) 129 | router.Handle(recorder, req10, context10) 130 | router.Handle(recorder, req11, context11) 131 | router.Handle(recorder, req12, context12) 132 | router.Handle(recorder, req13, context13) 133 | router.Handle(recorder, req14, context14) 134 | expect(t, result, "foobarbatbarfoofezpopbapwappowwappowoptsfoobazzingagetbazzingapostbazzingagroupceptionbzz") 135 | expect(t, recorder.Code, http.StatusNotFound) 136 | expect(t, recorder.Body.String(), "404 page not found\n") 137 | } 138 | 139 | func Test_RouterHandlerStatusCode(t *testing.T) { 140 | router := NewRouter() 141 | router.Get("/foo", func() string { 142 | return "foo" 143 | }) 144 | router.Get("/bar", func() (int, string) { 145 | return http.StatusForbidden, "bar" 146 | }) 147 | router.Get("/baz", func() (string, string) { 148 | return "baz", "BAZ!" 149 | }) 150 | router.Get("/bytes", func() []byte { 151 | return []byte("Bytes!") 152 | }) 153 | router.Get("/interface", func() interface{} { 154 | return "Interface!" 155 | }) 156 | 157 | // code should be 200 if none is returned from the handler 158 | recorder := httptest.NewRecorder() 159 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 160 | context := New().createContext(recorder, req) 161 | router.Handle(recorder, req, context) 162 | expect(t, recorder.Code, http.StatusOK) 163 | expect(t, recorder.Body.String(), "foo") 164 | 165 | // if a status code is returned, it should be used 166 | recorder = httptest.NewRecorder() 167 | req, _ = http.NewRequest("GET", "http://localhost:3000/bar", nil) 168 | context = New().createContext(recorder, req) 169 | router.Handle(recorder, req, context) 170 | expect(t, recorder.Code, http.StatusForbidden) 171 | expect(t, recorder.Body.String(), "bar") 172 | 173 | // shouldn't use the first returned value as a status code if not an integer 174 | recorder = httptest.NewRecorder() 175 | req, _ = http.NewRequest("GET", "http://localhost:3000/baz", nil) 176 | context = New().createContext(recorder, req) 177 | router.Handle(recorder, req, context) 178 | expect(t, recorder.Code, http.StatusOK) 179 | expect(t, recorder.Body.String(), "baz") 180 | 181 | // Should render bytes as a return value as well. 182 | recorder = httptest.NewRecorder() 183 | req, _ = http.NewRequest("GET", "http://localhost:3000/bytes", nil) 184 | context = New().createContext(recorder, req) 185 | router.Handle(recorder, req, context) 186 | expect(t, recorder.Code, http.StatusOK) 187 | expect(t, recorder.Body.String(), "Bytes!") 188 | 189 | // Should render interface{} values. 190 | recorder = httptest.NewRecorder() 191 | req, _ = http.NewRequest("GET", "http://localhost:3000/interface", nil) 192 | context = New().createContext(recorder, req) 193 | router.Handle(recorder, req, context) 194 | expect(t, recorder.Code, http.StatusOK) 195 | expect(t, recorder.Body.String(), "Interface!") 196 | } 197 | 198 | func Test_RouterHandlerStacking(t *testing.T) { 199 | router := NewRouter() 200 | recorder := httptest.NewRecorder() 201 | 202 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 203 | context := New().createContext(recorder, req) 204 | 205 | result := "" 206 | 207 | f1 := func() { 208 | result += "foo" 209 | } 210 | 211 | f2 := func(c Context) { 212 | result += "bar" 213 | c.Next() 214 | result += "bing" 215 | } 216 | 217 | f3 := func() string { 218 | result += "bat" 219 | return "Hello world" 220 | } 221 | 222 | f4 := func() { 223 | result += "baz" 224 | } 225 | 226 | router.Get("/foo", f1, f2, f3, f4) 227 | 228 | router.Handle(recorder, req, context) 229 | expect(t, result, "foobarbatbing") 230 | expect(t, recorder.Body.String(), "Hello world") 231 | } 232 | 233 | var routeTests = []struct { 234 | // in 235 | method string 236 | path string 237 | 238 | // out 239 | match RouteMatch 240 | params map[string]string 241 | }{ 242 | {"GET", "/foo/123/bat/321", ExactMatch, map[string]string{"bar": "123", "baz": "321"}}, 243 | {"POST", "/foo/123/bat/321", NoMatch, map[string]string{}}, 244 | {"GET", "/foo/hello/bat/world", ExactMatch, map[string]string{"bar": "hello", "baz": "world"}}, 245 | {"GET", "foo/hello/bat/world", NoMatch, map[string]string{}}, 246 | {"GET", "/foo/123/bat/321/", ExactMatch, map[string]string{"bar": "123", "baz": "321"}}, 247 | {"GET", "/foo/123/bat/321//", NoMatch, map[string]string{}}, 248 | {"GET", "/foo/123//bat/321/", NoMatch, map[string]string{}}, 249 | {"HEAD", "/foo/123/bat/321/", OverloadMatch, map[string]string{"bar": "123", "baz": "321"}}, 250 | } 251 | 252 | func Test_RouteMatching(t *testing.T) { 253 | route := newRoute("GET", "/foo/:bar/bat/:baz", nil) 254 | for _, tt := range routeTests { 255 | match, params := route.Match(tt.method, tt.path) 256 | if match != tt.match || params["bar"] != tt.params["bar"] || params["baz"] != tt.params["baz"] { 257 | t.Errorf("expected: (%v, %v) got: (%v, %v)", tt.match, tt.params, match, params) 258 | } 259 | } 260 | } 261 | 262 | func Test_MethodsFor(t *testing.T) { 263 | router := NewRouter() 264 | recorder := httptest.NewRecorder() 265 | 266 | req, _ := http.NewRequest("POST", "http://localhost:3000/foo", nil) 267 | context := New().createContext(recorder, req) 268 | context.MapTo(router, (*Routes)(nil)) 269 | router.Post("/foo/bar", func() { 270 | }) 271 | 272 | router.Post("/fo", func() { 273 | }) 274 | 275 | router.Get("/foo", func() { 276 | }) 277 | 278 | router.Put("/foo", func() { 279 | }) 280 | 281 | router.NotFound(func(routes Routes, w http.ResponseWriter, r *http.Request) { 282 | methods := routes.MethodsFor(r.URL.Path) 283 | if len(methods) != 0 { 284 | w.Header().Set("Allow", strings.Join(methods, ",")) 285 | w.WriteHeader(http.StatusMethodNotAllowed) 286 | } 287 | }) 288 | router.Handle(recorder, req, context) 289 | expect(t, recorder.Code, http.StatusMethodNotAllowed) 290 | expect(t, recorder.Header().Get("Allow"), "GET,PUT") 291 | } 292 | 293 | func Test_NotFound(t *testing.T) { 294 | router := NewRouter() 295 | recorder := httptest.NewRecorder() 296 | 297 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 298 | context := New().createContext(recorder, req) 299 | 300 | router.NotFound(func(res http.ResponseWriter) { 301 | http.Error(res, "Nope", http.StatusNotFound) 302 | }) 303 | 304 | router.Handle(recorder, req, context) 305 | expect(t, recorder.Code, http.StatusNotFound) 306 | expect(t, recorder.Body.String(), "Nope\n") 307 | } 308 | 309 | func Test_NotFoundAsHandler(t *testing.T) { 310 | router := NewRouter() 311 | recorder := httptest.NewRecorder() 312 | 313 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 314 | context := New().createContext(recorder, req) 315 | 316 | router.NotFound(func() string { 317 | return "not found" 318 | }) 319 | 320 | router.Handle(recorder, req, context) 321 | expect(t, recorder.Code, http.StatusOK) 322 | expect(t, recorder.Body.String(), "not found") 323 | 324 | recorder = httptest.NewRecorder() 325 | 326 | context = New().createContext(recorder, req) 327 | 328 | router.NotFound(func() (int, string) { 329 | return 404, "not found" 330 | }) 331 | 332 | router.Handle(recorder, req, context) 333 | expect(t, recorder.Code, http.StatusNotFound) 334 | expect(t, recorder.Body.String(), "not found") 335 | 336 | recorder = httptest.NewRecorder() 337 | 338 | context = New().createContext(recorder, req) 339 | 340 | router.NotFound(func() (int, string) { 341 | return 200, "" 342 | }) 343 | 344 | router.Handle(recorder, req, context) 345 | expect(t, recorder.Code, http.StatusOK) 346 | expect(t, recorder.Body.String(), "") 347 | } 348 | 349 | func Test_NotFoundStacking(t *testing.T) { 350 | router := NewRouter() 351 | recorder := httptest.NewRecorder() 352 | 353 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 354 | context := New().createContext(recorder, req) 355 | 356 | result := "" 357 | 358 | f1 := func() { 359 | result += "foo" 360 | } 361 | 362 | f2 := func(c Context) { 363 | result += "bar" 364 | c.Next() 365 | result += "bing" 366 | } 367 | 368 | f3 := func() string { 369 | result += "bat" 370 | return "Not Found" 371 | } 372 | 373 | f4 := func() { 374 | result += "baz" 375 | } 376 | 377 | router.NotFound(f1, f2, f3, f4) 378 | 379 | router.Handle(recorder, req, context) 380 | expect(t, result, "foobarbatbing") 381 | expect(t, recorder.Body.String(), "Not Found") 382 | } 383 | 384 | func Test_Any(t *testing.T) { 385 | router := NewRouter() 386 | router.Any("/foo", func(res http.ResponseWriter) { 387 | http.Error(res, "Nope", http.StatusNotFound) 388 | }) 389 | 390 | recorder := httptest.NewRecorder() 391 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 392 | context := New().createContext(recorder, req) 393 | router.Handle(recorder, req, context) 394 | 395 | expect(t, recorder.Code, http.StatusNotFound) 396 | expect(t, recorder.Body.String(), "Nope\n") 397 | 398 | recorder = httptest.NewRecorder() 399 | req, _ = http.NewRequest("PUT", "http://localhost:3000/foo", nil) 400 | context = New().createContext(recorder, req) 401 | router.Handle(recorder, req, context) 402 | 403 | expect(t, recorder.Code, http.StatusNotFound) 404 | expect(t, recorder.Body.String(), "Nope\n") 405 | } 406 | 407 | func Test_URLFor(t *testing.T) { 408 | router := NewRouter() 409 | 410 | router.Get("/foo", func() { 411 | // Nothing 412 | }).Name("foo") 413 | 414 | router.Post("/bar/:id", func(params Params) { 415 | // Nothing 416 | }).Name("bar") 417 | 418 | router.Get("/baz/:id/(?P[a-z]*)", func(params Params, routes Routes) { 419 | // Nothing 420 | }).Name("baz_id") 421 | 422 | router.Get("/bar/:id/:name", func(params Params, routes Routes) { 423 | expect(t, routes.URLFor("foo", nil), "/foo") 424 | expect(t, routes.URLFor("bar", 5), "/bar/5") 425 | expect(t, routes.URLFor("baz_id", 5, "john"), "/baz/5/john") 426 | expect(t, routes.URLFor("bar_id", 5, "john"), "/bar/5/john") 427 | }).Name("bar_id") 428 | 429 | // code should be 200 if none is returned from the handler 430 | recorder := httptest.NewRecorder() 431 | req, _ := http.NewRequest("GET", "http://localhost:3000/bar/foo/bar", nil) 432 | context := New().createContext(recorder, req) 433 | context.MapTo(router, (*Routes)(nil)) 434 | router.Handle(recorder, req, context) 435 | } 436 | 437 | func Test_AllRoutes(t *testing.T) { 438 | router := NewRouter() 439 | 440 | patterns := []string{"/foo", "/fee", "/fii"} 441 | methods := []string{"GET", "POST", "DELETE"} 442 | names := []string{"foo", "fee", "fii"} 443 | 444 | router.Get("/foo", func() {}).Name("foo") 445 | router.Post("/fee", func() {}).Name("fee") 446 | router.Delete("/fii", func() {}).Name("fii") 447 | 448 | for i, r := range router.All() { 449 | expect(t, r.Pattern(), patterns[i]) 450 | expect(t, r.Method(), methods[i]) 451 | expect(t, r.GetName(), names[i]) 452 | } 453 | } 454 | 455 | func Test_ActiveRoute(t *testing.T) { 456 | router := NewRouter() 457 | 458 | router.Get("/foo", func(r Route) { 459 | expect(t, r.Pattern(), "/foo") 460 | expect(t, r.GetName(), "foo") 461 | }).Name("foo") 462 | 463 | // code should be 200 if none is returned from the handler 464 | recorder := httptest.NewRecorder() 465 | req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) 466 | context := New().createContext(recorder, req) 467 | context.MapTo(router, (*Routes)(nil)) 468 | router.Handle(recorder, req, context) 469 | } 470 | -------------------------------------------------------------------------------- /static.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "net/url" 7 | "path" 8 | "path/filepath" 9 | "strings" 10 | ) 11 | 12 | // StaticOptions is a struct for specifying configuration options for the martini.Static middleware. 13 | type StaticOptions struct { 14 | // Prefix is the optional prefix used to serve the static directory content 15 | Prefix string 16 | // SkipLogging will disable [Static] log messages when a static file is served. 17 | SkipLogging bool 18 | // IndexFile defines which file to serve as index if it exists. 19 | IndexFile string 20 | // Expires defines which user-defined function to use for producing a HTTP Expires Header 21 | // https://developers.google.com/speed/docs/insights/LeverageBrowserCaching 22 | Expires func() string 23 | // Fallback defines a default URL to serve when the requested resource was 24 | // not found. 25 | Fallback string 26 | // Exclude defines a pattern for URLs this handler should never process. 27 | Exclude string 28 | } 29 | 30 | func prepareStaticOptions(options []StaticOptions) StaticOptions { 31 | var opt StaticOptions 32 | if len(options) > 0 { 33 | opt = options[0] 34 | } 35 | 36 | // Defaults 37 | if len(opt.IndexFile) == 0 { 38 | opt.IndexFile = "index.html" 39 | } 40 | // Normalize the prefix if provided 41 | if opt.Prefix != "" { 42 | // Ensure we have a leading '/' 43 | if opt.Prefix[0] != '/' { 44 | opt.Prefix = "/" + opt.Prefix 45 | } 46 | // Remove any trailing '/' 47 | opt.Prefix = strings.TrimRight(opt.Prefix, "/") 48 | } 49 | return opt 50 | } 51 | 52 | // Static returns a middleware handler that serves static files in the given directory. 53 | func Static(directory string, staticOpt ...StaticOptions) Handler { 54 | if !filepath.IsAbs(directory) { 55 | directory = filepath.Join(Root, directory) 56 | } 57 | dir := http.Dir(directory) 58 | opt := prepareStaticOptions(staticOpt) 59 | 60 | return func(res http.ResponseWriter, req *http.Request, log *log.Logger) { 61 | if req.Method != "GET" && req.Method != "HEAD" { 62 | return 63 | } 64 | if opt.Exclude != "" && strings.HasPrefix(req.URL.Path, opt.Exclude) { 65 | return 66 | } 67 | file := req.URL.Path 68 | // if we have a prefix, filter requests by stripping the prefix 69 | if opt.Prefix != "" { 70 | if !strings.HasPrefix(file, opt.Prefix) { 71 | return 72 | } 73 | file = file[len(opt.Prefix):] 74 | if file != "" && file[0] != '/' { 75 | return 76 | } 77 | } 78 | f, err := dir.Open(file) 79 | if err != nil { 80 | // try any fallback before giving up 81 | if opt.Fallback != "" { 82 | file = opt.Fallback // so that logging stays true 83 | f, err = dir.Open(opt.Fallback) 84 | } 85 | 86 | if err != nil { 87 | // discard the error? 88 | return 89 | } 90 | } 91 | defer f.Close() 92 | 93 | fi, err := f.Stat() 94 | if err != nil { 95 | return 96 | } 97 | 98 | // try to serve index file 99 | if fi.IsDir() { 100 | // redirect if missing trailing slash 101 | if !strings.HasSuffix(req.URL.Path, "/") { 102 | dest := url.URL{ 103 | Path: req.URL.Path + "/", 104 | RawQuery: req.URL.RawQuery, 105 | Fragment: req.URL.Fragment, 106 | } 107 | http.Redirect(res, req, dest.String(), http.StatusFound) 108 | return 109 | } 110 | 111 | file = path.Join(file, opt.IndexFile) 112 | f, err = dir.Open(file) 113 | if err != nil { 114 | return 115 | } 116 | defer f.Close() 117 | 118 | fi, err = f.Stat() 119 | if err != nil || fi.IsDir() { 120 | return 121 | } 122 | } 123 | 124 | if !opt.SkipLogging { 125 | log.Println("[Static] Serving " + file) 126 | } 127 | 128 | // Add an Expires header to the static content 129 | if opt.Expires != nil { 130 | res.Header().Set("Expires", opt.Expires()) 131 | } 132 | 133 | http.ServeContent(res, req, file, fi.ModTime(), f) 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /static_test.go: -------------------------------------------------------------------------------- 1 | package martini 2 | 3 | import ( 4 | "bytes" 5 | "io/ioutil" 6 | "log" 7 | "net/http" 8 | "net/http/httptest" 9 | "os" 10 | "path" 11 | "testing" 12 | 13 | "github.com/codegangsta/inject" 14 | ) 15 | 16 | var currentRoot, _ = os.Getwd() 17 | 18 | func Test_Static(t *testing.T) { 19 | response := httptest.NewRecorder() 20 | response.Body = new(bytes.Buffer) 21 | 22 | m := New() 23 | r := NewRouter() 24 | 25 | m.Use(Static(currentRoot)) 26 | m.Action(r.Handle) 27 | 28 | req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) 29 | if err != nil { 30 | t.Error(err) 31 | } 32 | m.ServeHTTP(response, req) 33 | expect(t, response.Code, http.StatusOK) 34 | expect(t, response.Header().Get("Expires"), "") 35 | if response.Body.Len() == 0 { 36 | t.Errorf("Got empty body for GET request") 37 | } 38 | } 39 | 40 | func Test_Static_Local_Path(t *testing.T) { 41 | Root = os.TempDir() 42 | response := httptest.NewRecorder() 43 | response.Body = new(bytes.Buffer) 44 | 45 | m := New() 46 | r := NewRouter() 47 | 48 | m.Use(Static(".")) 49 | f, err := ioutil.TempFile(Root, "static_content") 50 | if err != nil { 51 | t.Error(err) 52 | } 53 | f.WriteString("Expected Content") 54 | f.Close() 55 | m.Action(r.Handle) 56 | 57 | req, err := http.NewRequest("GET", "http://localhost:3000/"+path.Base(f.Name()), nil) 58 | if err != nil { 59 | t.Error(err) 60 | } 61 | m.ServeHTTP(response, req) 62 | expect(t, response.Code, http.StatusOK) 63 | expect(t, response.Header().Get("Expires"), "") 64 | expect(t, response.Body.String(), "Expected Content") 65 | } 66 | 67 | func Test_Static_Head(t *testing.T) { 68 | response := httptest.NewRecorder() 69 | response.Body = new(bytes.Buffer) 70 | 71 | m := New() 72 | r := NewRouter() 73 | 74 | m.Use(Static(currentRoot)) 75 | m.Action(r.Handle) 76 | 77 | req, err := http.NewRequest("HEAD", "http://localhost:3000/martini.go", nil) 78 | if err != nil { 79 | t.Error(err) 80 | } 81 | 82 | m.ServeHTTP(response, req) 83 | expect(t, response.Code, http.StatusOK) 84 | if response.Body.Len() != 0 { 85 | t.Errorf("Got non-empty body for HEAD request") 86 | } 87 | } 88 | 89 | func Test_Static_As_Post(t *testing.T) { 90 | response := httptest.NewRecorder() 91 | 92 | m := New() 93 | r := NewRouter() 94 | 95 | m.Use(Static(currentRoot)) 96 | m.Action(r.Handle) 97 | 98 | req, err := http.NewRequest("POST", "http://localhost:3000/martini.go", nil) 99 | if err != nil { 100 | t.Error(err) 101 | } 102 | 103 | m.ServeHTTP(response, req) 104 | expect(t, response.Code, http.StatusNotFound) 105 | } 106 | 107 | func Test_Static_BadDir(t *testing.T) { 108 | response := httptest.NewRecorder() 109 | 110 | m := Classic() 111 | 112 | req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) 113 | if err != nil { 114 | t.Error(err) 115 | } 116 | 117 | m.ServeHTTP(response, req) 118 | refute(t, response.Code, http.StatusOK) 119 | } 120 | 121 | func Test_Static_Options_Logging(t *testing.T) { 122 | response := httptest.NewRecorder() 123 | 124 | var buffer bytes.Buffer 125 | m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} 126 | m.Map(m.logger) 127 | m.Map(defaultReturnHandler()) 128 | 129 | opt := StaticOptions{} 130 | m.Use(Static(currentRoot, opt)) 131 | 132 | req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) 133 | if err != nil { 134 | t.Error(err) 135 | } 136 | 137 | m.ServeHTTP(response, req) 138 | expect(t, response.Code, http.StatusOK) 139 | expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") 140 | 141 | // Now without logging 142 | m.Handlers() 143 | buffer.Reset() 144 | 145 | // This should disable logging 146 | opt.SkipLogging = true 147 | m.Use(Static(currentRoot, opt)) 148 | 149 | m.ServeHTTP(response, req) 150 | expect(t, response.Code, http.StatusOK) 151 | expect(t, buffer.String(), "") 152 | } 153 | 154 | func Test_Static_Options_ServeIndex(t *testing.T) { 155 | response := httptest.NewRecorder() 156 | 157 | var buffer bytes.Buffer 158 | m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} 159 | m.Map(m.logger) 160 | m.Map(defaultReturnHandler()) 161 | 162 | opt := StaticOptions{IndexFile: "martini.go"} // Define martini.go as index file 163 | m.Use(Static(currentRoot, opt)) 164 | 165 | req, err := http.NewRequest("GET", "http://localhost:3000/", nil) 166 | if err != nil { 167 | t.Error(err) 168 | } 169 | 170 | m.ServeHTTP(response, req) 171 | expect(t, response.Code, http.StatusOK) 172 | expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") 173 | } 174 | 175 | func Test_Static_Options_Prefix(t *testing.T) { 176 | response := httptest.NewRecorder() 177 | 178 | var buffer bytes.Buffer 179 | m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} 180 | m.Map(m.logger) 181 | m.Map(defaultReturnHandler()) 182 | 183 | // Serve current directory under /public 184 | m.Use(Static(currentRoot, StaticOptions{Prefix: "/public"})) 185 | 186 | // Check file content behaviour 187 | req, err := http.NewRequest("GET", "http://localhost:3000/public/martini.go", nil) 188 | if err != nil { 189 | t.Error(err) 190 | } 191 | 192 | m.ServeHTTP(response, req) 193 | expect(t, response.Code, http.StatusOK) 194 | expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") 195 | } 196 | 197 | func Test_Static_Options_Expires(t *testing.T) { 198 | response := httptest.NewRecorder() 199 | 200 | var buffer bytes.Buffer 201 | m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} 202 | m.Map(m.logger) 203 | m.Map(defaultReturnHandler()) 204 | 205 | // Serve current directory under /public 206 | m.Use(Static(currentRoot, StaticOptions{Expires: func() string { return "46" }})) 207 | 208 | // Check file content behaviour 209 | req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) 210 | if err != nil { 211 | t.Error(err) 212 | } 213 | 214 | m.ServeHTTP(response, req) 215 | expect(t, response.Header().Get("Expires"), "46") 216 | } 217 | 218 | func Test_Static_Options_Fallback(t *testing.T) { 219 | response := httptest.NewRecorder() 220 | 221 | var buffer bytes.Buffer 222 | m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} 223 | m.Map(m.logger) 224 | m.Map(defaultReturnHandler()) 225 | 226 | // Serve current directory under /public 227 | m.Use(Static(currentRoot, StaticOptions{Fallback: "/martini.go"})) 228 | 229 | // Check file content behaviour 230 | req, err := http.NewRequest("GET", "http://localhost:3000/initram.go", nil) 231 | if err != nil { 232 | t.Error(err) 233 | } 234 | 235 | m.ServeHTTP(response, req) 236 | expect(t, response.Code, http.StatusOK) 237 | expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") 238 | } 239 | 240 | func Test_Static_Redirect(t *testing.T) { 241 | response := httptest.NewRecorder() 242 | 243 | m := New() 244 | m.Use(Static(currentRoot, StaticOptions{Prefix: "/public"})) 245 | 246 | req, err := http.NewRequest("GET", "http://localhost:3000/public?param=foo#bar", nil) 247 | if err != nil { 248 | t.Error(err) 249 | } 250 | 251 | m.ServeHTTP(response, req) 252 | expect(t, response.Code, http.StatusFound) 253 | expect(t, response.Header().Get("Location"), "/public/?param=foo#bar") 254 | } 255 | -------------------------------------------------------------------------------- /translations/README_de_DE.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | Martini ist ein mächtiges Package zur schnellen Entwicklung von modularen Webanwendungen und -services in Golang. 4 | 5 | ## Ein Projekt starten 6 | 7 | Nach 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`. 8 | 9 | ~~~ go 10 | package main 11 | 12 | import "github.com/go-martini/martini" 13 | 14 | func main() { 15 | m := martini.Classic() 16 | m.Get("/", func() string { 17 | return "Hallo Welt!" 18 | }) 19 | m.Run() 20 | } 21 | ~~~ 22 | 23 | Installiere anschließend das Martini Package (**Go 1.1** oder höher wird vorausgesetzt): 24 | ~~~ 25 | go get github.com/go-martini/martini 26 | ~~~ 27 | 28 | Starte den Server: 29 | ~~~ 30 | go run server.go 31 | ~~~ 32 | 33 | Der Martini-Webserver ist nun unter `localhost:3000` erreichbar. 34 | 35 | ## Hilfe 36 | 37 | Abonniere den [Emailverteiler](https://groups.google.com/forum/#!forum/martini-go) 38 | 39 | Schaue das [Demovideo](http://martini.codegangsta.io/#demo) 40 | 41 | Stelle Fragen auf Stackoverflow mit dem [Martini-Tag](http://stackoverflow.com/questions/tagged/martini) 42 | 43 | GoDoc [Dokumentation](http://godoc.org/github.com/go-martini/martini) 44 | 45 | 46 | ## Eigenschaften 47 | * Sehr einfach nutzbar 48 | * Nicht-intrusives Design 49 | * Leicht kombinierbar mit anderen Golang Packages 50 | * Ausgezeichnetes Path Matching und Routing 51 | * Modulares Design - einfaches Hinzufügen und Entfernen von Funktionen 52 | * Eine Vielzahl von guten Handlern/Middlewares nutzbar 53 | * Großer Funktionsumfang mitgeliefert 54 | * **Voll kompatibel mit dem [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) Interface.** 55 | * Standardmäßiges Ausliefern von Dateien (z.B. von AngularJS-Apps im HTML5-Modus) 56 | 57 | ## Mehr Middleware 58 | Mehr Informationen zur Middleware und Funktionalität findest Du in den Repositories der [martini-contrib](https://github.com/martini-contrib) Gruppe. 59 | 60 | ## Inhaltsverzeichnis 61 | * [Classic Martini](#classic-martini) 62 | * [Handler](#handler) 63 | * [Routing](#routing) 64 | * [Services](#services) 65 | * [Statische Dateien bereitstellen](#statische-dateien-bereitstellen) 66 | * [Middleware Handler](#middleware-handler) 67 | * [Next()](#next) 68 | * [Martini Env](#martini-env) 69 | * [FAQ](#faq) 70 | 71 | ## Classic Martini 72 | Einen 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: 73 | ~~~ go 74 | m := martini.Classic() 75 | // ... Middleware und Routing hier einfügen 76 | m.Run() 77 | ~~~ 78 | 79 | Aufgelistet findest Du einige Aspekte, die [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) automatich berücksichtigt: 80 | 81 | * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 82 | * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 83 | * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 84 | * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 85 | 86 | ### Handler 87 | Handler sind das Herz und die Seele von Martini. Ein Handler ist grundsätzlich jede Art von aufrufbaren Funktionen: 88 | ~~~ go 89 | m.Get("/", func() { 90 | println("Hallo Welt") 91 | }) 92 | ~~~ 93 | 94 | #### Rückgabewerte 95 | Wenn ein Handler Rückgabewerte beinhaltet, übergibt Martini diese an den aktuellen [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) in Form eines String: 96 | ~~~ go 97 | m.Get("/", func() string { 98 | return "Hallo Welt" // HTTP 200 : "Hallo Welt" 99 | }) 100 | ~~~ 101 | 102 | Die Rückgabe eines Statuscode ist optional: 103 | ~~~ go 104 | m.Get("/", func() (int, string) { 105 | return 418, "Ich bin eine Teekanne" // HTTP 418 : "Ich bin eine Teekanne" 106 | }) 107 | ~~~ 108 | 109 | #### Service Injection 110 | Handler 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.** 111 | 112 | Fügst Du einem Handler ein Argument hinzu, sucht Martini in seiner Liste von Services und versucht, die Abhängigkeiten via Type Assertion aufzulösen. 113 | ~~~ go 114 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res und req wurden von Martini injiziert 115 | res.WriteHeader(200) // HTTP 200 116 | }) 117 | ~~~ 118 | 119 | Die Folgenden Services sind Bestandteil von [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 120 | 121 | * [*log.Logger](http://godoc.org/log#Logger) - Globaler Logger für Martini. 122 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. 123 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` von benannten Parametern, welche durch Route Matching gefunden wurden. 124 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Routen Hilfeservice. 125 | * [martini.Route](http://godoc.org/github.com/go-martini/martini#Route) - Aktuelle, aktive Route. 126 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. 127 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request. 128 | 129 | ### Routing 130 | Eine Route ist in Martini eine HTTP-Methode gepaart mit einem URL-Matching-Pattern. Jede Route kann eine oder mehrere Handler-Methoden übernehmen: 131 | ~~~ go 132 | m.Get("/", func() { 133 | // zeige etwas an 134 | }) 135 | 136 | m.Patch("/", func() { 137 | // aktualisiere etwas 138 | }) 139 | 140 | m.Post("/", func() { 141 | // erstelle etwas 142 | }) 143 | 144 | m.Put("/", func() { 145 | // ersetze etwas 146 | }) 147 | 148 | m.Delete("/", func() { 149 | // lösche etwas 150 | }) 151 | 152 | m.Options("/", func() { 153 | // HTTP-Optionen 154 | }) 155 | 156 | m.NotFound(func() { 157 | // bearbeite 404-Fehler 158 | }) 159 | ~~~ 160 | 161 | Routen werden in der Reihenfolge, in welcher sie definiert wurden, zugeordnet. Die bei einer Anfrage zuerst zugeordnete Route wird daraufhin aufgerufen. 162 | 163 | Routenmuster enthalten ggf. benannte Parameter, die über den [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) Service abrufbar sind: 164 | ~~~ go 165 | m.Get("/hello/:name", func(params martini.Params) string { 166 | return "Hallo " + params["name"] 167 | }) 168 | ~~~ 169 | 170 | Routen können mit Globs versehen werden: 171 | ~~~ go 172 | m.Get("/hello/**", func(params martini.Params) string { 173 | return "Hallo " + params["_1"] 174 | }) 175 | ~~~ 176 | 177 | Reguläre Ausdrücke sind ebenfalls möglich: 178 | ~~~go 179 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 180 | return fmt.Sprintf ("Hallo %s", params["name"]) 181 | }) 182 | ~~~ 183 | Weitere Informationen zum Syntax regulärer Ausdrücke findest Du in der [Go Dokumentation](http://golang.org/pkg/regexp/syntax/). 184 | 185 | Routen-Handler können auch ineinander verschachtelt werden. Dies ist bei der Authentifizierung und den Berechtigungen nützlich. 186 | ~~~ go 187 | m.Get("/secret", authorize, func() { 188 | // wird ausgeführt, solange authorize nichts zurückgibt 189 | }) 190 | ~~~ 191 | 192 | Routengruppen können durch die Group-Methode hinzugefügt werden. 193 | ~~~ go 194 | m.Group("/books", func(r martini.Router) { 195 | r.Get("/:id", GetBooks) 196 | r.Post("/new", NewBook) 197 | r.Put("/update/:id", UpdateBook) 198 | r.Delete("/delete/:id", DeleteBook) 199 | }) 200 | ~~~ 201 | 202 | Sowohl Handlern als auch Middlewares können Gruppen übergeben werden. 203 | ~~~ go 204 | m.Group("/books", func(r martini.Router) { 205 | r.Get("/:id", GetBooks) 206 | r.Post("/new", NewBook) 207 | r.Put("/update/:id", UpdateBook) 208 | r.Delete("/delete/:id", DeleteBook) 209 | }, MyMiddleware1, MyMiddleware2) 210 | ~~~ 211 | 212 | ### Services 213 | Services sind Objekte, welche der Argumentliste von Handlern beigefügt werden können. 214 | Du kannst einem Service der *Global* oder *Request* Ebene zuordnen. 215 | 216 | #### Global Mapping 217 | Eine Martini-Instanz implementiert das inject.Injector Interface, sodass ein Service leicht zugeordnet werden kann: 218 | ~~~ go 219 | db := &MyDatabase{} 220 | m := martini.Classic() 221 | m.Map(db) // der Service ist allen Handlern unter *MyDatabase verfügbar 222 | // ... 223 | m.Run() 224 | ~~~ 225 | 226 | #### Request-Level Mapping 227 | Das Zuordnen auf der Request-Ebene kann in einem Handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) realisiert werden: 228 | ~~~ go 229 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 230 | logger := &MyCustomLogger{req} 231 | c.Map(logger) // zugeordnet als *MyCustomLogger 232 | } 233 | ~~~ 234 | 235 | #### Werten einem Interface zuordnen 236 | Einer 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: 237 | ~~~ go 238 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 239 | rw := NewSpecialResponseWriter(res) 240 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // überschribe ResponseWriter mit dem ResponseWriter Decorator 241 | } 242 | ~~~ 243 | 244 | ### Statische Dateien bereitstellen 245 | Eine [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. 246 | ~~~ go 247 | m.Use(martini.Static("assets")) // überträgt auch vom "assets"-Verzeichnis 248 | ~~~ 249 | 250 | #### Eine voreingestelle Datei übertragen 251 | Du 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. 252 | Dies 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. 253 | 254 | Das 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: 255 | ~~~ go 256 | static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) 257 | m.NotFound(static, http.NotFound) 258 | ~~~ 259 | 260 | ## Middleware Handler 261 | Middleware-Handler befinden sich logisch zwischen einer Anfrage via HTTP und dem Router. Im wesentlichen unterscheiden sie sich nicht von anderen Handlern in Martini. 262 | Du kannst einen Middleware-Handler dem Stack folgendermaßen anfügen: 263 | ~~~ go 264 | m.Use(func() { 265 | // durchlaufe die Middleware 266 | }) 267 | ~~~ 268 | 269 | Volle Kontrolle über den Middleware Stack erlangst Du mit der `Handlers`-Funktion. 270 | Sie ersetzt jeden zuvor definierten Handler: 271 | ~~~ go 272 | m.Handlers( 273 | Middleware1, 274 | Middleware2, 275 | Middleware3, 276 | ) 277 | ~~~ 278 | 279 | Middleware 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. 280 | ~~~ go 281 | // überprüfe einen API-Schlüssel 282 | m.Use(func(res http.ResponseWriter, req *http.Request) { 283 | if req.Header.Get("X-API-KEY") != "secret123" { 284 | res.WriteHeader(http.StatusUnauthorized) 285 | } 286 | }) 287 | ~~~ 288 | 289 | ### Next() 290 | [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. 291 | ~~~ go 292 | // protokolliere vor und nach einer Anfrage 293 | m.Use(func(c martini.Context, log *log.Logger){ 294 | log.Println("vor einer Anfrage") 295 | 296 | c.Next() 297 | 298 | log.Println("nach einer Anfrage") 299 | }) 300 | ~~~ 301 | 302 | ## Martini Env 303 | 304 | Einige 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. 305 | 306 | ## FAQ 307 | 308 | ### Wo finde ich eine bestimmte Middleware? 309 | 310 | Starte 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. 311 | 312 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler zum Parsen des `Accept-Language` HTTP-Header. 313 | * [accessflags](https://github.com/martini-contrib/accessflags) - Handler zur Ermöglichung von Zugriffskontrollen. 314 | * [auth](https://github.com/martini-contrib/auth) - Handler zur Authentifizierung. 315 | * [binding](https://github.com/martini-contrib/binding) - Handler zum Zuordnen/Validieren einer Anfrage zu einem Struct. 316 | * [cors](https://github.com/martini-contrib/cors) - Handler für CORS-Support. 317 | * [csrf](https://github.com/martini-contrib/csrf) - CSRF-Schutz für Applikationen 318 | * [encoder](https://github.com/martini-contrib/encoder) - Enkodierungsservice zum Datenrendering in den verschiedensten Formaten. 319 | * [gzip](https://github.com/martini-contrib/gzip) - Handler zum Ermöglichen von gzip-Kompression bei HTTP-Anfragen. 320 | * [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic Middleware 321 | * [logstasher](https://github.com/martini-contrib/logstasher) - Middlewaredie Logstashkompatibles JSON ausgibt 322 | * [method](https://github.com/martini-contrib/method) - Überschreibe eine HTTP-Method via Header oder Formularfelder. 323 | * [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. 324 | * [permissions2](https://github.com/xyproto/permissions2) - Handler zum Mitverfolgen von Benutzern, Loginstatus und Berechtigungen. 325 | * [render](https://github.com/martini-contrib/render) - Handler, der einen einfachen Service zum Rendern von JSON und HTML-Templates bereitstellt. 326 | * [secure](https://github.com/martini-contrib/secure) - Implementation von Sicherheitsfunktionen 327 | * [sessions](https://github.com/martini-contrib/sessions) - Handler mit einem Session service. 328 | * [sessionauth](https://github.com/martini-contrib/sessionauth) - Handler zur einfachen Aufforderung eines Logins für Routes und zur Bearbeitung von Benutzerlogins in der Sitzung 329 | * [strict](https://github.com/martini-contrib/strict) - Strikter Modus. 330 | * [strip](https://github.com/martini-contrib/strip) - URL-Prefix Stripping. 331 | * [staticbin](https://github.com/martini-contrib/staticbin) - Handler for serving static files from binary data 332 | * [throttle](https://github.com/martini-contrib/throttle) - Middleware zum Drosseln von HTTP-Anfragen. 333 | * [vauth](https://github.com/rafecolton/vauth) - Handler zur Webhook-Authentifizierung (momentan nur GitHub und TravisCI) 334 | * [web](https://github.com/martini-contrib/web) - hoisie web.go's Kontext 335 | 336 | ### Wie integriere ich in bestehende Systeme? 337 | 338 | Eine 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: 339 | 340 | ~~~ go 341 | package hello 342 | 343 | import ( 344 | "net/http" 345 | "github.com/go-martini/martini" 346 | ) 347 | 348 | func init() { 349 | m := martini.Classic() 350 | m.Get("/", func() string { 351 | return "Hallo Welt!" 352 | }) 353 | http.Handle("/", m) 354 | } 355 | ~~~ 356 | 357 | ### Wie ändere ich den Port/Host? 358 | 359 | Martinis `Run` Funktion sucht automatisch nach den PORT und HOST Umgebungsvariablen, um diese zu nutzen. Andernfalls ist localhost:3000 voreingestellt. 360 | Für mehr Flexibilität über den Port und den Host nutze stattdessen die `martini.RunOnAddr` Funktion. 361 | 362 | ~~~ go 363 | m := martini.Classic() 364 | // ... 365 | log.Fatal(m.RunOnAddr(":8080")) 366 | ~~~ 367 | 368 | ### Automatisches Aktualisieren? 369 | 370 | [Gin](https://github.com/codegangsta/gin) und [Fresh](https://github.com/pilu/fresh) aktualisieren Martini-Apps live. 371 | 372 | ## Bei Martini mitwirken 373 | 374 | Martinis 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. 375 | 376 | ## Über das Projekt 377 | 378 | Inspiriert von [Express](https://github.com/visionmedia/express) und [Sinatra](https://github.com/sinatra/sinatra) 379 | 380 | Martini wird leidenschaftlich von niemand Geringerem als dem [Code Gangsta](http://codegangsta.io/) entwickelt 381 | -------------------------------------------------------------------------------- /translations/README_es_ES.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | Martini es un poderoso paquete para escribir rápidamente aplicaciones/servicios web modulares en Golang. 4 | 5 | 6 | ## Vamos a iniciar 7 | 8 | Despué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`. 9 | 10 | ~~~ go 11 | package main 12 | 13 | import "github.com/go-martini/martini" 14 | 15 | func main() { 16 | m := martini.Classic() 17 | m.Get("/", func() string { 18 | return "Hola Mundo!" 19 | }) 20 | m.Run() 21 | } 22 | ~~~ 23 | 24 | Luego instale el paquete Martini (Es necesario **go 1.1** o superior): 25 | ~~~ 26 | go get github.com/go-martini/martini 27 | ~~~ 28 | 29 | Después corra su servidor: 30 | ~~~ 31 | go run server.go 32 | ~~~ 33 | 34 | Ahora tendrá un webserver Martini corriendo en el puerto `localhost:3000`. 35 | 36 | ## Obtenga ayuda 37 | 38 | Suscribase a la [Lista de email](https://groups.google.com/forum/#!forum/martini-go) 39 | 40 | Observe el [Video demostrativo](http://martini.codegangsta.io/#demo) 41 | 42 | Use la etiqueta [martini](http://stackoverflow.com/questions/tagged/martini) para preguntas en Stackoverflow 43 | 44 | Documentación [GoDoc](http://godoc.org/github.com/go-martini/martini) 45 | 46 | 47 | ## Caracteríticas 48 | * Extremadamente simple de usar. 49 | * Diseño no intrusivo. 50 | * Buena integración con otros paquetes Golang. 51 | * Enrutamiento impresionante. 52 | * Diseño modular - Fácil de añadir y remover funcionalidades. 53 | * Muy buen uso de handlers/middlewares. 54 | * Grandes características innovadoras. 55 | * **Compatibilidad total con la interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** 56 | * Sirviendo documentos por defecto (e.g. para servir aplicaciones AngularJS en modo HTML5). 57 | 58 | ## Más Middlewares 59 | Para más middlewares y funcionalidades, revisar los repositorios en [martini-contrib](https://github.com/martini-contrib). 60 | 61 | ## Lista de contenidos 62 | * [Classic Martini](#classic-martini) 63 | * [Handlers](#handlers) 64 | * [Routing](#routing) 65 | * [Services](#services) 66 | * [Serving Static Files](#serving-static-files) 67 | * [Middleware Handlers](#middleware-handlers) 68 | * [Next()](#next) 69 | * [Martini Env](#martini-env) 70 | * [FAQ](#faq) 71 | 72 | ## Classic Martini 73 | Para 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: 74 | ~~~ go 75 | m := martini.Classic() 76 | // middlewares y rutas aquí 77 | m.Run() 78 | ~~~ 79 | 80 | Algunas funcionalidades que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) ofrece automáticamente son: 81 | * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 82 | * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 83 | * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 84 | * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 85 | 86 | ### Handlers 87 | Handlers son el corazón y el alma de Martini. Un handler es básicamente cualquier tipo de función que puede ser llamada. 88 | ~~~ go 89 | m.Get("/", func() { 90 | println("hola mundo") 91 | }) 92 | ~~~ 93 | 94 | #### Retorno de Valores 95 | Si un handler retorna cualquier cosa, Martini escribirá el valor retornado como una cadena [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter): 96 | ~~~ go 97 | m.Get("/", func() string { 98 | return "hola mundo" // HTTP 200 : "hola mundo" 99 | }) 100 | ~~~ 101 | 102 | Usted también puede retornar un código de estado: 103 | ~~~ go 104 | m.Get("/", func() (int, string) { 105 | return 418, "soy una tetera" // HTTP 418 : "soy una tetera" 106 | }) 107 | ~~~ 108 | 109 | #### Inyección de Servicios 110 | Handlers 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.** 111 | 112 | Si 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: 113 | ~~~ go 114 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res y req son inyectados por Martini 115 | res.WriteHeader(200) // HTTP 200 116 | }) 117 | ~~~ 118 | 119 | Los siguientes servicios son incluidos con [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 120 | * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini. 121 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. 122 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nombres de los parámetros buscados por la ruta. 123 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Servicio de ayuda para las Rutas. 124 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escribe la interfaz. 125 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request. 126 | 127 | ### Rutas 128 | En 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: 129 | ~~~ go 130 | m.Get("/", func() { 131 | // mostrar algo 132 | }) 133 | 134 | m.Patch("/", func() { 135 | // actualizar algo 136 | }) 137 | 138 | m.Post("/", func() { 139 | // crear algo 140 | }) 141 | 142 | m.Put("/", func() { 143 | // reemplazar algo 144 | }) 145 | 146 | m.Delete("/", func() { 147 | // destruir algo 148 | }) 149 | 150 | m.Options("/", func() { 151 | // opciones HTTP 152 | }) 153 | 154 | m.NotFound(func() { 155 | // manipula 404 156 | }) 157 | ~~~ 158 | 159 | Las rutas son emparejadas en el orden en que son definidas. La primera ruta que coincide con la solicitud es invocada. 160 | 161 | Los 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): 162 | ~~~ go 163 | m.Get("/hello/:name", func(params martini.Params) string { 164 | return "Hello " + params["name"] 165 | }) 166 | ~~~ 167 | 168 | Las rutas se pueden combinar con globs: 169 | ~~~ go 170 | m.Get("/hello/**", func(params martini.Params) string { 171 | return "Hello " + params["_1"] 172 | }) 173 | ~~~ 174 | 175 | Las expresiones regulares pueden ser usadas también: 176 | ~~~go 177 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 178 | return fmt.Sprintf ("Hello %s", params["name"]) 179 | }) 180 | ~~~ 181 | Observe la [documentación](http://golang.org/pkg/regexp/syntax/) para mayor información sobre la sintaxis de expresiones regulares. 182 | 183 | 184 | Handlers de ruta pueden ser apilados encima de otros, lo cual es útil para cosas como autenticación y autorización: 185 | ~~~ go 186 | m.Get("/secret", authorize, func() { 187 | // será ejecutado cuando autorice escribir una respuesta 188 | }) 189 | ~~~ 190 | 191 | Grupos de rutas puede ser añadidas usando el método Group. 192 | ~~~ go 193 | m.Group("/books", func(r martini.Router) { 194 | r.Get("/:id", GetBooks) 195 | r.Post("/new", NewBook) 196 | r.Put("/update/:id", UpdateBook) 197 | r.Delete("/delete/:id", DeleteBook) 198 | }) 199 | ~~~ 200 | 201 | Al igual que usted puede pasar middlewares a un handler, puede pasar middlewares a grupos. 202 | ~~~ go 203 | m.Group("/books", func(r martini.Router) { 204 | r.Get("/:id", GetBooks) 205 | r.Post("/new", NewBook) 206 | r.Put("/update/:id", UpdateBook) 207 | r.Delete("/delete/:id", DeleteBook) 208 | }, MyMiddleware1, MyMiddleware2) 209 | ~~~ 210 | 211 | ### Servicios 212 | Lo 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*. 213 | 214 | #### Mapeo Global 215 | Una instancia de Martini implementa la interface `inject.Injector`, asi que el mapeo de un servicio es sencillo: 216 | ~~~ go 217 | db := &MyDatabase{} 218 | m := martini.Classic() 219 | m.Map(db) // el servicio estará disponible para todos los handlers como *MyDatabase. 220 | // ... 221 | m.Run() 222 | ~~~ 223 | 224 | #### Mapeo por Request 225 | El mapeo a nivel de request puede ser hecho en un handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): 226 | ~~~ go 227 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 228 | logger := &MyCustomLogger{req} 229 | c.Map(logger) // mapeado como *MyCustomLogger 230 | } 231 | ~~~ 232 | 233 | #### Valores de Mapeo para Interfaces 234 | Una 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: 235 | ~~~ go 236 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 237 | rw := NewSpecialResponseWriter(res) 238 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // sobreescribir ResponseWriter con nuestro ResponseWriter 239 | } 240 | ~~~ 241 | 242 | ### Sirviendo Archivos Estáticos 243 | Una 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. 244 | Usted puede servir más directorios, añadiendo más [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. 245 | ~~~ go 246 | m.Use(martini.Static("assets")) // sirviendo los archivos del directorio "assets" 247 | ~~~ 248 | 249 | ## Middleware Handlers 250 | Los 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: 251 | ~~~ go 252 | m.Use(func() { 253 | // Hacer algo con middleware 254 | }) 255 | ~~~ 256 | 257 | Puede tener el control total sobre la pila del Middleware con la función `Handlers`. Esto reemplazará a cualquier handler que haya sido establecido previamente: 258 | ~~~ go 259 | m.Handlers( 260 | Middleware1, 261 | Middleware2, 262 | Middleware3, 263 | ) 264 | ~~~ 265 | 266 | Middleware 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: 267 | ~~~ go 268 | // Valida una llave de api 269 | m.Use(func(res http.ResponseWriter, req *http.Request) { 270 | if req.Header.Get("X-API-KEY") != "secret123" { 271 | res.WriteHeader(http.StatusUnauthorized) 272 | } 273 | }) 274 | ~~~ 275 | 276 | ### Next() 277 | [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: 278 | ~~~ go 279 | // log antes y después de una solicitud 280 | m.Use(func(c martini.Context, log *log.Logger){ 281 | log.Println("antes de una solicitud") 282 | 283 | c.Next() 284 | 285 | log.Println("luego de una solicitud") 286 | }) 287 | ~~~ 288 | 289 | ## Martini Env 290 | 291 | Martini 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. 292 | 293 | ## FAQ 294 | 295 | ### ¿Dónde puedo encontrar una middleware X? 296 | 297 | Inicie 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. 298 | 299 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para analizar el `Accept-Language` HTTP header. 300 | * [accessflags](https://github.com/martini-contrib/accessflags) - Handler para habilitar Access Control. 301 | * [auth](https://github.com/martini-contrib/auth) - Handlers para autenticación. 302 | * [binding](https://github.com/martini-contrib/binding) - Handler para mapeo/validación de un request en una estructura. 303 | * [cors](https://github.com/martini-contrib/cors) - Handler habilita soporte para CORS. 304 | * [csrf](https://github.com/martini-contrib/csrf) - CSRF protección para aplicaciones. 305 | * [encoder](https://github.com/martini-contrib/encoder) - Servicio de codificador para renderizado de datos en varios formatos y gestión de contenidos. 306 | * [gzip](https://github.com/martini-contrib/gzip) - Handler para agregar compresión gzip para los requests. 307 | * [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic middleware 308 | * [logstasher](https://github.com/martini-contrib/logstasher) - Middleware que imprime logstash-compatiable JSON. 309 | * [method](https://github.com/martini-contrib/method) - HTTP method overriding via cabecera o campos de formulario. 310 | * [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. 311 | * [permissions2](https://github.com/xyproto/permissions2) - Handler para hacer seguimiento de usuarios, estados de login y permisos. 312 | * [render](https://github.com/martini-contrib/render) - Handler que provee un servicio para fácil renderizado de plantillas HTML y JSON. 313 | * [secure](https://github.com/martini-contrib/secure) - Implementa un par de rápidos triunfos de seguridad. 314 | * [sessions](https://github.com/martini-contrib/sessions) - Handler que provee un servicio de sesiones. 315 | * [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. 316 | * [strict](https://github.com/martini-contrib/strict) - Modo estricto (Strict Mode) 317 | * [strip](https://github.com/martini-contrib/strip) - Prefijo de extracción de URL. 318 | * [staticbin](https://github.com/martini-contrib/staticbin) - Handler para servir archivos estáticos desde datos binarios. 319 | * [throttle](https://github.com/martini-contrib/throttle) - Request rate throttling middleware. 320 | * [vauth](https://github.com/rafecolton/vauth) - Handlers para expender autenticación con webhooks (actualmente GitHub y TravisCI) 321 | * [web](https://github.com/martini-contrib/web) - Contexto hoisie web.go's 322 | 323 | ### ¿Cómo se integra con los servidores existentes? 324 | 325 | Una 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: 326 | 327 | ~~~ go 328 | package hello 329 | 330 | import ( 331 | "net/http" 332 | "github.com/go-martini/martini" 333 | ) 334 | 335 | func init() { 336 | m := martini.Classic() 337 | m.Get("/", func() string { 338 | return "Hola Mundo!" 339 | }) 340 | http.Handle("/", m) 341 | } 342 | ~~~ 343 | 344 | ### ¿Cómo cambiar el puerto/host? 345 | 346 | La 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`. 347 | 348 | ~~~ go 349 | m := martini.Classic() 350 | // ... 351 | log.Fatal(m.RunOnAddr(":8080")) 352 | ~~~ 353 | 354 | ### ¿Servidor con autoreload? 355 | 356 | [gin](https://github.com/codegangsta/gin) y [fresh](https://github.com/pilu/fresh) son ambas aplicaciones para autorecarga de Martini. 357 | 358 | ## Contribuyendo 359 | Martini 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. 360 | 361 | ## Sobre 362 | 363 | Inspirado por [Express](https://github.com/visionmedia/express) y [Sinatra](https://github.com/sinatra/sinatra) 364 | 365 | Martini está diseñado obsesivamente por nada menos que [Code Gangsta](http://codegangsta.io/) 366 | 367 | -------------------------------------------------------------------------------- /translations/README_fr_FR.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | Martini est une puissante bibliothèque pour développer rapidement des applications et services web en Golang. 4 | 5 | 6 | ## Pour commencer 7 | 8 | Aprè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'. 9 | 10 | ~~~ go 11 | package main 12 | 13 | import "github.com/go-martini/martini" 14 | 15 | func main() { 16 | m := martini.Classic() 17 | m.Get("/", func() string { 18 | return "Hello world!" 19 | }) 20 | m.Run() 21 | } 22 | ~~~ 23 | 24 | Installez ensuite le paquet Martini (**go 1.1** ou supérieur est requis) : 25 | 26 | ~~~ 27 | go get github.com/go-martini/martini 28 | ~~~ 29 | 30 | La commande suivante vous permettra de lancer votre serveur : 31 | ~~~ 32 | go run server.go 33 | ~~~ 34 | 35 | Vous avez à présent un serveur web Martini à l'écoute sur l'adresse et le port suivants : `localhost:3000`. 36 | 37 | ## Besoin d'aide 38 | - Souscrivez à la [Liste d'emails](https://groups.google.com/forum/#!forum/martini-go) 39 | - Regardez les vidéos [Demo en vidéo](http://martini.codegangsta.io/#demo) 40 | - Posez vos questions sur StackOverflow.com en utilisant le tag [martini](http://stackoverflow.com/questions/tagged/martini) 41 | - La documentation GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) 42 | 43 | 44 | ## Caractéristiques 45 | * Simple d'utilisation 46 | * Design non-intrusif 47 | * Compatible avec les autres paquets Golang 48 | * Gestionnaire d'URL et routeur disponibles 49 | * Modulable, permettant l'ajout et le retrait de fonctionnalités 50 | * Un grand nombre de handlers/middlewares disponibles 51 | * Prêt pour une utilisation immédiate 52 | * **Entièrement compatible avec l'interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** 53 | 54 | ## Plus de Middleware 55 | Pour plus de middlewares et de fonctionnalités, consultez le dépôt [martini-contrib](https://github.com/martini-contrib). 56 | 57 | ## Table des matières 58 | * [Classic Martini](#classic-martini) 59 | * [Handlers](#handlers) 60 | * [Routage](#routing) 61 | * [Services](#services) 62 | * [Serveur de fichiers statiques](#serving-static-files) 63 | * [Middleware Handlers](#middleware-handlers) 64 | * [Next()](#next) 65 | * [Martini Env](#martini-env) 66 | * [FAQ](#faq) 67 | 68 | ## Classic Martini 69 | Pour 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 : 70 | 71 | ~~~ go 72 | m := martini.Classic() 73 | // ... les middlewares and le routage sont insérés ici... 74 | m.Run() 75 | ~~~ 76 | 77 | Voici quelques handlers/middlewares que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) intègre par défault : 78 | * Logging des requêtes/réponses - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 79 | * Récupération sur erreur - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 80 | * Serveur de fichiers statiques - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 81 | * Routage - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 82 | 83 | ### Handlers 84 | Les Handlers sont le coeur et l'âme de Martini. N'importe quelle fonction peut être utilisée comme un handler. 85 | ~~~ go 86 | m.Get("/", func() { 87 | println("hello world") 88 | }) 89 | ~~~ 90 | 91 | #### Valeurs retournées 92 | Si 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```: 93 | ~~~ go 94 | m.Get("/", func() string { 95 | return "hello world" // HTTP 200 : "hello world" 96 | }) 97 | ~~~ 98 | Vous pouvez aussi optionnellement renvoyer un code de statut HTTP : 99 | ~~~ go 100 | m.Get("/", func() (int, string) { 101 | return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" 102 | }) 103 | ~~~ 104 | 105 | #### Injection de services 106 | Les 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```.** 107 | 108 | Si vous ajoutez un argument à votre Handler, Martini parcourera la liste des services et essayera de déterminer ses dépendances selon son type : 109 | ~~~ go 110 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini 111 | res.WriteHeader(200) // HTTP 200 112 | }) 113 | ~~~ 114 | Les services suivants sont inclus avec [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 115 | * [log.Logger](http://godoc.org/log#Logger) - Global logger for Martini. 116 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - Contexte d'une requête HTTP. 117 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` contenant les paramètres retrouvés par correspondance des routes. 118 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Service d'aide au routage. 119 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - Interface d'écriture de réponses HTTP. 120 | * [*http.Request](http://godoc.org/net/http/#Request) - Requête HTTP. 121 | 122 | ### Routeur 123 | Dans Martini, un chemin est une méthode HTTP liée à un modèle d'adresse URL. 124 | Chaque chemin peut avoir un seul ou plusieurs méthodes *handler* : 125 | ~~~ go 126 | m.Get("/", func() { 127 | // show something 128 | }) 129 | 130 | m.Patch("/", func() { 131 | // update something 132 | }) 133 | 134 | m.Post("/", func() { 135 | // create something 136 | }) 137 | 138 | m.Put("/", func() { 139 | // replace something 140 | }) 141 | 142 | m.Delete("/", func() { 143 | // destroy something 144 | }) 145 | 146 | m.Options("/", func() { 147 | // http options 148 | }) 149 | 150 | m.NotFound(func() { 151 | // handle 404 152 | }) 153 | ~~~ 154 | Les 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é. 155 | 156 | 157 | Les chemins peuvent inclure des paramètres nommés, accessibles avec le service [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) : 158 | ~~~ go 159 | m.Get("/hello/:name", func(params martini.Params) string { 160 | return "Hello " + params["name"] 161 | }) 162 | ~~~ 163 | 164 | Les chemins peuvent correspondre à des globs : 165 | ~~~ go 166 | m.Get("/hello/**", func(params martini.Params) string { 167 | return "Hello " + params["_1"] 168 | }) 169 | ~~~ 170 | Les expressions régulières peuvent aussi être utilisées : 171 | ~~~go 172 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 173 | return fmt.Sprintf ("Hello %s", params["name"]) 174 | }) 175 | ~~~ 176 | Jetez un oeil à la documentation [Go documentation](http://golang.org/pkg/regexp/syntax/) pour plus d'informations sur la syntaxe des expressions régulières. 177 | 178 | Les 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 : 179 | ~~~ go 180 | m.Get("/secret", authorize, func() { 181 | // this will execute as long as authorize doesn't write a response 182 | }) 183 | ~~~ 184 | 185 | Un groupe de chemins peut aussi être ajouté en utilisant la méthode ```Group``` : 186 | ~~~ go 187 | m.Group("/books", func(r martini.Router) { 188 | r.Get("/:id", GetBooks) 189 | r.Post("/new", NewBook) 190 | r.Put("/update/:id", UpdateBook) 191 | r.Delete("/delete/:id", DeleteBook) 192 | }) 193 | ~~~ 194 | 195 | Comme vous pouvez passer des middlewares à un handler, vous pouvez également passer des middlewares à des groupes : 196 | ~~~ go 197 | m.Group("/books", func(r martini.Router) { 198 | r.Get("/:id", GetBooks) 199 | r.Post("/new", NewBook) 200 | r.Put("/update/:id", UpdateBook) 201 | r.Delete("/delete/:id", DeleteBook) 202 | }, MyMiddleware1, MyMiddleware2) 203 | ~~~ 204 | 205 | ### Services 206 | Les 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*. 207 | 208 | 209 | #### Global Mapping 210 | Les instances Martini implémentent l'interace inject.Injector, ce qui facilite grandement le mapping de services : 211 | ~~~ go 212 | db := &MyDatabase{} 213 | m := martini.Classic() 214 | m.Map(db) // the service will be available to all handlers as *MyDatabase 215 | // ... 216 | m.Run() 217 | ~~~ 218 | 219 | #### Requête-Level Mapping 220 | Pour 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) : 221 | ~~~ go 222 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 223 | logger := &MyCustomLogger{req} 224 | c.Map(logger) // mapped as *MyCustomLogger 225 | } 226 | ~~~ 227 | 228 | #### Mapping de valeurs à des interfaces 229 | L'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 : 230 | ~~~ go 231 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 232 | rw := NewSpecialResponseWriter(res) 233 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter 234 | } 235 | ~~~ 236 | 237 | ### Serveur de fichiers statiques 238 | Une 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. 239 | Vous pouvez indiquer d'autres dossiers sources à l'aide du handler [martini.Static](http://godoc.org/github.com/go-martini/martini#Static). 240 | ~~~ go 241 | m.Use(martini.Static("assets")) // serve from the "assets" directory as well 242 | ~~~ 243 | 244 | ## Les middleware Handlers 245 | Les *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 : 246 | ~~~ go 247 | m.Use(func() { 248 | // do some middleware stuff 249 | }) 250 | ~~~ 251 | Vous 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 : 252 | ~~~ go 253 | m.Handlers( 254 | Middleware1, 255 | Middleware2, 256 | Middleware3, 257 | ) 258 | ~~~ 259 | Middleware 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 : 260 | ~~~ go 261 | // validate an api key 262 | m.Use(func(res http.ResponseWriter, req *http.Request) { 263 | if req.Header.Get("X-API-KEY") != "secret123" { 264 | res.WriteHeader(http.StatusUnauthorized) 265 | } 266 | }) 267 | ~~~ 268 | 269 | ### Next() (Suivant) 270 | [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 : 271 | ~~~ go 272 | // log before and after a request 273 | m.Use(func(c martini.Context, log *log.Logger){ 274 | log.Println("avant la requête") 275 | 276 | c.Next() 277 | 278 | log.Println("après la requête") 279 | }) 280 | ~~~ 281 | 282 | ## Martini Env 283 | Plusieurs 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. 284 | 285 | ## FAQ (Foire aux questions) 286 | 287 | ### Où puis-je trouver des middleware ? 288 | Commencer 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. 289 | 290 | * [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. 291 | * [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. 292 | * [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests 293 | * [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. 294 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. 295 | * [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. 296 | * [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. 297 | * [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. 298 | * [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. 299 | * [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. 300 | * [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. 301 | * [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. 302 | * [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI) 303 | 304 | ### Comment puis-je m'intègrer avec des serveurs existants ? 305 | Une 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 : 306 | 307 | ~~~ go 308 | package hello 309 | 310 | import ( 311 | "net/http" 312 | "github.com/go-martini/martini" 313 | ) 314 | 315 | func init() { 316 | m := martini.Classic() 317 | m.Get("/", func() string { 318 | return "Hello world!" 319 | }) 320 | http.Handle("/", m) 321 | } 322 | ~~~ 323 | 324 | ### Comment changer le port/adresse ? 325 | 326 | La 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. 327 | Pour avoir plus de flexibilité sur le port et l'adresse, utilisez la fonction `martini.RunOnAddr` à la place. 328 | 329 | ~~~ go 330 | m := martini.Classic() 331 | // ... 332 | log.Fatal(m.RunOnAddr(":8080")) 333 | ~~~ 334 | 335 | ### Rechargement du code en direct ? 336 | 337 | [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é. 338 | 339 | ## Contribuer 340 | Martini 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. 341 | 342 | ## A propos de Martini 343 | 344 | Inspiré 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. 345 | -------------------------------------------------------------------------------- /translations/README_ja_JP.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | MartiniはGolangによる、モジュール形式のウェブアプリケーション/サービスを作成するパワフルなパッケージです。 4 | 5 | ## はじめに 6 | 7 | Goをインストールし、[GOPATH](http://golang.org/doc/code.html#GOPATH)を設定した後、Martiniを始める最初の`.go`ファイルを作りましょう。これを`server.go`とします。 8 | 9 | ~~~ go 10 | package main 11 | 12 | import "github.com/go-martini/martini" 13 | 14 | func main() { 15 | m := martini.Classic() 16 | m.Get("/", func() string { 17 | return "Hello world!" 18 | }) 19 | m.Run() 20 | } 21 | ~~~ 22 | 23 | そのあとで、Martini パッケージをインストールします。(**go 1.1**か、それ以上のバーションが必要です。) 24 | 25 | ~~~ 26 | go get github.com/go-martini/martini 27 | ~~~ 28 | 29 | インストールが完了したら、サーバを起動しましょう。 30 | ~~~ 31 | go run server.go 32 | ~~~ 33 | 34 | そうすれば`localhost:3000`でMartiniのサーバが起動します。 35 | 36 | ## 分からないことがあったら? 37 | 38 | [メーリングリスト](https://groups.google.com/forum/#!forum/martini-go)に入る 39 | 40 | [デモビデオ](http://martini.codegangsta.io/#demo)をみる 41 | 42 | Stackoverflowで[martini tag](http://stackoverflow.com/questions/tagged/martini)を使い質問する 43 | 44 | GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) 45 | 46 | 47 | ## 特徴 48 | * 非常にシンプルに使用できる 49 | * 押し付けがましくないデザイン 50 | * 他のGolangパッケージとの協調性 51 | * 素晴らしいパスマッチングとルーティング 52 | * モジュラーデザイン - 機能性の付け外しが簡単 53 | * たくさんの良いハンドラ/ミドルウェア 54 | * 優れた 'すぐに使える' 機能たち 55 | * **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)との完全な互換性** 56 | 57 | ## もっとミドルウェアについて知るには? 58 | さらに多くのミドルウェアとその機能について知りたいときは、[martini-contrib](https://github.com/martini-contrib) オーガナイゼーションにあるリポジトリを確認してください。 59 | 60 | ## 目次(Table of Contents) 61 | * [Classic Martini](#classic-martini) 62 | * [ハンドラ](#handlers) 63 | * [ルーティング](#routing) 64 | * [サービス](#services) 65 | * [静的ファイル配信](#serving-static-files) 66 | * [ミドルウェアハンドラ](#middleware-handlers) 67 | * [Next()](#next) 68 | * [Martini Env](#martini-env) 69 | * [FAQ](#faq) 70 | 71 | ## Classic Martini 72 | 立ち上げ、すぐ実行できるように、[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) はほとんどのウェブアプリケーションで機能する、標準的な機能を提供します。 73 | ~~~ go 74 | m := martini.Classic() 75 | // ... middleware and routing goes here 76 | m.Run() 77 | ~~~ 78 | 79 | 下記が[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)が自動的に読み込む機能の一覧です。 80 | * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 81 | * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 82 | * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 83 | * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 84 | 85 | ### ハンドラ 86 | ハンドラはMartiniのコアであり、存在意義でもあります。ハンドラには基本的に、呼び出し可能な全ての関数が適応できます。 87 | ~~~ go 88 | m.Get("/", func() { 89 | println("hello world") 90 | }) 91 | ~~~ 92 | 93 | #### Return Values 94 | もしハンドラが何かを返す場合、Martiniはその結果を現在の[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)にstringとして書き込みます。 95 | ~~~ go 96 | m.Get("/", func() string { 97 | return "hello world" // HTTP 200 : "hello world" 98 | }) 99 | ~~~ 100 | 101 | 任意でステータスコードを返すこともできます。 102 | ~~~ go 103 | m.Get("/", func() (int, string) { 104 | return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" 105 | }) 106 | ~~~ 107 | 108 | #### Service Injection 109 | ハンドラはリフレクションによって実行されます。Martiniはハンドラの引数内の依存関係を**依存性の注入(Dependency Injection)**を使って解決しています。**これによって、Martiniはgolangの`http.HandlerFunc`と完全な互換性を備えています。** 110 | 111 | ハンドラに引数を追加すると、Martiniは内部のサービスを検索し、依存性をtype assertionによって解決しようと試みます。 112 | ~~~ go 113 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini 114 | res.WriteHeader(200) // HTTP 200 115 | }) 116 | ~~~ 117 | 118 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)にはこれらのサービスが内包されています: 119 | * [*log.Logger](http://godoc.org/log#Logger) - Martiniのためのグローバルなlogger. 120 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. 121 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string`型の、ルートマッチングによって検出されたパラメータ 122 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. 123 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. 124 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request. 125 | 126 | ### ルーティング 127 | Martiniでは、ルーティングはHTTPメソッドとURL-matching patternによって対になっており、それぞれが一つ以上のハンドラメソッドを持つことができます。 128 | ~~~ go 129 | m.Get("/", func() { 130 | // show something 131 | }) 132 | 133 | m.Patch("/", func() { 134 | // update something 135 | }) 136 | 137 | m.Post("/", func() { 138 | // create something 139 | }) 140 | 141 | m.Put("/", func() { 142 | // replace something 143 | }) 144 | 145 | m.Delete("/", func() { 146 | // destroy something 147 | }) 148 | 149 | m.Options("/", func() { 150 | // http options 151 | }) 152 | 153 | m.NotFound(func() { 154 | // handle 404 155 | }) 156 | ~~~ 157 | 158 | ルーティングはそれらの定義された順番に検索され、最初にマッチしたルーティングが呼ばれます。 159 | 160 | 名前付きパラメータを定義することもできます。これらのパラメータは[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)サービスを通じてアクセスすることができます: 161 | ~~~ go 162 | m.Get("/hello/:name", func(params martini.Params) string { 163 | return "Hello " + params["name"] 164 | }) 165 | ~~~ 166 | 167 | ワイルドカードを使用することができます: 168 | ~~~ go 169 | m.Get("/hello/**", func(params martini.Params) string { 170 | return "Hello " + params["_1"] 171 | }) 172 | ~~~ 173 | 174 | 正規表現も、このように使うことができます: 175 | ~~~go 176 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 177 | return fmt.Sprintf ("Hello %s", params["name"]) 178 | }) 179 | ~~~ 180 | 181 | もっと正規表現の構文をしりたい場合は、[Go documentation](http://golang.org/pkg/regexp/syntax/) を見てください。 182 | 183 | 184 | ハンドラは互いの上に積み重ねてることができます。これは、認証や承認処理の際に便利です: 185 | ~~~ go 186 | m.Get("/secret", authorize, func() { 187 | // this will execute as long as authorize doesn't write a response 188 | }) 189 | ~~~ 190 | 191 | ルーティンググループも、Groupメソッドを使用することで追加できます。 192 | ~~~ go 193 | m.Group("/books", func(r martini.Router) { 194 | r.Get("/:id", GetBooks) 195 | r.Post("/new", NewBook) 196 | r.Put("/update/:id", UpdateBook) 197 | r.Delete("/delete/:id", DeleteBook) 198 | }) 199 | ~~~ 200 | 201 | ハンドラにミドルウェアを渡せるのと同じように、グループにもミドルウェアを渡すことができます: 202 | ~~~ go 203 | m.Group("/books", func(r martini.Router) { 204 | r.Get("/:id", GetBooks) 205 | r.Post("/new", NewBook) 206 | r.Put("/update/:id", UpdateBook) 207 | r.Delete("/delete/:id", DeleteBook) 208 | }, MyMiddleware1, MyMiddleware2) 209 | ~~~ 210 | 211 | ### サービス 212 | サービスはハンドラの引数として注入されることで利用可能になるオブジェクトです。これらは*グローバル*、または*リクエスト*のレベルでマッピングすることができます。 213 | 214 | #### Global Mapping 215 | Martiniのインスタンスはinject.Injectorのインターフェースを実装しています。なので、サービスをマッピングすることは簡単です: 216 | ~~~ go 217 | db := &MyDatabase{} 218 | m := martini.Classic() 219 | m.Map(db) // the service will be available to all handlers as *MyDatabase 220 | // ... 221 | m.Run() 222 | ~~~ 223 | 224 | #### Request-Level Mapping 225 | リクエストレベルでのマッピングは[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)を使い、ハンドラ内で行うことができます: 226 | ~~~ go 227 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 228 | logger := &MyCustomLogger{req} 229 | c.Map(logger) // mapped as *MyCustomLogger 230 | } 231 | ~~~ 232 | 233 | #### Mapping values to Interfaces 234 | サービスの最も強力なことの一つは、インターフェースにサービスをマッピングできる機能です。例えば、[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)を機能を追加して上書きしたい場合、このようにハンドラを書くことができます: 235 | ~~~ go 236 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 237 | rw := NewSpecialResponseWriter(res) 238 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter 239 | } 240 | ~~~ 241 | 242 | ### 静的ファイル配信 243 | 244 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) インスタンスは、自動的にルート直下の "public" ディレクトリ以下の静的ファイルを配信します。[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)を追加することで、もっと多くのディレクトリを配信することもできます: 245 | ~~~ go 246 | m.Use(martini.Static("assets")) // serve from the "assets" directory as well 247 | ~~~ 248 | 249 | ## ミドルウェア ハンドラ 250 | ミドルウェア ハンドラは次に来るhttpリクエストとルーターの間に位置します。本質的には、その他のハンドラとの違いはありません。ミドルウェア ハンドラの追加はこのように行います: 251 | ~~~ go 252 | m.Use(func() { 253 | // do some middleware stuff 254 | }) 255 | ~~~ 256 | 257 | `Handlers`関数を使えば、ミドルウェアスタックを完全に制御できます。これは以前に設定されている全てのハンドラを置き換えます: 258 | 259 | ~~~ go 260 | m.Handlers( 261 | Middleware1, 262 | Middleware2, 263 | Middleware3, 264 | ) 265 | ~~~ 266 | 267 | ミドルウェア ハンドラはロギング、認証、承認プロセス、セッション、gzipping、エラーページの表示、その他httpリクエストの前後で怒らなければならないような場合に素晴らしく効果を発揮します。 268 | ~~~ go 269 | // validate an api key 270 | m.Use(func(res http.ResponseWriter, req *http.Request) { 271 | if req.Header.Get("X-API-KEY") != "secret123" { 272 | res.WriteHeader(http.StatusUnauthorized) 273 | } 274 | }) 275 | ~~~ 276 | 277 | ### Next() 278 | 279 | [Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) は他のハンドラが実行されたことを取得するために使用する機能です。これはhttpリクエストのあとに実行したい任意の関数があるときに素晴らしく機能します: 280 | ~~~ go 281 | // log before and after a request 282 | m.Use(func(c martini.Context, log *log.Logger){ 283 | log.Println("before a request") 284 | 285 | c.Next() 286 | 287 | log.Println("after a request") 288 | }) 289 | ~~~ 290 | 291 | ## Martini Env 292 | 293 | いくつかのMartiniのハンドラはdevelopment環境とproduction環境で別々の動作を提供するために`martini.Env`グローバル変数を使用しています。Martiniサーバを本番環境にデプロイする際には、`MARTINI_ENV=production`環境変数をセットすることをおすすめします。 294 | 295 | ## FAQ 296 | 297 | ### Middlewareを見つけるには? 298 | 299 | [martini-contrib](https://github.com/martini-contrib)プロジェクトをみることから始めてください。もし望みのものがなければ、新しいリポジトリをオーガナイゼーションに追加するために、martini-contribチームのメンバーにコンタクトを取ってみてください。 300 | 301 | * [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. 302 | * [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. 303 | * [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests 304 | * [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. 305 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. 306 | * [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. 307 | * [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. 308 | * [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. 309 | * [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. 310 | * [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. 311 | * [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. 312 | * [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. 313 | 314 | ### 既存のサーバに組み込むには? 315 | 316 | Martiniのインスタンスは`http.Handler`を実装しているので、既存のGoサーバ上でサブツリーを提供するのは簡単です。例えばこれは、Google App Engine上で動くMartiniアプリです: 317 | 318 | ~~~ go 319 | package hello 320 | 321 | import ( 322 | "net/http" 323 | "github.com/go-martini/martini" 324 | ) 325 | 326 | func init() { 327 | m := martini.Classic() 328 | m.Get("/", func() string { 329 | return "Hello world!" 330 | }) 331 | http.Handle("/", m) 332 | } 333 | ~~~ 334 | 335 | ### どうやってポート/ホストをかえるの? 336 | 337 | Martiniの`Run`関数はPORTとHOSTという環境変数を探し、その値を使用します。見つからない場合はlocalhost:3000がデフォルトで使用されます。もっと柔軟性をもとめるなら、`martini.RunOnAddr`関数が役に立ちます: 338 | 339 | ~~~ go 340 | m := martini.Classic() 341 | // ... 342 | log.Fatal(m.RunOnAddr(":8080")) 343 | ~~~ 344 | 345 | ### Live code reload? 346 | 347 | [gin](https://github.com/codegangsta/gin) と [fresh](https://github.com/pilu/fresh) 両方がMartiniアプリケーションを自動リロードできます。 348 | 349 | ## Contributing 350 | Martini本体は小さく、クリーンであるべきであり、ほとんどのコントリビューションは[martini-contrib](https://github.com/martini-contrib) オーガナイゼーション内で完結すべきですが、もしMartiniのコアにコントリビュートすることがあるなら、自由に行ってください。 351 | 352 | ## About 353 | 354 | Inspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra) 355 | 356 | Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) 357 | -------------------------------------------------------------------------------- /translations/README_ko_kr.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | 마티니(Martini)는 강력하고 손쉬운 웹애플리케이션 / 웹서비스개발을 위한 Golang 패키지입니다. 4 | 5 | ## 시작하기 6 | 7 | Go 인스톨 및 [GOPATH](http://golang.org/doc/code.html#GOPATH) 환경변수 설정 이후에, `.go` 파일 하나를 만들어 보죠..흠... 일단 `server.go`라고 부르겠습니다. 8 | ~~~go 9 | package main 10 | 11 | import "github.com/go-martini/martini" 12 | 13 | func main() { 14 | m := martini.Classic() 15 | m.Get("/", func() string { 16 | return "Hello, 세계!" 17 | }) 18 | m.Run() 19 | } 20 | ~~~ 21 | 22 | 마티니 패키지를 인스톨 합니다. (**go 1.1** 혹은 그 이상 버젼 필요): 23 | ~~~ 24 | go get github.com/go-martini/martini 25 | ~~~ 26 | 27 | 이제 서버를 돌려 봅시다: 28 | ~~~ 29 | go run server.go 30 | ~~~ 31 | 32 | 마티니 웹서버가 `localhost:3000`에서 돌아가고 있는 것을 확인하실 수 있을 겁니다. 33 | 34 | ## 도움이 필요하다면? 35 | 36 | [메일링 리스트](https://groups.google.com/forum/#!forum/martini-go)에 가입해 주세요 37 | 38 | [데모 비디오](http://martini.codegangsta.io/#demo)도 있어요. 39 | 40 | 혹은 Stackoverflow에 [마티니 태크](http://stackoverflow.com/questions/tagged/martini)를 이용해서 물어봐 주세요 41 | 42 | GoDoc [문서(documentation)](http://godoc.org/github.com/go-martini/martini) 43 | 44 | 문제는 전부다 영어로 되어 있다는 건데요 -_-;;; 45 | 나는 한글 아니면 보기 싫다! 하는 분들은 아래 링크를 참조하세요 46 | - [golang-korea](https://code.google.com/p/golang-korea/) 47 | - 혹은 ([RexK](http://github.com/RexK))의 이메일로 연락주세요. 48 | 49 | ## 주요기능 50 | * 사용하기 엄청 쉽습니다. 51 | * 비간섭(Non-intrusive) 디자인 52 | * 다른 Golang 패키지들과 잘 어울립니다. 53 | * 끝내주는 경로 매칭과 라우팅. 54 | * 모듈형 디자인 - 기능추가가 쉽고, 코드 꺼내오기도 쉬움. 55 | * 유용한 핸들러와 미들웨어가 많음. 56 | * 훌륭한 패키지화(out of the box) 기능들 57 | * **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 인터페이스와 호환율 100%** 58 | 59 | ## 미들웨어(Middleware) 60 | 미들웨어들과 추가기능들은 [martini-contrib](https://github.com/martini-contrib)에서 확인해 주세요. 61 | 62 | ## 목차 63 | * [Classic Martini](#classic-martini) 64 | * [핸들러](#핸들러handlers) 65 | * [라우팅](#라우팅routing) 66 | * [서비스](#서비스services) 67 | * [정적파일 서빙](#정적파일-서빙serving-static-files) 68 | * [미들웨어 핸들러](#미들웨어-핸들러middleware-handlers) 69 | * [Next()](#next) 70 | * [Martini Env](#martini-env) 71 | * [FAQ](#faq) 72 | 73 | ## Classic Martini 74 | 마티니를 쉽고 빠르게 이용하시려면, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)를 이용해 보세요. 보통 웹애플리케이션에서 사용하는 설정들이 이미 포함되어 있습니다. 75 | ~~~ go 76 | m := martini.Classic() 77 | // ... 미들웨어와 라우팅 설정은 이곳에 오면 작성하면 됩니다. 78 | m.Run() 79 | ~~~ 80 | 81 | 아래는 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)에 자동으로 제공되는 기본 기능들 입니다. 82 | 83 | * Request/Response 로그 기능 - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 84 | * 패닉 리커버리 (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 85 | * 정적 파일 서빙 - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 86 | * 라우팅(Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 87 | 88 | ### 핸들러(Handlers) 89 | 90 | 핸들러(Handlers)는 마티니의 핵심입니다. 핸들러는 기본적으로 실행 가능한 모든 형태의 함수들입니다. 91 | ~~~ go 92 | m.Get("/", func() { 93 | println("hello 세계") 94 | }) 95 | ~~~ 96 | 97 | #### 반환 값 (Return Values) 98 | 핸들러가 반환을 하는 함수라면, 마티니는 반환 값을 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)에 스트링으로 입력 할 것입니다. 99 | ~~~ go 100 | m.Get("/", func() string { 101 | return "hello 세계" // HTTP 200 : "hello 세계" 102 | }) 103 | ~~~ 104 | 105 | 원하신다면, 선택적으로 상태코드도 함께 반환 할 수 있습니다. 106 | ~~~ go 107 | m.Get("/", func() (int, string) { 108 | return 418, "난 주전자야!" // HTTP 418 : "난 주전자야!" 109 | }) 110 | ~~~ 111 | 112 | #### 서비스 주입(Service Injection) 113 | 핸들러들은 리플렉션을 통해 호출됩니다. 마티니는 *의존성 주입*을 이용해서 핸들러의 인수들을 주입합니다. **이것이 마티니를 `http.HandlerFunc` 인터페이스와 100% 호환할 수 있게 해줍니다.** 114 | 115 | 핸들러의 인수를 입력했다면, 마티니가 서비스 목록들을 살펴본 후 타입확인(type assertion)을 통해 의존성문제 해결을 시도 할 것입니다. 116 | ~~~ go 117 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res와 req는 마티니에 의해 주입되었다. 118 | res.WriteHeader(200) // HTTP 200 119 | }) 120 | ~~~ 121 | 122 | 아래 서비스들은 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):에 포함되어 있습니다. 123 | * [*log.Logger](http://godoc.org/log#Logger) - 마티니의 글로벌(전역) 로그. 124 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http 요청 컨텍스트. 125 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - 루트 매칭으로 찾은 인자를 `map[string]string`으로 변형. 126 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - 루트 도우미 서비스. 127 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer 인터페이스. 128 | * [*http.Request](http://godoc.org/net/http/#Request) - http 리퀘스트. 129 | 130 | ### 라우팅(Routing) 131 | 마티니에서 루트는 HTTP 메소드와 URL매칭 패턴의 페어입니다. 132 | 각 루트는 하나 혹은 그 이상의 핸들러 메소드를 가질 수 있습니다. 133 | ~~~ go 134 | m.Get("/", func() { 135 | // 보여줘 봐 136 | }) 137 | 138 | m.Patch("/", func() { 139 | // 업데이트 좀 해 140 | }) 141 | 142 | m.Post("/", func() { 143 | // 만들어봐 144 | }) 145 | 146 | m.Put("/", func() { 147 | // 변경해봐 148 | }) 149 | 150 | m.Delete("/", func() { 151 | // 없애버려! 152 | }) 153 | 154 | m.Options("/", func() { 155 | // http 옵션 메소드 156 | }) 157 | 158 | m.NotFound(func() { 159 | // 404 해결하기 160 | }) 161 | ~~~ 162 | 163 | 루트들은 정의된 순서대로 매칭된다. 들어온 요구에 처음으로 매칭된 루트가 호출된다. 164 | 165 | 루트 패턴은 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service로 액세스 가능한 인자들을 포함하기도 한다: 166 | ~~~ go 167 | m.Get("/hello/:name", func(params martini.Params) string { 168 | return "Hello " + params["name"] // :name을 Params인자에서 추출 169 | }) 170 | ~~~ 171 | 172 | 루트는 별표식(\*)으로 매칭 될 수도 있습니다: 173 | ~~~ go 174 | m.Get("/hello/**", func(params martini.Params) string { 175 | return "Hello " + params["_1"] 176 | }) 177 | ~~~ 178 | 179 | 정규식도 사용가능합니다: 180 | ~~~go 181 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 182 | return fmt.Sprintf ("Hello %s", params["name"]) 183 | }) 184 | ~~~ 185 | 정규식에 관하여 더 자세히 알고 싶다면 [Go documentation](http://golang.org/pkg/regexp/syntax/)을 참조해 주세요. 186 | 187 | 루트 핸들러는 스택을 쌓아 올릴 수 있습니다. 특히 유저 인증작업이나, 허가작업에 유용히 쓰일 수 있죠. 188 | ~~~ go 189 | m.Get("/secret", authorize, func() { 190 | // 이 함수는 authorize 함수가 resopnse에 결과를 쓰지 않는이상 실행 될 거에요. 191 | }) 192 | ~~~ 193 | 194 | ```RootGroup```은 루트들을 한 곳에 모아 정리하는데 유용합니다. 195 | ~~~ go 196 | m.Group("/books", func(r martini.Router) { 197 | r.Get("/:id", GetBooks) 198 | r.Post("/new", NewBook) 199 | r.Put("/update/:id", UpdateBook) 200 | r.Delete("/delete/:id", DeleteBook) 201 | }) 202 | ~~~ 203 | 204 | 핸들러에 미들웨어를 집어넣을 수 있는것과 같이, 그룹에도 미들웨어를 집어넣는 것이 가능합니다. 205 | ~~~ go 206 | m.Group("/books", func(r martini.Router) { 207 | r.Get("/:id", GetBooks) 208 | r.Post("/new", NewBook) 209 | r.Put("/update/:id", UpdateBook) 210 | r.Delete("/delete/:id", DeleteBook) 211 | }, MyMiddleware1, MyMiddleware2) 212 | ~~~ 213 | 214 | ### 서비스(Services) 215 | 서비스는 핸들러의 인수목록에 주입 될 수 있는 오브젝트들을 말합니다. 서비스는 *글로벌* 혹은 *리퀘스트* 레벨단위로 주입이 가능합니다. 216 | 217 | #### 글로벌 맵핑(Global Mapping) 218 | 마타니 인스턴스는 서비스 맵핑을 쉽게 하기 위해서 inject.Injector 인터페이스를 반형합니다: 219 | ~~~ go 220 | db := &MyDatabase{} 221 | m := martini.Classic() 222 | m.Map(db) // 서비스가 모든 핸들러에서 *MyDatabase로서 사용될 수 있습니다. 223 | // ... 224 | m.Run() 225 | ~~~ 226 | 227 | #### 리퀘스트 레벨 맵핑(Request-Level Mapping) 228 | 리퀘스트 레벨 맵핑은 핸들러안에서 [martini.Context](http://godoc.org/github.com/go-martini/martini#Context)를 사용하면 됩니다: 229 | ~~~ go 230 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 231 | logger := &MyCustomLogger{req} 232 | c.Map(logger) // *MyCustomLogger로서 맵핑 됨 233 | } 234 | ~~~ 235 | 236 | #### 인터페이스로 값들 맵핑(Mapping values to Interfaces) 237 | 서비스의 강력한 기능중 하나는 서비스를 인터페이스로 맵핑이 가능하다는 것입니다. 예를들어, [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)를 재정의(override)해서 부가 기능들을 수행하게 하고 싶으시다면, 아래와 같이 핸들러를 작성 하시면 됩니다. 238 | 239 | ~~~ go 240 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 241 | rw := NewSpecialResponseWriter(res) 242 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // ResponseWriter를 NewResponseWriter로 치환(override) 243 | } 244 | ~~~ 245 | 246 | ### 정적파일 서빙(Serving Static Files) 247 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 인스턴스는 "public" 폴더안에 있는 파일들을 정적파일로써 자동으로 서빙합니다. 더 많은 폴더들은 정적파일 폴더에 포함시키시려면 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 핸들러를 이용하시면 됩니다. 248 | 249 | ~~~ go 250 | m.Use(martini.Static("assets")) // "assets" 폴더에서도 정적파일 서빙. 251 | ~~~ 252 | 253 | ## 미들웨어 핸들러(Middleware Handlers) 254 | 미들웨어 핸들러는 http request와 라우팅 사이에서 작동합니다. 미들웨어 핸들러는 근본적으로 다른 핸들러들과는 다릅니다. 사용방법은 아래와 같습니다: 255 | ~~~ go 256 | m.Use(func() { 257 | // 미들웨어 임무 수행! 258 | }) 259 | ~~~ 260 | 261 | `Handlers`를 이용하여 미들웨어 스택들의 완전 컨트롤이 가능합니다. 다만, 이렇게 설정하시면 이전에 `Handlers`를 이용하여 설정한 핸들러들은 사라집니다: 262 | ~~~ go 263 | m.Handlers( 264 | Middleware1, 265 | Middleware2, 266 | Middleware3, 267 | ) 268 | ~~~ 269 | 270 | 미들웨어 핸들러는 로깅(logging), 허가(authorization), 인가(authentication), 세션, 압축(gzipping), 에러 페이지 등 등, http request의 전후로 실행되어야 할 일들을 처리하기 아주 좋습니다: 271 | ~~~ go 272 | // API 키 확인작업 273 | m.Use(func(res http.ResponseWriter, req *http.Request) { 274 | if req.Header.Get("X-API-KEY") != "비밀암호!!!" { 275 | res.WriteHeader(http.StatusUnauthorized) // HTTP 401 276 | } 277 | }) 278 | ~~~ 279 | 280 | ### Next() 281 | [Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)는 선택적 함수입니다. 이 함수는 http request가 다 작동 될때까지 기다립니다.따라서 http request 이후에 실행 되어야 할 업무들을 수행하기 좋은 함수입니다. 282 | ~~~ go 283 | // log before and after a request 284 | m.Use(func(c martini.Context, log *log.Logger){ 285 | log.Println("request전입니다.") 286 | 287 | c.Next() 288 | 289 | log.Println("request후 입니다.") 290 | }) 291 | ~~~ 292 | 293 | ## Martini Env 294 | 마티니 핸들러들은 `martini.Env` 글로벌 변수를 사용하여 개발환경에서는 프로덕션 환경과는 다르게 작동하기도 합니다. 따라서, 프로덕션 서버로 마티니 서버를 배포하시게 된다면 꼭 환경변수 `MARTINI_ENV=production`를 세팅해주시기 바랍니다. 295 | 296 | ## FAQ 297 | 298 | ### 미들웨어들을 어디서 찾아야 하나요? 299 | 300 | 깃헙에서 [martini-contrib](https://github.com/martini-contrib) 프로젝트들을 찾아보세요. 만약에 못 찾으시겠으면, martini-contrib 팀원들에게 연락해서 하나 만들어 달라고 해보세요. 301 | * [auth](https://github.com/martini-contrib/auth) - 인증작업을 도와주는 핸들러. 302 | * [binding](https://github.com/martini-contrib/binding) - request를 맵핑하고 검사하는 핸들러. 303 | * [gzip](https://github.com/martini-contrib/gzip) - gzip 핸들러. 304 | * [render](https://github.com/martini-contrib/render) - HTML 템플레이트들과 JSON를 사용하기 편하게 해주는 핸들러. 305 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - `Accept-Language` HTTP 해더를 파싱 할 때 유용한 핸들러. 306 | * [sessions](https://github.com/martini-contrib/sessions) - 세션 서비스를 제공하는 핸들러. 307 | * [strip](https://github.com/martini-contrib/strip) - URL 프리틱스를 없애주는 핸들러. 308 | * [method](https://github.com/martini-contrib/method) - 해더나 폼필드를 이용한 HTTP 메소드 치환. 309 | * [secure](https://github.com/martini-contrib/secure) - 몇몇 보안설정을 위한 핸들러. 310 | * [encoder](https://github.com/martini-contrib/encoder) - 데이터 렌더링과 컨텐트 타입을위한 인코딩 서비스. 311 | * [cors](https://github.com/martini-contrib/cors) - CORS 서포트를 위한 핸들러. 312 | * [oauth2](https://github.com/martini-contrib/oauth2) - OAuth2.0 로그인 핸들러. 페이스북, 구글, 깃헙 지원. 313 | 314 | ### 현재 작동중인 서버에 마티니를 적용하려면? 315 | 316 | 마티니 인스턴스는 `http.Handler` 인터페이스를 차용합니다. 따라서 Go 서버 서브트리로 쉽게 사용될 수 있습니다. 아래 코드는 구글 앱 엔진에서 작동하는 마티니 앱입니다: 317 | 318 | ~~~ go 319 | package hello 320 | 321 | import ( 322 | "net/http" 323 | "github.com/go-martini/martini" 324 | ) 325 | 326 | func init() { 327 | m := martini.Classic() 328 | m.Get("/", func() string { 329 | return "Hello 세계!" 330 | }) 331 | http.Handle("/", m) 332 | } 333 | ~~~ 334 | 335 | ### 포트와 호스트는 어떻게 바꾸나요? 336 | 337 | 마티니의 `Run` 함수는 PORT와 HOST 환경변수를 이용하는데, 설정이 안되어 있다면 localhost:3000으로 설정 되어 집니다. 338 | 좀더 유연하게 설정을 하고 싶다면, `martini.RunOnAddr`를 활용해 주세요. 339 | 340 | ~~~ go 341 | m := martini.Classic() 342 | // ... 343 | log.Fatal(m.RunOnAddr(":8080")) 344 | ~~~ 345 | 346 | ### 라이브 코드 리로드? 347 | 348 | [gin](https://github.com/codegangsta/gin) 과 [fresh](https://github.com/pilu/fresh) 가 마티니 앱의 라이브 리로드를 도와줍니다. 349 | 350 | ## 공헌하기(Contributing) 351 | 352 | 마티니는 간단하고 가벼운 패키지로 남을 것입니다. 따라서 보통 대부분의 공헌들은 [martini-contrib](https://github.com/martini-contrib) 그룹의 저장소로 가게 됩니다. 만약 마티니 코어에 기여하고 싶으시다면 주저없이 Pull Request를 해주세요. 353 | 354 | ## About 355 | 356 | [express](https://github.com/visionmedia/express) 와 [sinatra](https://github.com/sinatra/sinatra)의 영향을 받았습니다. 357 | 358 | 마티니는 [Code Gangsta](http://codegangsta.io/)가 디자인 했습니다. 359 | -------------------------------------------------------------------------------- /translations/README_pt_br.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | **NOTA:** O martini framework não é mais mantido. 4 | 5 | Martini é um poderoso pacote para escrever aplicações/serviços modulares em Golang.. 6 | 7 | 8 | ## Vamos começar 9 | 10 | Apó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`. 11 | 12 | ~~~ go 13 | package main 14 | 15 | import "github.com/go-martini/martini" 16 | 17 | func main() { 18 | m := martini.Classic() 19 | m.Get("/", func() string { 20 | return "Hello world!" 21 | }) 22 | m.Run() 23 | } 24 | ~~~ 25 | 26 | Então instale o pacote do Martini (É necessário **go 1.1** ou superior): 27 | ~~~ 28 | go get github.com/go-martini/martini 29 | ~~~ 30 | 31 | Então rode o servidor: 32 | ~~~ 33 | go run server.go 34 | ~~~ 35 | 36 | Agora você tem um webserver Martini rodando na porta `localhost:3000`. 37 | 38 | ## Obtenha ajuda 39 | 40 | Assine a [Lista de email](https://groups.google.com/forum/#!forum/martini-go) 41 | 42 | Veja o [Vídeo demonstrativo](http://martini.codegangsta.io/#demo) 43 | 44 | Use a tag [martini](http://stackoverflow.com/questions/tagged/martini) para perguntas no Stackoverflow 45 | 46 | 47 | 48 | ## Caracteríticas 49 | * Extrema simplicidade de uso. 50 | * Design não intrusivo. 51 | * Boa integração com outros pacotes Golang. 52 | * Router impressionante. 53 | * Design modular - Fácil para adicionar e remover funcionalidades. 54 | * Muito bom no uso handlers/middlewares. 55 | * Grandes caracteríticas inovadoras. 56 | * **Completa compatibilidade com a interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** 57 | 58 | ## Mais Middleware 59 | Para mais middleware e funcionalidades, veja os repositórios em [martini-contrib](https://github.com/martini-contrib). 60 | 61 | ## Tabela de Conteudos 62 | * [Classic Martini](#classic-martini) 63 | * [Handlers](#handlers) 64 | * [Routing](#routing) 65 | * [Services](#services) 66 | * [Serving Static Files](#serving-static-files) 67 | * [Middleware Handlers](#middleware-handlers) 68 | * [Next()](#next) 69 | * [Martini Env](#martini-env) 70 | * [FAQ](#faq) 71 | 72 | ## Classic Martini 73 | Para iniciar rapidamente, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) provê algumas ferramentas razoáveis para maioria das aplicações web: 74 | ~~~ go 75 | m := martini.Classic() 76 | // ... middleware e rota aqui 77 | m.Run() 78 | ~~~ 79 | 80 | Algumas das funcionalidade que o [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) oferece automaticamente são: 81 | * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 82 | * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 83 | * Servidor de arquivos státicos - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 84 | * Rotas - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 85 | 86 | ### Handlers 87 | Handlers são o coração e a alma do Martini. Um handler é basicamente qualquer função que pode ser chamada: 88 | ~~~ go 89 | m.Get("/", func() { 90 | println("hello world") 91 | }) 92 | ~~~ 93 | 94 | #### Retorno de Valores 95 | Se um handler retornar alguma coisa, Martini irá escrever o valor retornado como uma string ao [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter): 96 | ~~~ go 97 | m.Get("/", func() string { 98 | return "hello world" // HTTP 200 : "hello world" 99 | }) 100 | ~~~ 101 | 102 | Você também pode retornar o código de status: 103 | ~~~ go 104 | m.Get("/", func() (int, string) { 105 | return 418, "Eu sou um bule" // HTTP 418 : "Eu sou um bule" 106 | }) 107 | ~~~ 108 | 109 | #### Injeção de Serviços 110 | Handlers 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.** 111 | 112 | Se você adicionar um argumento ao seu Handler, Martini ira procurar na sua lista de serviços e tentar resolver sua dependencia pelo seu tipo: 113 | ~~~ go 114 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res e req são injetados pelo Martini 115 | res.WriteHeader(200) // HTTP 200 116 | }) 117 | ~~~ 118 | 119 | Os seguintes serviços são incluídos com [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 120 | * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini. 121 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. 122 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nomes dos parâmetros buscados pela rota. 123 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Serviço de auxílio as rotas. 124 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escreve a interface. 125 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request. 126 | 127 | ### Rotas 128 | No Martini, uma rota é um método HTTP emparelhado com um padrão de URL de correspondência. 129 | Cada rota pode ter um ou mais métodos handler: 130 | ~~~ go 131 | m.Get("/", func() { 132 | // mostra alguma coisa 133 | }) 134 | 135 | m.Patch("/", func() { 136 | // altera alguma coisa 137 | }) 138 | 139 | m.Post("/", func() { 140 | // cria alguma coisa 141 | }) 142 | 143 | m.Put("/", func() { 144 | // sobrescreve alguma coisa 145 | }) 146 | 147 | m.Delete("/", func() { 148 | // destrói alguma coisa 149 | }) 150 | 151 | m.Options("/", func() { 152 | // opções do HTTP 153 | }) 154 | 155 | m.NotFound(func() { 156 | // manipula 404 157 | }) 158 | ~~~ 159 | 160 | As rotas são combinadas na ordem em que são definidas. A primeira rota que corresponde a solicitação é chamada. 161 | 162 | O padrão de rotas pode incluir parâmetros que podem ser acessados via [martini.Params](http://godoc.org/github.com/go-martini/martini#Params): 163 | ~~~ go 164 | m.Get("/hello/:name", func(params martini.Params) string { 165 | return "Hello " + params["name"] 166 | }) 167 | ~~~ 168 | 169 | As rotas podem ser combinados com expressões regulares e globs: 170 | ~~~ go 171 | m.Get("/hello/**", func(params martini.Params) string { 172 | return "Hello " + params["_1"] 173 | }) 174 | ~~~ 175 | 176 | Expressões regulares podem ser bem usadas: 177 | ~~~go 178 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 179 | return fmt.Sprintf ("Hello %s", params["name"]) 180 | }) 181 | ~~~ 182 | Dê uma olhada na [documentação](http://golang.org/pkg/regexp/syntax/) para mais informações sobre expressões regulares. 183 | 184 | 185 | Handlers de rota podem ser empilhados em cima uns dos outros, o que é útil para coisas como autenticação e autorização: 186 | ~~~ go 187 | m.Get("/secret", authorize, func() { 188 | // Será executado quando authorize não escrever uma resposta 189 | }) 190 | ~~~ 191 | 192 | Grupos de rota podem ser adicionados usando o método Group. 193 | ~~~ go 194 | m.Group("/books", func(r martini.Router) { 195 | r.Get("/:id", GetBooks) 196 | r.Post("/new", NewBook) 197 | r.Put("/update/:id", UpdateBook) 198 | r.Delete("/delete/:id", DeleteBook) 199 | }) 200 | ~~~ 201 | 202 | Assim como você pode passar middlewares para um manipulador você pode passar middlewares para grupos. 203 | ~~~ go 204 | m.Group("/books", func(r martini.Router) { 205 | r.Get("/:id", GetBooks) 206 | r.Post("/new", NewBook) 207 | r.Put("/update/:id", UpdateBook) 208 | r.Delete("/delete/:id", DeleteBook) 209 | }, MyMiddleware1, MyMiddleware2) 210 | ~~~ 211 | 212 | ### Serviços 213 | Serviç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*. 214 | 215 | #### Mapeamento Global 216 | Um exemplo onde o Martini implementa a interface inject.Injector, então o mapeamento de um serviço é fácil: 217 | ~~~ go 218 | db := &MyDatabase{} 219 | m := martini.Classic() 220 | m.Map(db) // o serviço estará disponível para todos os handlers *MyDatabase. 221 | // ... 222 | m.Run() 223 | ~~~ 224 | 225 | #### Mapeamento por requisição 226 | Mapeamento do nível de request pode ser feito via handler através [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): 227 | ~~~ go 228 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 229 | logger := &MyCustomLogger{req} 230 | c.Map(logger) // mapeamento é *MyCustomLogger 231 | } 232 | ~~~ 233 | 234 | #### Valores de Mapeamento para Interfaces 235 | Uma 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: 236 | ~~~ go 237 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 238 | rw := NewSpecialResponseWriter(res) 239 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // substituir ResponseWriter com nosso ResponseWriter invólucro 240 | } 241 | ~~~ 242 | 243 | ### Servindo Arquivos Estáticos 244 | Uma 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. 245 | Você pode servir de mais diretórios, adicionando mais [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. 246 | ~~~ go 247 | m.Use(martini.Static("assets")) // servindo os arquivos do diretório "assets" 248 | ~~~ 249 | 250 | ## Middleware Handlers 251 | Middleware 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: 252 | ~~~ go 253 | m.Use(func() { 254 | // faz algo com middleware 255 | }) 256 | ~~~ 257 | 258 | Você pode ter o controle total sobre a pilha de middleware com a função `Handlers`. Isso irá substituir quaisquer manipuladores que foram previamente definidos: 259 | ~~~ go 260 | m.Handlers( 261 | Middleware1, 262 | Middleware2, 263 | Middleware3, 264 | ) 265 | ~~~ 266 | 267 | Middleware 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: 268 | ~~~ go 269 | // Valida uma chave de API 270 | m.Use(func(res http.ResponseWriter, req *http.Request) { 271 | if req.Header.Get("X-API-KEY") != "secret123" { 272 | res.WriteHeader(http.StatusUnauthorized) 273 | } 274 | }) 275 | ~~~ 276 | 277 | ### Next() 278 | [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: 279 | ~~~ go 280 | // log antes e depois do request 281 | m.Use(func(c martini.Context, log *log.Logger){ 282 | log.Println("antes do request") 283 | 284 | c.Next() 285 | 286 | log.Println("depois do request") 287 | }) 288 | ~~~ 289 | 290 | ## Martini Env 291 | 292 | Martini 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. 293 | 294 | ## FAQ 295 | 296 | ### Onde posso encontrar o middleware X? 297 | 298 | Inicie 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. 299 | 300 | * [auth](https://github.com/martini-contrib/auth) - Handlers para autenticação. 301 | * [binding](https://github.com/martini-contrib/binding) - Handler para mapeamento/validação de um request a estrutura. 302 | * [gzip](https://github.com/martini-contrib/gzip) - Handler para adicionar compreção gzip para o requests 303 | * [render](https://github.com/martini-contrib/render) - Handler que providencia uma rederização simples para JSON e templates HTML. 304 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para parsing do `Accept-Language` no header HTTP. 305 | * [sessions](https://github.com/martini-contrib/sessions) - Handler que prove o serviço de sessão. 306 | * [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. 307 | * [method](https://github.com/martini-contrib/method) - HTTP método de substituição via cabeçalho ou campos do formulário. 308 | * [secure](https://github.com/martini-contrib/secure) - Implementa rapidamente itens de segurança. 309 | * [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. 310 | * [cors](https://github.com/martini-contrib/cors) - Handler que habilita suporte a CORS. 311 | * [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. 312 | 313 | ### Como faço para integrar com os servidores existentes? 314 | 315 | Uma instância do Martini implementa `http.Handler`, de modo que pode ser facilmente utilizado para servir sub-rotas e diretórios 316 | em servidores Go existentes. Por exemplo, este é um aplicativo Martini trabalhando para Google App Engine: 317 | 318 | ~~~ go 319 | package hello 320 | 321 | import ( 322 | "net/http" 323 | "github.com/go-martini/martini" 324 | ) 325 | 326 | func init() { 327 | m := martini.Classic() 328 | m.Get("/", func() string { 329 | return "Hello world!" 330 | }) 331 | http.Handle("/", m) 332 | } 333 | ~~~ 334 | 335 | ### Como faço para alterar a porta/host? 336 | 337 | A 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. 338 | Para ter mais flexibilidade sobre a porta e host use a função `martini.RunOnAddr`. 339 | 340 | ~~~ go 341 | m := martini.Classic() 342 | // ... 343 | log.Fatal(m.RunOnAddr(":8080")) 344 | ~~~ 345 | 346 | ### Servidor com autoreload? 347 | 348 | [gin](https://github.com/codegangsta/gin) e [fresh](https://github.com/pilu/fresh) são aplicativos para autoreload do Martini. 349 | 350 | ## Contribuindo 351 | Martini é 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. 352 | 353 | ## Sobre 354 | 355 | Inspirado por [express](https://github.com/visionmedia/express) e [sinatra](https://github.com/sinatra/sinatra) 356 | 357 | Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) 358 | -------------------------------------------------------------------------------- /translations/README_ru_RU.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | Martini - мощный пакет для быстрой разработки веб приложений и сервисов на Golang. 4 | 5 | ## Начало работы 6 | 7 | После установки Golang и настройки вашего [GOPATH](http://golang.org/doc/code.html#GOPATH), создайте ваш первый `.go` файл. Назовем его `server.go`. 8 | 9 | ~~~ go 10 | package main 11 | 12 | import "github.com/go-martini/martini" 13 | 14 | func main() { 15 | m := martini.Classic() 16 | m.Get("/", func() string { 17 | return "Hello world!" 18 | }) 19 | m.Run() 20 | } 21 | ~~~ 22 | 23 | Потом установите пакет Martini (требуется **go 1.1** или выше): 24 | ~~~ 25 | go get github.com/go-martini/martini 26 | ~~~ 27 | 28 | Потом запустите ваш сервер: 29 | ~~~ 30 | go run server.go 31 | ~~~ 32 | 33 | И вы получите запущенный Martini сервер на `localhost:3000`. 34 | 35 | ## Помощь 36 | 37 | Присоединяйтесь к [рассылке](https://groups.google.com/forum/#!forum/martini-go) 38 | 39 | Задавайте вопросы на Stackoverflow используя [тэг martini](http://stackoverflow.com/questions/tagged/martini) 40 | 41 | GoDoc [документация](http://godoc.org/github.com/go-martini/martini) 42 | 43 | 44 | ## Возможности 45 | * Очень прост в использовании. 46 | * Ненавязчивый дизайн. 47 | * Хорошо сочетается с другими пакетами. 48 | * Потрясающий роутинг и маршрутизация. 49 | * Модульный дизайн - легко добавлять и исключать функциональность. 50 | * Большое количество хороших обработчиков/middlewares, готовых к использованию. 51 | * Отличный набор 'из коробки'. 52 | * **Полностью совместим с интерфейсом [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** 53 | 54 | ## Больше Middleware 55 | Смотрите репозитории организации [martini-contrib](https://github.com/martini-contrib), для большей информации о функциональности и middleware. 56 | 57 | ## Содержание 58 | * [Classic Martini](#classic-martini) 59 | * [Обработчики](#%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8) 60 | * [Роутинг](#%D0%A0%D0%BE%D1%83%D1%82%D0%B8%D0%BD%D0%B3) 61 | * [Сервисы](#%D0%A1%D0%B5%D1%80%D0%B2%D0%B8%D1%81%D1%8B) 62 | * [Отдача статических файлов](#%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) 63 | * [Middleware обработчики](#middleware-%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8) 64 | * [Next()](#next) 65 | * [Окружение](#%D0%9E%D0%BA%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) 66 | * [FAQ](#faq) 67 | 68 | ## Classic Martini 69 | Для быстрого старта [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) предлагает несколько предустановок, это используется для большинства веб приложений: 70 | ~~~ go 71 | m := martini.Classic() 72 | // ... middleware и роутинг здесь 73 | m.Run() 74 | ~~~ 75 | 76 | Ниже представлена уже подключенная [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) функциональность: 77 | 78 | * Request/Response логгирование - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 79 | * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 80 | * Отдача статики - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 81 | * Роутинг - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 82 | 83 | ### Обработчики 84 | Обработчики - это сердце и душа Martini. Обработчик - любая функция, которая может быть вызвана: 85 | ~~~ go 86 | m.Get("/", func() { 87 | println("hello world") 88 | }) 89 | ~~~ 90 | 91 | #### Возвращаемые значения 92 | Если обработчик возвращает что-либо, Martini запишет это как результат в текущий [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), в виде строки: 93 | ~~~ go 94 | m.Get("/", func() string { 95 | return "hello world" // HTTP 200 : "hello world" 96 | }) 97 | ~~~ 98 | 99 | Так же вы можете возвращать код статуса, опционально: 100 | ~~~ go 101 | m.Get("/", func() (int, string) { 102 | return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" 103 | }) 104 | ~~~ 105 | 106 | #### Внедрение сервисов 107 | Обработчики вызываются посредством рефлексии. Martini использует **Внедрение зависимости** для разрешения зависимостей в списке аргумента обработчика. **Это делает Martini полностью совместимым с интерфейсом `http.HandlerFunc`.** 108 | 109 | Если вы добавите аргументы в ваш обработчик, Martini будет пытаться найти этот список сервисов за счет проверки типов(type assertion): 110 | ~~~ go 111 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res и req будут внедрены Martini 112 | res.WriteHeader(200) // HTTP 200 113 | }) 114 | ~~~ 115 | 116 | Следующие сервисы включены в [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 117 | 118 | * [*log.Logger](http://godoc.org/log#Logger) - Глобальный логгер для Martini. 119 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request контекст. 120 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` именованных аргументов из роутера. 121 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Хэлпер роутеров. 122 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer интерфейс. 123 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request. 124 | 125 | ### Роутинг 126 | В Martini, роут - это объединенные паттерн и HTTP метод. 127 | Каждый роут может принимать один или несколько обработчиков: 128 | ~~~ go 129 | m.Get("/", func() { 130 | // показать что-то 131 | }) 132 | 133 | m.Patch("/", func() { 134 | // обновить что-то 135 | }) 136 | 137 | m.Post("/", func() { 138 | // создать что-то 139 | }) 140 | 141 | m.Put("/", func() { 142 | // изменить что-то 143 | }) 144 | 145 | m.Delete("/", func() { 146 | // удалить что-то 147 | }) 148 | 149 | m.Options("/", func() { 150 | // http опции 151 | }) 152 | 153 | m.NotFound(func() { 154 | // обработчик 404 155 | }) 156 | ~~~ 157 | 158 | Роуты могут сопоставляться с http запросами только в порядке объявления. Вызывается первый роут, который соответствует запросу. 159 | 160 | Паттерны роутов могут включать именованные параметры, доступные через [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) сервис: 161 | ~~~ go 162 | m.Get("/hello/:name", func(params martini.Params) string { 163 | return "Hello " + params["name"] 164 | }) 165 | ~~~ 166 | 167 | Роуты можно объявлять как glob'ы: 168 | ~~~ go 169 | m.Get("/hello/**", func(params martini.Params) string { 170 | return "Hello " + params["_1"] 171 | }) 172 | ~~~ 173 | 174 | Так же могут использоваться регулярные выражения: 175 | ~~~go 176 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 177 | return fmt.Sprintf ("Hello %s", params["name"]) 178 | }) 179 | ~~~ 180 | Синтаксис регулярных выражений смотрите [Go documentation](http://golang.org/pkg/regexp/syntax/). 181 | 182 | Обработчики роутов так же могут быть выстроены в стек, друг перед другом. Это очень удобно для таких задач как авторизация и аутентификация: 183 | ~~~ go 184 | m.Get("/secret", authorize, func() { 185 | // будет вызываться, в случае если authorize ничего не записал в ответ 186 | }) 187 | ~~~ 188 | 189 | Роуты так же могут быть объединены в группы, посредством метода Group: 190 | ~~~ go 191 | m.Group("/books", func(r martini.Router) { 192 | r.Get("/:id", GetBooks) 193 | r.Post("/new", NewBook) 194 | r.Put("/update/:id", UpdateBook) 195 | r.Delete("/delete/:id", DeleteBook) 196 | }) 197 | ~~~ 198 | 199 | Так же как вы можете добавить middleware для обычного обработчика, вы можете добавить middleware и для группы. 200 | ~~~ go 201 | m.Group("/books", func(r martini.Router) { 202 | r.Get("/:id", GetBooks) 203 | r.Post("/new", NewBook) 204 | r.Put("/update/:id", UpdateBook) 205 | r.Delete("/delete/:id", DeleteBook) 206 | }, MyMiddleware1, MyMiddleware2) 207 | ~~~ 208 | 209 | ### Сервисы 210 | Сервисы - это объекты, которые доступны для внедрения в аргументы обработчиков. Вы можете замапить сервисы на уровне всего приложения либо на уровне запроса. 211 | 212 | #### Глобальный маппинг 213 | Экземпляр Martini реализует интерфейс inject.Injector, поэтому замаппить сервис легко: 214 | ~~~ go 215 | db := &MyDatabase{} 216 | m := martini.Classic() 217 | m.Map(db) // сервис будет доступен для всех обработчиков как *MyDatabase 218 | // ... 219 | m.Run() 220 | ~~~ 221 | 222 | #### Маппинг уровня запроса 223 | Маппинг на уровне запроса можно сделать при помощи [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): 224 | ~~~ go 225 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 226 | logger := &MyCustomLogger{req} 227 | c.Map(logger) // как *MyCustomLogger 228 | } 229 | ~~~ 230 | 231 | #### Маппинг на определенный интерфейс 232 | Одна из мощных частей, того что касается сервисов - маппинг сервиса на определенный интерфейс. Например, если вы хотите переопределить [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) объектом, который оборачивает и добавляет новые операции, вы можете написать следующее: 233 | ~~~ go 234 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 235 | rw := NewSpecialResponseWriter(res) 236 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // переопределить ResponseWriter нашей оберткой 237 | } 238 | ~~~ 239 | 240 | ### Отдача статических файлов 241 | Экземпляр [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) автоматически отдает статические файлы из директории "public" в корне, рядом с вашим файлом `server.go`. 242 | Вы можете добавить еще директорий, добавляя [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) обработчики. 243 | ~~~ go 244 | m.Use(martini.Static("assets")) // отдача файлов из "assets" директории 245 | ~~~ 246 | 247 | ## Middleware Обработчики 248 | Middleware обработчики находятся между входящим http запросом и роутом. По сути, они ничем не отличаются от любого другого обработчика Martini. Вы можете добавить middleware обработчик в стек следующим образом: 249 | ~~~ go 250 | m.Use(func() { 251 | // делать какую то middleware работу 252 | }) 253 | ~~~ 254 | 255 | Для полного контроля над стеком middleware существует метод `Handlers`. В этом примере будут заменены все обработчики, которые были до этого: 256 | ~~~ go 257 | m.Handlers( 258 | Middleware1, 259 | Middleware2, 260 | Middleware3, 261 | ) 262 | ~~~ 263 | 264 | Middleware обработчики очень хорошо работают для таких вещей как логгирование, авторизация, аутентификация, сессии, сжатие, страницы ошибок и любые другие операции, которые должны быть выполнены до или после http запроса: 265 | ~~~ go 266 | // валидация api ключа 267 | m.Use(func(res http.ResponseWriter, req *http.Request) { 268 | if req.Header.Get("X-API-KEY") != "secret123" { 269 | res.WriteHeader(http.StatusUnauthorized) 270 | } 271 | }) 272 | ~~~ 273 | 274 | ### Next() 275 | [Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) опциональная функция, которая может быть вызвана в Middleware обработчике, для выхода из контекста, и возврата в него, после вызова всего стека обработчиков. Это можно использовать для операций, которые должны быть выполнены после http запроса: 276 | ~~~ go 277 | // логгирование до и после http запроса 278 | m.Use(func(c martini.Context, log *log.Logger){ 279 | log.Println("до запроса") 280 | 281 | c.Next() 282 | 283 | log.Println("после запроса") 284 | }) 285 | ~~~ 286 | 287 | ## Окружение 288 | Некоторые Martini обработчики используют глобальную переменную `martini.Env` для того, чтоб предоставить специальную функциональность для девелопмент и продакшн окружения. Рекомендуется устанавливать `MARTINI_ENV=production`, когда вы деплоите приложение на продакшн. 289 | 290 | ## FAQ 291 | 292 | ### Где найти готовые middleware? 293 | 294 | Начните поиск с [martini-contrib](https://github.com/martini-contrib) проектов. Если нет ничего подходящего, без колебаний пишите члену команды martini-contrib о добавлении нового репозитория в организацию. 295 | 296 | * [auth](https://github.com/martini-contrib/auth) - Обработчики для аутентификации. 297 | * [binding](https://github.com/martini-contrib/binding) - Обработчик для маппинга/валидации сырого запроса в определенную структуру(struct). 298 | * [gzip](https://github.com/martini-contrib/gzip) - Обработчик, добавляющий gzip сжатие для запросов. 299 | * [render](https://github.com/martini-contrib/render) - Обработчик, которые предоставляет сервис для легкого рендеринга JSON и HTML шаблонов. 300 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - Обработчик для парсинга `Accept-Language` HTTP заголовка. 301 | * [sessions](https://github.com/martini-contrib/sessions) - Сервис сессий. 302 | * [strip](https://github.com/martini-contrib/strip) - Удаление префиксов из URL. 303 | * [method](https://github.com/martini-contrib/method) - Подмена HTTP метода через заголовок. 304 | * [secure](https://github.com/martini-contrib/secure) - Набор для безопасности. 305 | * [encoder](https://github.com/martini-contrib/encoder) - Сервис для представления данных в нескольких форматах и взаимодействия с контентом. 306 | * [cors](https://github.com/martini-contrib/cors) - Поддержка CORS. 307 | * [oauth2](https://github.com/martini-contrib/oauth2) - Обработчик, предоставляющий OAuth 2.0 логин для Martini приложений. Вход через Google, Facebook и через Github поддерживаются. 308 | 309 | ### Как интегрироваться с существуюшими серверами? 310 | 311 | Экземпляр Martini реализует интерфейс `http.Handler`, потому - это очень просто использовать вместе с существующим Go проектом. Например, это работает для платформы Google App Engine: 312 | ~~~ go 313 | package hello 314 | 315 | import ( 316 | "net/http" 317 | "github.com/go-martini/martini" 318 | ) 319 | 320 | func init() { 321 | m := martini.Classic() 322 | m.Get("/", func() string { 323 | return "Hello world!" 324 | }) 325 | http.Handle("/", m) 326 | } 327 | ~~~ 328 | 329 | ### Как изменить порт и/или хост? 330 | Функция `Run` смотрит переменные окружиения PORT и HOST, и использует их. 331 | В противном случае Martini по умолчанию будет использовать `localhost:3000`. 332 | Для большей гибкости используйте вместо этого функцию `martini.RunOnAddr`. 333 | 334 | ~~~ go 335 | m := martini.Classic() 336 | // ... 337 | log.Fatal(m.RunOnAddr(":8080")) 338 | ~~~ 339 | 340 | ### Живая перезагрузка кода? 341 | 342 | [gin](https://github.com/codegangsta/gin) и [fresh](https://github.com/pilu/fresh) могут работать вместе с Martini. 343 | 344 | ## Вклад в общее дело 345 | 346 | Подразумевается что Martini чистый и маленький. Большинство улучшений должны быть в организации [martini-contrib](https://github.com/martini-contrib). Но если вы хотите улучшить ядро Martini, отправляйте пулл реквесты. 347 | 348 | ## О проекте 349 | 350 | Вдохновлен [express](https://github.com/visionmedia/express) и [sinatra](https://github.com/sinatra/sinatra) 351 | 352 | Martini создан [Code Gangsta](http://codegangsta.io/) 353 | -------------------------------------------------------------------------------- /translations/README_tr_TR.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | Martini Go dilinde hızlı ve modüler web uygulamaları ve servisleri için güçlü bir pakettir. 4 | 5 | 6 | ## Başlangıç 7 | 8 | Go 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. 9 | 10 | ~~~ go 11 | package main 12 | 13 | import "github.com/go-martini/martini" 14 | 15 | func main() { 16 | m := martini.Classic() 17 | m.Get("/", func() string { 18 | return "Hello world!" 19 | }) 20 | m.Run() 21 | } 22 | ~~~ 23 | 24 | Martini paketini kurduktan sonra (**go 1.1** ve daha üst go sürümü gerekmektedir.): 25 | 26 | ~~~ 27 | go get github.com/go-martini/martini 28 | ~~~ 29 | 30 | Daha sonra server'ımızı çalıştırıyoruz: 31 | 32 | ~~~ 33 | go run server.go 34 | ~~~ 35 | 36 | Şimdi elimizde çalışan bir adet Martini webserver `localhost:3000` adresinde bulunmaktadır. 37 | 38 | 39 | ## Yardım Almak İçin 40 | 41 | [Mail Listesi](https://groups.google.com/forum/#!forum/martini-go) 42 | 43 | [Örnek Video](http://martini.codegangsta.io/#demo) 44 | 45 | Stackoverflow üzerinde [martini etiketine](http://stackoverflow.com/questions/tagged/martini) sahip sorular 46 | 47 | [GO Diline ait Dökümantasyonlar](http://godoc.org/github.com/go-martini/martini) 48 | 49 | 50 | ## Özellikler 51 | * Oldukça basit bir kullanıma sahip. 52 | * Kısıtlama yok. 53 | * Golang paketleri ile rahat bir şekilde kullanılıyor. 54 | * Müthiş bir şekilde path eşleştirme ve yönlendirme. 55 | * Modüler dizayn - Kolay eklenen fonksiyonellik. 56 | * handlers/middlewares kullanımı çok iyi. 57 | * Büyük 'kutu dışarı' özellik seti. 58 | * **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) arayüzü ile tam uyumludur.** 59 | * Varsayılan belgelendirme işlemleri (örnek olarak, AngularJS uygulamalarının HTML5 modunda servis edilmesi). 60 | 61 | ## Daha Fazla Middleware(Ara Katman) 62 | 63 | Daha fazla ara katman ve fonksiyonellik için, şu repoları inceleyin [martini-contrib](https://github.com/martini-contrib). 64 | 65 | ## Tablo İçerikleri 66 | * [Classic Martini](#classic-martini) 67 | * [İşleyiciler / Handlers](#handlers) 68 | * [Yönlendirmeler / Routing](#routing) 69 | * [Servisler](#services) 70 | * [Statik Dosyaların Sunumu](#serving-static-files) 71 | * [Katman İşleyiciler / Middleware Handlers](#middleware-handlers) 72 | * [Next()](#next) 73 | * [Martini Env](#martini-env) 74 | * [FAQ](#faq) 75 | 76 | ## Classic Martini 77 | [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: 78 | 79 | ~~~ go 80 | m := martini.Classic() 81 | // ... middleware and routing goes here 82 | m.Run() 83 | ~~~ 84 | 85 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) aşağıdaki bazı fonsiyonelleri otomatik olarak çeker: 86 | 87 | * İstek/Yanıt Kayıtları (Request/Response Logging) - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 88 | * Hataların Düzeltilmesi (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 89 | * Statik Dosyaların Sunumu (Static File serving) - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 90 | * Yönlendirmeler (Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 91 | 92 | ### İşleyiciler (Handlers) 93 | İşleyiciler Martini'nin ruhu ve kalbidir. Bir işleyici temel olarak her türlü fonksiyonu çağırabilir: 94 | 95 | ~~~ go 96 | m.Get("/", func() { 97 | println("hello world") 98 | }) 99 | ~~~ 100 | 101 | #### Geriye Dönen Değerler 102 | 103 | Eğer bir işleyici geriye bir şey dönderiyorsa, Martini string olarak sonucu [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) ile yazacaktır: 104 | 105 | ~~~ go 106 | m.Get("/", func() string { 107 | return "hello world" // HTTP 200 : "hello world" 108 | }) 109 | ~~~ 110 | 111 | Ayrıca isteğe bağlı bir durum kodu dönderebilir: 112 | ~~~ go 113 | m.Get("/", func() (int, string) { 114 | return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" 115 | }) 116 | ~~~ 117 | 118 | #### Service Injection 119 | İş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.** 120 | 121 | Eğ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: 122 | 123 | ~~~ go 124 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini 125 | res.WriteHeader(200) // HTTP 200 126 | }) 127 | ~~~ 128 | 129 | Aşağıdaki servislerin içerikleri 130 | 131 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 132 | * [*log.Logger](http://godoc.org/log#Logger) - Martini için Global loglayıcı. 133 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request içereği. 134 | * [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. 135 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Yönledirilme için yardımcı olan yapıdır. 136 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http yanıtlarını yazacak olan yapıdır. 137 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request(http isteği yapar). 138 | 139 | ### Yönlendirme - Routing 140 | Martini'de bir yol HTTP metodu URL-matching pattern'i ile eşleştirilir. 141 | Her bir yol bir veya daha fazla işleyici metod alabilir: 142 | ~~~ go 143 | m.Get("/", func() { 144 | // show something 145 | }) 146 | 147 | m.Patch("/", func() { 148 | // update something 149 | }) 150 | 151 | m.Post("/", func() { 152 | // create something 153 | }) 154 | 155 | m.Put("/", func() { 156 | // replace something 157 | }) 158 | 159 | m.Delete("/", func() { 160 | // destroy something 161 | }) 162 | 163 | m.Options("/", func() { 164 | // http options 165 | }) 166 | 167 | m.NotFound(func() { 168 | // handle 404 169 | }) 170 | ~~~ 171 | 172 | Yollar sırayla tanımlandıkları şekilde eşleştirilir.Request ile eşleşen ilk rota çağrılır. 173 | 174 | Yol patternleri [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) servisi tarafından adlandırılan parametreleri içerebilir: 175 | ~~~ go 176 | m.Get("/hello/:name", func(params martini.Params) string { 177 | return "Hello " + params["name"] 178 | }) 179 | ~~~ 180 | 181 | Yollar globaller ile eşleşebilir: 182 | ~~~ go 183 | m.Get("/hello/**", func(params martini.Params) string { 184 | return "Hello " + params["_1"] 185 | }) 186 | ~~~ 187 | 188 | Düzenli ifadeler kullanılabilir: 189 | ~~~go 190 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 191 | return fmt.Sprintf ("Hello %s", params["name"]) 192 | }) 193 | ~~~ 194 | Düzenli ifadeler hakkında daha fazla bilgiyi [Go dökümanlarından](http://golang.org/pkg/regexp/syntax/) elde edebilirsiniz. 195 | 196 | Yol işleyicileri birbirlerinin üstüne istiflenebilir. Bu durum doğrulama ve yetkilendirme(authentication and authorization) işlemleri için iyi bir yöntemdir: 197 | ~~~ go 198 | m.Get("/secret", authorize, func() { 199 | // this will execute as long as authorize doesn't write a response 200 | }) 201 | ~~~ 202 | 203 | Yol grupları Grup metodlar kullanılarak eklenebilir. 204 | ~~~ go 205 | m.Group("/books", func(r martini.Router) { 206 | r.Get("/:id", GetBooks) 207 | r.Post("/new", NewBook) 208 | r.Put("/update/:id", UpdateBook) 209 | r.Delete("/delete/:id", DeleteBook) 210 | }) 211 | ~~~ 212 | 213 | Tıpkı ara katmanların işleyiciler için bazı ara katman işlemlerini atlayabileceği gibi gruplar içinde atlayabilir. 214 | ~~~ go 215 | m.Group("/books", func(r martini.Router) { 216 | r.Get("/:id", GetBooks) 217 | r.Post("/new", NewBook) 218 | r.Put("/update/:id", UpdateBook) 219 | r.Delete("/delete/:id", DeleteBook) 220 | }, MyMiddleware1, MyMiddleware2) 221 | ~~~ 222 | 223 | ### Servisler 224 | 225 | Servisler işleyicilerin arguman listesine enjekte edilecek kullanılabilir nesnelerdir. İstenildiği taktirde bir servis *Global* ve *Request* seviyesinde eşlenebilir. 226 | 227 | #### Global Eşleme - Global Mapping 228 | 229 | Bir martini örneği(instance) projeye enjekte edilir. 230 | A Martini instance implements the inject.Enjekte arayüzü, çok kolay bir şekilde servis eşlemesi yapar: 231 | ~~~ go 232 | db := &MyDatabase{} 233 | m := martini.Classic() 234 | m.Map(db) // the service will be available to all handlers as *MyDatabase 235 | // ... 236 | m.Run() 237 | ~~~ 238 | 239 | #### Request-Level Mapping 240 | Request düzeyinde eşleme yapmak üzere işleyici [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) ile oluşturulabilir: 241 | ~~~ go 242 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 243 | logger := &MyCustomLogger{req} 244 | c.Map(logger) // mapped as *MyCustomLogger 245 | } 246 | ~~~ 247 | 248 | #### Arayüz Eşleme Değerleri 249 | Servisler 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: 250 | 251 | ~~~ go 252 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 253 | rw := NewSpecialResponseWriter(res) 254 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter 255 | } 256 | ~~~ 257 | 258 | ### Statik Dosyaların Sunumu 259 | 260 | [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. 261 | 262 | Eğer istenirse daha fazla [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) işleyicisi eklenerek daha fazla dizin servis edilebilir. 263 | ~~~ go 264 | m.Use(martini.Static("assets")) // serve from the "assets" directory as well 265 | ~~~ 266 | 267 | #### Standart Dökümanların Sunulması - Serving a Default Document 268 | 269 | Eğ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. 270 | 271 | Herhangi 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. 272 | ~~~ go 273 | static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) 274 | m.NotFound(static, http.NotFound) 275 | ~~~ 276 | 277 | ## Ara Katman İşleyicileri 278 | Ara 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: 279 | ~~~ go 280 | m.Use(func() { 281 | // do some middleware stuff 282 | }) 283 | ~~~ 284 | 285 | `Handlers` fonksiyonu ile ara katman yığını üzerinde tüm kontrole sahip olunabilir. Bu daha önceden ayarlanmış herhangi bir işleyicinin yerini alacaktır: 286 | ~~~ go 287 | m.Handlers( 288 | Middleware1, 289 | Middleware2, 290 | Middleware3, 291 | ) 292 | ~~~ 293 | 294 | Orta 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: 295 | 296 | ~~~ go 297 | // validate an api key 298 | m.Use(func(res http.ResponseWriter, req *http.Request) { 299 | if req.Header.Get("X-API-KEY") != "secret123" { 300 | res.WriteHeader(http.StatusUnauthorized) 301 | } 302 | }) 303 | ~~~ 304 | 305 | ### Next() 306 | [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: 307 | ~~~ go 308 | // log before and after a request 309 | m.Use(func(c martini.Context, log *log.Logger){ 310 | log.Println("before a request") 311 | 312 | c.Next() 313 | 314 | log.Println("after a request") 315 | }) 316 | ~~~ 317 | 318 | ## Martini Env 319 | 320 | Bazı 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. 321 | 322 | ## FAQ 323 | 324 | ### Ara Katmanda X'i Nerede Bulurum? 325 | 326 | [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. 327 | 328 | * [auth](https://github.com/martini-contrib/auth) - Kimlik doğrulama için işleyiciler. 329 | * [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) 330 | * [gzip](https://github.com/martini-contrib/gzip) - İstekleri gzip sıkışıtırıp eklemek için kullanılan işleyici 331 | * [render](https://github.com/martini-contrib/render) - Kolay bir şekilde JSON ve HTML şablonları oluşturmak için kullanılan işleyici. 332 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - `Kabul edilen dile` göre HTTP başlığını oluşturmak için kullanılan işleyici. 333 | * [sessions](https://github.com/martini-contrib/sessions) - Oturum hizmeti vermek için kullanılır. 334 | * [strip](https://github.com/martini-contrib/strip) - İşleyicilere gitmeden önce URL'ye ait ön şeriti değiştirme işlemini yapar. 335 | * [method](https://github.com/martini-contrib/method) - Formlar ve başlık için http metodunu override eder. 336 | * [secure](https://github.com/martini-contrib/secure) - Birkaç hızlı güvenlik uygulaması ile kazanımda bulundurur. 337 | * [encoder](https://github.com/martini-contrib/encoder) - Encoder servis veri işlemleri için çeşitli format ve içerik sağlar. 338 | * [cors](https://github.com/martini-contrib/cors) - İşleyicilerin CORS desteği bulunur. 339 | * [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. 340 | * [vauth](https://github.com/rafecolton/vauth) - Webhook için giriş izni sağlar. (şimdilik sadece GitHub ve TravisCI ile) 341 | 342 | ### Mevcut Sunucular ile Nasıl Entegre Edilir? 343 | 344 | Bir 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: 345 | 346 | ~~~ go 347 | package hello 348 | 349 | import ( 350 | "net/http" 351 | "github.com/go-martini/martini" 352 | ) 353 | 354 | func init() { 355 | m := martini.Classic() 356 | m.Get("/", func() string { 357 | return "Hello world!" 358 | }) 359 | http.Handle("/", m) 360 | } 361 | ~~~ 362 | 363 | ### port/hostu nasıl değiştiririm? 364 | 365 | Martini'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. 366 | 367 | Port ve host için daha fazla esneklik isteniyorsa `martini.RunOnAddr` fonksiyonunu kullanın. 368 | 369 | ~~~ go 370 | m := martini.Classic() 371 | // ... 372 | log.Fatal(m.RunOnAddr(":8080")) 373 | ~~~ 374 | 375 | ### Anlık Kod Yüklemesi? 376 | 377 | [gin](https://github.com/codegangsta/gin) ve [fresh](https://github.com/pilu/fresh) anlık kod yüklemeleri yapan martini uygulamalarıdır. 378 | 379 | ## Katkıda Bulunmak 380 | Martini'nin temiz ve düzenli olaması gerekiyordu. 381 | Martini 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. 382 | 383 | ## Hakkında 384 | 385 | [express](https://github.com/visionmedia/express) ve [sinatra](https://github.com/sinatra/sinatra) projelerinden esinlenmiştir. 386 | 387 | Martini [Code Gangsta](http://codegangsta.io/) tarafından tasarlanılmıştır. 388 | -------------------------------------------------------------------------------- /translations/README_zh_cn.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | Martini是一个强大为了编写模块化Web应用而生的GO语言框架. 4 | 5 | ## 第一个应用 6 | 7 | 在你安装了GO语言和设置了你的[GOPATH](http://golang.org/doc/code.html#GOPATH)之后, 创建你的自己的`.go`文件, 这里我们假设它的名字叫做 `server.go`. 8 | 9 | ~~~ go 10 | package main 11 | 12 | import "github.com/go-martini/martini" 13 | 14 | func main() { 15 | m := martini.Classic() 16 | m.Get("/", func() string { 17 | return "Hello world!" 18 | }) 19 | m.Run() 20 | } 21 | ~~~ 22 | 23 | 然后安装Martini的包. (注意Martini需要Go语言1.1或者以上的版本支持): 24 | ~~~ 25 | go get github.com/go-martini/martini 26 | ~~~ 27 | 28 | 最后运行你的服务: 29 | ~~~ 30 | go run server.go 31 | ~~~ 32 | 33 | 这时你将会有一个Martini的服务监听了, 地址是: `localhost:3000`. 34 | 35 | ## 获得帮助 36 | 37 | 请加入: [邮件列表](https://groups.google.com/forum/#!forum/martini-go) 38 | 39 | 或者可以查看在线演示地址: [演示视频](http://martini.codegangsta.io/#demo) 40 | 41 | ## 功能列表 42 | * 使用极其简单. 43 | * 无侵入式的设计. 44 | * 很好的与其他的Go语言包协同使用. 45 | * 超赞的路径匹配和路由. 46 | * 模块化的设计 - 容易插入功能件,也容易将其拔出来. 47 | * 已有很多的中间件可以直接使用. 48 | * 框架内已拥有很好的开箱即用的功能支持. 49 | * **完全兼容[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)接口.** 50 | 51 | ## 更多中间件 52 | 更多的中间件和功能组件, 请查看代码仓库: [martini-contrib](https://github.com/martini-contrib). 53 | 54 | ## 目录 55 | * [核心 Martini](#classic-martini) 56 | * [处理器](#handlers) 57 | * [路由](#routing) 58 | * [服务](#services) 59 | * [服务静态文件](#serving-static-files) 60 | * [中间件处理器](#middleware-handlers) 61 | * [Next()](#next) 62 | * [常见问答](#faq) 63 | 64 | ## 核心 Martini 65 | 为了更快速的启用Martini, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 提供了一些默认的方便Web开发的工具: 66 | ~~~ go 67 | m := martini.Classic() 68 | // ... middleware and routing goes here 69 | m.Run() 70 | ~~~ 71 | 72 | 下面是Martini核心已经包含的功能 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 73 | * Request/Response Logging (请求/响应日志) - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 74 | * Panic Recovery (容错) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 75 | * Static File serving (静态文件服务) - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 76 | * Routing (路由) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 77 | 78 | ### 处理器 79 | 处理器是Martini的灵魂和核心所在. 一个处理器基本上可以是任何的函数: 80 | ~~~ go 81 | m.Get("/", func() { 82 | println("hello world") 83 | }) 84 | ~~~ 85 | 86 | #### 返回值 87 | 当一个处理器返回结果的时候, Martini将会把返回值作为字符串写入到当前的[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)里面: 88 | ~~~ go 89 | m.Get("/", func() string { 90 | return "hello world" // HTTP 200 : "hello world" 91 | }) 92 | ~~~ 93 | 94 | 另外你也可以选择性的返回多一个状态码: 95 | ~~~ go 96 | m.Get("/", func() (int, string) { 97 | return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" 98 | }) 99 | ~~~ 100 | 101 | #### 服务的注入 102 | 处理器是通过反射来调用的. Martini 通过*Dependency Injection* *(依赖注入)* 来为处理器注入参数列表. **这样使得Martini与Go语言的`http.HandlerFunc`接口完全兼容.** 103 | 104 | 如果你加入一个参数到你的处理器, Martini将会搜索它参数列表中的服务,并且通过类型判断来解决依赖关系: 105 | ~~~ go 106 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是通过Martini注入的 107 | res.WriteHeader(200) // HTTP 200 108 | }) 109 | ~~~ 110 | 111 | 下面的这些服务已经被包含在核心Martini中: [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): 112 | * [*log.Logger](http://godoc.org/log#Logger) - Martini的全局日志. 113 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context (请求上下文). 114 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. (名字和参数键值对的参数列表) 115 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. (路由协助处理) 116 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. (响应结果的流接口) 117 | * [*http.Request](http://godoc.org/net/http/#Request) - http Request. (http请求) 118 | 119 | ### 路由 120 | 在Martini中, 路由是一个HTTP方法配对一个URL匹配模型. 每一个路由可以对应一个或多个处理器方法: 121 | ~~~ go 122 | m.Get("/", func() { 123 | // 显示 124 | }) 125 | 126 | m.Patch("/", func() { 127 | // 更新 128 | }) 129 | 130 | m.Post("/", func() { 131 | // 创建 132 | }) 133 | 134 | m.Put("/", func() { 135 | // 替换 136 | }) 137 | 138 | m.Delete("/", func() { 139 | // 删除 140 | }) 141 | 142 | m.Options("/", func() { 143 | // http 选项 144 | }) 145 | 146 | m.NotFound(func() { 147 | // 处理 404 148 | }) 149 | ~~~ 150 | 151 | 路由匹配的顺序是按照他们被定义的顺序执行的. 最先被定义的路由将会首先被用户请求匹配并调用. 152 | 153 | 路由模型可能包含参数列表, 可以通过[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)服务来获取: 154 | ~~~ go 155 | m.Get("/hello/:name", func(params martini.Params) string { 156 | return "Hello " + params["name"] 157 | }) 158 | ~~~ 159 | 160 | 路由匹配可以通过正则表达式或者glob的形式: 161 | ~~~ go 162 | m.Get("/hello/**", func(params martini.Params) string { 163 | return "Hello " + params["_1"] 164 | }) 165 | ~~~ 166 | 167 | 也可以这样使用正则表达式: 168 | ~~~go 169 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 170 | return fmt.Sprintf ("Hello %s", params["name"]) 171 | }) 172 | ~~~ 173 | 有关正则表达式的更多信息请参见[Go官方文档](http://golang.org/pkg/regexp/syntax/). 174 | 175 | 176 | 路由处理器可以被相互叠加使用, 例如很有用的地方可以是在验证和授权的时候: 177 | ~~~ go 178 | m.Get("/secret", authorize, func() { 179 | // 该方法将会在authorize方法没有输出结果的时候执行. 180 | }) 181 | ~~~ 182 | 183 | 也可以通过 Group 方法, 将 route 编成一組. 184 | ~~~ go 185 | m.Group("/books", func(r martini.Router) { 186 | r.Get("/:id", GetBooks) 187 | r.Post("/new", NewBook) 188 | r.Put("/update/:id", UpdateBook) 189 | r.Delete("/delete/:id", DeleteBook) 190 | }) 191 | ~~~ 192 | 193 | 就像为 handler 增加 middleware 方法一样, 你也可以为一组 routes 增加 middleware. 194 | ~~~ go 195 | m.Group("/books", func(r martini.Router) { 196 | r.Get("/:id", GetBooks) 197 | r.Post("/new", NewBook) 198 | r.Put("/update/:id", UpdateBook) 199 | r.Delete("/delete/:id", DeleteBook) 200 | }, MyMiddleware1, MyMiddleware2) 201 | ~~~ 202 | 203 | ### 服务 204 | 服务即是被注入到处理器中的参数. 你可以映射一个服务到 *全局* 或者 *请求* 的级别. 205 | 206 | 207 | #### 全局映射 208 | 如果一个Martini实现了inject.Injector的接口, 那么映射成为一个服务就非常简单: 209 | ~~~ go 210 | db := &MyDatabase{} 211 | m := martini.Classic() 212 | m.Map(db) // *MyDatabase 这个服务将可以在所有的处理器中被使用到. 213 | // ... 214 | m.Run() 215 | ~~~ 216 | 217 | #### 请求级别的映射 218 | 映射在请求级别的服务可以用[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)来完成: 219 | ~~~ go 220 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 221 | logger := &MyCustomLogger{req} 222 | c.Map(logger) // 映射成为了 *MyCustomLogger 223 | } 224 | ~~~ 225 | 226 | #### 映射值到接口 227 | 关于服务最强悍的地方之一就是它能够映射服务到接口. 例如说, 假设你想要覆盖[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)成为一个对象, 那么你可以封装它并包含你自己的额外操作, 你可以如下这样来编写你的处理器: 228 | ~~~ go 229 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 230 | rw := NewSpecialResponseWriter(res) 231 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // 覆盖 ResponseWriter 成为我们封装过的 ResponseWriter 232 | } 233 | ~~~ 234 | 235 | ### 服务静态文件 236 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 默认会服务位于你服务器环境根目录下的"public"文件夹. 237 | 你可以通过加入[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)的处理器来加入更多的静态文件服务的文件夹. 238 | ~~~ go 239 | m.Use(martini.Static("assets")) // 也会服务静态文件于"assets"的文件夹 240 | ~~~ 241 | 242 | ## 中间件处理器 243 | 中间件处理器是工作于请求和路由之间的. 本质上来说和Martini其他的处理器没有分别. 你可以像如下这样添加一个中间件处理器到它的堆中: 244 | ~~~ go 245 | m.Use(func() { 246 | // 做一些中间件该做的事情 247 | }) 248 | ~~~ 249 | 250 | 你可以通过`Handlers`函数对中间件堆有完全的控制. 它将会替换掉之前的任何设置过的处理器: 251 | ~~~ go 252 | m.Handlers( 253 | Middleware1, 254 | Middleware2, 255 | Middleware3, 256 | ) 257 | ~~~ 258 | 259 | 中间件处理器可以非常好处理一些功能,像logging(日志), authorization(授权), authentication(认证), sessions(会话), error pages(错误页面), 以及任何其他的操作需要在http请求发生之前或者之后的: 260 | 261 | ~~~ go 262 | // 验证api密匙 263 | m.Use(func(res http.ResponseWriter, req *http.Request) { 264 | if req.Header.Get("X-API-KEY") != "secret123" { 265 | res.WriteHeader(http.StatusUnauthorized) 266 | } 267 | }) 268 | ~~~ 269 | 270 | ### Next() 271 | [Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)是一个可选的函数用于中间件处理器暂时放弃执行直到其他的处理器都执行完毕. 这样就可以很好的处理在http请求完成后需要做的操作. 272 | ~~~ go 273 | // log 记录请求完成前后 (*译者注: 很巧妙,掌声鼓励.) 274 | m.Use(func(c martini.Context, log *log.Logger){ 275 | log.Println("before a request") 276 | 277 | c.Next() 278 | 279 | log.Println("after a request") 280 | }) 281 | ~~~ 282 | 283 | ## Martini Env 284 | 一些handler使用环境变量 `martini.Env` 对开发环境和生产环境提供特殊功能. 推荐在生产环境设置环境变量 `MARTINI_ENV=production`. 285 | 286 | 287 | ## 常见问答 288 | 289 | ### 我在哪里可以找到中间件资源? 290 | 291 | 可以查看 [martini-contrib](https://github.com/martini-contrib) 项目. 如果看了觉得没有什么好货色, 可以联系martini-contrib的团队成员为你创建一个新的代码资源库. 292 | 293 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析`Accept-Language` HTTP报头的处理器。 294 | * [accessflags](https://github.com/martini-contrib/accessflags) - 启用访问控制处理器. 295 | * [auth](https://github.com/martini-contrib/auth) - 认证处理器。 296 | * [binding](https://github.com/martini-contrib/binding) - 映射/验证raw请求到结构体(structure)里的处理器。 297 | * [cors](https://github.com/martini-contrib/cors) - 提供支持 CORS 的处理器。 298 | * [csrf](https://github.com/martini-contrib/csrf) - 为应用提供CSRF防护。 299 | * [encoder](https://github.com/martini-contrib/encoder) - 提供用于多种格式的数据渲染或内容协商的编码服务。 300 | * [gzip](https://github.com/martini-contrib/gzip) - 通过giz方式压缩请求信息的处理器。 301 | * [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic 中间件 302 | * [logstasher](https://github.com/martini-contrib/logstasher) - logstash日志兼容JSON中间件 303 | * [method](https://github.com/martini-contrib/method) - 通过请求头或表单域覆盖HTTP方法。 304 | * [oauth2](https://github.com/martini-contrib/oauth2) - 基于 OAuth 2.0 的应用登录处理器。支持谷歌、Facebook和Github的登录。 305 | * [permissions2](https://github.com/xyproto/permissions2) - 跟踪用户,登录状态和权限控制器 306 | * [render](https://github.com/martini-contrib/render) - 渲染JSON和HTML模板的处理器。 307 | * [secure](https://github.com/martini-contrib/secure) - 提供一些安全方面的速效方案。 308 | * [sessions](https://github.com/martini-contrib/sessions) - 提供`Session`服务支持的处理器。 309 | * [sessionauth](https://github.com/martini-contrib/sessionauth) - 提供简单的方式使得路由需要登录, 并在Session中处理用户登录 310 | * [strip](https://github.com/martini-contrib/strip) - 用于过滤指定的URL前缀。 311 | * [strip](https://github.com/martini-contrib/strip) - URL前缀剥离。 312 | * [staticbin](https://github.com/martini-contrib/staticbin) - 从二进制数据中提供静态文件服务的处理器。 313 | * [throttle](https://github.com/martini-contrib/throttle) - 请求速率调节中间件. 314 | * [vauth](https://github.com/rafecolton/vauth) - 负责webhook认证的处理器(目前支持GitHub和TravisCI)。 315 | * [web](https://github.com/martini-contrib/web) - hoisie web.go's Context 316 | 317 | ### 我如何整合到我现有的服务器中? 318 | 319 | 由于Martini实现了 `http.Handler`, 所以它可以很简单的应用到现有Go服务器的子集中. 例如说这是一段在Google App Engine中的示例: 320 | 321 | ~~~ go 322 | package hello 323 | 324 | import ( 325 | "net/http" 326 | "github.com/go-martini/martini" 327 | ) 328 | 329 | func init() { 330 | m := martini.Classic() 331 | m.Get("/", func() string { 332 | return "Hello world!" 333 | }) 334 | http.Handle("/", m) 335 | } 336 | ~~~ 337 | 338 | ### 我如何修改port/host? 339 | 340 | Martini的`Run`函数会检查PORT和HOST的环境变量并使用它们. 否则Martini将会默认使用localhost:3000 341 | 如果想要自定义PORT和HOST, 使用`martini.RunOnAddr`函数来代替. 342 | 343 | ~~~ go 344 | m := martini.Classic() 345 | // ... 346 | m.RunOnAddr(":8080") 347 | ~~~ 348 | 349 | ## 贡献 350 | Martini项目想要保持简单且干净的代码. 大部分的代码应该贡献到[martini-contrib](https://github.com/martini-contrib)组织中作为一个项目. 如果你想要贡献Martini的核心代码也可以发起一个Pull Request. 351 | 352 | ## 关于 353 | 354 | 灵感来自于 [express](https://github.com/visionmedia/express) 和 [sinatra](https://github.com/sinatra/sinatra) 355 | 356 | Martini作者 [Code Gangsta](http://codegangsta.io/) 357 | 译者: [Leon](http://github.com/leonli) 358 | -------------------------------------------------------------------------------- /translations/README_zh_tw.md: -------------------------------------------------------------------------------- 1 | # 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) 2 | 3 | Martini 是一個使用 Go 語言來快速開發模組化 Web 應用程式或服務的強大套件 4 | 5 | ## 開始 6 | 7 | 在您安裝Go語言以及設定好 8 | [GOPATH](http://golang.org/doc/code.html#GOPATH)環境變數後, 9 | 開始寫您第一支`.go`檔, 我們將稱它為`server.go` 10 | 11 | ~~~ go 12 | package main 13 | 14 | import "github.com/go-martini/martini" 15 | 16 | func main() { 17 | m := martini.Classic() 18 | m.Get("/", func() string { 19 | return "Hello 世界!" 20 | }) 21 | m.Run() 22 | } 23 | ~~~ 24 | 25 | 然後安裝Martini套件 (**go 1.1**以上的版本是必要的) 26 | ~~~ 27 | go get github.com/go-martini/martini 28 | ~~~ 29 | 30 | 然後利用以下指令執行你的程式: 31 | ~~~ 32 | go run server.go 33 | ~~~ 34 | 35 | 此時, 您將會看到一個 Martini Web 伺服器在`localhost:3000`上執行 36 | 37 | ## 尋求幫助 38 | 39 | 可以加入 [Mailing list](https://groups.google.com/forum/#!forum/martini-go) 40 | 41 | 觀看 [Demo Video](http://martini.codegangsta.io/#demo) 42 | 43 | ## 功能 44 | 45 | * 超容易使用 46 | * 非侵入式設計 47 | * 很容易跟其他Go套件同時使用 48 | * 很棒的路徑matching和routing方式 49 | * 模組化設計 - 容易增加或移除功能 50 | * 有很多handlers或middlewares可以直接使用 51 | * 已經提供很多內建功能 52 | * **跟[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 介面**完全相容 53 | * 預設document服務 (例如, 提供AngularJS在HTML5模式的服務) 54 | 55 | ## 其他Middleware 56 | 尋找更多的middleware或功能, 請到 [martini-contrib](https://github.com/martini-contrib)程式集搜尋 57 | 58 | ## 目錄 59 | * [Classic Martini](#classic-martini) 60 | * [Handlers](#handlers) 61 | * [Routing](#routing) 62 | * [Services (服務)](#services) 63 | * [Serving Static Files (伺服靜態檔案)](#serving-static-files) 64 | * [Middleware Handlers](#middleware-handlers) 65 | * [Next()](#next) 66 | * [Martini Env](#martini-env) 67 | * [FAQ (常見問題與答案)](#faq) 68 | 69 | ## Classic Martini 70 | 71 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 72 | 提供大部份web應用程式所需要的基本預設功能: 73 | 74 | ~~~ go 75 | m := martini.Classic() 76 | // ... middleware 或 routing 寫在這裡 77 | m.Run() 78 | ~~~ 79 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 80 | 會自動提供以下功能 81 | * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) 82 | * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) 83 | * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 84 | * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) 85 | 86 | 87 | ### Handlers 88 | Handlers 是 Martini 的核心, 每個 handler 就是一個基本的呼叫函式, 例如: 89 | ~~~ go 90 | m.Get("/", func() { 91 | println("hello 世界") 92 | }) 93 | ~~~ 94 | 95 | #### 回傳值 96 | 如果一個 handler 有回傳值, Martini就會用字串的方式將結果寫回現在的 97 | [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 例如: 98 | ~~~ go 99 | m.Get("/", func() string { 100 | return "hello 世界" // HTTP 200 : "hello 世界" 101 | }) 102 | ~~~ 103 | 104 | 你也可以選擇回傳狀態碼, 例如: 105 | ~~~ go 106 | m.Get("/", func() (int, string) { 107 | return 418, "我是一個茶壺" // HTTP 418 : "我是一個茶壺" 108 | }) 109 | ~~~ 110 | 111 | #### 注入服務 (Service Injection) 112 | Handlers 是透過 reflection 方式被喚起, Martini 使用 *Dependency Injection* 的方法 113 | 載入 Handler 變數所需要的相關物件 **這也是 Martini 跟 Go 語言`http.HandlerFunc`介面 114 | 完全相容的原因** 115 | 116 | 如果你在 Handler 裡加入一個變數, Martini 會嘗試著從它的服務清單裡透過 type assertion 117 | 方式將相關物件載入 118 | ~~~ go 119 | m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是由 Martini 注入 120 | res.WriteHeader(200) // HTTP 200 121 | }) 122 | ~~~ 123 | 124 | [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 包含以下物件: 125 | * [*log.Logger](http://godoc.org/log#Logger) - Martini 的全區域 Logger. 126 | * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request 內文. 127 | * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. 128 | * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper 服務. 129 | * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http 回應 writer 介面. 130 | * [*http.Request](http://godoc.org/net/http/#Request) - http 請求. 131 | 132 | ### Routing 133 | 在 Martini 裡, 一個 route 就是一個 HTTP 方法與其 URL 的比對模式. 134 | 每個 route 可以有ㄧ或多個 handler 方法: 135 | ~~~ go 136 | m.Get("/", func() { 137 | // 顯示(值) 138 | }) 139 | 140 | m.Patch("/", func() { 141 | // 更新 142 | }) 143 | 144 | m.Post("/", func() { 145 | // 產生 146 | }) 147 | 148 | m.Put("/", func() { 149 | // 取代 150 | }) 151 | 152 | m.Delete("/", func() { 153 | // 刪除 154 | }) 155 | 156 | m.Options("/", func() { 157 | // http 選項 158 | }) 159 | 160 | m.NotFound(func() { 161 | // handle 404 162 | }) 163 | ~~~ 164 | 165 | Routes 依照它們被定義時的順序做比對. 第一個跟請求 (request) 相同的 route 就被執行. 166 | 167 | Route 比對模式可以包含變數部分, 可以透過 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) 物件來取值: 168 | ~~~ go 169 | m.Get("/hello/:name", func(params martini.Params) string { 170 | return "Hello " + params["name"] 171 | }) 172 | ~~~ 173 | 174 | Routes 也可以用 "**" 來配對, 例如: 175 | ~~~ go 176 | m.Get("/hello/**", func(params martini.Params) string { 177 | return "Hello " + params["_1"] 178 | }) 179 | ~~~ 180 | 181 | 也可以用正規表示法 (regular expressions) 來做比對, 例如: 182 | ~~~go 183 | m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { 184 | return fmt.Sprintf ("Hello %s", params["name"]) 185 | }) 186 | ~~~ 187 | 更多有關正規表示法文法的資訊, 請參考 [Go 文件](http://golang.org/pkg/regexp/syntax/). 188 | 189 | Route handlers 也可以相互堆疊, 尤其是認證與授權相當好用: 190 | ~~~ go 191 | m.Get("/secret", authorize, func() { 192 | // 這裏開始處理授權問題, 而非寫出回應 193 | }) 194 | ~~~ 195 | 196 | 也可以用 Group 方法, 將 route 編成一組. 197 | ~~~ go 198 | m.Group("/books", func(r martini.Router) { 199 | r.Get("/:id", GetBooks) 200 | r.Post("/new", NewBook) 201 | r.Put("/update/:id", UpdateBook) 202 | r.Delete("/delete/:id", DeleteBook) 203 | }) 204 | ~~~ 205 | 206 | 跟對 handler 增加 middleware 方法一樣, 你也可以為一組 routes 增加 middleware. 207 | ~~~ go 208 | m.Group("/books", func(r martini.Router) { 209 | r.Get("/:id", GetBooks) 210 | r.Post("/new", NewBook) 211 | r.Put("/update/:id", UpdateBook) 212 | r.Delete("/delete/:id", DeleteBook) 213 | }, MyMiddleware1, MyMiddleware2) 214 | ~~~ 215 | 216 | ### Services 217 | 服務是一些物件可以被注入 Handler 變數裡的東西, 可以分對應到 *Global* 或 *Request* 兩種等級. 218 | 219 | #### Global Mapping (全域級對應) 220 | 一個 Martini 實體 (instance) 實現了 inject.Injector 介面, 所以非常容易對應到所需要的服務, 例如: 221 | ~~~ go 222 | db := &MyDatabase{} 223 | m := martini.Classic() 224 | m.Map(db) // 所以 *MyDatabase 就可以被所有的 handlers 使用 225 | // ... 226 | m.Run() 227 | ~~~ 228 | 229 | #### Request-Level Mapping (請求級對應) 230 | 如果只在一個 handler 裡定義, 透由 [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) 獲得一個請求 (request) 級的對應: 231 | ~~~ go 232 | func MyCustomLoggerHandler(c martini.Context, req *http.Request) { 233 | logger := &MyCustomLogger{req} 234 | c.Map(logger) // 對應到 *MyCustomLogger 235 | } 236 | ~~~ 237 | 238 | #### 透由介面對應 239 | 有關服務, 最強的部分是它還能對應到一個介面 (interface), 例如, 240 | 如果你想要包裹並增加一個變數而改寫 (override) 原有的 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 你的 handler 可以寫成: 241 | ~~~ go 242 | func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { 243 | rw := NewSpecialResponseWriter(res) 244 | c.MapTo(rw, (*http.ResponseWriter)(nil)) // 我們包裹的 ResponseWriter 蓋掉原始的 ResponseWrite 245 | } 246 | ~~~ 247 | 248 | ### Serving Static Files 249 | 一個[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 實體會將伺服器根目錄下 public 子目錄裡的檔案自動當成靜態檔案處理. 你也可以手動用 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 增加其他目錄, 例如. 250 | ~~~ go 251 | m.Use(martini.Static("assets")) // "assets" 子目錄裡, 也視為靜態檔案 252 | ~~~ 253 | 254 | #### Serving a Default Document 255 | 當某些 URL 找不到時, 你也可以指定本地檔案的 URL 來顯示. 256 | 你也可以用開頭除外 (exclusion prefix) 的方式, 來忽略某些 URLs, 257 | 它尤其在某些伺服器同時伺服靜態檔案, 而且還有額外 handlers 處理 (例如 REST API) 時, 特別好用. 258 | 比如說, 在比對找不到之後, 想要用靜態檔來處理特別好用. 259 | 260 | 以下範例, 就是在 URL 開頭不是`/api/v`而且也不是本地檔案的情況下, 顯示`/index.html`檔: 261 | ~~~ go 262 | static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) 263 | m.NotFound(static, http.NotFound) 264 | ~~~ 265 | 266 | ## Middleware Handlers 267 | Middleware Handlers 位於進來的 http 請求與 router 之間, 在 Martini 裡, 本質上它跟其他 268 | Handler 沒有什麼不同, 例如, 你可加入一個 middleware 方法如下 269 | ~~~ go 270 | m.Use(func() { 271 | // 做 middleware 的事 272 | }) 273 | ~~~ 274 | 275 | 你也可以用`Handlers`完全控制 middelware 層, 把先前設定的 handlers 都替換掉, 例如: 276 | ~~~ go 277 | m.Handlers( 278 | Middleware1, 279 | Middleware2, 280 | Middleware3, 281 | ) 282 | ~~~ 283 | 284 | Middleware Handlers 成被拿來處理 http 請求之前和之後的事, 尤其是用來紀錄logs, 授權, 認證, 285 | sessions, 壓縮 (gzipping), 顯示錯誤頁面等等, 都非常好用, 例如: 286 | ~~~ go 287 | // validate an api key 288 | m.Use(func(res http.ResponseWriter, req *http.Request) { 289 | if req.Header.Get("X-API-KEY") != "secret123" { 290 | res.WriteHeader(http.StatusUnauthorized) 291 | } 292 | }) 293 | ~~~ 294 | 295 | ### Next() 296 | [Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) 是 Middleware Handlers 可以呼叫的選項功能, 用來等到其他 handlers 處理完再開始執行. 297 | 它常常被用來處理那些必須在 http 請求之後才能發生的事件, 例如: 298 | ~~~ go 299 | // 在請求前後加 logs 300 | m.Use(func(c martini.Context, log *log.Logger){ 301 | log.Println("before a request") 302 | 303 | c.Next() 304 | 305 | log.Println("after a request") 306 | }) 307 | ~~~ 308 | 309 | ## Martini Env 310 | 311 | 有些 Martini handlers 使用 `martini.Env` 全區域變數, 來當成開發環境或是上架 (production) 312 | 環境的設定判斷. 建議用 `MARTINI_ENV=production` 環境變數來設定 Martini 伺服器是上架與否. 313 | 314 | ## FAQ 315 | 316 | ### 我去哪可以找到 middleware X? 317 | 318 | 可以從 [martini-contrib](https://github.com/martini-contrib) 裡的專案找起. 319 | 如果那裡沒有, 請與 martini-contrib 團隊聯絡, 將它加入. 320 | 321 | * [auth](https://github.com/martini-contrib/auth) - 處理認證的 Handler. 322 | * [binding](https://github.com/martini-contrib/binding) - 323 | 處理一個單純的請求對應到一個結構體與確認內容正確與否的 Handler. 324 | * [gzip](https://github.com/martini-contrib/gzip) - 對請求加 gzip 壓縮的 Handler. 325 | * [render](https://github.com/martini-contrib/render) - 提供簡單處理 JSON 和 326 | HTML 樣板成形 (rendering) 的 Handler. 327 | * [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析 `Accept-Language` HTTP 檔頭的 Handler. 328 | * [sessions](https://github.com/martini-contrib/sessions) - 提供 Session 服務的 Handler. 329 | * [strip](https://github.com/martini-contrib/strip) - URL 字頭處理 (Prefix stripping). 330 | * [method](https://github.com/martini-contrib/method) - 透過 Header 或表格 (form) 欄位蓋過 HTTP 方法 (method). 331 | * [secure](https://github.com/martini-contrib/secure) - 提供一些簡單的安全機制. 332 | * [encoder](https://github.com/martini-contrib/encoder) - 轉換資料格式之 Encoder 服務. 333 | * [cors](https://github.com/martini-contrib/cors) - 啟動支援 CORS 之 Handler. 334 | * [oauth2](https://github.com/martini-contrib/oauth2) - 讓 Martini 應用程式能提供 OAuth 2.0 登入的 Handler. 其中支援 Google 登錄, Facebook Connect 與 Github 的登入等. 335 | * [vauth](https://github.com/rafecolton/vauth) - 處理 vender webhook 認證的 Handler (目前支援 GitHub 以及 TravisCI) 336 | 337 | ### 我如何整合到現有的伺服器? 338 | 339 | Martini 實作 `http.Handler`,所以可以非常容易整合到現有的 Go 伺服器裡. 340 | 以下寫法, 是一個能在 Google App Engine 上運行的 Martini 應用程式: 341 | 342 | ~~~ go 343 | package hello 344 | 345 | import ( 346 | "net/http" 347 | "github.com/go-martini/martini" 348 | ) 349 | 350 | func init() { 351 | m := martini.Classic() 352 | m.Get("/", func() string { 353 | return "Hello world!" 354 | }) 355 | http.Handle("/", m) 356 | } 357 | ~~~ 358 | 359 | ### 我要如何改變 port/host? 360 | 361 | Martini 的 `Run` 功能會看 PORT 及 HOST 當時的環境變數, 否則 Martini 會用 localhost:3000 362 | 當預設值. 讓 port 及 host 更有彈性, 可以用 `martini.RunOnAddr` 取代. 363 | 364 | ~~~ go 365 | m := martini.Classic() 366 | // ... 367 | log.Fatal(m.RunOnAddr(":8080")) 368 | ~~~ 369 | 370 | ### 可以線上更新 (live reload) 嗎? 371 | 372 | [gin](https://github.com/codegangsta/gin) 和 [fresh](https://github.com/pilu/fresh) 可以幫 Martini 程式做到線上更新. 373 | 374 | ## 貢獻 375 | Martini 盡量保持小而美的精神, 大多數的程式貢獻者可以在 [martini-contrib](https://github.com/martini-contrib) 組織提供代碼. 如果你想要對 Martini 核心提出貢獻, 請丟出 Pull Request. 376 | 377 | ## 關於 378 | 379 | 靈感來自與 [express](https://github.com/visionmedia/express) 以及 [sinatra](https://github.com/sinatra/sinatra) 380 | 381 | Martini 由 [Code Gangsta](http://codegangsta.io/) 公司設計出品 (著魔地) 382 | -------------------------------------------------------------------------------- /wercker.yml: -------------------------------------------------------------------------------- 1 | box: wercker/golang@1.1.1 --------------------------------------------------------------------------------