gofast

package module
Version: v0.0.0-...-4c8fa9c Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2019 License: MIT Imports: 9 Imported by: 0

README

Gofast - A light, fast and simple Go micro-framework

GoDoc Build Status

This is a light and fast micro-framework I wrote in order to train to Go language.

This project uses "pongo2" library for rendering templates (compatible with Django Jinja templates)

Installation

Prior to Go 1.11:

$ git clone git@github.com:eko/gofast.git
$ go get -u github.com/flosch/pongo2
$ go get -u golang.org/x/net/http2
$ go get -u golang.org/sirupsen/logrus

Prefer using dep?

$ dep ensure

When using Go 1.11 (go modules) or later:

$ go build ./...

Running an application

$ go run app.go
2015/01/26 21:57:35 gofast v1.0-beta
2015/01/26 21:57:48 [POST] 200 | route: 'add' | url: "/add/toto" (time: 143.238us)

This will run the application on port 8080. Optionnaly, you can provide a port number this way:

$ PORT=8005 go run app.go

A simple application example

Because an example will explain it better, here is an application example with things you can do with Gofast:

package main

import (
    "github.com/eko/gofast"
)

func main() {
    app := gofast.Bootstrap()
    app.SetAssetsDirectory("assets")
    app.SetViewsDirectory("views")

    // This adds a fallback route for 404 (not found) resources
    app.SetFallback(func(context gofast.Context) {
        context.GetResponse().SetStatusCode(404)
        app.Render(context, "404.html")
    })

    // You can add a simple GET route
    app.Get("homepage", "/$", func(context gofast.Context) {
        app.Render(context, "index.html")
    })

    // ... or add a more complex POST route with a URL parameter
    app.Post("add", "/add/([a-zA-Z]+)$", func(context gofast.Context) {
        request  := context.GetRequest()

        pattern := context.GetRoute().GetPattern()
        url     := request.GetHttpRequest().URL.Path

        request.AddParameter("name", pattern.FindStringSubmatch(url)[1])

        // ... your custom code

        app.Render(context, "add.html")
    })

    app.Listen()
}

HTTP/2 Support

You can use HTTP/2 support by using the following line instead of app.Listen():

app.ListenHttp2("./fullchain.pem", "./privkey.pem")

Of course, you will have to precize SSL certificate and private key.

You can also set Link headers in order to preload assets:

response := c.GetResponse()

response.Header().Add("Link", "</assets/img/rocket.png>; rel=preload")
response.Header().Add("Link", "</assets/css/style.css>; rel=preload")

Templating

You can use all Pongo2 template features and retrieve data like this:

{% extends "../layout.html" %}

{% block navigation %}
    {% include "../include/navigation.html" with current="blog" %}
{% endblock %}

<h2>Retrieve a "name" parameter</h2>
<p>{{ request.GetParameter("name") }}</p>

<h2>Retrieve a "data" POST form value</h2>
<p>{{ request.GetFormValue("data") }}</p>

You have access to both request and response objects from context.

Requesting this example

Using the example given below, here is the request results:

> $ curl -X GET http://127.0.0.1:8080/
<h1>Welcome to the index template!</h1>

> $ curl -X POST -d'data=my post data' http://127.0.0.1:8080/add/toto
<h2>Retrieve a "name" parameter</h2>
<p>toto</p>

<h2>Retrieve a "data" POST form value</h2>
<p>my post data</p>

Middlewares

You can add some middlewares in your application by the following way:

app.Use(func(context gofast.Context, next gofast.MiddlewareFunc) gofast.Handler {
  // Some code before calling the next middleware
  handler := next(context, next)
  // Some code after calling the next middleware

  return handler
})

It allows you to access context (request, response, current route) and also allows to define a new handler function to update the application behavior.

Default CORS headers

Following CORS headers are enabled by default when the request has an "Origin" header:

Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: domainname.tld

You can override any header (including CORS ones) by the following way into each action:

app.Get("retrieve-data", "/retrieve$", func(context gofast.Context) {
    response := context.GetResponse()
    response.Header().Set("Access-Control-Allow-Methods", "GET")
    response.Header().Set("Content-Type", "application/json")

    fmt.Fprint(response, "{result: 200}")
})

Use the logger

The Logrus logger instance can be used to write information in your application stdout if you need it. You can retrieve the logger instance from the context as follows:

app.Get("test-logger", "/test-logger$", func(context gofast.Context) {
    logger := context.GetLogger()
    logger.Info("Roger, this is my log information!")
})

Documentation

Index

Constants

View Source
const (
	PORT    string = ":8080"
	VERSION string = "1.0-beta"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	// contains filtered or unexported fields
}

func NewContext

func NewContext() Context

NewContext creates a new context component instance

func (*Context) AddDefaultHeaders

func (c *Context) AddDefaultHeaders()

AddDefaultHeaders adds some defaults headers to send with the response

func (*Context) GetLogger

func (c *Context) GetLogger() *logrus.Logger

GetLogger returns a Logrus logger instance

func (*Context) GetRequest

func (c *Context) GetRequest() *Request

GetRequest returns a HTTP request component instance

func (*Context) GetResponse

func (c *Context) GetResponse() *Response

GetResponse returns a HTTP response component instance

func (*Context) GetRoute

func (c *Context) GetRoute() *Route

GetRoute returns a route instance

func (*Context) SetLogger

func (c *Context) SetLogger(logger *logrus.Logger)

SetLogger sets Logrus logger instance

func (*Context) SetRequest

func (c *Context) SetRequest(req *http.Request)

SetRequest sets a HTTP request instance

func (*Context) SetResponse

func (c *Context) SetResponse(res http.ResponseWriter)

SetResponse sets a HTTP response instance

func (*Context) SetRoute

