fiber

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2020 License: Apache-2.0 Imports: 14 Imported by: 0

README

Fiber

IMPORTANT: Do not use this in production, API might change before we release v1.0.0!

Latest Release GoDoc Go Report GitHub license

Fiber is an Express style HTTP framework implementation running on FastHTTP, the fastest HTTP engine for Go. The package make use of similar framework convention as they are in expressjs. People switching from Nodejs to Golang often end up in a bad learning curve to start building their webapps, this project is meant to ease things up, but with performance in mind (Express on steriods)

Full API Documentation

Click here

Benchmarks

See all benchmarks

Installing

Assuming you’ve already installed Go, install the Fiber package by calling the following command:

$ go get -u github.com/fenny/fiber

Hello world

Embedded below is essentially the simplest Fiber app you can create.

$ create server.go
package main

import "github.com/fenny/fiber"

func main() {
  app := fiber.New()
  app.Get("/", func(c *fiber.Ctx) {
    c.Send("Hello, World!")
  })
  app.Listen(8080)
}
$ go run server.go

Browse to http://localhost:8080 and you should see Hello, World! on the page.

Basic routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one handler function, that is executed when the route is matched.

Route definition takes the following structures:

// Function signature
app.Method(func(*fiber.Ctx))
app.Method(path string, func(*fiber.Ctx))
  • app is an instance of Fiber.
  • Method is an HTTP request method, in capitalization: Get, Put, Post etc
  • path string is a path or prefix (for static files) on the server.
  • *func(fiber.Ctx) is a function executed when the route is matched.

This tutorial assumes that an instance of fiber named app is created and the server is running. If you are not familiar with creating an app and starting it, see the Hello world example.

The following examples illustrate defining simple routes.

// Respond with Hello, World! on the homepage:
app.Get("/", func(c *fiber.Ctx) {
  c.Send("Hello, World!")
})

//Respond to POST request on the root route (/), the application’s home page:
app.Post("/", func(c *fiber.Ctx) {
  c.Send("Got a POST request")
})

// Respond to a PUT request to the /user route:
app.Put("/user", func(c *fiber.Ctx) {
  c.Send("Got a PUT request at /user")
})

// Respond to a DELETE request to the /user route:
app.Delete("/user", func(c *fiber.Ctx) {
  c.Send("Got a DELETE request at /user")
})

Static files

To serve static files such as images, CSS files, and JavaScript files, replace your function handler with a file or directory string.

// Function signature
app.Static(root string)
app.Static(prefix, root string)

For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:

app.Static("./public")

Now, you can load the files that are in the public directory:

http://localhost:8080/images/kitten.jpg
http://localhost:8080/css/style.css
http://localhost:8080/js/app.js
http://localhost:8080/images/bg.png
http://localhost:8080/hello.html

To use multiple static assets directories, call the express.static middleware function multiple times:

app.Static("./public")
app.Static("./files")

?>For best results, use a reverse proxy cache like NGINX to improve performance of serving static assets.

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

app.Static("/static", "./public")

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:8080/static/images/kitten.jpg
http://localhost:8080/static/css/style.css
http://localhost:8080/static/js/app.js
http://localhost:8080/static/images/bg.png
http://localhost:8080/static/hello.html

Caught a mistake? Edit this page on GitHub!

Documentation

Index

Constants

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5
	// StatusSwitchProxy       = 306 // RFC 7231, 6.4.6 (Unused)
	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

Credits @valyala https://github.com/valyala/fasthttp/blob/master/status.go

View Source
const Version = "0.7.0"

Version for debugging

Variables

This section is empty.

Functions

This section is empty.

Types

type Cookie struct {
	Expire int // time.Unix(1578981376, 0)
	MaxAge int
	Domain string
	Path   string

	HttpOnly bool
	Secure   bool
	SameSite string
}

Cookie :

type Ctx

type Ctx struct {
	Fasthttp *fasthttp.RequestCtx
	// contains filtered or unexported fields
}

Ctx struct

func (*Ctx) Accepts added in v0.5.5

func (ctx *Ctx) Accepts(typ string) bool

Accepts :

func (*Ctx) AcceptsCharsets added in v0.5.5

func (ctx *Ctx) AcceptsCharsets(charset string) bool

AcceptsCharsets :

func (*Ctx) AcceptsEncodings added in v0.5.5

func (ctx *Ctx) AcceptsEncodings(encoding string) bool

AcceptsEncodings :

func (*Ctx) AcceptsLanguages added in v0.5.5

func (ctx *Ctx) AcceptsLanguages(lang string) bool

AcceptsLanguages :

func (*Ctx) Append added in v0.5.5

func (ctx *Ctx) Append(field string, values ...string)

Append :

func (*Ctx) Attachment

func (ctx *Ctx) Attachment(name ...string)

Attachment :

func (*Ctx) BaseUrl added in v0.5.5

func (ctx *Ctx) BaseUrl() string

BaseUrl :

func (*Ctx) BasicAuth

func (ctx *Ctx) BasicAuth() (user, pass string, ok bool)

BasicAuth :

func (*Ctx) Body

func (ctx *Ctx) Body(args ...interface{}) string

Body :

func (*Ctx) ClearCookie added in v0.5.5

func (ctx *Ctx) ClearCookie(name ...string)

ClearCookie :

func (*Ctx) Cookie added in v0.5.5

func (ctx *Ctx) Cookie(key, value string, options ...interface{})

Cookie :

func (*Ctx) Cookies

func (ctx *Ctx) Cookies(args ...interface{}) string

Cookies :

func (*Ctx) Download

func (ctx *Ctx) Download(file string, name ...string)

Download :

func (*Ctx) End added in v0.5.5

func (ctx *Ctx) End()

End TODO

func (*Ctx) FormFile

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

FormFile :

func (*Ctx) FormValue

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

FormValue :

func (*Ctx) Format added in v0.5.5

func (ctx *Ctx) Format()

Format TODO

func (*Ctx) Fresh added in v0.5.5

func (ctx *Ctx) Fresh() bool

Fresh TODO https://expressjs.com/en/4x/api.html#req.fresh

func (*Ctx) Get

func (ctx *Ctx) Get(key string) string

Get :

func (*Ctx) HeadersSent added in v0.5.5

func (ctx *Ctx) HeadersSent()

HeadersSent TODO

func (*Ctx) Hostname

func (ctx *Ctx) Hostname() string

Hostname :

func (*Ctx) Ip added in v0.5.5

func (ctx *Ctx) Ip() string

Ip :

func (*Ctx) Ips added in v0.5.5

func (ctx *Ctx) Ips() []string

Ips https://expressjs.com/en/4x/api.html#req.ips

func (*Ctx) Is

func (ctx *Ctx) Is(ext string) bool

Is :

func (*Ctx) Json

func (ctx *Ctx) Json(v interface{}) error

Json :

func (*Ctx) Jsonp added in v0.5.5

func (ctx *Ctx) Jsonp(v interface{}, cb ...string) error

Jsonp :

func (ctx *Ctx) Links(link ...string)

Links :

func (*Ctx) Locals added in v0.5.5

func (ctx *Ctx) Locals(key string, val ...string) string

Locals :

func (*Ctx) Location

func (ctx *Ctx) Location(path string)

Location :

func (*Ctx) Method

func (ctx *Ctx) Method() string

Method :

func (*Ctx) MultipartForm

func (ctx *Ctx) MultipartForm() (*multipart.Form, error)

MultipartForm :

func (*Ctx) Next

func (ctx *Ctx) Next()

Next :

func (*Ctx) OriginalUrl added in v0.5.5

func (ctx *Ctx) OriginalUrl() string

OriginalUrl :

func (*Ctx) Params

func (ctx *Ctx) Params(key string) string

Params :

func (*Ctx) Path

func (ctx *Ctx) Path() string

Path :

func (*Ctx) Protocol

func (ctx *Ctx) Protocol() string

Protocol :

func (*Ctx) Query

func (ctx *Ctx) Query(key string) string

Query :

func (*Ctx) Range added in v0.5.5

func (ctx *Ctx) Range()

Range TODO

func (*Ctx) Redirect

func (ctx *Ctx) Redirect(path string, status ...int)

Redirect :

func (*Ctx) Render added in v0.5.5

func (ctx *Ctx) Render()

Render TODO https://expressjs.com/en/4x/api.html#res.render

func (*Ctx) Route added in v0.5.5

func (ctx *Ctx) Route() (s struct {
	Method   string
	Path     string
	Wildcard bool
	Regex    *regexp.Regexp
	Params   []string
	Values   []string
	Handler  func(*Ctx)
})

Route : Only use in debugging

func (*Ctx) Secure

func (ctx *Ctx) Secure() bool

Secure :

func (*Ctx) Send

func (ctx *Ctx) Send(args ...interface{})

Send :

func (*Ctx) SendBytes added in v0.5.5

func (ctx *Ctx) SendBytes(body []byte)

SendBytes : Same as Send() but without type assertion

func (*Ctx) SendFile

func (ctx *Ctx) SendFile(file string, gzip ...bool)

SendFile :

func (*Ctx) SendStatus added in v0.5.5

func (ctx *Ctx) SendStatus(status int)

SendStatus :

func (*Ctx) SendString added in v0.5.5

func (ctx *Ctx) SendString(body string)

SendString : Same as Send() but without type assertion

func (*Ctx) Set

func (ctx *Ctx) Set(key string, val string)

Set :

func (*Ctx) SignedCookies added in v0.5.5

func (ctx *Ctx) SignedCookies()

SignedCookies TODO

func (*Ctx) Stale added in v0.5.5

func (ctx *Ctx) Stale() bool

Stale TODO https://expressjs.com/en/4x/api.html#req.fresh

func (*Ctx) Status

func (ctx *Ctx) Status(status int) *Ctx

Status :

func (*Ctx) Subdomains added in v0.5.5

func (ctx *Ctx) Subdomains() (subs []string)

Subdomains :

func (*Ctx) Type

func (ctx *Ctx) Type(ext string) *Ctx

Type :

func (*Ctx) Vary added in v0.5.5

func (ctx *Ctx) Vary(field ...string)

Vary :

func (*Ctx) Write

func (ctx *Ctx) Write(args ...interface{})

Write :

func (*Ctx) Xhr

func (ctx *Ctx) Xhr() bool

Xhr :

type Fasthttp added in v0.5.5

type Fasthttp struct {
	Concurrency                        int
	DisableKeepAlive                   bool
	ReadBufferSize                     int
	WriteBufferSize                    int
	ReadTimeout                        time.Duration
	WriteTimeout                       time.Duration
	IdleTimeout                        time.Duration
	MaxConnsPerIP                      int
	MaxRequestsPerConn                 int
	TCPKeepalive                       bool
	TCPKeepalivePeriod                 time.Duration
	MaxRequestBodySize                 int
	ReduceMemoryUsage                  bool
	GetOnly                            bool
	DisableHeaderNamesNormalizing      bool
	SleepWhenConcurrencyLimitsExceeded time.Duration
	NoDefaultContentType               bool
	KeepHijackedConns                  bool
}

Fasthttp settings https://github.com/valyala/fasthttp/blob/master/server.go#L150

type Fiber

type Fiber struct {

	// Server name header
	Server string
	// Disable the fiber banner on launch
	Banner bool
	// RedirectTrailingSlash TODO*
	RedirectTrailingSlash bool
	// Provide certificate files to enable TLS
	CertKey  string
	CertFile string
	// Fasthttp server settings
	Fasthttp *Fasthttp
	// contains filtered or unexported fields
}

Fiber structure

func New

func New() *Fiber

New creates a Fiber instance

func (*Fiber) All

func (r *Fiber) All(args ...interface{})

All matches any HTTP method

func (*Fiber) Connect

func (r *Fiber) Connect(args ...interface{})

Connect establishes a tunnel to the server identified by the target resource.

func (*Fiber) Delete

func (r *Fiber) Delete(args ...interface{})

Delete deletes the specified resource.

func (*Fiber) Get

func (r *Fiber) Get(args ...interface{})

Get requests a representation of the specified resource. Requests using GET should only retrieve data.

func (*Fiber) Head

func (r *Fiber) Head(args ...interface{})

Head asks for a response identical to that of a GET request, but without the response body.

func (*Fiber) Listen

func (r *Fiber) Listen(port int, addr ...string)

Listen starts the server with the correct settings

func (*Fiber) Options

func (r *Fiber) Options(args ...interface{})

Options is used to describe the communication options for the target resource.

func (*Fiber) Patch

func (r *Fiber) Patch(args ...interface{})

Patch is used to apply partial modifications to a resource.

func (*Fiber) Post

func (r *Fiber) Post(args ...interface{})

Post is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

func (*Fiber) Put

func (r *Fiber) Put(args ...interface{})

Put replaces all current representations of the target resource with the request payload.

func (*Fiber) Static added in v0.7.0

func (r *Fiber) Static(args ...string)

Static :

func (*Fiber) Trace

func (r *Fiber) Trace(args ...interface{})

Trace performs a message loop-back test along the path to the target resource.

func (*Fiber) Use

func (r *Fiber) Use(args ...interface{})

Use is another name for All() People using Expressjs are used to this

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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