air

package module
v0.0.0-...-7a6af9e Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2018 License: Unlicense Imports: 45 Imported by: 0

README

Air

Build Status Coverage Status Go Report Card GoDoc

An ideally refined web framework for Go. You can use it to build a web application as natural as breathing.

High-performance? Fastest? Almost all the web frameworks are using these words to tell people that they are the best. Maybe they are, maybe not. Air does not intend to follow the crowd. It can only guarantee you one thing: it can serve properly.

Features

  • Singleton
    • Air is uncountable
    • Only one package air.*
    • One instance alone
  • API
    • As less as possible
    • As simple as possible
    • As expressive as possible
  • Method
    • GET (cache-friendly)
    • HEAD (cache-friendly)
    • POST
    • PUT
    • PATCH
    • DELETE
    • CONNECT
    • OPTIONS
    • TRACE
  • Logger
    • DEBUG
    • INFO
    • WARN
    • ERROR
    • FATAL
    • PANIC
  • Server
    • HTTP/2 support
    • SSL/TLS support
    • ACME support
    • Graceful shutdown support
    • WebSocket support
  • Router
    • Based on the Radix Tree
    • Has a good inspection mechanism
    • Group routes support
  • Gas (also called middleware)
    • Router level:
      • Before router
      • After router
    • Route level
    • Group level
  • Binder
    • application/json
    • application/xml
    • application/x-www-form-urlencoded
    • multipart/form-data
  • Minifier
    • text/html
    • text/css
    • application/javascript
    • application/json
    • application/xml
    • image/svg+xml
    • image/jpeg
    • image/png
  • Renderer
    • Rich template functions
    • Hot update support
  • Coffer
    • Accesses binary asset files by using the runtime memory
    • Significantly improves the performance of the air.Response#File()
    • Asset file minimization:
      • .html
      • .css
      • .js
      • .json
      • .xml
      • .svg
      • .jpg
      • .jpeg
      • .png
    • Hot update support
  • Error
    • Centralized handling

Installation

Open your terminal and execute

$ go get github.com/aofei/air

done.

The only requirement is the Go, <= v1.11 (module support).

Hello, 世界

Create a file named hello.go

package main

import "github.com/aofei/air"

func main() {
	air.GET("/", func(req *air.Request, res *air.Response) error {
		return res.WriteString("Hello, 世界")
	})
	air.Serve()
}

and run it

$ go run hello.go

then visit http://localhost:2333.

Documentation

Gases

As we all know that the air is a mixture of gases. So the same is that this framework adopts the gas as its composition. Everyone can create new gas and use it within this framework simply.

A gas is a function chained in the HTTP request-response cycle with access to air.Request and air.Response which it uses to perform a specific action, for example, logging every request or recovering from panics.

If you are looking for some useful gases, simply visit here.

Examples

If you want to be familiar with this framework as soon as possible, simply visit here.

Community

If you want to discuss this framework, or ask questions about it, simply post questions or ideas here.

Contributing

If you want to help build this framework, simply follow this to send pull requests here.

License

This project is licensed under the Unlicense.

License can be found here.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ACMECertRoot = "acme-certs"

ACMECertRoot is the root of the ACME certificates.

It is called "acme_cert_root" in the configuration file.

View Source
var Address = "localhost:2333"

Address is the TCP address that the server listens on.

It is called "address" in the configuration file.

View Source
var AppName = "air"

AppName is the name of the current web application.

It is called "app_name" in the configuration file.

View Source
var AssetExts = []string{
	".html",
	".css",
	".js",
	".json",
	".xml",
	".svg",
	".jpg",
	".jpeg",
	".png",
	".gif",
}

AssetExts is the filename extensions of the asset files used to distinguish the asset files in the `AssetRoot` when loading them into the coffer.

It is called "asset_exts" in the configuration file.

View Source
var AssetRoot = "assets"

AssetRoot is the root of the asset files. All the asset files inside it will be recursively parsed into the coffer.

It is called "asset_root" in the configuration file.

View Source
var AutoCert = false

AutoCert sets whether or not to use let's encrypt for TLS

View Source
var AutoPushEnabled = false

AutoPushEnabled indicates whether the auto push is enabled.

It is called "auto_push_enabled" in the configuration file.

View Source
var CofferEnabled = false

CofferEnabled indicates whether the coffer is enabled.

It is called "coffer_enabled" in the configuration file.