func (c *Context) SetRoute(route *Route)

SetRoute sets a route instance

type Gofast

type Gofast struct {
	*logrus.Logger
	*Router
	*Templating
	*Middleware
}

func Bootstrap

func Bootstrap() *Gofast

Bootstrap bootstraps a new instance

func (*Gofast) HandleRoute

func (g *Gofast) HandleRoute(res http.ResponseWriter, req *http.Request, route Route)

HandleRoute handles a route with the initialized context

func (*Gofast) Listen

func (g *Gofast) Listen()

Listen listens and handles HTTP requests

func (*Gofast) ListenHttp2

func (g *Gofast) ListenHttp2(certificate string, key string)

ListenHttp2 listens and handles HTTP/2 requests

func (*Gofast) PrepareHttpServer

func (g *Gofast) PrepareHttpServer() string

PrepareHttpServer prepares a HTTP server

func (*Gofast) ServeHTTP

func (g *Gofast) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP serves HTTP request by matching the correct route

type Handler

type Handler func(context Context)

type Middleware

type Middleware struct {
	// contains filtered or unexported fields
}

func NewMiddleware

func NewMiddleware() Middleware

NewMiddleware creates a new middleware component instance

func (*Middleware) HandleMiddlewares

func (m *Middleware) HandleMiddlewares(context Context) Handler

HandleMiddlewares handles middlewares and returns handler

func (*Middleware) Use

func (m *Middleware) Use(middleware MiddlewareFunc)

Use adds a new middleware

type MiddlewareFunc

type MiddlewareFunc func(context Context, middleware MiddlewareFunc) Handler

type Parameter

type Parameter struct {
	// contains filtered or unexported fields
}

type Request

type Request struct {
	// contains filtered or unexported fields
}

func NewRequest

func NewRequest(req *http.Request) Request

NewRequest creates a new Request component instance

func (*Request) AddParameter

func (r *Request) AddParameter(name string, value interface{})

AddParameter adds a request parameter

func (*Request) GetFormValue

func (r *Request) GetFormValue(name string) interface{}

GetFormValue returns a POST form value from given name

func (*Request) GetHeader

func (r *Request) GetHeader(name string) string

GetHeader returns a request header from its name

func (*Request) GetHttpRequest

func (r *Request) GetHttpRequest() *http.Request

GetHttpRequest returs HTTP request

func (*Request) GetParameter

func (r *Request) GetParameter(name string) interface{}

GetParameter returns a request parameter from given name

type Response

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

func NewResponse

func NewResponse(res http.ResponseWriter) Response

NewResponse creates a new Response component instance

func (*Response) GetStatusCode

func (r *Response) GetStatusCode() int

GetStatusCode returns Response status code

func (*Response) SetStatusCode

func (r *Response) SetStatusCode(statusCode int)

SetStatusCode sets Response status code

type Route

type Route struct {
	// contains filtered or unexported fields
}

func (*Route) GetHandler

func (r *Route) GetHandler() Handler

GetHandler returns a route handler

func (*Route) GetPattern

func (r *Route) GetPattern() *regexp.Regexp

GetPattern returns a route pattern

func (*Route) SetHandler

func (r *Route) SetHandler(handler Handler)

SetHandler sets a route handler

type RouteLen

type RouteLen []Route

func (RouteLen) Len

func (this RouteLen) Len() int

Len route sort functions

func (RouteLen) Less

func (this RouteLen) Less(i, j int) bool

func (RouteLen) Swap

func (this RouteLen) Swap(i, j int)

type Router

type Router struct {
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() Router

NewRouter creates a new router component instance

func (*Router) Add

func (r *Router) Add(method string, name string, pattern string, handler Handler)

Add adds a new route to router

func (*Router) All

func (r *Router) All(name string, pattern string, handler Handler)

func (*Router) Delete

func (r *Router) Delete(name string, pattern string, handler Handler)

func (*Router) Get

func (r *Router) Get(name string, pattern string, handler Handler)

Get adds different HTTP methods route

func (*Router) GetFallback

func (r *Router) GetFallback() Route

GetFallback returns fallback route (for 404 error pages)

func (*Router) GetRoute

func (r *Router) GetRoute(name string) Route

GetRoute returns a Route from given name

func (*Router) GetRoutes

func (r *Router) GetRoutes() []Route

GetRoutes returns all routes available in router

func (*Router) Head

func (r *Router) Head(name string, pattern string, handler Handler)

func (*Router) Options

func (r *Router) Options(name string, pattern string, handler Handler)

func (*Router) Patch

func (r *Router) Patch(name string, pattern string, handler Handler)

func (*Router) Post

func (r *Router) Post(name string, pattern string, handler Handler)

func (*Router) Put

func (r *Router) Put(name string, pattern string, handler Handler)

func (*Router) SetFallback

func (r *Router) SetFallback(handler Handler)

SetFallback sets route fallback (for 404 error pages)

type Templating

type Templating struct {
	// contains filtered or unexported fields
}

func NewTemplating

func NewTemplating() Templating

NewTemplating creates a new templating component instance

func (*Templating) GetAssetsDirectory

func (t *Templating) GetAssetsDirectory() string

GetAssetsDirectory returns templating assets directory

func (*Templating) GetViewsDirectory

func (t *Templating) GetViewsDirectory() string

GetViewsDirectory returns templating views directory

func (*Templating) Render

func (t *Templating) Render(context Context, name string)

Render renders a template

func (*Templating) SetAssetsDirectory

func (t *Templating) SetAssetsDirectory(name string)

SetAssetsDirectory sets templating assets directory

func (*Templating) SetViewsDirectory

func (t *Templating) SetViewsDirectory(name string)

SetViewsDirectory sets templating views directory

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto