martini web框架介绍 ## 序 Martini是Web框架,没有自带ORM或详细的分层内容。使用Martini开发时,还需要选取适合的ORM等其他包。 ## 安装 ``` go get github.com/codegangsta/martini ``` ## 使用 我们可以使用如下的代码来测试我们安装的包是否是可用的: ``` // server.go package main import "github.com/codegangsta/martini" func main() { m := martini.Classic() m.Get("/", func() string { return "Hello world!" }) m.Run() } ``` 在命令行中输入下面的命令运行上面的代码: ``` go run server.go ``` 接下来我们就可以使用如下的网址访问我们的应用: ``` http://localhost:3000 ``` ### 说明: 1. m := martini.Classic\(\)创建一个典型的martini实例。 2. m.Get\("/", func\(\) string { ... }\)接收对\的GET方法请求,第二个参数是对一请求的处理方法。 3. m.Run\(\)运行服务器。 ## API (主要内容翻译自官方文档) 常量 下面的常量定义用于指定应用所处的环境: ``` const ( Dev string = "development" Prod string = "production" Test string = "test" ) ``` ### 变量 我们使用如下的变量来控制应用所处的环境: ``` var Env = Dev ``` ### type BeforeFunc BeforeFunc类型的方法在ResponseWriter方法被生效前调用。 ``` type BeforeFunc func(ResponseWriter) ``` 如: ``` BeforeFunc XXX(req ResponseWriter){ // ... } ``` ### type ClassicMartini 带有典型方法的Martini实例类型。 ``` type ClassicMartini struct { *Martini Router } ``` #### func Classic\(\) \*ClassicMartini 我们可以使用这个方法创建一个典型的Martini实例。然后我们就可以使用这个Martini实例来进行应用的管理: ``` func Classic() *ClassicMartini ``` ### type Context Request请求的上下文内容。 ``` type Context interface { inject.Injector // 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 Next() // Written returns whether or not the response for this context has been written. Written() bool } ### type Handler Handler可以是任意的方法,Marniti会尝试注入服务到Handler方法的参数列表中。如果不能成功注入的话,Marniti会panic。 ``` type Handler interface{} \`\`\` #### func Logger\(\) Handler Logger返回一个中间件处理器,用于记录request的请求输入与响应输出。 ``` func Logger() Handler ``` #### func Recovery\(\) Handler Recovery返回一个中间件,用于修复错误并在可能的情况下返回一个500给客户端。在开发模式的时候,Recovery会将错误信息输出为HTML页面。 ``` func Recovery() Handler ``` #### func Static\(directory string, staticOpt ...StaticOptions\) Handler Static返回一个中间件处理器,用于服务给定目录的静态文件。 ``` func Static(directory string, staticOpt ...StaticOptions) Handler ``` ### type Martini Martini实例是整个Web应用的顶层。inject.Injector方法在全局层面上映射服务。 ``` type Martini struct { inject.Injector // contains filtered or unexported fields } ``` #### func New\(\) \*Martini 创建包含全部功能的Martini实例。 ``` func New() *Martini ``` #### func \(m \*Martini\) Action\(handler Handler\) Action方法在所有的Martini中间件都被引入之后调用。在ClassicMartini中,是martini.Router。 ``` func (m *Martini) Action(handler Handler) ``` #### func \(m \*Martini\) Handlers\(handlers ...Handler\) 设置给定的Handler处理方法栈。当处理器中存在不可调用的方法的时候,会产生异常。 ``` func (m *Martini) Handlers(handlers ...Handler) ``` #### func \(m \*Martini\) Run\(\) 获取http包中的server.Listening。默认使用os.GetEnv\("PORT"\)或3000作为访问端口号. ``` func (m *Martini) Run() ``` #### func \(m Martini\) ServeHTTP\(res http.ResponseWriter, req http.Request\) ServeHTTP是Martini实例的入口。一般用于控制HTTP服务器。 ``` func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) ``` #### func \(m \*Martini\) Use\(handler Handler\) 将一个Handle处理方法添加到处理栈中。当处理方法不可用的时候会出现异常。 ``` func (m *Martini) Use(handler Handler) ``` #### type Params 已命名路由的键值对映射。一个martini.Params可以被注入到任意的路由处理方法中。 ``` type Params map[string]string ``` #### type ResponseWriter ResponseWriter对http.ResponseWriter进行包装,它提供有关响应的扩展信息。如果以方法的形式调用,推荐使用这个中间件处理器来包装一个响应。 ``` type ResponseWriter interface { http.ResponseWriter http.Flusher // Status returns the status code of the response or 0 if the response has not been written. Status() int // Written returns whether or not the ResponseWriter has been written. Written() bool // Size returns the size of the response body. Size() int // Before allows for a function to be called before the ResponseWriter has been written to. This is // useful for setting headers or any other operations that must happen before a response has been written. Before(BeforeFunc) } ``` #### func NewResponseWriter\(rw http.ResponseWriter\) ResponseWriter 创建一个包装http.ResponseWriter的ResponseWriter类型实例。 ``` func NewResponseWriter(rw http.ResponseWriter) ResponseWriter ``` ### type ReturnHandler ReturnHandler是Martini提供的用于路由处理并返回内容的服务。ReturnHandler对于向基于值传递的ResponseWriter写入是可响应的。 ``` type ReturnHandler func(Context, []reflect.Value) ``` ### type Route Route是一个用于表示Martini路由层的接口。 ``` type Route interface { // URLWith returns a rendering of the Route's url with the given string params. URLWith([]string) string Name(string) } ``` ### type Router Router是Martini的路由接口。提供HTTP变量、处理方法栈、依赖注入。 ``` type Router interface { // Get adds a route for a HTTP GET request to the specified matching pattern. Get(string, ...Handler) Route // Patch adds a route for a HTTP PATCH request to the specified matching pattern. Patch(string, ...Handler) Route // Post adds a route for a HTTP POST request to the specified matching pattern. Post(string, ...Handler) Route // Put adds a route for a HTTP PUT request to the specified matching pattern. Put(string, ...Handler) Route // Delete adds a route for a HTTP DELETE request to the specified matching pattern. Delete(string, ...Handler) Route // Options adds a route for a HTTP OPTIONS request to the specified matching pattern. Options(string, ...Handler) Route // Head adds a route for a HTTP HEAD request to the specified matching pattern. Head(string, ...Handler) Route // Any adds a route for any HTTP method request to the specified matching pattern. Any(string, ...Handler) Route // NotFound sets the handlers that are called when a no route matches a request. Throws a basic 404 by default. NotFound(...Handler) // Handle is the entry point for routing. This is used as a martini.Handler Handle(http.ResponseWriter, *http.Request, Context) } ``` #### func NewRouter\(\) Router 创建一个路由实例。 ``` func NewRouter() Router ``` ### type Routes Routes是Martini路由层的辅助服务。 ``` type Routes interface { // URLFor returns a rendered URL for the given route. Optional params can be passed to fulfill named parameters in the route. URLFor(name string, params ...interface{}) string // MethodsFor returns an array of methods available for the path MethodsFor(path string) []string } ``` ### type StaticOptions StaticOptions是一个为martini.Static中间件指定配置选项的结构体。 ``` type StaticOptions struct { // Prefix is the optional prefix used to serve the static directory content Prefix string // SkipLogging can be used to switch log messages to *log.logger off. SkipLogging bool // IndexFile defines which file to serve as index if it exists. IndexFile string } ``` ## 参考 1. [官网](http://martini.codegangsta.io/) 2. [@Github](https://github.com/codegangsta/martini) 3. [@GoDOC](http://godoc.org/github.com/codegangsta/martini)