fiber

package module
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2020 License: MIT Imports: 20 Imported by: 1,263

README

Fiber

Fiber is an Express styled HTTP framework implementation running on Fasthttp, the fastest HTTP engine for Go. The package make use of similar framework convention as they are in express. People switching from Node to Go often end up in a bad learning curve to start building their webapps, this project is meant to ease things up for fast development, but with zero memory allocation and performance in mind. See API Documentation

Features

  • Optimized for speed and low memory usage.
  • Rapid Server-Side Programming
  • Easy routing with parameters
  • Static files with custom prefix
  • Middleware with Next support
  • Express API endpoints
  • API Documentation

Installing

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

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

Hello world

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

$ create server.go
package main

import "github.com/gofiber/fiber"

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

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

Static files

To serve static files, use the Static method.

package main

import "github.com/gofiber/fiber"

func main() {
  app := fiber.New()
  app.Static("./public")
  app.Listen(8080)
}

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

http://localhost:8080/images/gopher.png
http://localhost:8080/css/style.css
http://localhost:8080/js/jquery.js
http://localhost:8080/hello.html

Middleware

Middleware has never been so easy, just like express you call the Next() matching route function!

package main

import "github.com/gofiber/fiber"

func main() {
  app := fiber.New()
  app.Get("/api*", func(c *fiber.Ctx) {
    c.Locals("auth", "admin")
    c.Next()
  })
  app.Get("/api/back-end/:action?", func(c *fiber.Ctx) {
    if c.Locals("auth") != "admin" {
      c.Status(403).Send("Forbidden")
      return
    }
    c.Send("Hello, Admin!")
  })
  app.Listen(8080)
}

API Documentation

We created an extended API documentation including examples, click here

License

gofiber/fiber is free and open-source software licensed under the MIT License.

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.9.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

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

Accepts :

func (*Ctx) AcceptsCharsets

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

AcceptsCharsets :

func (*Ctx) AcceptsEncodings

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

AcceptsEncodings :

func (*Ctx) AcceptsLanguages

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

AcceptsLanguages :

func (*Ctx) Append

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

Append :

func (*Ctx) Attachment

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

Attachment :

func (*Ctx) BaseUrl

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

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

ClearCookie :

func (*Ctx) Cookie

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

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

func (ctx *Ctx) Format()

Format TODO

func (*Ctx) Fresh

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

func (ctx *Ctx) HeadersSent()

HeadersSent TODO

func (*Ctx) Hostname

func (ctx *Ctx) Hostname() string

Hostname :

func (*Ctx) Ip

func (ctx *Ctx) Ip() string

Ip :

func (*Ctx) Ips

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

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

Jsonp :

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

Links :

func (*Ctx) Locals

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

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

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

func (ctx *Ctx) Range()

Range TODO

func (*Ctx) Redirect

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

Redirect :

func (*Ctx) Render

func (ctx *Ctx) Render()

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

func (*Ctx) Route

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

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

func (ctx *Ctx) SendStatus(status int)

SendStatus :

func (*Ctx) SendString

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

func (ctx *Ctx) SignedCookies()

SignedCookies TODO

func (*Ctx) Stale

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

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

Subdomains :

func (*Ctx) Type

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

Type :

func (*Ctx) Vary

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

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
	// Provide certificate files to enable TLS
	CertKey  string
	CertFile string
	// Fasthttp server settings
	Fasthttp *Fasthttp
	// ALPHA SETTINGS, DO NOT USE!
	RedirectTrailingSlash bool
	Prefork               bool
	// 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

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
JackTT - Gopher 🇻🇳