View Source
var (
	// Compressable - list of compressable file types, append to it if needed
	Compressable = []string{"", ".txt", ".htm", ".html", ".css", ".toml", ".php", ".js", ".json", ".md", ".mdown", ".xml", ".svg", ".go", ".cgi", ".py", ".pl", ".aspx", ".asp"}
)
View Source
var Config = obj{}

Config is a set of key-value pairs parsed from the configuration file found in the path specified by a command-line flag named "config". The default path of the configuration file is "config.toml".

View Source
var DebugMode = false

DebugMode indicates whether the current web application is in debug mode.

It is called "debug_mode" in the configuration file.

View Source
var DevAutoCert = false

DevAutoCert don't run autocert if DebugMode/DevMode is on

View Source
var ErrorHandler = func(err error, req *Request, res *Response) {
	if res.Written {
		return
	}

	if res.Status < 400 {
		res.Status = 500
	}

	m := err.Error()
	if res.Status == 500 && !DebugMode {
		m = "internal server error"
	}

	if req.Method == "GET" || req.Method == "HEAD" {
		delete(req.Headers, "etag")
		delete(req.Headers, "last-modified")
	}

	res.WriteString(m)
}

ErrorHandler is the centralized error handler for the server.

View Source
var Gases = []Gas{}

Gases is the `Gas` chain that performs after routing.

View Source
var HTTPSEnforced = true

HTTPSEnforced indicates whether the HTTPS is enforced.

It is called "https_enforced" in the configuration file.

View Source
var HostWhitelist = []string{}

HostWhitelist is the hosts allowed by the server.

It is called "host_whitelist" in the configuration file.

View Source
var IdleTimeout = time.Duration(0)

IdleTimeout is the maximum amount of time the server waits for the next request. If it is zero, the value of `ReadTimeout` is used. If both are zero, `ReadHeaderTimeout` is used.

It is called "idle_timeout" in the configuration file.

View Source
var LoggerLowestLevel = LoggerLevelDebug

LoggerLowestLevel is the lowest level of the logger.

It will be forced to `LoggerLevelDebug` when the `DebugMode` is true.

It is called "logger_lowest_level" in the configuration file.

View Source
var LoggerOutput = io.Writer(os.Stdout)

LoggerOutput is the output destination of the logger.

View Source
var MaintainerEmail = ""

MaintainerEmail is the e-mail address of the one who is responsible for maintaining the current web application.

It is called "maintainer_email" in the configuration file.

View Source
var MaxHeaderBytes = 1 << 20

MaxHeaderBytes is the maximum number of bytes the server will read parsing the request header's names and values, including the request line.

It is called "max_header_bytes" in the configuration file.

View Source
var MethodNotAllowedHandler = func(req *Request, res *Response) error {
	res.Status = 405
	return errors.New("method not allowed")
}

MethodNotAllowedHandler is a `Handler` that returns method not allowed error.

View Source
var MinifierEnabled = false

MinifierEnabled indicates whether the minifier is enabled.

It is called "minifier_enabled" in the configuration file.

View Source
var NotFoundHandler = func(req *Request, res *Response) error {
	res.Status = 404
	return errors.New("not found")
}

NotFoundHandler is a `Handler` that returns not found error.

View Source
var Pregases = []Gas{}

Pregases is the `Gas` chain that performs before routing.

View Source
var ReadHeaderTimeout = time.Duration(0)

ReadHeaderTimeout is the amount of time allowed the server reads the request headers.

It is called "read_header_timeout" in the configuration file.

View Source
var ReadTimeout = time.Duration(0)

ReadTimeout is the maximum duration the server reads the request.

It is called "read_timeout" in the configuration file.

View Source
var TLSCertFile = ""

TLSCertFile is the path to the TLS certificate file used when starting the server.

It is called "tls_cert_file" in the configuration file.

View Source
var TLSKeyFile = ""

TLSKeyFile is the path to the TLS key file used when starting the server.

It is called "tls_key_file" in the configuration file.

View Source
var TemplateExts = []string{".html"}

TemplateExts is the filename extensions of the HTML templates used to distinguish the HTML template files in the `TemplateRoot` when parsing them into the renderer.

It is called "template_exts" in the configuration file.

View Source
var TemplateFuncMap = obj{
	"strlen":  strlen,
	"substr":  substr,
	"timefmt": timefmt,
}

TemplateFuncMap is the HTML template function map the renderer renders the HTML templates.

View Source
var TemplateLeftDelim = "{{"

TemplateLeftDelim is the left side of the HTML template delimiter the renderer renders the HTML templates.

