1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-08 12:31:58 +00:00

Version 3.0.0-beta cleaned

This commit is contained in:
Makis Maropoulos
2016-05-30 17:08:09 +03:00
commit c26668a489
114 changed files with 14552 additions and 0 deletions

37
config/basicauth.go Normal file
View File

@@ -0,0 +1,37 @@
package config
import (
"time"
"github.com/imdario/mergo"
)
const (
DefaultBasicAuthRealm = "Authorization Required"
DefaultBasicAuthContextKey = "auth"
)
type BasicAuth struct {
// Users a map of login and the value (username/password)
Users map[string]string
// Realm http://tools.ietf.org/html/rfc2617#section-1.2. Default is "Authorization Required"
Realm string
// ContextKey the key for ctx.GetString(...). Default is 'auth'
ContextKey string
// Expires expiration duration, default is 0 never expires
Expires time.Duration
}
// DefaultBasicAuth returns the default configs for the BasicAuth middleware
func DefaultBasicAuth() BasicAuth {
return BasicAuth{make(map[string]string), DefaultBasicAuthRealm, DefaultBasicAuthContextKey, 0}
}
// Merge MergeSingle the default with the given config and returns the result
func (c BasicAuth) MergeSingle(cfg BasicAuth) (config BasicAuth) {
config = cfg
mergo.Merge(&config, c)
return
}

16
config/config.go Normal file
View File

@@ -0,0 +1,16 @@
// Package config defines the default settings and semantic variables
package config
import (
"time"
)
var (
// StaticCacheDuration expiration duration for INACTIVE file handlers
StaticCacheDuration = 20 * time.Second
// CompressedFileSuffix is the suffix to add to the name of
// cached compressed file when using the .StaticFS function.
//
// Defaults to iris-fasthttp.gz
CompressedFileSuffix = "iris-fasthttp.gz"
)

44
config/editor.go Normal file
View File

@@ -0,0 +1,44 @@
package config
import "github.com/imdario/mergo"
type Editor struct {
// Host if empty used the iris server's host
Host string
// Port if 0 4444
Port int
// WorkingDir if empty "./"
WorkingDir string
// Username if empty iris
Username string
// Password if empty admin!123
Password string
}
// DefaultEditor returns the default configs for the Editor plugin
func DefaultEditor() Editor {
return Editor{"", 4444, "." + pathSeparator, DefaultUsername, DefaultPassword}
}
// Merge merges the default with the given config and returns the result
func (c Editor) Merge(cfg []Editor) (config Editor) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// Merge MergeSingle the default with the given config and returns the result
func (c Editor) MergeSingle(cfg Editor) (config Editor) {
config = cfg
mergo.Merge(&config, c)
return
}

166
config/iris.go Normal file
View File

