『Golang』Martini框架入门
本文介紹golang中的優秀web開發框架martini!
序
Martini框架是使用Go語言作為開發語言的一個強力的快速構建模塊化web應用與服務的開發框架。Martini是一個專門用來處理Web相關內容的框架,其并沒有自帶有關ORM或詳細的分層內容。所以當我們使用Martini作為我們的開發框架時,我們還需要選取適合的ORM等其他包。
安裝
go get github.com/codegangsta/martini使用
我們可以使用如下的代碼來測試我們安裝的包是否是可用的:
// server.gopackage mainimport "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說明:
API
(主要內容翻譯自官方文檔)
常量 下面的常量定義用于指定應用所處的環境:
const (Dev string = "development"Prod string = "production"Test string = "test" )變量
我們使用如下的變量來控制應用所處的環境:
var Env = Devtype BeforeFunc
BeforeFunc類型的方法在ResponseWriter方法被生效前調用。
type BeforeFunc func(ResponseWriter)如:
BeforeFunc XXX(req ResponseWriter){// ... }type ClassicMartini
帶有典型方法的Martini實例類型。
type ClassicMartini struct {*MartiniRouter }func Classic() *ClassicMartini
我們可以使用這個方法創建一個典型的Martini實例。然后我們就可以使用這個Martini實例來進行應用的管理:
func Classic() *ClassicMartinitype 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 requestNext()// Written returns whether or not the response for this context has been written.Written() bool }### type HandlerHandler可以是任意的方法,Marniti會嘗試注入服務到Handler方法的參數列表中。如果不能成功注入的話,Marniti會panic。type Handler interface{} ```
func Logger() Handler
Logger返回一個中間件處理器,用于記錄request的請求輸入與響應輸出。
func Logger() Handlerfunc Recovery() Handler
Recovery返回一個中間件,用于修復錯誤并在可能的情況下返回一個500給客戶端。在開發模式的時候,Recovery會將錯誤信息輸出為HTML頁面。
func Recovery() Handlerfunc Static(directory string, staticOpt ...StaticOptions) Handler
Static返回一個中間件處理器,用于服務給定目錄的靜態文件。
func Static(directory string, staticOpt ...StaticOptions) Handlertype Martini
Martini實例是整個Web應用的頂層。inject.Injector方法在全局層面上映射服務。
type Martini struct {inject.Injector// contains filtered or unexported fields }func New() *Martini
創建包含全部功能的Martini實例。
func New() *Martinifunc (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]stringtype ResponseWriter
ResponseWriter對http.ResponseWriter進行包裝,它提供有關響應的擴展信息。如果以方法的形式調用,推薦使用這個中間件處理器來包裝一個響應。
type ResponseWriter interface {http.ResponseWriterhttp.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) ResponseWritertype 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) stringName(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.HandlerHandle(http.ResponseWriter, *http.Request, Context) }func NewRouter() Router
創建一個路由實例。
func NewRouter() Routertype 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 pathMethodsFor(path string) []string }type StaticOptions
StaticOptions是一個為martini.Static中間件指定配置選項的結構體。
type StaticOptions struct {// Prefix is the optional prefix used to serve the static directory contentPrefix 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 }參考
轉載于:https://www.cnblogs.com/sitemanager/p/3973907.html
總結
以上是生活随笔為你收集整理的『Golang』Martini框架入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 每一对顶点之间的最短路径
- 下一篇: 页面间传递参数