It is called "template_left_delim" in the configuration file.

View Source
var TemplateRightDelim = "}}"

TemplateRightDelim is the right side of the HTML template delimiter the renderer renders the HTML templates.

It is called "template_right_delim" in the configuration file.

View Source
var TemplateRoot = "templates"

TemplateRoot is the root of the HTML templates. All the HTML templates inside it will be recursively parsed into the renderer.

It is called "template_root" in the configuration file.

View Source
var TheServer = &server{
	Server: &http.Server{},
}

TheServer is the singleton of the `server`.

View Source
var WebSocketHandshakeTimeout = time.Duration(0)

WebSocketHandshakeTimeout is the maximum amount of time the server waits for the WebSocket handshake to complete.

It is called "websocket_handshake_timeout" in the configuration file.

View Source
var WebSocketSubprotocols = []string{}

WebSocketSubprotocols is the server's supported WebSocket subprotocols.

It is called "websocket_subprotocols" in the configuration file.

View Source
var WriteTimeout = time.Duration(0)

WriteTimeout is the maximum duration the server writes an response.

It is called "write_timeout" in the configuration file.

Functions

func CONNECT

func CONNECT(path string, h Handler, gases ...Gas)

CONNECT registers a new CONNECT route for the path with the matching h in the router with the optional route-level gases.

func Close

func Close() error

Close closes the server immediately.

func DEBUG

func DEBUG(msg string, extras ...obj)

DEBUG logs the msg at the `LoggerLevelDebug` with the optional extras.

func DELETE

func DELETE(path string, h Handler, gases ...Gas)

DELETE registers a new DELETE route for the path with the matching h in the router with the optional route-level gases.

func ERROR

func ERROR(msg string, extras ...obj)

ERROR logs the msg at the `LoggerLevelError` with the optional extras.

func FATAL

func FATAL(msg string, extras ...obj)

FATAL logs the msg at the `LoggerLevelFatal` with the optional extras followed by a call to `os.Exit(1)`.

func FILE

func FILE(path, filename string, gases ...Gas)

FILE registers a new route with the path to serve a static file with the filename and the optional route-level gases.

func GET

func GET(path string, h Handler, gases ...Gas)

GET registers a new GET route for the path with the matching h in the router with the optional route-level gases.

func HEAD(path string, h Handler, gases ...Gas)

HEAD registers a new HEAD route for the path with the matching h in the router with the optional route-level gases.

func INFO

func INFO(msg string, extras ...obj)

INFO logs the msg at the `LoggerLevelInfo` with the optional extras.

func OPTIONS

func OPTIONS(path string, h Handler, gases ...Gas)

OPTIONS registers a new OPTIONS route for the path with the matching h in the router with the optional route-level gases.

func PANIC

func PANIC(msg string, extras ...obj)

PANIC logs the msg at the `LoggerLevelPanic` with the optional extras followed by a call to `panic()`.

func PATCH

func PATCH(path string, h Handler, gases ...Gas)

PATCH registers a new PATCH route for the path with the matching h in the router with the optional route-level gases.

func POST

func POST(path string, h Handler, gases ...Gas)

POST registers a new POST route for the path with the matching h in the router with the optional route-level gases.

func PUT

func PUT(path string, h Handler, gases ...Gas)

PUT registers a new PUT route for the path with the matching h in the router with the optional route-level gases.

func STATIC

func STATIC(prefix, root string, gases ...Gas)

STATIC registers a new route with the path prefix to serve the static files from the root with the optional route-level gases.

func Serve

func Serve() error

Serve starts the server.

func Shutdown

func Shutdown(timeout time.Duration) error

Shutdown gracefully shuts down the server without interrupting any active connections until timeout. It waits indefinitely for connections to return to idle and then shut down when the timeout is less than or equal to zero.

func TRACE

func TRACE(path string, h Handler, gases ...Gas)

TRACE registers a new TRACE route for the path with the matching h in the router with the optional route-level gases.

func WARN

func WARN(msg string, extras ...obj)

WARN logs the msg at the `LoggerLevelWarn` with the optional extras.

Types

type Cookie struct {
	Name     string
	Value    string
	Expires  time.Time
	MaxAge   int
	Domain   string
	Path     string
	Secure   bool
	HTTPOnly bool
}

Cookie is an HTTP cookie.

func (*Cookie) String

func (c *Cookie) String() string

String returns the serialization string of the c.

type Gas

type Gas func(Handler) Handler

