百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
M

martini

> 编程语言
开源

Go 的类网络框架

11.6K stars0 点赞1 次浏览
访问官网GitHub

工具介绍

Go 的类网络框架

Martini

NOTE: The martini framework is no longer maintained.

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

Language Translations:

  • 繁體中文
  • 简体中文
  • Português Brasileiro (pt_BR)
  • Español
  • 한국어 번역
  • Русский
  • 日本語
  • French
  • Turkish
  • German
  • Polski

Getting Started

After installing Go and setting up your GOPATH, create your first .go file. We'll call it server.go.

go
package main

import "github.com/go-martini/martini"

func main() {
  m := martini.Classic()
  m.Get("/", func() string {
    return "Hello world!"
  })
  m.Run()
}

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

go get github.com/go-martini/martini

Then run your server:

go run server.go

You will now have a Martini webserver running on localhost:3000.

Getting Help

Join the Mailing list

Watch the Demo Video

Ask questions on Stackoverflow using the martini tag

GoDoc documentation

Features

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

More Middleware

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

Table of Contents

  • Classic Martini
    • Handlers
    • Routing
    • Services
    • Serving Static Files
  • Middleware Handlers
    • Next()
  • Martini Env
  • FAQ

Classic Martini

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

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

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

  • Request/Response Logging - martini.Logger
  • Panic Recovery - martini.Recovery
  • Static File serving - martini.Static
  • Routing - martini.Router

Handlers

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

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

Return Values

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

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

You can also optionally return a status code:

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

Service Injection

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

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

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

The following services are included with martini.Classic():

  • *log.Logger - Global logger for Martini.
  • martini.Context - http request context.
  • martini.Params - map[string]string of named params found by route matching.
  • martini.Routes - Route helper service.
  • martini.Route - Current active route.
  • http.ResponseWriter - http Response writer interface.
  • *http.Request - http Request.

Routing

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

go
m.Get("/", func() {
  // show something
})

m.Patch("/", func() {
  // update something
})

m.Post("/", func() {
  // create something
})

m.Put("/", func() {
  // replace something
})

m.Delete("/", func() {
  // destroy something
})

m.Options("/", func() {
  // http options
})

m.NotFound(func() {
  // handle 404
})

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

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

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

Routes can be matched with globs:

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

Regular expressions can be used as well:

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

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

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

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

Route groups can be added too using the Group method.

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

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

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

Services

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

Global Mapping

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

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

Request-Level Mapping

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

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

Mapping values to Interfaces

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

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

Serving Static Files

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

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

Serving a Default Document

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

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

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

Middleware Handlers

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

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

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

go
m.Handlers(
  Middleware1,
  Middleware2,
  Middleware3,
)

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

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

Next()

Context.Next() is an optional function that Middleware Handlers can call to yield the until after the other Handlers have been executed. This works really well for any operations that must happen after an http request:

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

  c.Next()

  log.Println("after a request")
})

Martini Env

Some Martini handlers make use of 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.

FAQ

Where do I find middleware X?

Start by looking in the 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.

  • acceptlang - Handler for parsing the Accept-Language HTTP header.
  • accessflags - Handler to enable Access Control.
  • [auth](https://gi

Issues· 17 开放

查看全部 Issues在 GitHub 打开
  • #436

    性爱

    更新于 2025年12月19日
  • #435

    包 GitHub.com/go-martini/martini 不是主包

    更新于 2025年3月19日
  • #434

    足球

    更新于 2024年1月2日
  • #429

    路由匹配中出现 # 问题

    更新于 2023年1月16日
  • #432

    这个项目死了吗?

    更新于 2020年10月22日
  • #431

    如何成为维护者?

    更新于 2020年7月24日
  • #428

    如何使用 Martini 突破中间件链

    更新于 2020年7月24日
  • #430

    贡献, 阿拉伯语翻译

    更新于 2020年7月14日
  • #426

    如何包含处理已登录用户角色的授权中间件

    更新于 2020年3月11日
  • #425

    在启动时对参数进行类型检查

    更新于 2020年3月4日

> 标签

Go

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月28日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言