gem

package module
v0.0.0-...-a681200 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 19, 2017 License: BSD-3-Clause Imports: 17 Imported by: 0

README

Gem Web Framework

GoDoc Build Status Go Report Card Coverage Status Sourcegraph

Gem is an easy to use and high performance web framework written in Go(golang), it supports HTTP/2, and provides leveled logger and frequently used middlewares.

Note: requires go1.8 or above.

Starter Kit is available, it provides a convenient way to create an application.

Features

Getting Started

Install
$ go get -u github.com/go-gem/gem
Quick Start
package main

import (
    "log"

    "github.com/go-gem/gem"
)

func index(ctx *gem.Context) {
    ctx.HTML(200, "hello world")
}

func main() {
    // Create server.
    srv := gem.New(":8080")
    
    // Create router.
    router := gem.NewRouter()
    // Register handler
    router.GET("/", index)
    
    // Start server.
    log.Println(srv.ListenAndServe(router.Handler()))
}
Context

Context embedded http.ResponseWriter and *http.Request, and provides some useful APIs and shortcut, see https://godoc.org/github.com/go-gem/gem#Context.

Logger

AFAIK, the following leveled logging packages are compatible with Gem web framework:

  • logrus - structured, pluggable logging for Go
  • go-logging - golang logging library
  • gem-log - default logger
  • Please let me know if I missed the other logging packages :)

Logger includes four levels: debug, info, error and fatal.

APIs

  • Debug and Debugf
  • Info and Infof
  • Error and Errorf
  • Fatal and Fatalf

For example:

// set logrus logger as server's logger.
srv.SetLogger(logrus.New())

// we can use it in handler.
router.GET("/logger", func(ctx *gem.Context) {
		ctx.Logger().Debug("debug")
		ctx.Logger().Info("info")
		ctx.Logger().Error("error")
})
Static Files
router.ServeFiles("/tmp/*filepath", http.Dir(os.TempDir()))

Note: the first parameter must end with *filepath.

REST APIs

The router is friendly to REST APIs.

// user list
router.GET("/users", func(ctx *gem.Context) {
    ctx.JSON(200, userlist)    
})

// add user
router.POST("/users", func(ctx *gem.Context) {
    ctx.Request.ParseForm()
    name := ctx.Request.FormValue("name")
    
    // add user
    
    ctx.JSON(200, msg)
})

// user profile.
router.GET("/users/:name", func(ctx *gem.Context) {
    // firstly, we need get the username from the URL query.
    name, err := gem.String(ctx.UserValue("name"))
    if err != nil {
        ctx.JSON(404, userNotFound)
        return
    }
    
    // return user profile.
    ctx.JSON(200, userProfileByName(name))
})

// update user profile
router.PUT("/users/:name", func(ctx *gem.Context) {
    // firstly, we need get the username from the URL query.
    name, err := gem.String(ctx.UserValue("name"))
    if err != nil {
        ctx.JSON(404, userNotFound)
        return
    }
    
    // get nickname
    ctx.Request.ParseForm()
    nickname := ctx.Request.FormValue("nickname")
    
    // update user nickname.
    
    ctx.JSON(200, msg)
})

