Getting started with the "golang" Marini framework

Source: Internet
Author: User

This article introduces golang's excellent web development framework, Marini!

Collation

The Marini framework is a powerful and fast development framework that uses the go language to build modular web applications and services. Marini is a framework specifically used to process web-related content. It does not contain ORM or detailed layered content. So when we use Marini as our development framework, we also need to select suitable orm and other packages.

Install
go get github.com/codegangsta/martini
Use

We can use the following code to test whether the installed package is available:

// server.gopackage mainimport "github.com/codegangsta/martini"func main() {  m := martini.Classic()  m.Get("/", func() string {    return "Hello world!"  })  m.Run()}

Enter the following command in the command line to run the above Code:

go run server.go

Next we can use the following URL to access our application:

http://localhost:3000
Note:
  1. M: = Marini. Classic () to create a typical Marini instance.
  2. M. Get ("/", func () string {...}) receives the get Method Request to \. The second parameter is the processing method of a request.
  3. M. Run () run the server.
API

(Main content translated from official documents)

The constant definitions below the constant are used to specify the environment where the application is located:

const (    Dev  string = "development"    Prod string = "production"    Test string = "test")
Variable

The following variables are used to control the application environment:

var Env = Dev
Type beforefunc

Beforefunc type method is called before the responsewriter method is effective.

type BeforeFunc func(ResponseWriter)

For example:

BeforeFunc XXX(req ResponseWriter){    // ...}
Type classicmarini

The type of a Marini instance with a typical method.

type ClassicMartini struct {    *Martini    Router}
Func classic () * classicmarini

We can use this method to create a typical Marini instance. Then we can use this Marini instance for application management:

func Classic() *ClassicMartini
Type Context

The context of the 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 handlerhandler can be any method, marniti Will try to inject the service to the parameter list of the handler method. If the injection fails, marniti will panic.

Type handler interface {}'''

Func logger () Handler

Logger returns a middleware processor used to record request input and response output.

func Logger() Handler
Func recovery () Handler

Recovery returns a middleware for fixing errors and, if possible, returns a 500 to the client. In the development mode, recovery outputs the error information as an HTML page.

func Recovery() Handler
Func static (directory string, staticopt... staticoptions) Handler

Static returns a middleware processor used to serve static files in a given directory.

func Static(directory string, staticOpt ...StaticOptions) Handler
Type Marini

The Marini instance is the top layer of the entire web application. The inject. injector method maps services globally.

type Martini struct {    inject.Injector    // contains filtered or unexported fields}
Func new () * Marini

Create a Marini instance that contains all functions.

func New() *Martini
Func (M * Marini) Action (handler)

The action method is called after all the Marini middleware is introduced. In classicmarini, It is Marini. router.

func (m *Martini) Action(handler Handler)
Func (M * Marini) handlers (handlers... handler)

Set the given handler processing method stack. An exception occurs when an uncallable method exists in the processor.

func (m *Martini) Handlers(handlers ...Handler)
Func (M * Marini) Run ()

Obtain server. listening from the http package. OS. getenv ("Port") or 3000 is used as the access port number by default.

func (m *Martini) Run()
Func (M Marini) servehttp (res http. responsewriter, req HTTP. Request)

Servehttp is the entry to the Marini instance. It is generally used to control HTTP servers.

func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request)
Func (M * Marini) Use (handler)

Add a handle Processing Method to the Processing Stack. An exception occurs when the processing method is unavailable.

func (m *Martini) Use(handler Handler)
Type Params

The key-Value Pair ing of the named route. A Marini. Params can be injected into any routing method.

type Params map[string]string
Type responsewriter

Responsewriter encapsulates HTTP. responsewriter, which provides extended response information. We recommend that you use this middleware processor to encapsulate a response if it is called as a method.

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

Create a responsewriter-type instance that encapsulates HTTP. responsewriter.

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter
Type returnhandler

Returnhandler is a service provided by Marini for routing processing and returning content. Returnhandler is responsive for writing to value-based responsewriter.

type ReturnHandler func(Context, []reflect.Value)
Type route

Route is an interface used to represent the Marini routing layer.

type Route interface {    // URLWith returns a rendering of the Route‘s url with the given string params.    URLWith([]string) string    Name(string)}
Type Router

Rotini is the routing interface of Marini. Provides HTTP variables, processing method stacks, and dependency injection.

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

Create a route instance.

func NewRouter() Router
Type routes

Routes is a secondary service of the Marini routing layer.

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 is a struct that specifies configuration options for the Marini. Static middleware.

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}
Reference
  1. Official Website
  2. @ GitHub
  3. @ Godoc

Getting started with the "golang" Marini framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.