Gas defines a function to process gases.

type Group

type Group struct {
	Prefix string
	Gases  []Gas
}

Group is a set of sub-routes for a specified route. It can be used for inner routes that share common gases or functionality that should be separate from the parent while still inheriting from it.

func (*Group) CONNECT

func (g *Group) CONNECT(path string, h Handler, gases ...Gas)

CONNECT implements the `CONNECT()`.

func (*Group) DELETE

func (g *Group) DELETE(path string, h Handler, gases ...Gas)

DELETE implements the `DELETE()`.

func (*Group) FILE

func (g *Group) FILE(path, file string, gases ...Gas)

FILE implements the `FILE()`.

func (*Group) GET

func (g *Group) GET(path string, h Handler, gases ...Gas)

GET implements the `GET()`.

func (*Group) HEAD

func (g *Group) HEAD(path string, h Handler, gases ...Gas)

HEAD implements the `HEAD()`.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h Handler, gases ...Gas)

OPTIONS implements the `OPTIONS()`.

func (*Group) PATCH

func (g *Group) PATCH(path string, h Handler, gases ...Gas)

PATCH implements the `PATCH()`.

func (*Group) POST

func (g *Group) POST(path string, h Handler, gases ...Gas)

POST implements the `POST()`.

func (*Group) PUT

func (g *Group) PUT(path string, h Handler, gases ...Gas)

PUT implements the `PUT()`.

func (*Group) STATIC

func (g *Group) STATIC(prefix, root string, gases ...Gas)

STATIC implements the `STATIC()`.

func (*Group) TRACE

func (g *Group) TRACE(path string, h Handler, gases ...Gas)

TRACE implements the `TRACE()`.

type Handler

type Handler func(*Request, *Response) error

Handler defines a function to serve requests.

type Header struct {
	Name   string
	Values []string
}

Header is an HTTP header.

func GenHeader

func GenHeader(name string, values ...string) *Header

GenHeader makes a new header from a name and some values

func (*Header) Set

func (h *Header) Set(values ...string)

Set easier way to set the header's value(s)

func (*Header) Value

func (h *Header) Value() string

Value returns the first value of the h. It returns "" if the h is nil or there are no values.

type LoggerLevel

type LoggerLevel uint8

LoggerLevel is the level of the logger.

const (
	// LoggerLevelDebug defines the debug level of the logger.
	LoggerLevelDebug LoggerLevel = iota

	// LoggerLevelInfo defines the info level of the logger.
	LoggerLevelInfo

	// LoggerLevelWarn defines the warn level of the logger.
	LoggerLevelWarn

	// LoggerLevelError defines the error level of the logger.
	LoggerLevelError

	// LoggerLevelFatal defines the fatal level of the logger.
	LoggerLevelFatal

	// LoggerLevelPanic defines the panic level of the logger.
	LoggerLevelPanic

	// LoggerLevelOff defines the off level of the logger. It will turn off
	// the logger.
	LoggerLevelOff
)

The logger levels.

func (LoggerLevel) String

func (ll LoggerLevel) String() string

String returns the string value of the ll.

type Request

type Request struct {
	Method        string
	Scheme        string
	Authority     string
	Path          string
	Headers       map[string]*Header
	Body          io.Reader
	ContentLength int64
	Cookies       map[string]*Cookie
	Params        map[string]*RequestParam
	RemoteAddress string
	ClientAddress string
	Values        obj

	Request *http.Request
	// contains filtered or unexported fields
}

Request is an HTTP request.

func (*Request) Bind

func (r *Request) Bind(v interface{}) error

Bind binds the r into the v.

func (*Request) Cookie

func (r *Request) Cookie(name string) (string, bool)

Cookie gets a cookie's string value

func (*Request) DefaultQuery

func (r *Request) DefaultQuery(key, defaultValue string) string

DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string. See: Query() and GetQuery() for further information.

GET /?name=Manu&lastname=
c.DefaultQuery("name", "unknown") == "Manu"
c.DefaultQuery("id", "none") == "none"
c.DefaultQuery("lastname", "none") == ""

func (*Request) GetQuery

func (r *Request) GetQuery(key string) (string, bool)

GetQuery is like Query(), it returns the keyed url query value if it exists `(value, true)` (even when the value is an empty string), otherwise it returns `("", false)`. It is shortcut for `c.Request.URL.Query().Get(key)`

GET /?name=Manu&lastname=
("Manu", true) == c.GetQuery("name")
("", false) == c.GetQuery("id")
("", true) == c.GetQuery("lastname")