@@ -0,0 +1,166 @@
package config
import (
"github.com/imdario/mergo"
)
const DefaultProfilePath = "/debug/pprof"
type (
// Iris configs for the station
// All fields can be changed before server's listen except the DisablePathCorrection field
//
// MaxRequestBodySize is the only options that can be changed after server listen -
// using Config().MaxRequestBodySize = ...
// Render's rest config can be changed after declaration but before server's listen -
// using Config().Render.Rest...
// Render's Template config can be changed after declaration but before server's listen -
// using Config().Render.Template...
// Sessions config can be changed after declaration but before server's listen -
// using Config().Sessions...
// and so on...
Iris struct {
// MaxRequestBodySize Maximum request body size.
//
// The server rejects requests with bodies exceeding this limit.
//
// By default request body size is -1, unlimited.
MaxRequestBodySize int64
// DisablePathCorrection corrects and redirects the requested path to the registed path
// for example, if /home/ path is requested but no handler for this Route found,
// then the Router checks if /home handler exists, if yes,
// (permant)redirects the client to the correct path /home
//
// Default is false
DisablePathCorrection bool
// DisablePathEscape when is false then its escapes the path, the named parameters (if any).
// Change to true it if you want something like this https://github.com/kataras/iris/issues/135 to work
//
// When do you need to Disable(true) it:
// accepts parameters with slash '/'
// Request: http://localhost:8080/details/Project%2FDelta
// ctx.Param("project") returns the raw named parameter: Project%2FDelta
// which you can escape it manually with net/url:
// projectName, _ := url.QueryUnescape(c.Param("project").
// Look here: https://github.com/kataras/iris/issues/135 for more
//
// Default is false
DisablePathEscape bool
// DisableLog turn it to true if you want to disable logger,
// Iris prints/logs ONLY errors, so be careful when you enable it
DisableLog bool
// DisableBanner outputs the iris banner at startup
//
// Default is false
DisableBanner bool
// Profile set to true to enable web pprof (debug profiling)
// Default is false, enabling makes available these 7 routes:
// /debug/pprof/cmdline
// /debug/pprof/profile
// /debug/pprof/symbol
// /debug/pprof/goroutine
// /debug/pprof/heap
// /debug/pprof/threadcreate
// /debug/pprof/pprof/block
Profile bool
// ProfilePath change it if you want other url path than the default
// Default is /debug/pprof , which means yourhost.com/debug/pprof
ProfilePath string
// Sessions the config for sessions
// contains 3(three) properties
// Provider: (look /sessions/providers)
// Secret: cookie's name (string)
// Life: cookie life (time.Duration)
Sessions Sessions
// Render contains the configs for template and rest configuration
Render Render
Websocket Websocket
}
// Render struct keeps organise all configuration about rendering, templates and rest currently.
Render struct {
// Template the configs for template
Template Template
// Rest configs for rendering.
//
// these options inside this config don't have any relation with the TemplateEngine
// from github.com/kataras/iris/rest
Rest Rest
}
)
// DefaultRender returns default configuration for templates and rest rendering
func DefaultRender() Render {
return Render{
// set the default template config both not nil and default Engine to Standar
Template: DefaultTemplate(),
// set the default configs for rest
Rest: DefaultRest(),
}
}
// Default returns the default configuration for the Iris staton
func Default() Iris {
return Iris{
DisablePathCorrection: false,
DisablePathEscape: false,
MaxRequestBodySize: -1,
DisableLog: false,
DisableBanner: false,
Profile: false,
ProfilePath: DefaultProfilePath,
Sessions: DefaultSessions(),
Render: DefaultRender(),
Websocket: DefaultWebsocket(),
}
}
// Merge merges the default with the given config and returns the result
// receives an array because the func caller is variadic
func (c Iris) Merge(cfg []Iris) (config Iris) {
// I tried to make it more generic with interfaces for all configs, inside config.go but it fails,
// so do it foreach configuration np they aint so much...
if cfg != nil && len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// Merge MergeSingle the default with the given config and returns the result
func (c Iris) MergeSingle(cfg Iris) (config Iris) {
config = cfg
mergo.Merge(&config, c)
return
}
/* maybe some day
// FromFile returns the configuration for Iris station
//
// receives one parameter
// pathIni(string) the file path of the configuration-ini style
//
// returns an error if something bad happens
func FromFile(pathIni string) (c Iris, err error) {
c = Iris{}
err = ini.MapTo(&c, pathIni)
return
}
*/

40
config/iriscontrol.go Normal file
View File

@@ -0,0 +1,40 @@
package config
import "github.com/imdario/mergo"
var (
// DefaultUsername used for default (basic auth) username in IrisControl's & Editor's default configuration
DefaultUsername = "iris"
// DefaultPassword used for default (basic auth) password in IrisControl's & Editor's default configuration
DefaultPassword = "admin!123"
)
// IrisControl the options which iris control needs
// contains the port (int) and authenticated users with their passwords (map[string]string)
type IrisControl struct {
// Port the port
Port int
// Users the authenticated users, [username]password
Users map[string]string
}
// DefaultIrisControl returns the default configs for IrisControl plugin
func DefaultIrisControl() IrisControl {
users := make(map[string]string, 0)
users[DefaultUsername] = DefaultPassword
return IrisControl{4000, users}
}
// Merge merges the default with the given config and returns the result
func (c IrisControl) Merge(cfg []IrisControl) (config IrisControl) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}

48
config/logger.go Normal file
View File

@@ -0,0 +1,48 @@
package config
import "github.com/imdario/mergo"
import (
"io"
"os"
)
var (
// TimeFormat default time format for any kind of datetime parsing
TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
)
type (
Logger struct {
Out io.Writer
Prefix string
Flag int
}
)
func DefaultLogger() Logger {
return Logger{Out: os.Stdout, Prefix: "", Flag: 0}
}
// Merge merges the default with the given config and returns the result
func (c Logger) Merge(cfg []Logger) (config Logger) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// Merge MergeSingle the default with the given config and returns the result
func (c Logger) MergeSingle(cfg Logger) (config Logger) {
config = cfg
mergo.Merge(&config, c)
return
}

189
config/render.go Normal file
View File

@@ -0,0 +1,189 @@
package config
import (
"html/template"
"github.com/flosch/pongo2"
"github.com/imdario/mergo"
)
const (
NoEngine EngineType = -1
HTMLEngine EngineType = 0
PongoEngine EngineType = 1
MarkdownEngine EngineType = 2
JadeEngine EngineType = 3
AmberEngine EngineType = 4
DefaultEngine EngineType = HTMLEngine
// to disable layout for a particular file
NoLayout = "@.|.@iris_no_layout@.|.@"
)
var (
// Charset character encoding.
Charset = "UTF-8"
)
type (
// Rest is a struct for specifying configuration options for the rest.Render object.
Rest struct {
// Appends the given character set to the Content-Type header. Default is "UTF-8".
Charset string
// Gzip enable it if you want to render with gzip compression. Default is false
Gzip bool
// Outputs human readable JSON.
IndentJSON bool
// Outputs human readable XML. Default is false.
IndentXML bool
// Prefixes the JSON output with the given bytes. Default is false.
PrefixJSON []byte
// Prefixes the XML output with the given bytes.
PrefixXML []byte
// Unescape HTML characters "&<>" to their original values. Default is false.
UnEscapeHTML bool
// Streams JSON responses instead of marshalling prior to sending. Default is false.
StreamingJSON bool
// Disables automatic rendering of http.StatusInternalServerError when an error occurs. Default is false.
DisableHTTPErrorRendering bool
// MarkdownSanitize sanitizes the markdown. Default is false.
MarkdownSanitize bool
}
EngineType int8
Template struct {
// contains common configs for both HTMLTemplate & Pongo
Engine EngineType
Gzip bool
// Minify minifies the html result,
// Note: according to this https://github.com/tdewolff/minify/issues/35, also it removes some </tags> when minify on writer, remove this from Iris until fix.
// Default is false
//Minify bool
IsDevelopment bool
Directory string
Extensions []string
ContentType string
Charset string
Asset func(name string) ([]byte, error)
AssetNames func() []string
Layout string
HTMLTemplate HTMLTemplate // contains specific configs for HTMLTemplate standard html/template
Pongo Pongo // contains specific configs for pongo2
// Markdown template engine it doesn't supports Layout & binding context
Markdown Markdown // contains specific configs for markdown
Jade Jade // contains specific configs for Jade
Amber Amber // contains specific configs for Amber
}
HTMLTemplate struct {
RequirePartials bool
// Delims
Left string
Right string
// Funcs for HTMLTemplate html/template
Funcs template.FuncMap
}
Pongo struct {
// Filters for pongo2, map[name of the filter] the filter function . The filters are auto register
Filters map[string]pongo2.FilterFunction
// Globals share context fields between templates. https://github.com/flosch/pongo2/issues/35
Globals map[string]interface{}
}
Markdown struct {
Sanitize bool // if true then returns safe html, default is false
}
// Jade empty for now
// stay tuned
Jade struct {
}
Amber struct {
// Funcs for the html/template result, amber default funcs are not overrided so use it without worries
Funcs template.FuncMap
}
)
// DefaultRest returns the default config for rest
func DefaultRest() Rest {
return Rest{
Charset: Charset,
IndentJSON: false,
IndentXML: false,
PrefixJSON: []byte(""),
PrefixXML: []byte(""),
UnEscapeHTML: false,
StreamingJSON: false,
DisableHTTPErrorRendering: false,
MarkdownSanitize: false,
}
}
// Merge merges the default with the given config and returns the result
func (c Rest) Merge(cfg []Rest) (config Rest) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// MergeSingle merges the default with the given config and returns the result
func (c Rest) MergeSingle(cfg Rest) (config Rest) {
config = cfg
mergo.Merge(&config, c)
return
}
func DefaultTemplate() Template {
return Template{
Engine: DefaultEngine, //or HTMLTemplate
Gzip: false,
IsDevelopment: false,
Directory: "templates",
Extensions: []string{".html"},
ContentType: "text/html",
Charset: "UTF-8",
Layout: "", // currently this is the only config which not working for pongo2 yet but I will find a way
HTMLTemplate: HTMLTemplate{Left: "{{", Right: "}}", Funcs: template.FuncMap{}},
Pongo: Pongo{Filters: make(map[string]pongo2.FilterFunction, 0), Globals: make(map[string]interface{}, 0)},
Markdown: Markdown{Sanitize: false},
Amber: Amber{Funcs: template.FuncMap{}},
Jade: Jade{},
}
}
// Merge merges the default with the given config and returns the result
func (c Template) Merge(cfg []Template) (config Template) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// MergeSingle merges the default with the given config and returns the result
func (c Template) MergeSingle(cfg Template) (config Template) {
config = cfg
mergo.Merge(&config, c)
return
}

44
config/server.go Normal file
View File

@@ -0,0 +1,44 @@
package config
import (
"os"
"github.com/imdario/mergo"
)
const (
// DefaultServerAddr the default server addr
DefaultServerAddr = ":8080"
)
// ServerName the response header of the 'Server' value when writes to the client
const ServerName = "iris"
// Server used inside server for listening
type Server struct {
// ListenningAddr the addr that server listens to
ListeningAddr string
CertFile string
KeyFile string
// Mode this is for unix only
Mode os.FileMode
}
// DefaultServer returns the default configs for the server
func DefaultServer() Server {
return Server{DefaultServerAddr, "", "", 0}
}
// Merge merges the default with the given config and returns the result
func (c Server) Merge(cfg []Server) (config Server) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}

145
config/sessions.go Normal file
View File

@@ -0,0 +1,145 @@
package config
import (
"time"
"github.com/imdario/mergo"
)
var (
universe time.Time // 0001-01-01 00:00:00 +0000 UTC
// CookieExpireNever the default cookie's life for sessions, unlimited
CookieExpireNever = universe
)
const (
// DefaultCookieName the secret cookie's name for sessions
DefaultCookieName = "irissessionid"
DefaultSessionGcDuration = time.Duration(2) * time.Hour
// DefaultRedisNetwork the redis network option, "tcp"
DefaultRedisNetwork = "tcp"
// DefaultRedisAddr the redis address option, "127.0.0.1:6379"
DefaultRedisAddr = "127.0.0.1:6379"
// DefaultRedisIdleTimeout the redis idle timeout option, time.Duration(5) * time.Minute
DefaultRedisIdleTimeout = time.Duration(5) * time.Minute
// DefaultRedisMaxAgeSeconds the redis storage last parameter (SETEX), 31556926.0 (1 year)
DefaultRedisMaxAgeSeconds = 31556926.0 //1 year
)
type (
// Redis the redis configuration used inside sessions
Redis struct {
// Network "tcp"
Network string
// Addr "127.0.01:6379"
Addr string
// Password string .If no password then no 'AUTH'. Default ""
Password string
// If Database is empty "" then no 'SELECT'. Default ""
Database string
// MaxIdle 0 no limit
MaxIdle int
// MaxActive 0 no limit
MaxActive int
// IdleTimeout time.Duration(5) * time.Minute
IdleTimeout time.Duration
// Prefix "myprefix-for-this-website". Default ""
Prefix string
// MaxAgeSeconds how much long the redis should keep the session in seconds. Default 31556926.0 (1 year)
MaxAgeSeconds int
}
// Sessions the configuration for sessions
// has 4 fields
// first is the providerName (string) ["memory","redis"]
// second is the cookieName, the session's name (string) ["mysessionsecretcookieid"]
// third is the time which the client's cookie expires
// forth is the gcDuration (time.Duration) when this time passes it removes the unused sessions from the memory until the user come back
Sessions struct {
// Provider string, usage iris.Config().Provider = "memory" or "redis". If you wan to customize redis then import the package, and change it's config
Provider string
// Cookie string, the session's client cookie name, for example: "irissessionid"
Cookie string
//Expires the date which the cookie must expires. Default infinitive/unlimited life
Expires time.Time
// GcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration)
// for example: time.Duration(2)*time.Hour. it will check every 2 hours if cookie hasn't be used for 2 hours,
// deletes it from memory until the user comes back, then the session continue to work as it was
//
// Default 2 hours
GcDuration time.Duration
}
)
// DefaultSessions the default configs for Sessions
func DefaultSessions() Sessions {
return Sessions{
Provider: "memory", // the default provider is "memory", if you set it to "" means that sessions are disabled.
Cookie: DefaultCookieName,
Expires: CookieExpireNever,
GcDuration: DefaultSessionGcDuration,
}
}
// Merge merges the default with the given config and returns the result
func (c Sessions) Merge(cfg []Sessions) (config Sessions) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// Merge MergeSingle the default with the given config and returns the result
func (c Sessions) MergeSingle(cfg Sessions) (config Sessions) {
config = cfg
mergo.Merge(&config, c)
return
}
// DefaultRedis returns the default configuration for Redis service
func DefaultRedis() Redis {
return Redis{
Network: DefaultRedisNetwork,
Addr: DefaultRedisAddr,
Password: "",
Database: "",
MaxIdle: 0,
MaxActive: 0,
IdleTimeout: DefaultRedisIdleTimeout,
Prefix: "",
MaxAgeSeconds: DefaultRedisMaxAgeSeconds,
}
}
// Merge merges the default with the given config and returns the result
func (c Redis) Merge(cfg []Redis) (config Redis) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// Merge MergeSingle the default with the given config and returns the result
func (c Redis) MergeSingle(cfg Redis) (config Redis) {
config = cfg
mergo.Merge(&config, c)
return
}

132
config/typescript.go Normal file
View File

@@ -0,0 +1,132 @@
package config
import (
"os"
"reflect"
"github.com/imdario/mergo"
)
var (
pathSeparator = string(os.PathSeparator)
nodeModules = pathSeparator + "node_modules" + pathSeparator
)
type (
// Tsconfig the struct for tsconfig.json
Tsconfig struct {
CompilerOptions CompilerOptions `json:"compilerOptions"`
Exclude []string `json:"exclude"`
}
// CompilerOptions contains all the compiler options used by the tsc (typescript compiler)
CompilerOptions struct {
Declaration bool `json:"declaration"`
Module string `json:"module"`
Target string `json:"target"`
Watch bool `json:"watch"`
Charset string `json:"charset"`
Diagnostics bool `json:"diagnostics"`
EmitBOM bool `json:"emitBOM"`
EmitDecoratorMetadata bool `json:"emitDecoratorMetadata"`
ExperimentalDecorators bool `json:"experimentalDecorators"`
InlineSourceMap bool `json:"inlineSourceMap"`
InlineSources bool `json:"inlineSources"`
IsolatedModules bool `json:"isolatedModules"`
Jsx string `json:"jsx"`
ReactNamespace string `json:"reactNamespace"`
ListFiles bool `json:"listFiles"`
Locale string `json:"locale"`
MapRoot string `json:"mapRoot"`
ModuleResolution string `json:"moduleResolution"`
NewLine string `json:"newLine"`
NoEmit bool `json:"noEmit"`
NoEmitOnError bool `json:"noEmitOnError"`
NoEmitHelpers bool `json:"noEmitHelpers"`
NoImplicitAny bool `json:"noImplicitAny"`
NoLib bool `json:"noLib"`
NoResolve bool `json:"noResolve"`
SkipDefaultLibCheck bool `json:"skipDefaultLibCheck"`
OutDir string `json:"outDir"`
OutFile string `json:"outFile"`
PreserveConstEnums bool `json:"preserveConstEnums"`
Pretty bool `json:"pretty"`
RemoveComments bool `json:"removeComments"`
RootDir string `json:"rootDir"`
SourceMap bool `json:"sourceMap"`
SourceRoot string `json:"sourceRoot"`
StripInternal bool `json:"stripInternal"`
SuppressExcessPropertyErrors bool `json:"suppressExcessPropertyErrors"`
SuppressImplicitAnyIndexErrors bool `json:"suppressImplicitAnyIndexErrors"`
AllowUnusedLabels bool `json:"allowUnusedLabels"`
NoImplicitReturns bool `json:"noImplicitReturns"`
NoFallthroughCasesInSwitch bool `json:"noFallthroughCasesInSwitch"`
AllowUnreachableCode bool `json:"allowUnreachableCode"`
ForceConsistentCasingInFileNames bool `json:"forceConsistentCasingInFileNames"`
AllowSyntheticDefaultImports bool `json:"allowSyntheticDefaultImports"`
AllowJs bool `json:"allowJs"`
NoImplicitUseStrict bool `json:"noImplicitUseStrict"`
}
Typescript struct {
Bin string
Dir string
Ignore string
Tsconfig Tsconfig
Editor Editor
}
)
// CompilerArgs returns the CompilerOptions' contents of the Tsconfig
// it reads the json tags, add '--' at the start of each one and returns an array of strings
func (tsconfig Tsconfig) CompilerArgs() []string {
//val := reflect.ValueOf(tsconfig).Elem().FieldByName("CompilerOptions") -> for tsconfig *Tsconfig
val := reflect.ValueOf(tsconfig).FieldByName("CompilerOptions")
compilerOpts := make([]string, val.NumField())
for i := 0; i < val.NumField(); i++ {
typeField := val.Type().Field(i)
compilerOpts[i] = "--" + typeField.Tag.Get("json")
}
return compilerOpts
}
// DefaultTsconfig returns the default Tsconfig, with CompilerOptions module: commonjs, target: es5 and ignore the node_modules
func DefaultTsconfig() Tsconfig {
return Tsconfig{
CompilerOptions: CompilerOptions{
Module: "commonjs",
Target: "es5",
NoImplicitAny: false,
SourceMap: false,
},
Exclude: []string{"node_modules"},
}
}
// DefaultTypescript returns the default Options of the Typescript plugin
// Bin and Editor are setting in runtime via the plugin
func DefaultTypescript() Typescript {
root, err := os.Getwd()
if err != nil {
panic("Typescript Plugin: Cannot get the Current Working Directory !!! [os.getwd()]")
}
c := Typescript{Dir: root + pathSeparator, Ignore: nodeModules, Tsconfig: DefaultTsconfig()}
return c
}
// Merge merges the default with the given config and returns the result
func (c Typescript) Merge(cfg []Typescript) (config Typescript) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}

78
config/websocket.go Normal file
View File

@@ -0,0 +1,78 @@
package config
import (
"time"
"github.com/imdario/mergo"
)
// Currently only these 5 values are used for real
const (
// DefaultWriteTimeout 10 * time.Second
DefaultWriteTimeout = 10 * time.Second
// DefaultPongTimeout 60 * time.Second
DefaultPongTimeout = 60 * time.Second
// DefaultPingPeriod (DefaultPongTimeout * 9) / 10
DefaultPingPeriod = (DefaultPongTimeout * 9) / 10
// DefaultMaxMessageSize 1024
DefaultMaxMessageSize = 1024
)
//
// Websocket the config contains options for 'websocket' package
type Websocket struct {
// WriteTimeout time allowed to write a message to the connection.
// Default value is 10 * time.Second
WriteTimeout time.Duration
// PongTimeout allowed to read the next pong message from the connection
// Default value is 60 * time.Second
PongTimeout time.Duration
// PingPeriod send ping messages to the connection with this period. Must be less than PongTimeout
// Default value is (PongTimeout * 9) / 10
PingPeriod time.Duration
// MaxMessageSize max message size allowed from connection
// Default value is 1024
MaxMessageSize int
// Endpoint is the path which the websocket server will listen for clients/connections
// Default value is empty string, if you don't set it the Websocket server is disabled.
Endpoint string
// Headers the response headers before upgrader
// Default is empty
Headers map[string]string
}
// DefaultWebsocket returns the default config for iris-ws websocket package
func DefaultWebsocket() Websocket {
return Websocket{
WriteTimeout: DefaultWriteTimeout,
PongTimeout: DefaultPongTimeout,
PingPeriod: DefaultPingPeriod,
MaxMessageSize: DefaultMaxMessageSize,
Headers: make(map[string]string, 0),
Endpoint: "",
}
}
// Merge merges the default with the given config and returns the result
func (c Websocket) Merge(cfg []Websocket) (config Websocket) {
if len(cfg) > 0 {
config = cfg[0]
mergo.Merge(&config, c)
} else {
_default := c
config = _default
}
return
}
// MergeSingle merges the default with the given config and returns the result
func (c Websocket) MergeSingle(cfg Websocket) (config Websocket) {
config = cfg
mergo.Merge(&config, c)
return
}