{"id":13470061,"url":"https://github.com/go-martini/martini","last_synced_at":"2025-12-16T19:05:25.271Z","repository":{"id":11498691,"uuid":"13975314","full_name":"go-martini/martini","owner":"go-martini","description":"Classy web framework for Go","archived":false,"fork":false,"pushed_at":"2022-03-29T19:42:09.000Z","size":496,"stargazers_count":11619,"open_issues_count":15,"forks_count":1165,"subscribers_count":512,"default_branch":"master","last_synced_at":"2024-02-15T03:33:26.979Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"martini.codegangsta.io","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/go-martini.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-10-30T02:34:07.000Z","updated_at":"2024-02-11T19:36:40.000Z","dependencies_parsed_at":"2022-07-14T02:20:31.517Z","dependency_job_id":null,"html_url":"https://github.com/go-martini/martini","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-martini%2Fmartini","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-martini%2Fmartini/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-martini%2Fmartini/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-martini%2Fmartini/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/go-martini","download_url":"https://codeload.github.com/go-martini/martini/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":222131035,"owners_count":16936304,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T16:00:22.348Z","updated_at":"2025-12-16T19:05:20.229Z","avatar_url":"https://github.com/go-martini.png","language":"Go","funding_links":[],"categories":["Go","Web 后端","Web框架","Go의 웹 프레임워크","Web Frameworks","Micro Frameworks inspired by Sinatra (Other Languages)","Service Toolkits"],"sub_categories":["GOPATH","Advanced Console UIs","Go"],"readme":"# Martini  [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master \"wercker status\")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini)\n\n### **NOTE:** The martini framework is no longer maintained.\n\nMartini is a powerful package for quickly writing modular web applications/services in Golang.\n\nLanguage Translations:\n* [繁體中文](translations/README_zh_tw.md)\n* [简体中文](translations/README_zh_cn.md)\n* [Português Brasileiro (pt_BR)](translations/README_pt_br.md)\n* [Español](translations/README_es_ES.md)\n* [한국어 번역](translations/README_ko_kr.md)\n* [Русский](translations/README_ru_RU.md)\n* [日本語](translations/README_ja_JP.md)\n* [French](translations/README_fr_FR.md)\n* [Turkish](translations/README_tr_TR.md)\n* [German](translations/README_de_DE.md)\n* [Polski](translations/README_pl_PL.md)\n\n## Getting Started\n\nAfter installing Go and setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH), create your first `.go` file. We'll call it `server.go`.\n\n~~~ go\npackage main\n\nimport \"github.com/go-martini/martini\"\n\nfunc main() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  m.Run()\n}\n~~~\n\nThen install the Martini package (**go 1.1** or greater is required):\n~~~\ngo get github.com/go-martini/martini\n~~~\n\nThen run your server:\n~~~\ngo run server.go\n~~~\n\nYou will now have a Martini webserver running on `localhost:3000`.\n\n## Getting Help\n\nJoin the [Mailing list](https://groups.google.com/forum/#!forum/martini-go)\n\nWatch the [Demo Video](http://martini.codegangsta.io/#demo)\n\nAsk questions on Stackoverflow using the [martini tag](http://stackoverflow.com/questions/tagged/martini)\n\nGoDoc [documentation](http://godoc.org/github.com/go-martini/martini)\n\n\n## Features\n* Extremely simple to use.\n* Non-intrusive design.\n* Plays nice with other Golang packages.\n* Awesome path matching and routing.\n* Modular design - Easy to add functionality, easy to rip stuff out.\n* Lots of good handlers/middlewares to use.\n* Great 'out of the box' feature set.\n* **Fully compatible with the [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) interface.**\n* Default document serving (e.g., for serving AngularJS apps in HTML5 mode).\n\n## More Middleware\nFor more middleware and functionality, check out the repositories in the  [martini-contrib](https://github.com/martini-contrib) organization.\n\n## Table of Contents\n* [Classic Martini](#classic-martini)\n  * [Handlers](#handlers)\n  * [Routing](#routing)\n  * [Services](#services)\n  * [Serving Static Files](#serving-static-files)\n* [Middleware Handlers](#middleware-handlers)\n  * [Next()](#next)\n* [Martini Env](#martini-env)\n* [FAQ](#faq)\n\n## Classic Martini\nTo get up and running quickly, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) provides some reasonable defaults that work well for most web applications:\n~~~ go\n  m := martini.Classic()\n  // ... middleware and routing goes here\n  m.Run()\n~~~\n\nBelow is some of the functionality [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) pulls in automatically:\n  * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger)\n  * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery)\n  * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static)\n  * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router)\n\n### Handlers\nHandlers are the heart and soul of Martini. A handler is basically any kind of callable function:\n~~~ go\nm.Get(\"/\", func() {\n  println(\"hello world\")\n})\n~~~\n\n#### Return Values\nIf a handler returns something, Martini will write the result to the current [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) as a string:\n~~~ go\nm.Get(\"/\", func() string {\n  return \"hello world\" // HTTP 200 : \"hello world\"\n})\n~~~\n\nYou can also optionally return a status code:\n~~~ go\nm.Get(\"/\", func() (int, string) {\n  return 418, \"i'm a teapot\" // HTTP 418 : \"i'm a teapot\"\n})\n~~~\n\n#### Service Injection\nHandlers are invoked via reflection. Martini makes use of *Dependency Injection* to resolve dependencies in a Handlers argument list. **This makes Martini completely  compatible with golang's `http.HandlerFunc` interface.**\n\nIf you add an argument to your Handler, Martini will search its list of services and attempt to resolve the dependency via type assertion:\n~~~ go\nm.Get(\"/\", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini\n  res.WriteHeader(200) // HTTP 200\n})\n~~~\n\nThe following services are included with [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):\n  * [*log.Logger](http://godoc.org/log#Logger) - Global logger for Martini.\n  * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context.\n  * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching.\n  * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service.\n  * [martini.Route](http://godoc.org/github.com/go-martini/martini#Route) - Current active route.\n  * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface.\n  * [*http.Request](http://godoc.org/net/http/#Request) - http Request.\n\n### Routing\nIn Martini, a route is an HTTP method paired with a URL-matching pattern.\nEach route can take one or more handler methods:\n~~~ go\nm.Get(\"/\", func() {\n  // show something\n})\n\nm.Patch(\"/\", func() {\n  // update something\n})\n\nm.Post(\"/\", func() {\n  // create something\n})\n\nm.Put(\"/\", func() {\n  // replace something\n})\n\nm.Delete(\"/\", func() {\n  // destroy something\n})\n\nm.Options(\"/\", func() {\n  // http options\n})\n\nm.NotFound(func() {\n  // handle 404\n})\n~~~\n\nRoutes are matched in the order they are defined. The first route that\nmatches the request is invoked.\n\nRoute patterns may include named parameters, accessible via the [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service:\n~~~ go\nm.Get(\"/hello/:name\", func(params martini.Params) string {\n  return \"Hello \" + params[\"name\"]\n})\n~~~\n\nRoutes can be matched with globs:\n~~~ go\nm.Get(\"/hello/**\", func(params martini.Params) string {\n  return \"Hello \" + params[\"_1\"]\n})\n~~~\n\nRegular expressions can be used as well:\n~~~go\nm.Get(\"/hello/(?P\u003cname\u003e[a-zA-Z]+)\", func(params martini.Params) string {\n  return fmt.Sprintf (\"Hello %s\", params[\"name\"])\n})\n~~~\nTake a look at the [Go documentation](http://golang.org/pkg/regexp/syntax/) for more info about regular expressions syntax .\n\nRoute handlers can be stacked on top of each other, which is useful for things like authentication and authorization:\n~~~ go\nm.Get(\"/secret\", authorize, func() {\n  // this will execute as long as authorize doesn't write a response\n})\n~~~\n\nRoute groups can be added too using the Group method.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n})\n~~~\n\nJust like you can pass middlewares to a handler you can pass middlewares to groups.\n~~~ go\nm.Group(\"/books\", func(r martini.Router) {\n    r.Get(\"/:id\", GetBooks)\n    r.Post(\"/new\", NewBook)\n    r.Put(\"/update/:id\", UpdateBook)\n    r.Delete(\"/delete/:id\", DeleteBook)\n}, MyMiddleware1, MyMiddleware2)\n~~~\n\n### Services\nServices are objects that are available to be injected into a Handler's argument list. You can map a service on a *Global* or *Request* level.\n\n#### Global Mapping\nA Martini instance implements the inject.Injector interface, so mapping a service is easy:\n~~~ go\ndb := \u0026MyDatabase{}\nm := martini.Classic()\nm.Map(db) // the service will be available to all handlers as *MyDatabase\n// ...\nm.Run()\n~~~\n\n#### Request-Level Mapping\nMapping on the request level can be done in a handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context):\n~~~ go\nfunc MyCustomLoggerHandler(c martini.Context, req *http.Request) {\n  logger := \u0026MyCustomLogger{req}\n  c.Map(logger) // mapped as *MyCustomLogger\n}\n~~~\n\n#### Mapping values to Interfaces\nOne of the most powerful parts about services is the ability to map a service to an interface. For instance, if you wanted to override the [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) with an object that wrapped it and performed extra operations, you can write the following handler:\n~~~ go\nfunc WrapResponseWriter(res http.ResponseWriter, c martini.Context) {\n  rw := NewSpecialResponseWriter(res)\n  c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter\n}\n~~~\n\n### Serving Static Files\nA [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) instance automatically serves static files from the \"public\" directory in the root of your server.\nYou can serve from more directories by adding more [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers.\n~~~ go\nm.Use(martini.Static(\"assets\")) // serve from the \"assets\" directory as well\n~~~\n\n#### Serving a Default Document\nYou can specify the URL of a local file to serve when the requested URL is not\nfound. You can also specify an exclusion prefix so that certain URLs are ignored.\nThis is useful for servers that serve both static files and have additional\nhandlers defined (e.g., REST API). When doing so, it's useful to define the\nstatic handler as a part of the NotFound chain.\n\nThe following example serves the `/index.html` file whenever any URL is\nrequested that does not match any local file and does not start with `/api/v`:\n~~~ go\nstatic := martini.Static(\"assets\", martini.StaticOptions{Fallback: \"/index.html\", Exclude: \"/api/v\"})\nm.NotFound(static, http.NotFound)\n~~~\n\n## Middleware Handlers\nMiddleware Handlers sit between the incoming http request and the router. In essence they are no different than any other Handler in Martini. You can add a middleware handler to the stack like so:\n~~~ go\nm.Use(func() {\n  // do some middleware stuff\n})\n~~~\n\nYou can have full control over the middleware stack with the `Handlers` function. This will replace any handlers that have been previously set:\n~~~ go\nm.Handlers(\n  Middleware1,\n  Middleware2,\n  Middleware3,\n)\n~~~\n\nMiddleware Handlers work really well for things like logging, authorization, authentication, sessions, gzipping, error pages and any other operations that must happen before or after an http request:\n~~~ go\n// validate an api key\nm.Use(func(res http.ResponseWriter, req *http.Request) {\n  if req.Header.Get(\"X-API-KEY\") != \"secret123\" {\n    res.WriteHeader(http.StatusUnauthorized)\n  }\n})\n~~~\n\n### Next()\n[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) is an optional function that Middleware Handlers can call to yield the until after the other Handlers have been executed. This works really well for any operations that must happen after an http request:\n~~~ go\n// log before and after a request\nm.Use(func(c martini.Context, log *log.Logger){\n  log.Println(\"before a request\")\n\n  c.Next()\n\n  log.Println(\"after a request\")\n})\n~~~\n\n## Martini Env\n\nSome Martini handlers make use of the `martini.Env` global variable to provide special functionality for development environments vs production environments. It is recommended that the `MARTINI_ENV=production` environment variable to be set when deploying a Martini server into a production environment.\n\n## FAQ\n\n### Where do I find middleware X?\n\nStart by looking in the [martini-contrib](https://github.com/martini-contrib) projects. If it is not there feel free to contact a martini-contrib team member about adding a new repo to the organization.\n\n* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header.\n* [accessflags](https://github.com/martini-contrib/accessflags) - Handler to enable Access Control.\n* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication.\n* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure.\n* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support.\n* [csrf](https://github.com/martini-contrib/csrf) - CSRF protection for applications\n* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation.\n* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests\n* [gorelic](https://github.com/martini-contrib/gorelic) - NewRelic middleware\n* [logstasher](https://github.com/martini-contrib/logstasher) - Middleware that prints logstash-compatible JSON \n* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields.\n* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported.\n* [permissions2](https://github.com/xyproto/permissions2) - Handler for keeping track of users, login states and permissions.\n* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates.\n* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins.\n* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service.\n* [sessionauth](https://github.com/martini-contrib/sessionauth) - Handler that provides a simple way to make routes require a login, and to handle user logins in the session\n* [strict](https://github.com/martini-contrib/strict) - Strict Mode \n* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping.\n* [staticbin](https://github.com/martini-contrib/staticbin) - Handler for serving static files from binary data\n* [throttle](https://github.com/martini-contrib/throttle) - Request rate throttling middleware.\n* [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI)\n* [web](https://github.com/martini-contrib/web) - hoisie web.go's Context\n\n### How do I integrate with existing servers?\n\nA Martini instance implements `http.Handler`, so it can easily be used to serve subtrees\non existing Go servers. For example this is a working Martini app for Google App Engine:\n\n~~~ go\npackage hello\n\nimport (\n  \"net/http\"\n  \"github.com/go-martini/martini\"\n)\n\nfunc init() {\n  m := martini.Classic()\n  m.Get(\"/\", func() string {\n    return \"Hello world!\"\n  })\n  http.Handle(\"/\", m)\n}\n~~~\n\n### How do I change the port/host?\n\nMartini's `Run` function looks for the PORT and HOST environment variables and uses those. Otherwise Martini will default to localhost:3000.\nTo have more flexibility over port and host, use the `martini.RunOnAddr` function instead.\n\n~~~ go\n  m := martini.Classic()\n  // ...\n  m.RunOnAddr(\":8080\")\n~~~\n\n### Live code reload?\n\n[gin](https://github.com/codegangsta/gin) and [fresh](https://github.com/pilu/fresh) both live reload martini apps.\n\n## Contributing\nMartini is meant to be kept tiny and clean. Most contributions should end up in a repository in the [martini-contrib](https://github.com/martini-contrib) organization. If you do have a contribution for the core of Martini feel free to put up a Pull Request.\n\n## License\nMartini is distributed by The MIT License, see LICENSE\n\n## About\n\nInspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra)\n\nMartini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-martini%2Fmartini","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgo-martini%2Fmartini","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-martini%2Fmartini/lists"}