func (*Request) GetQueryArray

func (r *Request) GetQueryArray(key string) ([]string, bool)

GetQueryArray returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Request) Header

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

Header fetches the header value or returns an empty string if there's no matching header

func (*Request) Param

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

Param returns a Route Param's string value if it exists

func (*Request) ParseCookies

func (r *Request) ParseCookies()

ParseCookies parses the cookies sent with the r into the `r.Cookies`.

It will be called after routing. Relax, you can of course call it before routing, it will only take effect on the very first call.

func (*Request) ParseParams

func (r *Request) ParseParams()

ParseParams parses the params sent with the r into the `r.Params`.

It will be called after routing. Relax, you can of course call it before routing, it will only take effect on the very first call.

func (*Request) Query

func (r *Request) Query(key string) string

Query returns the keyed url query value if it exists, otherwise it returns an empty string `("")`. It is shortcut for `c.Request.URL.Query().Get(key)`

    GET /path?id=1234&name=Manu&value=
	   c.Query("id") == "1234"
	   c.Query("name") == "Manu"
	   c.Query("value") == ""
	   c.Query("wtf") == ""

func (*Request) QueryArray

func (r *Request) QueryArray(key string) []string

QueryArray returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.

func (*Request) RawCookie

func (r *Request) RawCookie(name string) *Cookie

RawCookie gets the raw *Cookie

type RequestParam

type RequestParam struct {
	Name   string
	Values []*RequestParamValue
}

RequestParam is an HTTP request param.

func (*RequestParam) Value

func (rp *RequestParam) Value() *RequestParamValue

Value returns the first value of the rp. It returns nil if the rp is nil or there are no values.

type RequestParamFileValue

type RequestParamFileValue struct {
	Filename      string
	Headers       map[string]*Header
	ContentLength int64
	// contains filtered or unexported fields
}

RequestParamFileValue is an HTTP request param file value.

func (*RequestParamFileValue) Read

func (v *RequestParamFileValue) Read(b []byte) (int, error)

Read implements the `io.Reader`.

func (*RequestParamFileValue) Seek

func (v *RequestParamFileValue) Seek(offset int64, whence int) (int64, error)

Seek implements the `io.Seeker`.

type RequestParamValue

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

RequestParamValue is an HTTP request param value.

func (*RequestParamValue) Bool

func (rpv *RequestParamValue) Bool() (bool, error)

Bool returns a `bool` from the rpv's underlying value.

func (*RequestParamValue) File

File returns a `RequestParamFileValue` from the rpv's underlying value.

func (*RequestParamValue) Float32

func (rpv *RequestParamValue) Float32() (float32, error)

Float32 returns a `float32` from the rpv's underlying value.

func (*RequestParamValue) Float64

func (rpv *RequestParamValue) Float64() (float64, error)

Float64 returns a `float64` from the rpv's underlying value.

func (*RequestParamValue) Int

func (rpv *RequestParamValue) Int() (int, error)

Int returns an `int` from the rpv's underlying value.

func (*RequestParamValue) Int16

func (rpv *RequestParamValue) Int16() (int16, error)

Int16 returns an `int16` from the rpv's underlying value.

func (*RequestParamValue) Int32

func (rpv *RequestParamValue) Int32() (int32, error)

Int32 returns an `int32` from the rpv's underlying value.

func (*RequestParamValue) Int64

func (rpv *RequestParamValue) Int64() (int64, error)

Int64 returns an `int64` from the rpv's underlying value.

func (*RequestParamValue) Int8

func (rpv *RequestParamValue) Int8() (int8, error)

Int8 returns an `int8` from the rpv's underlying value.

func (*RequestParamValue) String

func (rpv *RequestParamValue) String() string

String returns a `string` from the rpv's underlying value.

func (*RequestParamValue) Uint

func (rpv *RequestParamValue) Uint() (uint, error)

Uint returns an `uint` from the rpv's underlying value.

func (*RequestParamValue) Uint16

func (rpv *RequestParamValue) Uint16() (uint16, error)

Uint16 returns an `uint16` from the rpv's underlying value.

func (*RequestParamValue) Uint32

func (rpv *RequestParamValue) Uint32() (uint32, error)

Uint32 returns an `uint32` from the rpv's underlying value.

func (*RequestParamValue) Uint64

func (rpv *RequestParamValue) Uint64() (uint64, error)

Uint64 returns an `uint64` from the rpv's underlying value.

func (*RequestParamValue) Uint8

func (rpv *RequestParamValue) Uint8() (uint8, error)

Uint8 returns an `uint8` from the rpv's underlying value.

type Response

type Response struct {
	Status        int
	Headers       map[string]*Header
	ContentLength int64
	Body          io.Writer
	Cookies       map[string]*Cookie
	Written       bool

	Writer http.ResponseWriter
	// contains filtered or unexported fields
}

Response is an HTTP response.

func (*Response) Header

func (r *Response) Header(name string) (string, bool)

Header get a Header if it exists

func (*Response) Push

func (r *Response) Push(target string, headers map[string]*Header) error

Push initiates an HTTP/2 server push. This constructs a synthetic request using the target and headers, serializes that request into a PUSH_PROMISE frame, then dispatches that request using the server's request handler. The target must either be an absolute path (like "/path") or an absolute URL that contains a valid host and the same scheme as the parent request. If the target is a path, it will inherit the scheme and host of the parent request. The headers specifies additional promised request headers. The headers cannot include HTTP/2 pseudo headers like ":path" and ":scheme", which will be added automatically.

func (*Response) Redirect

func (r *Response) Redirect(url string) error

Redirect responds to the client with a redirection to the url.

func (*Response) Render

func (r *Response) Render(m map[string]interface{}, templates ...string) error

Render renders one or more HTML templates with the m and responds to the client with the "text/html" content. The results rendered by the former can be inherited by accessing the `m["InheritedHTML"]`.

func (*Response) SetCookie

func (r *Response) SetCookie(name string, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Response) SetHeader

func (r *Response) SetHeader(name string, values ...string)

SetHeader adds a header to the response

func (*Response) SetHeaderValues

func (r *Response) SetHeaderValues(name string, values []string)

SetHeaderValues adds a header to the response with an array of string values

func (*Response) WebSocket

func (r *Response) WebSocket() (*WebSocket, error)

WebSocket switches the connection to the WebSocket protocol.

func (*Response) Write

func (r *Response) Write(content io.ReadSeeker) error

Write responds to the client with the content.

func (*Response) WriteBlob

func (r *Response) WriteBlob(b []byte) error

WriteBlob responds to the client with the content b.

func (*Response) WriteFile

func (r *Response) WriteFile(filename string) error

WriteFile responds to the client with a file content with the filename.

func (*Response) WriteHTML

func (r *Response) WriteHTML(h string) error

WriteHTML responds to the client with the "text/html" content h.

func (*Response) WriteJSON

func (r *Response) WriteJSON(v interface{}) error

WriteJSON responds to the client with the "application/json" content v.

func (*Response) WriteMsgPack

func (r *Response) WriteMsgPack(v interface{}) error

WriteMsgPack responds to the client with the "application/msgpack" content v.

func (*Response) WriteString

func (r *Response) WriteString(s string) error

WriteString responds to the client with the "text/plain" content s.

func (*Response) WriteXML

func (r *Response) WriteXML(v interface{}) error

WriteXML responds to the client with the "application/xml" content v.

type WebSocket

type WebSocket struct {
	TextHandler            func(text string) error
	BinaryHandler          func(b []byte) error
	ConnectionCloseHandler func(statusCode int, reason string) error
	PingHandler            func(appData string) error
	PongHandler            func(appData string) error
	ErrorHandler           func(err error)
	// contains filtered or unexported fields
}

WebSocket is a WebSocket peer.

func (*WebSocket) Close

func (ws *WebSocket) Close() error

Close closes the ws without sending or waiting for a close message.

func (*WebSocket) WriteBinary

func (ws *WebSocket) WriteBinary(b []byte) error

WriteBinary writes the b to the remote peer of the ws.

func (*WebSocket) WriteConnectionClose

func (ws *WebSocket) WriteConnectionClose(statusCode int, reason string) error

WriteConnectionClose writes a connection close to the remote peer of the ws with the statusCode and the reason.

func (*WebSocket) WritePing

func (ws *WebSocket) WritePing(appData string) error

WritePing writes a ping to the remote peer of the ws with the appData.

func (*WebSocket) WritePong

func (ws *WebSocket) WritePong(appData string) error

WritePong writes a pong to the remote peer of the ws with the appData.

func (*WebSocket) WriteText

func (ws *WebSocket) WriteText(text string) error

WriteText writes the text to the remote peer of the ws.

Jump to

Keyboard shortcuts

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