// delete user
router.DELETE("/users/:name", func(ctx *gem.Context) {
    // firstly, we need get the username from the URL query.
    name, err := gem.String(ctx.UserValue("name"))
    if err != nil {
        ctx.JSON(404, userNotFound)
        return
    }
    
    // delete user.
    
    ctx.JSON(200, msg)
}
HTTP/2 Server Push

See https://github.com/go-gem/examples/tree/master/http2.

router.GET("/", func(ctx *gem.Context) {
	if err := ctx.Push("/images/logo.png", nil); err != nil {
		ctx.Logger().Info(err)
	}

	ctx.HTML(200, `<html><head></head><body><img src="/images/logo.png"/></body></html>`)
})
router.ServeFiles("/images/*filepath", http.Dir(imagesDir))
Use Middleware

It is easy to implement a middleware, see Middleware interface, you just need to implement the Wrap function.

type Middleware interface {
    Wrap(next Handler) Handler
}

For example, we defined a simple debug middleware:

type Debug struct{}

// Wrap implements the Middleware interface.
func (d *Debug) Wrap(next gem.Handler) gem.Handler {
    // gem.HandlerFunc is an adapter like http.HandlerFunc.
	return gem.HandlerFunc(func(ctx *gem.Context) {
		// print request info.
		log.Println(ctx.Request.URL, ctx.Request.Method)

		// call the next handler.
		next.Handle(ctx)
	})
}

and then we should register it:

register the middleware for all handlers via Router.Use.

router.Use(&Debug{})

we can also set up the middleware for specific handler via HandlerOption.

router.GET("/specific", specificHandler, &gem.HandlerOption{Middlewares:[]gem.Middleware{&Debug{}}})

Gem also provides some frequently used middlewares, see Middlewares.

Share data between middlewares

Context provides two useful methods: SetUserValue and UserValue to share data between middlewares.

// Store data into context in one middleware
ctx.SetUserValue("name", "foo")

// Get data from context in other middleware or handler
ctx.UserValue("name")

Middlewares

Please let me know that you composed some middlewares, I will mention it here, I believe it would be helpful to users.

Semantic Versioning

Gem follows semantic versioning 2.0.0 managed through GitHub releases.

Support Us

  • ⭐ the project.
  • Spread the word.
  • Contribute to the project.

Contribute

We’re always looking for help, so if you would like to contribute, we’d love to have you!

Changes

The v2 and v1 are totally different:

  • v2 built on top of net/http instead of fasthttp.

  • v2 require go1.8 or above.

  • v2 is compatible with Windows.

FAQ

  • Why choose net/http instead of fasthttp?

    1. net/http has much more third-party packages than fasthttp.

    2. fasthttp doesn't support HTTP/2 yet.

LICENSE

BSD 3-Clause License, see LICENSE and AUTHORS.

Inspiration & Credits

For respecting the third party packages, I added their author into AUTHORS, and listed those packages here.

  • httprouter - LICENSE. Gem's router is a custom version of httprouter, thanks to httprouter.

Documentation

Overview

Package gem is a high performance web framework, it is friendly to REST APIs.

Note: This package requires go1.8 or above.

Features

1. High performance

2. Friendly to REST API

3. Full test of all APIs

4. Pretty and fast router

5. HTTP/2 support

6. Leveled logging - included four levels `debug`, `info`, `error` and `fatal`, there are many third-party implements the Logger:

logrus - Structured, pluggable logging for Go - https://github.com/Sirupsen/logrus
go-logging - Golang logging library - https://github.com/op/go-logging
gem-log - default logger - https://github.com/go-gem/log

7. Middlewares

CSRF Middleware - Cross-Site Request Forgery protection - https://github.com/go-gem/middleware-csrf
CORS Middleware -  Cross-Origin Resource Sharing - https://github.com/go-gem/middleware-cors
AUTH Middleware - HTTP Basic and HTTP Digest authentication - https://github.com/go-gem/middleware-auth
JWT Middleware - JSON WEB TOKEN authentication - https://github.com/go-gem/middleware-jwt
Compress Middleware - compress response body - https://github.com/go-gem/middleware-compress
Request Body Limit Middleware - limit request body size - https://github.com/go-gem/middleware-body-limit

8. Frozen APIs since the stable version `2.0.0` was released

Install

use go get command to install:

$ go get -u github.com/go-gem/gem

Quick Start

a simple HTTP server:

package main

import (
    "log"

    "github.com/go-gem/gem"
)

func index(ctx *gem.Context) {
    ctx.HTML(200, "hello world")
}

func main() {
    // Create server.
    srv := gem.New(":8080")

    // Create router.
    router := gem.NewRouter()
    // Register handler
    router.GET("/", index)

    // Start server.
    log.Println(srv.ListenAndServe(router.Handler()))
}

Logger

AFAIK, the following leveled logging packages are compatible with Gem web framework:

1. logrus - structured, pluggable logging for Go - https://github.com/Sirupsen/logrus

2. go-logging - golang logging library - https://github.com/op/go-logging

3. gem-log - default logger, maintained by Gem Authors - https://github.com/go-gem/log

Logger(https://godoc.org/github.com/go-gem/gem#Logger) includes four levels: debug, info, error and fatal, their APIs are Debug and Debugf, Info and Infof, Error and Errorf, Fatal and Fatalf.

We take logrus as example to show that how to set and use logger.

// set logrus logger as server's logger.
srv.SetLogger(logrus.New())

// we can use it in handler.
router.GET("/logger", func(ctx *gem.Context) {
		ctx.Logger().Debug("debug")
		ctx.Logger().Info("info")
		ctx.Logger().Error("error")
})

Static Files

example that serve static files:

router.ServeFiles("/tmp/*filepath", http.Dir(os.TempDir()))

Note: the path(first parameter) must end with `*filepath`.

REST APIs

The router is friendly to REST APIs.

// user list
router.GET("/users", func(ctx *gem.Context) {
    ctx.JSON(200, userlist)
})

// add user
router.POST("/users", func(ctx *gem.Context) {
    ctx.Request.ParseForm()
    name := ctx.Request.FormValue("name")

    // add user

    ctx.JSON(200, msg)
})

// user profile.
router.GET("/users/:name", func(ctx *gem.Context) {
    // firstly, we need get the username from the URL query.
    name, ok := ctx.UserValue("name").(string)
    if !ok {
	ctx.JSON(404, userNotFound)
	return
    }

    // return user profile.
    ctx.JSON(200, userProfileByName(name))
})

// update user profile
router.PUT("/users/:name", func(ctx *gem.Context) {
    // firstly, we need get the username from the URL query.
    name, ok := ctx.UserValue("name").(string)
    if !ok {
	ctx.JSON(404, userNotFound)
	return
    }

    // get nickname
    ctx.Request.ParseForm()
    nickname := ctx.Request.FormValue("nickname")

    // update user nickname.

    ctx.JSON(200, msg)
})

// delete user
router.DELETE("/users/:name", func(ctx *gem.Context) {
    // firstly, we need get the username from the URL query.
    name, ok := ctx.UserValue("name").(string)
    if !ok {
	ctx.JSON(404, userNotFound)
	return
    }

    // delete user.

    ctx.JSON(200, msg)
}

HTTP2 Server Push

see https://github.com/go-gem/examples/tree/master/http2

router.GET("/", func(ctx *gem.Context) {
	if err := ctx.Push("/images/logo.png", nil); err != nil {
		ctx.Logger().Info(err)
	}

	ctx.HTML(200, `<html><head></head><body><img src="/images/logo.png"/></body></html>`)
})
router.ServeFiles("/images/*filepath", http.Dir(imagesDir))

Use Middleware

It is easy to implement a middleware, see Middleware(https://godoc.org/github.com/go-gem/gem#Middleware) interface, you just need to implement the `Wrap` function.

type Middleware interface {
    Wrap(next Handler) Handler
}

For example, we defined a simple debug middleware:

type Debug struct{}

// Wrap implements the Middleware interface.
func (d *Debug) Wrap(next gem.Handler) gem.Handler {
	// gem.HandlerFunc is adapter like http.HandlerFunc.
	return gem.HandlerFunc(func(ctx *gem.Context) {
		// print request info.
		log.Println(ctx.Request.URL, ctx.Request.Method)

		// call the next handler.
		next.Handle(ctx)
	})
}

and then we should register it:

register the middleware for all handlers via Router.Use(https://godoc.org/github.com/go-gem/gem#Router.Use).

router.Use(&Debug{})

we can also register the middleware for specific handler via HandlerOption(https://godoc.org/github.com/go-gem/gem#HandlerOption).

router.GET("/specific", specificHandler, &gem.HandlerOption{Middlewares:[]gem.Middleware{&Debug{}}})

Gem also provides some frequently used middlewares, such as:

1. CSRF Middleware - Cross-Site Request Forgery protection - https://github.com/go-gem/middleware-csrf

2. CORS Middleware - Cross-Origin Resource Sharing - https://github.com/go-gem/middleware-cors

3. AUTH Middleware - HTTP Basic and HTTP Digest authentication - https://github.com/go-gem/middleware-auth

4. JWT Middleware - JSON WEB TOKEN authentication - https://github.com/go-gem/middleware-jwt

5. Compress Middleware - Compress response body - https://github.com/go-gem/middleware-compress

6. Request Body Limit Middleware - limit request body maximum size - https://github.com/go-gem/middleware-body-limit

Share data between middlewares

Context provides two useful methods: `SetUserValue` and `UserValue` to share data between middlewares.

// Store data into context in one middleware
ctx.SetUserValue("name", "foo")

// Get data from context in other middleware or handler
ctx.UserValue("name")

Index

Constants

View Source
const (
	MIMEHTML = "text/html"
	MIMEJSON = "application/json"
	MIMEXML  = "application/xml"
)

MIME types

View Source
const (
	MethodGet     = "GET"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodDelete  = "DELETE"
	MethodHead    = "HEAD"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodPatch   = "PATCH"
)

Request methods.

Variables

This section is empty.

Functions

func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func Int

func Int(v interface{}) (int, error)

Int convert v to int.

By default, zero and non nil error would be returned.

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections.

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

func String

func String(v interface{}) (string, error)

String convert v to string.

By default, empty string and non nil error would be returned.

func Version

func Version() string

Version return version number.

Types

type Application

type Application struct {
	ServerOpt ServerOption `json:"server"`
	AssetsOpt AssetsOption `json:"assets"`

	TemplatesOpt TemplatesOption `json:"templates"`
	// contains filtered or unexported fields
}

func NewApplication

func NewApplication(filename string) (*Application, error)

NewApplication

func (*Application) Close

func (app *Application) Close() (errs []error)

Close close application, all the close callbacks will be invoked.

func (*Application) Component

func (app *Application) Component(name string) interface{}

Component returns a component via the given name.

func (*Application) Init

func (app *Application) Init() (err error)

Init initialize application, All the initialized callbacks.

func (*Application) InitControllers

func (app *Application) InitControllers() (err error)

InitControllers initialize controllers.

func (*Application) Router

func (app *Application) Router() *Router

Router returns an instance of router.

func (*Application) SetCloseCallback

func (app *Application) SetCloseCallback(callback ApplicationCallback)

SetCloseCallback set user-defined close callback.

func (*Application) SetComponent

func (app *Application) SetComponent(name string, component interface{}) error

SetComponent set component by the given name and component.

If the component already exists, returns an non-nil error.

func (*Application) SetController

func (app *Application) SetController(path string, controller Controller)

SetController set controller with the given route's path and controller instance.

func (*Application) SetInitCallback

func (app *Application) SetInitCallback(callback ApplicationCallback)

SetInitCallback set user-defined initialized callback.

func (*Application) Templates

func (app *Application) Templates() *Templates

Templates returns an instance of templates manager.

type ApplicationCallback

type ApplicationCallback func() error

ApplicationCallback is type of func that defines

type AssetsOption

type AssetsOption struct {
	Root          string            `json:"root"`
	Dirs          map[string]string `json:"dirs"`
	HandlerOption *HandlerOption
}

type Context

type Context struct {
	Request  *http.Request
	Response http.ResponseWriter
	// contains filtered or unexported fields
}

Context contains *http.Request and http.Response.

func (*Context) Error

func (ctx *Context) Error(error string, code int)

Error is a shortcut of http.Error

func (*Context) FormFile

func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile is a shortcut of http.Request.FormFile.

func (*Context) FormValue

func (ctx *Context) FormValue(key string) string

FormValue is a shortcut of http.Request.FormValue.

func (*Context) HTML

func (ctx *Context) HTML(code int, body string)

HTML responses HTML data and custom status code to client.

func (*Context) Host

func (ctx *Context) Host() string

Host returns the value of http.Request.Host.

func (*Context) IsAjax

func (ctx *Context) IsAjax() bool

IsAjax returns true if request is an AJAX (XMLHttpRequest) request.

func (*Context) IsDelete

func (ctx *Context) IsDelete() bool

IsDelete returns true if request method is DELETE.

func (*Context) IsGet

func (ctx *Context) IsGet() bool

IsGet returns true if request method is GET.

func (*Context) IsHead

func (ctx *Context) IsHead() bool

IsHead returns true if request method is HEAD.

func (*Context) IsPost

func (ctx *Context) IsPost() bool

IsPost returns true if request method is POST.

func (*Context) IsPut

func (ctx *Context) IsPut() bool

IsPut returns true if request method is PUT.

func (*Context) JSON

func (ctx *Context) JSON(code int, v interface{})

JSON responses JSON data and custom status code to client.

func (*Context) Logger

func (ctx *Context) Logger() Logger

Logger returns the server's logger.

func (*Context) NotFound

func (ctx *Context) NotFound()

NotFound is a shortcut of http.NotFound

func (*Context) ParseForm

func (ctx *Context) ParseForm() error

ParseForm is a shortcut of http.Request.ParseForm.

func (*Context) PostFormValue

func (ctx *Context) PostFormValue(key string) string

PostFormValue is a shortcut of http.Request.PostFormValue.

func (*Context) Push

func (ctx *Context) Push(target string, opts *http.PushOptions) error

Push HTTP/2 server push.

If http.Response does not implements http.Pusher, returns errNotSupportHTTP2ServerPush.

func (*Context) Redirect

func (ctx *Context) Redirect(url string, code int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

func (*Context) Referer

func (ctx *Context) Referer() string

Referer is a shortcut of http.Request.Referer.

func (*Context) SetContentType

func (ctx *Context) SetContentType(v string)

SetContentType set response Content-Type.

func (*Context) SetServer

func (ctx *Context) SetServer(server *Server)

SetServer for testing, do not use it in other places.

func (*Context) SetStatusCode

func (ctx *Context) SetStatusCode(code int)

SetStatusCode is shortcut of http.ResponseWriter.WriteHeader.

func (*Context) SetUserValue

func (ctx *Context) SetUserValue(key string, value interface{})

SetUserValue stores the given value under the given key in ctx.

func (*Context) URL

func (ctx *Context) URL() *url.URL

URL is shortcut of http.Request.URL.

func (*Context) UserValue

func (ctx *Context) UserValue(key string) interface{}

UserValue returns the value stored via SetUserValue* under the given key.

func (*Context) Write

func (ctx *Context) Write(p []byte) (n int, err error)

Write is a shortcut of http.Response.Write.

func (*Context) XML

func (ctx *Context) XML(code int, v interface{}, headers ...string)

XML responses XML data and custom status code to client.

type Controller

type Controller interface {
	Init(app *Application) error
	Methods() []string
	HandlerOptions() map[string]*HandlerOption
	GET(ctx *Context)
	POST(ctx *Context)
	DELETE(ctx *Context)
	PUT(ctx *Context)
	HEAD(ctx *Context)
	OPTIONS(ctx *Context)
	PATCH(ctx *Context)
}

type Handler

type Handler interface {
	Handle(*Context)
}

Handler for processing incoming requests.

type HandlerFunc

type HandlerFunc func(*Context)

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(ctx *Context)

Handle calls f(ctx).

type HandlerOption

type HandlerOption struct {
	Middlewares []Middleware
}

HandlerOption option for handler.

func NewHandlerOption

func NewHandlerOption(middlewares ...Middleware) *HandlerOption

NewHandlerOption returns HandlerOption instance by the given middlewares.

type Logger

type Logger interface {
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})

	Info(v ...interface{})
	Infof(format string, v ...interface{})

	Error(v ...interface{})
	Errorf(format string, v ...interface{})

	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
}

Logger defines a logging interface.

type Middleware

type Middleware interface {
	Wrap(next Handler) Handler
}

Middleware interface.

type Router

type Router struct {

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 307 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 307 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// Configurable http.Handler which is called when no matching route is
	// found. If it is not set, http.NotFound is used.
	NotFound Handler

	// Configurable http.Handler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed Handler

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code
	// 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of
	// unrecovered panics.
	PanicHandler func(*Context, interface{})
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func NewRouter

func NewRouter() *Router

NewRouter returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) DELETE

func (r *Router) DELETE(path string, handle HandlerFunc, opts ...*HandlerOption)

DELETE is a shortcut for router.Handle("DELETE", path, handle)

func (*Router) GET

func (r *Router) GET(path string, handle HandlerFunc, opts ...*HandlerOption)

GET is a shortcut for router.Handle("GET", path, handle)

func (*Router) HEAD

func (r *Router) HEAD(path string, handle HandlerFunc, opts ...*HandlerOption)

HEAD is a shortcut for router.Handle("HEAD", path, handle)

func (*Router) Handle

func (r *Router) Handle(method, path string, handle HandlerFunc, opts ...*HandlerOption)

Handle registers a new request handle with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) Handler

func (r *Router) Handler() Handler

Handler returns a Handler that wrapped by middlewarers.

func (*Router) Lookup

func (r *Router) Lookup(method, path string, ctx *Context) (Handler, bool)

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handle HandlerFunc, opts ...*HandlerOption)

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)

func (*Router) PATCH

func (r *Router) PATCH(path string, handle HandlerFunc, opts ...*HandlerOption)

PATCH is a shortcut for router.Handle("PATCH", path, handle)

func (*Router) POST

func (r *Router) POST(path string, handle HandlerFunc, opts ...*HandlerOption)

POST is a shortcut for router.Handle("POST", path, handle)

func (*Router) PUT

func (r *Router) PUT(path string, handle HandlerFunc, opts ...*HandlerOption)

PUT is a shortcut for router.Handle("PUT", path, handle)

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, root http.FileSystem, opts ...*HandlerOption)

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:

router.ServeFiles("/src/*filepath", http.Dir("/var/www"))

func (*Router) Use

func (r *Router) Use(middleware Middleware)

Use register middleware.

type Server

type Server struct {
	Server *http.Server
	// contains filtered or unexported fields
}

Server contains *http.Server.

func New

func New(addr string) *Server

New return a Server instance by the given address.

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe(handler Handler) error

ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections.

func (*Server) ListenAndServeTLS

func (srv *Server) ListenAndServeTLS(certFile, keyFile string, handler Handler) error

ListenAndServeTLS listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP keep-alives.

func (*Server) SetLogger

func (srv *Server) SetLogger(logger Logger)

SetLogger set logger.

type ServerOption

type ServerOption struct {
	Addr     string `json:"addr"`
	CertFile string `json:"cert_file"`
	KeyFile  string `json:"key_file"`
}

type Templates

type Templates struct {
	Path      string
	Suffix    string
	Delims    []string
	FuncMap   template.FuncMap
	LayoutDir string
	// contains filtered or unexported fields
}

Templates is a templates manager.

func NewTemplates

func NewTemplates(path string) *Templates

NewTemplates returns a Templates instance with the given path and default options.

func (*Templates) Filenames

func (ts *Templates) Filenames(filenames ...string) []string

Filenames converts relative paths to absolute paths.

func (*Templates) Layout

func (ts *Templates) Layout(name string) (*template.Template, error)

if the layout does not exists, returns non-nil error.

func (*Templates) New

func (ts *Templates) New(filenames ...string) (*template.Template, error)

New returns a template.Template instance with the Templates's option and template.ParseFiles.

Note: filenames should be absolute paths, either uses Templates.Filenames or specifies manually.

func (*Templates) Render

func (ts *Templates) Render(layoutName string, filenames ...string) (*template.Template, error)

Render uses layout to render template.

func (*Templates) SetLayout

func (ts *Templates) SetLayout(filenames ...string) error

SetLayout set layout.

type TemplatesOption

type TemplatesOption struct {
	Root      string   `json:"root"`
	Suffix    string   `json:"suffix"`
	LayoutDir string   `json:"layout_dir"`
	Layouts   []string `json:"layouts"`
}

type WebController

type WebController struct{}

WebController is an empty controller that implements Controller interface.

func (*WebController) DELETE

func (wc *WebController) DELETE(ctx *Context)

DELETE implements Controller's DELETE method.

func (*WebController) GET

func (wc *WebController) GET(ctx *Context)

GET implements Controller's GET method.

func (*WebController) HEAD

func (wc *WebController) HEAD(ctx *Context)

HEAD implements Controller's HEAD method.

func (*WebController) HandlerOptions

func (wc *WebController) HandlerOptions() map[string]*HandlerOption

HandlerOptions defines handler's option.

The key should be the name of request method, case-sensitive, such as GET, POST.

func (*WebController) Init

func (wc *WebController) Init(app *Application) error

Init initialize the controller.

It would be invoked when register a controller.

func (*WebController) Methods

func (wc *WebController) Methods() []string

Methods defines which handlers should be registered.

The value should be the name of request method, case-sensitive, such as GET, POST. By default, GET and POST's handler will be registered.

func (*WebController) OPTIONS

func (wc *WebController) OPTIONS(ctx *Context)

OPTIONS implements Controller's OPTIONS method.

func (*WebController) PATCH

func (wc *WebController) PATCH(ctx *Context)

PATCH implements Controller's PATCH method.

func (*WebController) POST

func (wc *WebController) POST(ctx *Context)

POST implements Controller's POST method.

func (*WebController) PUT

func (wc *WebController) PUT(ctx *Context)

PUT implements Controller's PUT method.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL