id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
167,000
goadesign/goa
design/apidsl/current.go
actionDefinition
func actionDefinition() (*design.ActionDefinition, bool) { a, ok := dslengine.CurrentDefinition().(*design.ActionDefinition) if !ok { dslengine.IncompatibleDSL() } return a, ok }
go
func actionDefinition() (*design.ActionDefinition, bool) { a, ok := dslengine.CurrentDefinition().(*design.ActionDefinition) if !ok { dslengine.IncompatibleDSL() } return a, ok }
[ "func", "actionDefinition", "(", ")", "(", "*", "design", ".", "ActionDefinition", ",", "bool", ")", "{", "a", ",", "ok", ":=", "dslengine", ".", "CurrentDefinition", "(", ")", ".", "(", "*", "design", ".", "ActionDefinition", ")", "\n", "if", "!", "ok", "{", "dslengine", ".", "IncompatibleDSL", "(", ")", "\n", "}", "\n", "return", "a", ",", "ok", "\n", "}" ]
// actionDefinition returns true and current context if it is an ActionDefinition, // nil and false otherwise.
[ "actionDefinition", "returns", "true", "and", "current", "context", "if", "it", "is", "an", "ActionDefinition", "nil", "and", "false", "otherwise", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L117-L123
167,001
goadesign/goa
design/apidsl/current.go
responseDefinition
func responseDefinition() (*design.ResponseDefinition, bool) { r, ok := dslengine.CurrentDefinition().(*design.ResponseDefinition) if !ok { dslengine.IncompatibleDSL() } return r, ok }
go
func responseDefinition() (*design.ResponseDefinition, bool) { r, ok := dslengine.CurrentDefinition().(*design.ResponseDefinition) if !ok { dslengine.IncompatibleDSL() } return r, ok }
[ "func", "responseDefinition", "(", ")", "(", "*", "design", ".", "ResponseDefinition", ",", "bool", ")", "{", "r", ",", "ok", ":=", "dslengine", ".", "CurrentDefinition", "(", ")", ".", "(", "*", "design", ".", "ResponseDefinition", ")", "\n", "if", "!", "ok", "{", "dslengine", ".", "IncompatibleDSL", "(", ")", "\n", "}", "\n", "return", "r", ",", "ok", "\n", "}" ]
// responseDefinition returns true and current context if it is a ResponseDefinition, // nil and false otherwise.
[ "responseDefinition", "returns", "true", "and", "current", "context", "if", "it", "is", "a", "ResponseDefinition", "nil", "and", "false", "otherwise", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L127-L133
167,002
goadesign/goa
goagen/gen_app/writers.go
IsPathParam
func (c *ContextTemplateData) IsPathParam(param string) bool { params := c.Params pp := false if params.Type.IsObject() { for _, r := range c.Routes { pp = false for _, p := range r.Params() { if p == param { pp = true break } } if !pp { break } } } return pp }
go
func (c *ContextTemplateData) IsPathParam(param string) bool { params := c.Params pp := false if params.Type.IsObject() { for _, r := range c.Routes { pp = false for _, p := range r.Params() { if p == param { pp = true break } } if !pp { break } } } return pp }
[ "func", "(", "c", "*", "ContextTemplateData", ")", "IsPathParam", "(", "param", "string", ")", "bool", "{", "params", ":=", "c", ".", "Params", "\n", "pp", ":=", "false", "\n", "if", "params", ".", "Type", ".", "IsObject", "(", ")", "{", "for", "_", ",", "r", ":=", "range", "c", ".", "Routes", "{", "pp", "=", "false", "\n", "for", "_", ",", "p", ":=", "range", "r", ".", "Params", "(", ")", "{", "if", "p", "==", "param", "{", "pp", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "pp", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "pp", "\n", "}" ]
// IsPathParam returns true if the given parameter name corresponds to a path parameter for all // the context action routes. Such parameter is required but does not need to be validated as // httptreemux takes care of that.
[ "IsPathParam", "returns", "true", "if", "the", "given", "parameter", "name", "corresponds", "to", "a", "path", "parameter", "for", "all", "the", "context", "action", "routes", ".", "Such", "parameter", "is", "required", "but", "does", "not", "need", "to", "be", "validated", "as", "httptreemux", "takes", "care", "of", "that", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L131-L149
167,003
goadesign/goa
goagen/gen_app/writers.go
HasParamAndHeader
func (c *ContextTemplateData) HasParamAndHeader(name string) bool { if c.Params == nil || c.Headers == nil { return false } headerAtt := c.Headers.Type.ToObject()[name] headerName := codegen.GoifyAtt(headerAtt, name, true) for paramName, paramAtt := range c.Params.Type.ToObject() { paramName = codegen.GoifyAtt(paramAtt, paramName, true) if headerName == paramName { return true } } return false }
go
func (c *ContextTemplateData) HasParamAndHeader(name string) bool { if c.Params == nil || c.Headers == nil { return false } headerAtt := c.Headers.Type.ToObject()[name] headerName := codegen.GoifyAtt(headerAtt, name, true) for paramName, paramAtt := range c.Params.Type.ToObject() { paramName = codegen.GoifyAtt(paramAtt, paramName, true) if headerName == paramName { return true } } return false }
[ "func", "(", "c", "*", "ContextTemplateData", ")", "HasParamAndHeader", "(", "name", "string", ")", "bool", "{", "if", "c", ".", "Params", "==", "nil", "||", "c", ".", "Headers", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "headerAtt", ":=", "c", ".", "Headers", ".", "Type", ".", "ToObject", "(", ")", "[", "name", "]", "\n", "headerName", ":=", "codegen", ".", "GoifyAtt", "(", "headerAtt", ",", "name", ",", "true", ")", "\n", "for", "paramName", ",", "paramAtt", ":=", "range", "c", ".", "Params", ".", "Type", ".", "ToObject", "(", ")", "{", "paramName", "=", "codegen", ".", "GoifyAtt", "(", "paramAtt", ",", "paramName", ",", "true", ")", "\n", "if", "headerName", "==", "paramName", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasParamAndHeader returns true if the generated struct field name for the given header name // matches the generated struct field name of a param in c.Params.
[ "HasParamAndHeader", "returns", "true", "if", "the", "generated", "struct", "field", "name", "for", "the", "given", "header", "name", "matches", "the", "generated", "struct", "field", "name", "of", "a", "param", "in", "c", ".", "Params", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L153-L167
167,004
goadesign/goa
goagen/gen_app/writers.go
MustValidate
func (c *ContextTemplateData) MustValidate(name string) bool { return c.Params.IsRequired(name) && !c.IsPathParam(name) }
go
func (c *ContextTemplateData) MustValidate(name string) bool { return c.Params.IsRequired(name) && !c.IsPathParam(name) }
[ "func", "(", "c", "*", "ContextTemplateData", ")", "MustValidate", "(", "name", "string", ")", "bool", "{", "return", "c", ".", "Params", ".", "IsRequired", "(", "name", ")", "&&", "!", "c", ".", "IsPathParam", "(", "name", ")", "\n", "}" ]
// MustValidate returns true if code that checks for the presence of the given param must be // generated.
[ "MustValidate", "returns", "true", "if", "code", "that", "checks", "for", "the", "presence", "of", "the", "given", "param", "must", "be", "generated", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L171-L173
167,005
goadesign/goa
goagen/gen_app/writers.go
IterateResponses
func (c *ContextTemplateData) IterateResponses(it func(*design.ResponseDefinition) error) error { m := make(map[int]*design.ResponseDefinition, len(c.Responses)) var s []int for _, resp := range c.Responses { status := resp.Status m[status] = resp s = append(s, status) } sort.Ints(s) for _, status := range s { if err := it(m[status]); err != nil { return err } } return nil }
go
func (c *ContextTemplateData) IterateResponses(it func(*design.ResponseDefinition) error) error { m := make(map[int]*design.ResponseDefinition, len(c.Responses)) var s []int for _, resp := range c.Responses { status := resp.Status m[status] = resp s = append(s, status) } sort.Ints(s) for _, status := range s { if err := it(m[status]); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "ContextTemplateData", ")", "IterateResponses", "(", "it", "func", "(", "*", "design", ".", "ResponseDefinition", ")", "error", ")", "error", "{", "m", ":=", "make", "(", "map", "[", "int", "]", "*", "design", ".", "ResponseDefinition", ",", "len", "(", "c", ".", "Responses", ")", ")", "\n", "var", "s", "[", "]", "int", "\n", "for", "_", ",", "resp", ":=", "range", "c", ".", "Responses", "{", "status", ":=", "resp", ".", "Status", "\n", "m", "[", "status", "]", "=", "resp", "\n", "s", "=", "append", "(", "s", ",", "status", ")", "\n", "}", "\n", "sort", ".", "Ints", "(", "s", ")", "\n", "for", "_", ",", "status", ":=", "range", "s", "{", "if", "err", ":=", "it", "(", "m", "[", "status", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// IterateResponses iterates through the responses sorted by status code.
[ "IterateResponses", "iterates", "through", "the", "responses", "sorted", "by", "status", "code", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L176-L191
167,006
goadesign/goa
goagen/gen_app/writers.go
NewContextsWriter
func NewContextsWriter(filename string) (*ContextsWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &ContextsWriter{ SourceFile: file, Finalizer: codegen.NewFinalizer(), Validator: codegen.NewValidator(), }, nil }
go
func NewContextsWriter(filename string) (*ContextsWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &ContextsWriter{ SourceFile: file, Finalizer: codegen.NewFinalizer(), Validator: codegen.NewValidator(), }, nil }
[ "func", "NewContextsWriter", "(", "filename", "string", ")", "(", "*", "ContextsWriter", ",", "error", ")", "{", "file", ",", "err", ":=", "codegen", ".", "SourceFileFor", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "ContextsWriter", "{", "SourceFile", ":", "file", ",", "Finalizer", ":", "codegen", ".", "NewFinalizer", "(", ")", ",", "Validator", ":", "codegen", ".", "NewValidator", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewContextsWriter returns a contexts code writer. // Contexts provide the glue between the underlying request data and the user controller.
[ "NewContextsWriter", "returns", "a", "contexts", "code", "writer", ".", "Contexts", "provide", "the", "glue", "between", "the", "underlying", "request", "data", "and", "the", "user", "controller", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L195-L205
167,007
goadesign/goa
goagen/gen_app/writers.go
NewControllersWriter
func NewControllersWriter(filename string) (*ControllersWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &ControllersWriter{ SourceFile: file, Finalizer: codegen.NewFinalizer(), Validator: codegen.NewValidator(), }, nil }
go
func NewControllersWriter(filename string) (*ControllersWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &ControllersWriter{ SourceFile: file, Finalizer: codegen.NewFinalizer(), Validator: codegen.NewValidator(), }, nil }
[ "func", "NewControllersWriter", "(", "filename", "string", ")", "(", "*", "ControllersWriter", ",", "error", ")", "{", "file", ",", "err", ":=", "codegen", ".", "SourceFileFor", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "ControllersWriter", "{", "SourceFile", ":", "file", ",", "Finalizer", ":", "codegen", ".", "NewFinalizer", "(", ")", ",", "Validator", ":", "codegen", ".", "NewValidator", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewControllersWriter returns a handlers code writer. // Handlers provide the glue between the underlying request data and the user controller.
[ "NewControllersWriter", "returns", "a", "handlers", "code", "writer", ".", "Handlers", "provide", "the", "glue", "between", "the", "underlying", "request", "data", "and", "the", "user", "controller", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L298-L308
167,008
goadesign/goa
goagen/gen_app/writers.go
WriteInitService
func (w *ControllersWriter) WriteInitService(encoders, decoders []*EncoderTemplateData) error { ctx := map[string]interface{}{ "API": design.Design, "Encoders": encoders, "Decoders": decoders, } return w.ExecuteTemplate("service", serviceT, nil, ctx) }
go
func (w *ControllersWriter) WriteInitService(encoders, decoders []*EncoderTemplateData) error { ctx := map[string]interface{}{ "API": design.Design, "Encoders": encoders, "Decoders": decoders, } return w.ExecuteTemplate("service", serviceT, nil, ctx) }
[ "func", "(", "w", "*", "ControllersWriter", ")", "WriteInitService", "(", "encoders", ",", "decoders", "[", "]", "*", "EncoderTemplateData", ")", "error", "{", "ctx", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "design", ".", "Design", ",", "\"", "\"", ":", "encoders", ",", "\"", "\"", ":", "decoders", ",", "}", "\n", "return", "w", ".", "ExecuteTemplate", "(", "\"", "\"", ",", "serviceT", ",", "nil", ",", "ctx", ")", "\n", "}" ]
// WriteInitService writes the initService function
[ "WriteInitService", "writes", "the", "initService", "function" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L311-L318
167,009
goadesign/goa
goagen/gen_app/writers.go
Execute
func (w *ControllersWriter) Execute(data []*ControllerTemplateData) error { if len(data) == 0 { return nil } for _, d := range data { if err := w.ExecuteTemplate("controller", ctrlT, nil, d); err != nil { return err } if err := w.ExecuteTemplate("mount", mountT, nil, d); err != nil { return err } if len(d.Origins) > 0 { if err := w.ExecuteTemplate("handleCORS", handleCORST, nil, d); err != nil { return err } } fn := template.FuncMap{ "newCoerceData": newCoerceData, "finalizeCode": w.Finalizer.Code, "arrayAttribute": arrayAttribute, "validationCode": w.Validator.Code, "valueTypeOf": valueTypeOf, "fromString": fromString, } if err := w.ExecuteTemplate("unmarshal", unmarshalT, fn, d); err != nil { return err } } return nil }
go
func (w *ControllersWriter) Execute(data []*ControllerTemplateData) error { if len(data) == 0 { return nil } for _, d := range data { if err := w.ExecuteTemplate("controller", ctrlT, nil, d); err != nil { return err } if err := w.ExecuteTemplate("mount", mountT, nil, d); err != nil { return err } if len(d.Origins) > 0 { if err := w.ExecuteTemplate("handleCORS", handleCORST, nil, d); err != nil { return err } } fn := template.FuncMap{ "newCoerceData": newCoerceData, "finalizeCode": w.Finalizer.Code, "arrayAttribute": arrayAttribute, "validationCode": w.Validator.Code, "valueTypeOf": valueTypeOf, "fromString": fromString, } if err := w.ExecuteTemplate("unmarshal", unmarshalT, fn, d); err != nil { return err } } return nil }
[ "func", "(", "w", "*", "ControllersWriter", ")", "Execute", "(", "data", "[", "]", "*", "ControllerTemplateData", ")", "error", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "d", ":=", "range", "data", "{", "if", "err", ":=", "w", ".", "ExecuteTemplate", "(", "\"", "\"", ",", "ctrlT", ",", "nil", ",", "d", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "w", ".", "ExecuteTemplate", "(", "\"", "\"", ",", "mountT", ",", "nil", ",", "d", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "d", ".", "Origins", ")", ">", "0", "{", "if", "err", ":=", "w", ".", "ExecuteTemplate", "(", "\"", "\"", ",", "handleCORST", ",", "nil", ",", "d", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "fn", ":=", "template", ".", "FuncMap", "{", "\"", "\"", ":", "newCoerceData", ",", "\"", "\"", ":", "w", ".", "Finalizer", ".", "Code", ",", "\"", "\"", ":", "arrayAttribute", ",", "\"", "\"", ":", "w", ".", "Validator", ".", "Code", ",", "\"", "\"", ":", "valueTypeOf", ",", "\"", "\"", ":", "fromString", ",", "}", "\n", "if", "err", ":=", "w", ".", "ExecuteTemplate", "(", "\"", "\"", ",", "unmarshalT", ",", "fn", ",", "d", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Execute writes the handlers GoGenerator
[ "Execute", "writes", "the", "handlers", "GoGenerator" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L321-L350
167,010
goadesign/goa
goagen/gen_app/writers.go
NewSecurityWriter
func NewSecurityWriter(filename string) (*SecurityWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &SecurityWriter{SourceFile: file}, nil }
go
func NewSecurityWriter(filename string) (*SecurityWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &SecurityWriter{SourceFile: file}, nil }
[ "func", "NewSecurityWriter", "(", "filename", "string", ")", "(", "*", "SecurityWriter", ",", "error", ")", "{", "file", ",", "err", ":=", "codegen", ".", "SourceFileFor", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "SecurityWriter", "{", "SourceFile", ":", "file", "}", ",", "nil", "\n", "}" ]
// NewSecurityWriter returns a security functionality code writer. // Those functionalities are there to support action-middleware related to security.
[ "NewSecurityWriter", "returns", "a", "security", "functionality", "code", "writer", ".", "Those", "functionalities", "are", "there", "to", "support", "action", "-", "middleware", "related", "to", "security", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L354-L360
167,011
goadesign/goa
goagen/gen_app/writers.go
Execute
func (w *SecurityWriter) Execute(schemes []*design.SecuritySchemeDefinition) error { return w.ExecuteTemplate("security_schemes", securitySchemesT, nil, schemes) }
go
func (w *SecurityWriter) Execute(schemes []*design.SecuritySchemeDefinition) error { return w.ExecuteTemplate("security_schemes", securitySchemesT, nil, schemes) }
[ "func", "(", "w", "*", "SecurityWriter", ")", "Execute", "(", "schemes", "[", "]", "*", "design", ".", "SecuritySchemeDefinition", ")", "error", "{", "return", "w", ".", "ExecuteTemplate", "(", "\"", "\"", ",", "securitySchemesT", ",", "nil", ",", "schemes", ")", "\n", "}" ]
// Execute adds the different security schemes and middleware supporting functions.
[ "Execute", "adds", "the", "different", "security", "schemes", "and", "middleware", "supporting", "functions", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L363-L365
167,012
goadesign/goa
goagen/gen_app/writers.go
NewResourcesWriter
func NewResourcesWriter(filename string) (*ResourcesWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &ResourcesWriter{SourceFile: file}, nil }
go
func NewResourcesWriter(filename string) (*ResourcesWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &ResourcesWriter{SourceFile: file}, nil }
[ "func", "NewResourcesWriter", "(", "filename", "string", ")", "(", "*", "ResourcesWriter", ",", "error", ")", "{", "file", ",", "err", ":=", "codegen", ".", "SourceFileFor", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "ResourcesWriter", "{", "SourceFile", ":", "file", "}", ",", "nil", "\n", "}" ]
// NewResourcesWriter returns a contexts code writer. // Resources provide the glue between the underlying request data and the user controller.
[ "NewResourcesWriter", "returns", "a", "contexts", "code", "writer", ".", "Resources", "provide", "the", "glue", "between", "the", "underlying", "request", "data", "and", "the", "user", "controller", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L369-L375
167,013
goadesign/goa
goagen/gen_app/writers.go
NewMediaTypesWriter
func NewMediaTypesWriter(filename string) (*MediaTypesWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &MediaTypesWriter{SourceFile: file, Validator: codegen.NewValidator()}, nil }
go
func NewMediaTypesWriter(filename string) (*MediaTypesWriter, error) { file, err := codegen.SourceFileFor(filename) if err != nil { return nil, err } return &MediaTypesWriter{SourceFile: file, Validator: codegen.NewValidator()}, nil }
[ "func", "NewMediaTypesWriter", "(", "filename", "string", ")", "(", "*", "MediaTypesWriter", ",", "error", ")", "{", "file", ",", "err", ":=", "codegen", ".", "SourceFileFor", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "MediaTypesWriter", "{", "SourceFile", ":", "file", ",", "Validator", ":", "codegen", ".", "NewValidator", "(", ")", "}", ",", "nil", "\n", "}" ]
// NewMediaTypesWriter returns a contexts code writer. // Media types contain the data used to render response bodies.
[ "NewMediaTypesWriter", "returns", "a", "contexts", "code", "writer", ".", "Media", "types", "contain", "the", "data", "used", "to", "render", "response", "bodies", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L384-L390
167,014
goadesign/goa
goagen/gen_app/writers.go
newCoerceData
func newCoerceData(name string, att *design.AttributeDefinition, pointer bool, pkg string, depth int) map[string]interface{} { return map[string]interface{}{ "Name": name, "VarName": codegen.Goify(name, false), "Pointer": pointer, "Attribute": att, "Pkg": pkg, "Depth": depth, } }
go
func newCoerceData(name string, att *design.AttributeDefinition, pointer bool, pkg string, depth int) map[string]interface{} { return map[string]interface{}{ "Name": name, "VarName": codegen.Goify(name, false), "Pointer": pointer, "Attribute": att, "Pkg": pkg, "Depth": depth, } }
[ "func", "newCoerceData", "(", "name", "string", ",", "att", "*", "design", ".", "AttributeDefinition", ",", "pointer", "bool", ",", "pkg", "string", ",", "depth", "int", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "return", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "name", ",", "\"", "\"", ":", "codegen", ".", "Goify", "(", "name", ",", "false", ")", ",", "\"", "\"", ":", "pointer", ",", "\"", "\"", ":", "att", ",", "\"", "\"", ":", "pkg", ",", "\"", "\"", ":", "depth", ",", "}", "\n", "}" ]
// newCoerceData is a helper function that creates a map that can be given to the "Coerce" template.
[ "newCoerceData", "is", "a", "helper", "function", "that", "creates", "a", "map", "that", "can", "be", "given", "to", "the", "Coerce", "template", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L443-L452
167,015
goadesign/goa
goagen/gen_app/writers.go
arrayAttribute
func arrayAttribute(a *design.AttributeDefinition) *design.AttributeDefinition { return a.Type.(*design.Array).ElemType }
go
func arrayAttribute(a *design.AttributeDefinition) *design.AttributeDefinition { return a.Type.(*design.Array).ElemType }
[ "func", "arrayAttribute", "(", "a", "*", "design", ".", "AttributeDefinition", ")", "*", "design", ".", "AttributeDefinition", "{", "return", "a", ".", "Type", ".", "(", "*", "design", ".", "Array", ")", ".", "ElemType", "\n", "}" ]
// arrayAttribute returns the array element attribute definition.
[ "arrayAttribute", "returns", "the", "array", "element", "attribute", "definition", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L455-L457
167,016
goadesign/goa
goagen/gen_app/writers.go
valueTypeOf
func valueTypeOf(prefix string, att *design.AttributeDefinition) string { switch att.Type.Kind() { case design.BooleanKind: return prefix + "bool" case design.IntegerKind: return prefix + "int" case design.NumberKind: return prefix + "float" case design.StringKind: return prefix + "string" case design.ArrayKind: return valueTypeOf(prefix+"[]", arrayAttribute(att)) case design.HashKind: key, elm := hashAttribute(att) return valueTypeOf(prefix+"map["+valueTypeOf("", key)+"]", elm) } return prefix + "interface{}" }
go
func valueTypeOf(prefix string, att *design.AttributeDefinition) string { switch att.Type.Kind() { case design.BooleanKind: return prefix + "bool" case design.IntegerKind: return prefix + "int" case design.NumberKind: return prefix + "float" case design.StringKind: return prefix + "string" case design.ArrayKind: return valueTypeOf(prefix+"[]", arrayAttribute(att)) case design.HashKind: key, elm := hashAttribute(att) return valueTypeOf(prefix+"map["+valueTypeOf("", key)+"]", elm) } return prefix + "interface{}" }
[ "func", "valueTypeOf", "(", "prefix", "string", ",", "att", "*", "design", ".", "AttributeDefinition", ")", "string", "{", "switch", "att", ".", "Type", ".", "Kind", "(", ")", "{", "case", "design", ".", "BooleanKind", ":", "return", "prefix", "+", "\"", "\"", "\n", "case", "design", ".", "IntegerKind", ":", "return", "prefix", "+", "\"", "\"", "\n", "case", "design", ".", "NumberKind", ":", "return", "prefix", "+", "\"", "\"", "\n", "case", "design", ".", "StringKind", ":", "return", "prefix", "+", "\"", "\"", "\n", "case", "design", ".", "ArrayKind", ":", "return", "valueTypeOf", "(", "prefix", "+", "\"", "\"", ",", "arrayAttribute", "(", "att", ")", ")", "\n", "case", "design", ".", "HashKind", ":", "key", ",", "elm", ":=", "hashAttribute", "(", "att", ")", "\n", "return", "valueTypeOf", "(", "prefix", "+", "\"", "\"", "+", "valueTypeOf", "(", "\"", "\"", ",", "key", ")", "+", "\"", "\"", ",", "elm", ")", "\n", "}", "\n", "return", "prefix", "+", "\"", "\"", "\n", "}" ]
// valueTypeOf returns the golang type definition string from attribute definition
[ "valueTypeOf", "returns", "the", "golang", "type", "definition", "string", "from", "attribute", "definition" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L465-L482
167,017
goadesign/goa
goagen/gen_app/writers.go
fromString
func fromString(att *design.AttributeDefinition, varName string) string { switch att.Type.Kind() { case design.BooleanKind: return "strconv.ParseBool(" + varName + ")" case design.IntegerKind: return "strconv.Atoi(" + varName + ")" case design.NumberKind: return "strconv.ParseFloat(" + varName + ")" case design.StringKind: return varName + ", (error)(nil)" case design.ArrayKind: case design.HashKind: return valueTypeOf("", att) + "{}, (error)(nil)" } return "(" + valueTypeOf("", att) + ")(nil), (error)(nil)" }
go
func fromString(att *design.AttributeDefinition, varName string) string { switch att.Type.Kind() { case design.BooleanKind: return "strconv.ParseBool(" + varName + ")" case design.IntegerKind: return "strconv.Atoi(" + varName + ")" case design.NumberKind: return "strconv.ParseFloat(" + varName + ")" case design.StringKind: return varName + ", (error)(nil)" case design.ArrayKind: case design.HashKind: return valueTypeOf("", att) + "{}, (error)(nil)" } return "(" + valueTypeOf("", att) + ")(nil), (error)(nil)" }
[ "func", "fromString", "(", "att", "*", "design", ".", "AttributeDefinition", ",", "varName", "string", ")", "string", "{", "switch", "att", ".", "Type", ".", "Kind", "(", ")", "{", "case", "design", ".", "BooleanKind", ":", "return", "\"", "\"", "+", "varName", "+", "\"", "\"", "\n", "case", "design", ".", "IntegerKind", ":", "return", "\"", "\"", "+", "varName", "+", "\"", "\"", "\n", "case", "design", ".", "NumberKind", ":", "return", "\"", "\"", "+", "varName", "+", "\"", "\"", "\n", "case", "design", ".", "StringKind", ":", "return", "varName", "+", "\"", "\"", "\n", "case", "design", ".", "ArrayKind", ":", "case", "design", ".", "HashKind", ":", "return", "valueTypeOf", "(", "\"", "\"", ",", "att", ")", "+", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", "+", "valueTypeOf", "(", "\"", "\"", ",", "att", ")", "+", "\"", "\"", "\n", "}" ]
// fromString returns the gocode expression to convert string typed varName value to go-type defined in the attribute
[ "fromString", "returns", "the", "gocode", "expression", "to", "convert", "string", "typed", "varName", "value", "to", "go", "-", "type", "defined", "in", "the", "attribute" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_app/writers.go#L485-L500
167,018
streadway/amqp
confirms.go
Publish
func (c *confirms) Publish() uint64 { c.m.Lock() defer c.m.Unlock() c.published++ return c.published }
go
func (c *confirms) Publish() uint64 { c.m.Lock() defer c.m.Unlock() c.published++ return c.published }
[ "func", "(", "c", "*", "confirms", ")", "Publish", "(", ")", "uint64", "{", "c", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "m", ".", "Unlock", "(", ")", "\n\n", "c", ".", "published", "++", "\n", "return", "c", ".", "published", "\n", "}" ]
// publish increments the publishing counter
[ "publish", "increments", "the", "publishing", "counter" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/confirms.go#L31-L37
167,019
streadway/amqp
confirms.go
confirm
func (c *confirms) confirm(confirmation Confirmation) { delete(c.sequencer, c.expecting) c.expecting++ for _, l := range c.listeners { l <- confirmation } }
go
func (c *confirms) confirm(confirmation Confirmation) { delete(c.sequencer, c.expecting) c.expecting++ for _, l := range c.listeners { l <- confirmation } }
[ "func", "(", "c", "*", "confirms", ")", "confirm", "(", "confirmation", "Confirmation", ")", "{", "delete", "(", "c", ".", "sequencer", ",", "c", ".", "expecting", ")", "\n", "c", ".", "expecting", "++", "\n", "for", "_", ",", "l", ":=", "range", "c", ".", "listeners", "{", "l", "<-", "confirmation", "\n", "}", "\n", "}" ]
// confirm confirms one publishing, increments the expecting delivery tag, and // removes bookkeeping for that delivery tag.
[ "confirm", "confirms", "one", "publishing", "increments", "the", "expecting", "delivery", "tag", "and", "removes", "bookkeeping", "for", "that", "delivery", "tag", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/confirms.go#L41-L47
167,020
streadway/amqp
confirms.go
resequence
func (c *confirms) resequence() { for c.expecting <= c.published { sequenced, found := c.sequencer[c.expecting] if !found { return } c.confirm(sequenced) } }
go
func (c *confirms) resequence() { for c.expecting <= c.published { sequenced, found := c.sequencer[c.expecting] if !found { return } c.confirm(sequenced) } }
[ "func", "(", "c", "*", "confirms", ")", "resequence", "(", ")", "{", "for", "c", ".", "expecting", "<=", "c", ".", "published", "{", "sequenced", ",", "found", ":=", "c", ".", "sequencer", "[", "c", ".", "expecting", "]", "\n", "if", "!", "found", "{", "return", "\n", "}", "\n", "c", ".", "confirm", "(", "sequenced", ")", "\n", "}", "\n", "}" ]
// resequence confirms any out of order delivered confirmations
[ "resequence", "confirms", "any", "out", "of", "order", "delivered", "confirmations" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/confirms.go#L50-L58
167,021
streadway/amqp
confirms.go
One
func (c *confirms) One(confirmed Confirmation) { c.m.Lock() defer c.m.Unlock() if c.expecting == confirmed.DeliveryTag { c.confirm(confirmed) } else { c.sequencer[confirmed.DeliveryTag] = confirmed } c.resequence() }
go
func (c *confirms) One(confirmed Confirmation) { c.m.Lock() defer c.m.Unlock() if c.expecting == confirmed.DeliveryTag { c.confirm(confirmed) } else { c.sequencer[confirmed.DeliveryTag] = confirmed } c.resequence() }
[ "func", "(", "c", "*", "confirms", ")", "One", "(", "confirmed", "Confirmation", ")", "{", "c", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "m", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "expecting", "==", "confirmed", ".", "DeliveryTag", "{", "c", ".", "confirm", "(", "confirmed", ")", "\n", "}", "else", "{", "c", ".", "sequencer", "[", "confirmed", ".", "DeliveryTag", "]", "=", "confirmed", "\n", "}", "\n", "c", ".", "resequence", "(", ")", "\n", "}" ]
// one confirms one publishing and all following in the publishing sequence
[ "one", "confirms", "one", "publishing", "and", "all", "following", "in", "the", "publishing", "sequence" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/confirms.go#L61-L71
167,022
streadway/amqp
confirms.go
Multiple
func (c *confirms) Multiple(confirmed Confirmation) { c.m.Lock() defer c.m.Unlock() for c.expecting <= confirmed.DeliveryTag { c.confirm(Confirmation{c.expecting, confirmed.Ack}) } c.resequence() }
go
func (c *confirms) Multiple(confirmed Confirmation) { c.m.Lock() defer c.m.Unlock() for c.expecting <= confirmed.DeliveryTag { c.confirm(Confirmation{c.expecting, confirmed.Ack}) } c.resequence() }
[ "func", "(", "c", "*", "confirms", ")", "Multiple", "(", "confirmed", "Confirmation", ")", "{", "c", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "m", ".", "Unlock", "(", ")", "\n\n", "for", "c", ".", "expecting", "<=", "confirmed", ".", "DeliveryTag", "{", "c", ".", "confirm", "(", "Confirmation", "{", "c", ".", "expecting", ",", "confirmed", ".", "Ack", "}", ")", "\n", "}", "\n", "c", ".", "resequence", "(", ")", "\n", "}" ]
// multiple confirms all publishings up until the delivery tag
[ "multiple", "confirms", "all", "publishings", "up", "until", "the", "delivery", "tag" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/confirms.go#L74-L82
167,023
streadway/amqp
confirms.go
Close
func (c *confirms) Close() error { c.m.Lock() defer c.m.Unlock() for _, l := range c.listeners { close(l) } c.listeners = nil return nil }
go
func (c *confirms) Close() error { c.m.Lock() defer c.m.Unlock() for _, l := range c.listeners { close(l) } c.listeners = nil return nil }
[ "func", "(", "c", "*", "confirms", ")", "Close", "(", ")", "error", "{", "c", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "m", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "l", ":=", "range", "c", ".", "listeners", "{", "close", "(", "l", ")", "\n", "}", "\n", "c", ".", "listeners", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// Close closes all listeners, discarding any out of sequence confirmations
[ "Close", "closes", "all", "listeners", "discarding", "any", "out", "of", "sequence", "confirmations" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/confirms.go#L85-L94
167,024
streadway/amqp
write.go
write
func (f *heartbeatFrame) write(w io.Writer) (err error) { return writeFrame(w, frameHeartbeat, f.ChannelId, []byte{}) }
go
func (f *heartbeatFrame) write(w io.Writer) (err error) { return writeFrame(w, frameHeartbeat, f.ChannelId, []byte{}) }
[ "func", "(", "f", "*", "heartbeatFrame", ")", "write", "(", "w", "io", ".", "Writer", ")", "(", "err", "error", ")", "{", "return", "writeFrame", "(", "w", ",", "frameHeartbeat", ",", "f", ".", "ChannelId", ",", "[", "]", "byte", "{", "}", ")", "\n", "}" ]
// Heartbeat // // Payload is empty
[ "Heartbeat", "Payload", "is", "empty" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/write.go#L57-L59
167,025
streadway/amqp
write.go
write
func (f *bodyFrame) write(w io.Writer) (err error) { return writeFrame(w, frameBody, f.ChannelId, f.Body) }
go
func (f *bodyFrame) write(w io.Writer) (err error) { return writeFrame(w, frameBody, f.ChannelId, f.Body) }
[ "func", "(", "f", "*", "bodyFrame", ")", "write", "(", "w", "io", ".", "Writer", ")", "(", "err", "error", ")", "{", "return", "writeFrame", "(", "w", ",", "frameBody", ",", "f", ".", "ChannelId", ",", "f", ".", "Body", ")", "\n", "}" ]
// Body // // Payload is one byterange from the full body who's size is declared in the // Header frame
[ "Body", "Payload", "is", "one", "byterange", "from", "the", "full", "body", "who", "s", "size", "is", "declared", "in", "the", "Header", "frame" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/write.go#L206-L208
167,026
streadway/amqp
consumers.go
add
func (subs *consumers) add(tag string, consumer chan Delivery) { subs.Lock() defer subs.Unlock() if prev, found := subs.chans[tag]; found { close(prev) } in := make(chan *Delivery) subs.chans[tag] = in subs.Add(1) go subs.buffer(in, consumer) }
go
func (subs *consumers) add(tag string, consumer chan Delivery) { subs.Lock() defer subs.Unlock() if prev, found := subs.chans[tag]; found { close(prev) } in := make(chan *Delivery) subs.chans[tag] = in subs.Add(1) go subs.buffer(in, consumer) }
[ "func", "(", "subs", "*", "consumers", ")", "add", "(", "tag", "string", ",", "consumer", "chan", "Delivery", ")", "{", "subs", ".", "Lock", "(", ")", "\n", "defer", "subs", ".", "Unlock", "(", ")", "\n\n", "if", "prev", ",", "found", ":=", "subs", ".", "chans", "[", "tag", "]", ";", "found", "{", "close", "(", "prev", ")", "\n", "}", "\n\n", "in", ":=", "make", "(", "chan", "*", "Delivery", ")", "\n", "subs", ".", "chans", "[", "tag", "]", "=", "in", "\n\n", "subs", ".", "Add", "(", "1", ")", "\n", "go", "subs", ".", "buffer", "(", "in", ",", "consumer", ")", "\n", "}" ]
// On key conflict, close the previous channel.
[ "On", "key", "conflict", "close", "the", "previous", "channel", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/consumers.go#L85-L98
167,027
streadway/amqp
consumers.go
send
func (subs *consumers) send(tag string, msg *Delivery) bool { subs.Lock() defer subs.Unlock() buffer, found := subs.chans[tag] if found { buffer <- msg } return found }
go
func (subs *consumers) send(tag string, msg *Delivery) bool { subs.Lock() defer subs.Unlock() buffer, found := subs.chans[tag] if found { buffer <- msg } return found }
[ "func", "(", "subs", "*", "consumers", ")", "send", "(", "tag", "string", ",", "msg", "*", "Delivery", ")", "bool", "{", "subs", ".", "Lock", "(", ")", "\n", "defer", "subs", ".", "Unlock", "(", ")", "\n\n", "buffer", ",", "found", ":=", "subs", ".", "chans", "[", "tag", "]", "\n", "if", "found", "{", "buffer", "<-", "msg", "\n", "}", "\n\n", "return", "found", "\n", "}" ]
// Sends a delivery to a the consumer identified by `tag`. // If unbuffered channels are used for Consume this method // could block all deliveries until the consumer // receives on the other end of the channel.
[ "Sends", "a", "delivery", "to", "a", "the", "consumer", "identified", "by", "tag", ".", "If", "unbuffered", "channels", "are", "used", "for", "Consume", "this", "method", "could", "block", "all", "deliveries", "until", "the", "consumer", "receives", "on", "the", "other", "end", "of", "the", "channel", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/consumers.go#L132-L142
167,028
streadway/amqp
_examples/pubsub/pubsub.go
Close
func (s session) Close() error { if s.Connection == nil { return nil } return s.Connection.Close() }
go
func (s session) Close() error { if s.Connection == nil { return nil } return s.Connection.Close() }
[ "func", "(", "s", "session", ")", "Close", "(", ")", "error", "{", "if", "s", ".", "Connection", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "Connection", ".", "Close", "(", ")", "\n", "}" ]
// Close tears the connection down, taking the channel with it.
[ "Close", "tears", "the", "connection", "down", "taking", "the", "channel", "with", "it", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/_examples/pubsub/pubsub.go#L38-L43
167,029
streadway/amqp
_examples/pubsub/pubsub.go
redial
func redial(ctx context.Context, url string) chan chan session { sessions := make(chan chan session) go func() { sess := make(chan session) defer close(sessions) for { select { case sessions <- sess: case <-ctx.Done(): log.Println("shutting down session factory") return } conn, err := amqp.Dial(url) if err != nil { log.Fatalf("cannot (re)dial: %v: %q", err, url) } ch, err := conn.Channel() if err != nil { log.Fatalf("cannot create channel: %v", err) } if err := ch.ExchangeDeclare(exchange, "fanout", false, true, false, false, nil); err != nil { log.Fatalf("cannot declare fanout exchange: %v", err) } select { case sess <- session{conn, ch}: case <-ctx.Done(): log.Println("shutting down new session") return } } }() return sessions }
go
func redial(ctx context.Context, url string) chan chan session { sessions := make(chan chan session) go func() { sess := make(chan session) defer close(sessions) for { select { case sessions <- sess: case <-ctx.Done(): log.Println("shutting down session factory") return } conn, err := amqp.Dial(url) if err != nil { log.Fatalf("cannot (re)dial: %v: %q", err, url) } ch, err := conn.Channel() if err != nil { log.Fatalf("cannot create channel: %v", err) } if err := ch.ExchangeDeclare(exchange, "fanout", false, true, false, false, nil); err != nil { log.Fatalf("cannot declare fanout exchange: %v", err) } select { case sess <- session{conn, ch}: case <-ctx.Done(): log.Println("shutting down new session") return } } }() return sessions }
[ "func", "redial", "(", "ctx", "context", ".", "Context", ",", "url", "string", ")", "chan", "chan", "session", "{", "sessions", ":=", "make", "(", "chan", "chan", "session", ")", "\n\n", "go", "func", "(", ")", "{", "sess", ":=", "make", "(", "chan", "session", ")", "\n", "defer", "close", "(", "sessions", ")", "\n\n", "for", "{", "select", "{", "case", "sessions", "<-", "sess", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "conn", ",", "err", ":=", "amqp", ".", "Dial", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ",", "url", ")", "\n", "}", "\n\n", "ch", ",", "err", ":=", "conn", ".", "Channel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "ch", ".", "ExchangeDeclare", "(", "exchange", ",", "\"", "\"", ",", "false", ",", "true", ",", "false", ",", "false", ",", "nil", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "select", "{", "case", "sess", "<-", "session", "{", "conn", ",", "ch", "}", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "sessions", "\n", "}" ]
// redial continually connects to the URL, exiting the program when no longer possible
[ "redial", "continually", "connects", "to", "the", "URL", "exiting", "the", "program", "when", "no", "longer", "possible" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/_examples/pubsub/pubsub.go#L46-L85
167,030
streadway/amqp
_examples/pubsub/pubsub.go
publish
func publish(sessions chan chan session, messages <-chan message) { for session := range sessions { var ( running bool reading = messages pending = make(chan message, 1) confirm = make(chan amqp.Confirmation, 1) ) pub := <-session // publisher confirms for this channel/connection if err := pub.Confirm(false); err != nil { log.Printf("publisher confirms not supported") close(confirm) // confirms not supported, simulate by always nacking } else { pub.NotifyPublish(confirm) } log.Printf("publishing...") Publish: for { var body message select { case confirmed, ok := <-confirm: if !ok { break Publish } if !confirmed.Ack { log.Printf("nack message %d, body: %q", confirmed.DeliveryTag, string(body)) } reading = messages case body = <-pending: routingKey := "ignored for fanout exchanges, application dependent for other exchanges" err := pub.Publish(exchange, routingKey, false, false, amqp.Publishing{ Body: body, }) // Retry failed delivery on the next session if err != nil { pending <- body pub.Close() break Publish } case body, running = <-reading: // all messages consumed if !running { return } // work on pending delivery until ack'd pending <- body reading = nil } } } }
go
func publish(sessions chan chan session, messages <-chan message) { for session := range sessions { var ( running bool reading = messages pending = make(chan message, 1) confirm = make(chan amqp.Confirmation, 1) ) pub := <-session // publisher confirms for this channel/connection if err := pub.Confirm(false); err != nil { log.Printf("publisher confirms not supported") close(confirm) // confirms not supported, simulate by always nacking } else { pub.NotifyPublish(confirm) } log.Printf("publishing...") Publish: for { var body message select { case confirmed, ok := <-confirm: if !ok { break Publish } if !confirmed.Ack { log.Printf("nack message %d, body: %q", confirmed.DeliveryTag, string(body)) } reading = messages case body = <-pending: routingKey := "ignored for fanout exchanges, application dependent for other exchanges" err := pub.Publish(exchange, routingKey, false, false, amqp.Publishing{ Body: body, }) // Retry failed delivery on the next session if err != nil { pending <- body pub.Close() break Publish } case body, running = <-reading: // all messages consumed if !running { return } // work on pending delivery until ack'd pending <- body reading = nil } } } }
[ "func", "publish", "(", "sessions", "chan", "chan", "session", ",", "messages", "<-", "chan", "message", ")", "{", "for", "session", ":=", "range", "sessions", "{", "var", "(", "running", "bool", "\n", "reading", "=", "messages", "\n", "pending", "=", "make", "(", "chan", "message", ",", "1", ")", "\n", "confirm", "=", "make", "(", "chan", "amqp", ".", "Confirmation", ",", "1", ")", "\n", ")", "\n\n", "pub", ":=", "<-", "session", "\n\n", "// publisher confirms for this channel/connection", "if", "err", ":=", "pub", ".", "Confirm", "(", "false", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "close", "(", "confirm", ")", "// confirms not supported, simulate by always nacking", "\n", "}", "else", "{", "pub", ".", "NotifyPublish", "(", "confirm", ")", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ")", "\n\n", "Publish", ":", "for", "{", "var", "body", "message", "\n", "select", "{", "case", "confirmed", ",", "ok", ":=", "<-", "confirm", ":", "if", "!", "ok", "{", "break", "Publish", "\n", "}", "\n", "if", "!", "confirmed", ".", "Ack", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "confirmed", ".", "DeliveryTag", ",", "string", "(", "body", ")", ")", "\n", "}", "\n", "reading", "=", "messages", "\n\n", "case", "body", "=", "<-", "pending", ":", "routingKey", ":=", "\"", "\"", "\n", "err", ":=", "pub", ".", "Publish", "(", "exchange", ",", "routingKey", ",", "false", ",", "false", ",", "amqp", ".", "Publishing", "{", "Body", ":", "body", ",", "}", ")", "\n", "// Retry failed delivery on the next session", "if", "err", "!=", "nil", "{", "pending", "<-", "body", "\n", "pub", ".", "Close", "(", ")", "\n", "break", "Publish", "\n", "}", "\n\n", "case", "body", ",", "running", "=", "<-", "reading", ":", "// all messages consumed", "if", "!", "running", "{", "return", "\n", "}", "\n", "// work on pending delivery until ack'd", "pending", "<-", "body", "\n", "reading", "=", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// publish publishes messages to a reconnecting session to a fanout exchange. // It receives from the application specific source of messages.
[ "publish", "publishes", "messages", "to", "a", "reconnecting", "session", "to", "a", "fanout", "exchange", ".", "It", "receives", "from", "the", "application", "specific", "source", "of", "messages", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/_examples/pubsub/pubsub.go#L89-L146
167,031
streadway/amqp
_examples/pubsub/pubsub.go
subscribe
func subscribe(sessions chan chan session, messages chan<- message) { queue := identity() for session := range sessions { sub := <-session if _, err := sub.QueueDeclare(queue, false, true, true, false, nil); err != nil { log.Printf("cannot consume from exclusive queue: %q, %v", queue, err) return } routingKey := "application specific routing key for fancy toplogies" if err := sub.QueueBind(queue, routingKey, exchange, false, nil); err != nil { log.Printf("cannot consume without a binding to exchange: %q, %v", exchange, err) return } deliveries, err := sub.Consume(queue, "", false, true, false, false, nil) if err != nil { log.Printf("cannot consume from: %q, %v", queue, err) return } log.Printf("subscribed...") for msg := range deliveries { messages <- message(msg.Body) sub.Ack(msg.DeliveryTag, false) } } }
go
func subscribe(sessions chan chan session, messages chan<- message) { queue := identity() for session := range sessions { sub := <-session if _, err := sub.QueueDeclare(queue, false, true, true, false, nil); err != nil { log.Printf("cannot consume from exclusive queue: %q, %v", queue, err) return } routingKey := "application specific routing key for fancy toplogies" if err := sub.QueueBind(queue, routingKey, exchange, false, nil); err != nil { log.Printf("cannot consume without a binding to exchange: %q, %v", exchange, err) return } deliveries, err := sub.Consume(queue, "", false, true, false, false, nil) if err != nil { log.Printf("cannot consume from: %q, %v", queue, err) return } log.Printf("subscribed...") for msg := range deliveries { messages <- message(msg.Body) sub.Ack(msg.DeliveryTag, false) } } }
[ "func", "subscribe", "(", "sessions", "chan", "chan", "session", ",", "messages", "chan", "<-", "message", ")", "{", "queue", ":=", "identity", "(", ")", "\n\n", "for", "session", ":=", "range", "sessions", "{", "sub", ":=", "<-", "session", "\n\n", "if", "_", ",", "err", ":=", "sub", ".", "QueueDeclare", "(", "queue", ",", "false", ",", "true", ",", "true", ",", "false", ",", "nil", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "queue", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "routingKey", ":=", "\"", "\"", "\n", "if", "err", ":=", "sub", ".", "QueueBind", "(", "queue", ",", "routingKey", ",", "exchange", ",", "false", ",", "nil", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "exchange", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "deliveries", ",", "err", ":=", "sub", ".", "Consume", "(", "queue", ",", "\"", "\"", ",", "false", ",", "true", ",", "false", ",", "false", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "queue", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ")", "\n\n", "for", "msg", ":=", "range", "deliveries", "{", "messages", "<-", "message", "(", "msg", ".", "Body", ")", "\n", "sub", ".", "Ack", "(", "msg", ".", "DeliveryTag", ",", "false", ")", "\n", "}", "\n", "}", "\n", "}" ]
// subscribe consumes deliveries from an exclusive queue from a fanout exchange and sends to the application specific messages chan.
[ "subscribe", "consumes", "deliveries", "from", "an", "exclusive", "queue", "from", "a", "fanout", "exchange", "and", "sends", "to", "the", "application", "specific", "messages", "chan", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/_examples/pubsub/pubsub.go#L160-L190
167,032
streadway/amqp
_examples/pubsub/pubsub.go
read
func read(r io.Reader) <-chan message { lines := make(chan message) go func() { defer close(lines) scan := bufio.NewScanner(r) for scan.Scan() { lines <- message(scan.Bytes()) } }() return lines }
go
func read(r io.Reader) <-chan message { lines := make(chan message) go func() { defer close(lines) scan := bufio.NewScanner(r) for scan.Scan() { lines <- message(scan.Bytes()) } }() return lines }
[ "func", "read", "(", "r", "io", ".", "Reader", ")", "<-", "chan", "message", "{", "lines", ":=", "make", "(", "chan", "message", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "lines", ")", "\n", "scan", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "for", "scan", ".", "Scan", "(", ")", "{", "lines", "<-", "message", "(", "scan", ".", "Bytes", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "lines", "\n", "}" ]
// read is this application's translation to the message format, scanning from // stdin.
[ "read", "is", "this", "application", "s", "translation", "to", "the", "message", "format", "scanning", "from", "stdin", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/_examples/pubsub/pubsub.go#L194-L204
167,033
streadway/amqp
_examples/pubsub/pubsub.go
write
func write(w io.Writer) chan<- message { lines := make(chan message) go func() { for line := range lines { fmt.Fprintln(w, string(line)) } }() return lines }
go
func write(w io.Writer) chan<- message { lines := make(chan message) go func() { for line := range lines { fmt.Fprintln(w, string(line)) } }() return lines }
[ "func", "write", "(", "w", "io", ".", "Writer", ")", "chan", "<-", "message", "{", "lines", ":=", "make", "(", "chan", "message", ")", "\n", "go", "func", "(", ")", "{", "for", "line", ":=", "range", "lines", "{", "fmt", ".", "Fprintln", "(", "w", ",", "string", "(", "line", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "lines", "\n", "}" ]
// write is this application's subscriber of application messages, printing to // stdout.
[ "write", "is", "this", "application", "s", "subscriber", "of", "application", "messages", "printing", "to", "stdout", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/_examples/pubsub/pubsub.go#L208-L216
167,034
streadway/amqp
connection.go
DefaultDial
func DefaultDial(connectionTimeout time.Duration) func(network, addr string) (net.Conn, error) { return func(network, addr string) (net.Conn, error) { conn, err := net.DialTimeout(network, addr, connectionTimeout) if err != nil { return nil, err } // Heartbeating hasn't started yet, don't stall forever on a dead server. // A deadline is set for TLS and AMQP handshaking. After AMQP is established, // the deadline is cleared in openComplete. if err := conn.SetDeadline(time.Now().Add(connectionTimeout)); err != nil { return nil, err } return conn, nil } }
go
func DefaultDial(connectionTimeout time.Duration) func(network, addr string) (net.Conn, error) { return func(network, addr string) (net.Conn, error) { conn, err := net.DialTimeout(network, addr, connectionTimeout) if err != nil { return nil, err } // Heartbeating hasn't started yet, don't stall forever on a dead server. // A deadline is set for TLS and AMQP handshaking. After AMQP is established, // the deadline is cleared in openComplete. if err := conn.SetDeadline(time.Now().Add(connectionTimeout)); err != nil { return nil, err } return conn, nil } }
[ "func", "DefaultDial", "(", "connectionTimeout", "time", ".", "Duration", ")", "func", "(", "network", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "func", "(", "network", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "net", ".", "DialTimeout", "(", "network", ",", "addr", ",", "connectionTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Heartbeating hasn't started yet, don't stall forever on a dead server.", "// A deadline is set for TLS and AMQP handshaking. After AMQP is established,", "// the deadline is cleared in openComplete.", "if", "err", ":=", "conn", ".", "SetDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "connectionTimeout", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}", "\n", "}" ]
// DefaultDial establishes a connection when config.Dial is not provided
[ "DefaultDial", "establishes", "a", "connection", "when", "config", ".", "Dial", "is", "not", "provided" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L115-L131
167,035
streadway/amqp
connection.go
DialConfig
func DialConfig(url string, config Config) (*Connection, error) { var err error var conn net.Conn uri, err := ParseURI(url) if err != nil { return nil, err } if config.SASL == nil { config.SASL = []Authentication{uri.PlainAuth()} } if config.Vhost == "" { config.Vhost = uri.Vhost } addr := net.JoinHostPort(uri.Host, strconv.FormatInt(int64(uri.Port), 10)) dialer := config.Dial if dialer == nil { dialer = DefaultDial(defaultConnectionTimeout) } conn, err = dialer("tcp", addr) if err != nil { return nil, err } if uri.Scheme == "amqps" { if config.TLSClientConfig == nil { config.TLSClientConfig = new(tls.Config) } // If ServerName has not been specified in TLSClientConfig, // set it to the URI host used for this connection. if config.TLSClientConfig.ServerName == "" { config.TLSClientConfig.ServerName = uri.Host } client := tls.Client(conn, config.TLSClientConfig) if err := client.Handshake(); err != nil { conn.Close() return nil, err } conn = client } return Open(conn, config) }
go
func DialConfig(url string, config Config) (*Connection, error) { var err error var conn net.Conn uri, err := ParseURI(url) if err != nil { return nil, err } if config.SASL == nil { config.SASL = []Authentication{uri.PlainAuth()} } if config.Vhost == "" { config.Vhost = uri.Vhost } addr := net.JoinHostPort(uri.Host, strconv.FormatInt(int64(uri.Port), 10)) dialer := config.Dial if dialer == nil { dialer = DefaultDial(defaultConnectionTimeout) } conn, err = dialer("tcp", addr) if err != nil { return nil, err } if uri.Scheme == "amqps" { if config.TLSClientConfig == nil { config.TLSClientConfig = new(tls.Config) } // If ServerName has not been specified in TLSClientConfig, // set it to the URI host used for this connection. if config.TLSClientConfig.ServerName == "" { config.TLSClientConfig.ServerName = uri.Host } client := tls.Client(conn, config.TLSClientConfig) if err := client.Handshake(); err != nil { conn.Close() return nil, err } conn = client } return Open(conn, config) }
[ "func", "DialConfig", "(", "url", "string", ",", "config", "Config", ")", "(", "*", "Connection", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "conn", "net", ".", "Conn", "\n\n", "uri", ",", "err", ":=", "ParseURI", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "config", ".", "SASL", "==", "nil", "{", "config", ".", "SASL", "=", "[", "]", "Authentication", "{", "uri", ".", "PlainAuth", "(", ")", "}", "\n", "}", "\n\n", "if", "config", ".", "Vhost", "==", "\"", "\"", "{", "config", ".", "Vhost", "=", "uri", ".", "Vhost", "\n", "}", "\n\n", "addr", ":=", "net", ".", "JoinHostPort", "(", "uri", ".", "Host", ",", "strconv", ".", "FormatInt", "(", "int64", "(", "uri", ".", "Port", ")", ",", "10", ")", ")", "\n\n", "dialer", ":=", "config", ".", "Dial", "\n", "if", "dialer", "==", "nil", "{", "dialer", "=", "DefaultDial", "(", "defaultConnectionTimeout", ")", "\n", "}", "\n\n", "conn", ",", "err", "=", "dialer", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "uri", ".", "Scheme", "==", "\"", "\"", "{", "if", "config", ".", "TLSClientConfig", "==", "nil", "{", "config", ".", "TLSClientConfig", "=", "new", "(", "tls", ".", "Config", ")", "\n", "}", "\n\n", "// If ServerName has not been specified in TLSClientConfig,", "// set it to the URI host used for this connection.", "if", "config", ".", "TLSClientConfig", ".", "ServerName", "==", "\"", "\"", "{", "config", ".", "TLSClientConfig", ".", "ServerName", "=", "uri", ".", "Host", "\n", "}", "\n\n", "client", ":=", "tls", ".", "Client", "(", "conn", ",", "config", ".", "TLSClientConfig", ")", "\n", "if", "err", ":=", "client", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "conn", "=", "client", "\n", "}", "\n\n", "return", "Open", "(", "conn", ",", "config", ")", "\n", "}" ]
// DialConfig accepts a string in the AMQP URI format and a configuration for // the transport and connection setup, returning a new Connection. Defaults to // a server heartbeat interval of 10 seconds and sets the initial read deadline // to 30 seconds.
[ "DialConfig", "accepts", "a", "string", "in", "the", "AMQP", "URI", "format", "and", "a", "configuration", "for", "the", "transport", "and", "connection", "setup", "returning", "a", "new", "Connection", ".", "Defaults", "to", "a", "server", "heartbeat", "interval", "of", "10", "seconds", "and", "sets", "the", "initial", "read", "deadline", "to", "30", "seconds", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L164-L215
167,036
streadway/amqp
connection.go
demux
func (c *Connection) demux(f frame) { if f.channel() == 0 { c.dispatch0(f) } else { c.dispatchN(f) } }
go
func (c *Connection) demux(f frame) { if f.channel() == 0 { c.dispatch0(f) } else { c.dispatchN(f) } }
[ "func", "(", "c", "*", "Connection", ")", "demux", "(", "f", "frame", ")", "{", "if", "f", ".", "channel", "(", ")", "==", "0", "{", "c", ".", "dispatch0", "(", "f", ")", "\n", "}", "else", "{", "c", ".", "dispatchN", "(", "f", ")", "\n", "}", "\n", "}" ]
// All methods sent to the connection channel should be synchronous so we // can handle them directly without a framing component
[ "All", "methods", "sent", "to", "the", "connection", "channel", "should", "be", "synchronous", "so", "we", "can", "handle", "them", "directly", "without", "a", "framing", "component" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L432-L438
167,037
streadway/amqp
connection.go
heartbeater
func (c *Connection) heartbeater(interval time.Duration, done chan *Error) { const maxServerHeartbeatsInFlight = 3 var sendTicks <-chan time.Time if interval > 0 { ticker := time.NewTicker(interval) defer ticker.Stop() sendTicks = ticker.C } lastSent := time.Now() for { select { case at, stillSending := <-c.sends: // When actively sending, depend on sent frames to reset server timer if stillSending { lastSent = at } else { return } case at := <-sendTicks: // When idle, fill the space with a heartbeat frame if at.Sub(lastSent) > interval-time.Second { if err := c.send(&heartbeatFrame{}); err != nil { // send heartbeats even after close/closeOk so we // tick until the connection starts erroring return } } case conn := <-c.deadlines: // When reading, reset our side of the deadline, if we've negotiated one with // a deadline that covers at least 2 server heartbeats if interval > 0 { conn.SetReadDeadline(time.Now().Add(maxServerHeartbeatsInFlight * interval)) } case <-done: return } } }
go
func (c *Connection) heartbeater(interval time.Duration, done chan *Error) { const maxServerHeartbeatsInFlight = 3 var sendTicks <-chan time.Time if interval > 0 { ticker := time.NewTicker(interval) defer ticker.Stop() sendTicks = ticker.C } lastSent := time.Now() for { select { case at, stillSending := <-c.sends: // When actively sending, depend on sent frames to reset server timer if stillSending { lastSent = at } else { return } case at := <-sendTicks: // When idle, fill the space with a heartbeat frame if at.Sub(lastSent) > interval-time.Second { if err := c.send(&heartbeatFrame{}); err != nil { // send heartbeats even after close/closeOk so we // tick until the connection starts erroring return } } case conn := <-c.deadlines: // When reading, reset our side of the deadline, if we've negotiated one with // a deadline that covers at least 2 server heartbeats if interval > 0 { conn.SetReadDeadline(time.Now().Add(maxServerHeartbeatsInFlight * interval)) } case <-done: return } } }
[ "func", "(", "c", "*", "Connection", ")", "heartbeater", "(", "interval", "time", ".", "Duration", ",", "done", "chan", "*", "Error", ")", "{", "const", "maxServerHeartbeatsInFlight", "=", "3", "\n\n", "var", "sendTicks", "<-", "chan", "time", ".", "Time", "\n", "if", "interval", ">", "0", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "interval", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "sendTicks", "=", "ticker", ".", "C", "\n", "}", "\n\n", "lastSent", ":=", "time", ".", "Now", "(", ")", "\n\n", "for", "{", "select", "{", "case", "at", ",", "stillSending", ":=", "<-", "c", ".", "sends", ":", "// When actively sending, depend on sent frames to reset server timer", "if", "stillSending", "{", "lastSent", "=", "at", "\n", "}", "else", "{", "return", "\n", "}", "\n\n", "case", "at", ":=", "<-", "sendTicks", ":", "// When idle, fill the space with a heartbeat frame", "if", "at", ".", "Sub", "(", "lastSent", ")", ">", "interval", "-", "time", ".", "Second", "{", "if", "err", ":=", "c", ".", "send", "(", "&", "heartbeatFrame", "{", "}", ")", ";", "err", "!=", "nil", "{", "// send heartbeats even after close/closeOk so we", "// tick until the connection starts erroring", "return", "\n", "}", "\n", "}", "\n\n", "case", "conn", ":=", "<-", "c", ".", "deadlines", ":", "// When reading, reset our side of the deadline, if we've negotiated one with", "// a deadline that covers at least 2 server heartbeats", "if", "interval", ">", "0", "{", "conn", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "maxServerHeartbeatsInFlight", "*", "interval", ")", ")", "\n", "}", "\n\n", "case", "<-", "done", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Ensures that at least one frame is being sent at the tuned interval with a // jitter tolerance of 1s
[ "Ensures", "that", "at", "least", "one", "frame", "is", "being", "sent", "at", "the", "tuned", "interval", "with", "a", "jitter", "tolerance", "of", "1s" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L538-L581
167,038
streadway/amqp
connection.go
allocateChannel
func (c *Connection) allocateChannel() (*Channel, error) { c.m.Lock() defer c.m.Unlock() if c.IsClosed() { return nil, ErrClosed } id, ok := c.allocator.next() if !ok { return nil, ErrChannelMax } ch := newChannel(c, uint16(id)) c.channels[uint16(id)] = ch return ch, nil }
go
func (c *Connection) allocateChannel() (*Channel, error) { c.m.Lock() defer c.m.Unlock() if c.IsClosed() { return nil, ErrClosed } id, ok := c.allocator.next() if !ok { return nil, ErrChannelMax } ch := newChannel(c, uint16(id)) c.channels[uint16(id)] = ch return ch, nil }
[ "func", "(", "c", "*", "Connection", ")", "allocateChannel", "(", ")", "(", "*", "Channel", ",", "error", ")", "{", "c", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "m", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "IsClosed", "(", ")", "{", "return", "nil", ",", "ErrClosed", "\n", "}", "\n\n", "id", ",", "ok", ":=", "c", ".", "allocator", ".", "next", "(", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "ErrChannelMax", "\n", "}", "\n\n", "ch", ":=", "newChannel", "(", "c", ",", "uint16", "(", "id", ")", ")", "\n", "c", ".", "channels", "[", "uint16", "(", "id", ")", "]", "=", "ch", "\n\n", "return", "ch", ",", "nil", "\n", "}" ]
// allocateChannel records but does not open a new channel with a unique id. // This method is the initial part of the channel lifecycle and paired with // releaseChannel
[ "allocateChannel", "records", "but", "does", "not", "open", "a", "new", "channel", "with", "a", "unique", "id", ".", "This", "method", "is", "the", "initial", "part", "of", "the", "channel", "lifecycle", "and", "paired", "with", "releaseChannel" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L595-L612
167,039
streadway/amqp
connection.go
releaseChannel
func (c *Connection) releaseChannel(id uint16) { c.m.Lock() defer c.m.Unlock() delete(c.channels, id) c.allocator.release(int(id)) }
go
func (c *Connection) releaseChannel(id uint16) { c.m.Lock() defer c.m.Unlock() delete(c.channels, id) c.allocator.release(int(id)) }
[ "func", "(", "c", "*", "Connection", ")", "releaseChannel", "(", "id", "uint16", ")", "{", "c", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "m", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "c", ".", "channels", ",", "id", ")", "\n", "c", ".", "allocator", ".", "release", "(", "int", "(", "id", ")", ")", "\n", "}" ]
// releaseChannel removes a channel from the registry as the final part of the // channel lifecycle
[ "releaseChannel", "removes", "a", "channel", "from", "the", "registry", "as", "the", "final", "part", "of", "the", "channel", "lifecycle" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L616-L622
167,040
streadway/amqp
connection.go
openChannel
func (c *Connection) openChannel() (*Channel, error) { ch, err := c.allocateChannel() if err != nil { return nil, err } if err := ch.open(); err != nil { c.releaseChannel(ch.id) return nil, err } return ch, nil }
go
func (c *Connection) openChannel() (*Channel, error) { ch, err := c.allocateChannel() if err != nil { return nil, err } if err := ch.open(); err != nil { c.releaseChannel(ch.id) return nil, err } return ch, nil }
[ "func", "(", "c", "*", "Connection", ")", "openChannel", "(", ")", "(", "*", "Channel", ",", "error", ")", "{", "ch", ",", "err", ":=", "c", ".", "allocateChannel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "ch", ".", "open", "(", ")", ";", "err", "!=", "nil", "{", "c", ".", "releaseChannel", "(", "ch", ".", "id", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ch", ",", "nil", "\n", "}" ]
// openChannel allocates and opens a channel, must be paired with closeChannel
[ "openChannel", "allocates", "and", "opens", "a", "channel", "must", "be", "paired", "with", "closeChannel" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L625-L636
167,041
streadway/amqp
connection.go
closeChannel
func (c *Connection) closeChannel(ch *Channel, e *Error) { ch.shutdown(e) c.releaseChannel(ch.id) }
go
func (c *Connection) closeChannel(ch *Channel, e *Error) { ch.shutdown(e) c.releaseChannel(ch.id) }
[ "func", "(", "c", "*", "Connection", ")", "closeChannel", "(", "ch", "*", "Channel", ",", "e", "*", "Error", ")", "{", "ch", ".", "shutdown", "(", "e", ")", "\n", "c", ".", "releaseChannel", "(", "ch", ".", "id", ")", "\n", "}" ]
// closeChannel releases and initiates a shutdown of the channel. All channel // closures should be initiated here for proper channel lifecycle management on // this connection.
[ "closeChannel", "releases", "and", "initiates", "a", "shutdown", "of", "the", "channel", ".", "All", "channel", "closures", "should", "be", "initiated", "here", "for", "proper", "channel", "lifecycle", "management", "on", "this", "connection", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L641-L644
167,042
streadway/amqp
connection.go
openComplete
func (c *Connection) openComplete() error { // We clear the deadlines and let the heartbeater reset the read deadline if requested. // RabbitMQ uses TCP flow control at this point for pushback so Writes can // intentionally block. if deadliner, ok := c.conn.(interface { SetDeadline(time.Time) error }); ok { _ = deadliner.SetDeadline(time.Time{}) } c.allocator = newAllocator(1, c.Config.ChannelMax) return nil }
go
func (c *Connection) openComplete() error { // We clear the deadlines and let the heartbeater reset the read deadline if requested. // RabbitMQ uses TCP flow control at this point for pushback so Writes can // intentionally block. if deadliner, ok := c.conn.(interface { SetDeadline(time.Time) error }); ok { _ = deadliner.SetDeadline(time.Time{}) } c.allocator = newAllocator(1, c.Config.ChannelMax) return nil }
[ "func", "(", "c", "*", "Connection", ")", "openComplete", "(", ")", "error", "{", "// We clear the deadlines and let the heartbeater reset the read deadline if requested.", "// RabbitMQ uses TCP flow control at this point for pushback so Writes can", "// intentionally block.", "if", "deadliner", ",", "ok", ":=", "c", ".", "conn", ".", "(", "interface", "{", "SetDeadline", "(", "time", ".", "Time", ")", "error", "\n", "}", ")", ";", "ok", "{", "_", "=", "deadliner", ".", "SetDeadline", "(", "time", ".", "Time", "{", "}", ")", "\n", "}", "\n\n", "c", ".", "allocator", "=", "newAllocator", "(", "1", ",", "c", ".", "Config", ".", "ChannelMax", ")", "\n", "return", "nil", "\n", "}" ]
// openComplete performs any final Connection initialization dependent on the // connection handshake and clears any state needed for TLS and AMQP handshaking.
[ "openComplete", "performs", "any", "final", "Connection", "initialization", "dependent", "on", "the", "connection", "handshake", "and", "clears", "any", "state", "needed", "for", "TLS", "and", "AMQP", "handshaking", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/connection.go#L814-L826
167,043
streadway/amqp
allocator.go
reserve
func (a *allocator) reserve(n int) bool { if a.reserved(n) { return false } a.pool.SetBit(a.pool, n-a.low, allocated) return true }
go
func (a *allocator) reserve(n int) bool { if a.reserved(n) { return false } a.pool.SetBit(a.pool, n-a.low, allocated) return true }
[ "func", "(", "a", "*", "allocator", ")", "reserve", "(", "n", "int", ")", "bool", "{", "if", "a", ".", "reserved", "(", "n", ")", "{", "return", "false", "\n", "}", "\n", "a", ".", "pool", ".", "SetBit", "(", "a", ".", "pool", ",", "n", "-", "a", ".", "low", ",", "allocated", ")", "\n", "return", "true", "\n", "}" ]
// reserve claims the bit if it is not already claimed, returning true if // successfully claimed.
[ "reserve", "claims", "the", "bit", "if", "it", "is", "not", "already", "claimed", "returning", "true", "if", "successfully", "claimed", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/allocator.go#L90-L96
167,044
streadway/amqp
allocator.go
reserved
func (a *allocator) reserved(n int) bool { return a.pool.Bit(n-a.low) == allocated }
go
func (a *allocator) reserved(n int) bool { return a.pool.Bit(n-a.low) == allocated }
[ "func", "(", "a", "*", "allocator", ")", "reserved", "(", "n", "int", ")", "bool", "{", "return", "a", ".", "pool", ".", "Bit", "(", "n", "-", "a", ".", "low", ")", "==", "allocated", "\n", "}" ]
// reserved returns true if the integer has been allocated
[ "reserved", "returns", "true", "if", "the", "integer", "has", "been", "allocated" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/allocator.go#L99-L101
167,045
streadway/amqp
allocator.go
release
func (a *allocator) release(n int) { a.pool.SetBit(a.pool, n-a.low, free) }
go
func (a *allocator) release(n int) { a.pool.SetBit(a.pool, n-a.low, free) }
[ "func", "(", "a", "*", "allocator", ")", "release", "(", "n", "int", ")", "{", "a", ".", "pool", ".", "SetBit", "(", "a", ".", "pool", ",", "n", "-", "a", ".", "low", ",", "free", ")", "\n", "}" ]
// release frees the use of the number for another allocation
[ "release", "frees", "the", "use", "of", "the", "number", "for", "another", "allocation" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/allocator.go#L104-L106
167,046
streadway/amqp
auth.go
pickSASLMechanism
func pickSASLMechanism(client []Authentication, serverMechanisms []string) (auth Authentication, ok bool) { for _, auth = range client { for _, mech := range serverMechanisms { if auth.Mechanism() == mech { return auth, true } } } return }
go
func pickSASLMechanism(client []Authentication, serverMechanisms []string) (auth Authentication, ok bool) { for _, auth = range client { for _, mech := range serverMechanisms { if auth.Mechanism() == mech { return auth, true } } } return }
[ "func", "pickSASLMechanism", "(", "client", "[", "]", "Authentication", ",", "serverMechanisms", "[", "]", "string", ")", "(", "auth", "Authentication", ",", "ok", "bool", ")", "{", "for", "_", ",", "auth", "=", "range", "client", "{", "for", "_", ",", "mech", ":=", "range", "serverMechanisms", "{", "if", "auth", ".", "Mechanism", "(", ")", "==", "mech", "{", "return", "auth", ",", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// Finds the first mechanism preferred by the client that the server supports.
[ "Finds", "the", "first", "mechanism", "preferred", "by", "the", "client", "that", "the", "server", "supports", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/auth.go#L52-L62
167,047
streadway/amqp
uri.go
PlainAuth
func (uri URI) PlainAuth() *PlainAuth { return &PlainAuth{ Username: uri.Username, Password: uri.Password, } }
go
func (uri URI) PlainAuth() *PlainAuth { return &PlainAuth{ Username: uri.Username, Password: uri.Password, } }
[ "func", "(", "uri", "URI", ")", "PlainAuth", "(", ")", "*", "PlainAuth", "{", "return", "&", "PlainAuth", "{", "Username", ":", "uri", ".", "Username", ",", "Password", ":", "uri", ".", "Password", ",", "}", "\n", "}" ]
// PlainAuth returns a PlainAuth structure based on the parsed URI's // Username and Password fields.
[ "PlainAuth", "returns", "a", "PlainAuth", "structure", "based", "on", "the", "parsed", "URI", "s", "Username", "and", "Password", "fields", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/uri.go#L121-L126
167,048
streadway/amqp
uri.go
AMQPlainAuth
func (uri URI) AMQPlainAuth() *AMQPlainAuth { return &AMQPlainAuth{ Username: uri.Username, Password: uri.Password, } }
go
func (uri URI) AMQPlainAuth() *AMQPlainAuth { return &AMQPlainAuth{ Username: uri.Username, Password: uri.Password, } }
[ "func", "(", "uri", "URI", ")", "AMQPlainAuth", "(", ")", "*", "AMQPlainAuth", "{", "return", "&", "AMQPlainAuth", "{", "Username", ":", "uri", ".", "Username", ",", "Password", ":", "uri", ".", "Password", ",", "}", "\n", "}" ]
// AMQPlainAuth returns a PlainAuth structure based on the parsed URI's // Username and Password fields.
[ "AMQPlainAuth", "returns", "a", "PlainAuth", "structure", "based", "on", "the", "parsed", "URI", "s", "Username", "and", "Password", "fields", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/uri.go#L130-L135
167,049
streadway/amqp
channel.go
newChannel
func newChannel(c *Connection, id uint16) *Channel { return &Channel{ connection: c, id: id, rpc: make(chan message), consumers: makeConsumers(), confirms: newConfirms(), recv: (*Channel).recvMethod, errors: make(chan *Error, 1), } }
go
func newChannel(c *Connection, id uint16) *Channel { return &Channel{ connection: c, id: id, rpc: make(chan message), consumers: makeConsumers(), confirms: newConfirms(), recv: (*Channel).recvMethod, errors: make(chan *Error, 1), } }
[ "func", "newChannel", "(", "c", "*", "Connection", ",", "id", "uint16", ")", "*", "Channel", "{", "return", "&", "Channel", "{", "connection", ":", "c", ",", "id", ":", "id", ",", "rpc", ":", "make", "(", "chan", "message", ")", ",", "consumers", ":", "makeConsumers", "(", ")", ",", "confirms", ":", "newConfirms", "(", ")", ",", "recv", ":", "(", "*", "Channel", ")", ".", "recvMethod", ",", "errors", ":", "make", "(", "chan", "*", "Error", ",", "1", ")", ",", "}", "\n", "}" ]
// Constructs a new channel with the given framing rules
[ "Constructs", "a", "new", "channel", "with", "the", "given", "framing", "rules" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/channel.go#L78-L88
167,050
streadway/amqp
channel.go
shutdown
func (ch *Channel) shutdown(e *Error) { ch.destructor.Do(func() { ch.m.Lock() defer ch.m.Unlock() // Grab an exclusive lock for the notify channels ch.notifyM.Lock() defer ch.notifyM.Unlock() // Broadcast abnormal shutdown if e != nil { for _, c := range ch.closes { c <- e } } // Signal that from now on, Channel.send() should call // Channel.sendClosed() atomic.StoreInt32(&ch.closed, 1) // Notify RPC if we're selecting if e != nil { ch.errors <- e } ch.consumers.close() for _, c := range ch.closes { close(c) } for _, c := range ch.flows { close(c) } for _, c := range ch.returns { close(c) } for _, c := range ch.cancels { close(c) } // Set the slices to nil to prevent the dispatch() range from sending on // the now closed channels after we release the notifyM mutex ch.flows = nil ch.closes = nil ch.returns = nil ch.cancels = nil if ch.confirms != nil { ch.confirms.Close() } close(ch.errors) ch.noNotify = true }) }
go
func (ch *Channel) shutdown(e *Error) { ch.destructor.Do(func() { ch.m.Lock() defer ch.m.Unlock() // Grab an exclusive lock for the notify channels ch.notifyM.Lock() defer ch.notifyM.Unlock() // Broadcast abnormal shutdown if e != nil { for _, c := range ch.closes { c <- e } } // Signal that from now on, Channel.send() should call // Channel.sendClosed() atomic.StoreInt32(&ch.closed, 1) // Notify RPC if we're selecting if e != nil { ch.errors <- e } ch.consumers.close() for _, c := range ch.closes { close(c) } for _, c := range ch.flows { close(c) } for _, c := range ch.returns { close(c) } for _, c := range ch.cancels { close(c) } // Set the slices to nil to prevent the dispatch() range from sending on // the now closed channels after we release the notifyM mutex ch.flows = nil ch.closes = nil ch.returns = nil ch.cancels = nil if ch.confirms != nil { ch.confirms.Close() } close(ch.errors) ch.noNotify = true }) }
[ "func", "(", "ch", "*", "Channel", ")", "shutdown", "(", "e", "*", "Error", ")", "{", "ch", ".", "destructor", ".", "Do", "(", "func", "(", ")", "{", "ch", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "ch", ".", "m", ".", "Unlock", "(", ")", "\n\n", "// Grab an exclusive lock for the notify channels", "ch", ".", "notifyM", ".", "Lock", "(", ")", "\n", "defer", "ch", ".", "notifyM", ".", "Unlock", "(", ")", "\n\n", "// Broadcast abnormal shutdown", "if", "e", "!=", "nil", "{", "for", "_", ",", "c", ":=", "range", "ch", ".", "closes", "{", "c", "<-", "e", "\n", "}", "\n", "}", "\n\n", "// Signal that from now on, Channel.send() should call", "// Channel.sendClosed()", "atomic", ".", "StoreInt32", "(", "&", "ch", ".", "closed", ",", "1", ")", "\n\n", "// Notify RPC if we're selecting", "if", "e", "!=", "nil", "{", "ch", ".", "errors", "<-", "e", "\n", "}", "\n\n", "ch", ".", "consumers", ".", "close", "(", ")", "\n\n", "for", "_", ",", "c", ":=", "range", "ch", ".", "closes", "{", "close", "(", "c", ")", "\n", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "ch", ".", "flows", "{", "close", "(", "c", ")", "\n", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "ch", ".", "returns", "{", "close", "(", "c", ")", "\n", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "ch", ".", "cancels", "{", "close", "(", "c", ")", "\n", "}", "\n\n", "// Set the slices to nil to prevent the dispatch() range from sending on", "// the now closed channels after we release the notifyM mutex", "ch", ".", "flows", "=", "nil", "\n", "ch", ".", "closes", "=", "nil", "\n", "ch", ".", "returns", "=", "nil", "\n", "ch", ".", "cancels", "=", "nil", "\n\n", "if", "ch", ".", "confirms", "!=", "nil", "{", "ch", ".", "confirms", ".", "Close", "(", ")", "\n", "}", "\n\n", "close", "(", "ch", ".", "errors", ")", "\n", "ch", ".", "noNotify", "=", "true", "\n", "}", ")", "\n", "}" ]
// shutdown is called by Connection after the channel has been removed from the // connection registry.
[ "shutdown", "is", "called", "by", "Connection", "after", "the", "channel", "has", "been", "removed", "from", "the", "connection", "registry", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/channel.go#L92-L149
167,051
streadway/amqp
channel.go
dispatch
func (ch *Channel) dispatch(msg message) { switch m := msg.(type) { case *channelClose: // lock before sending connection.close-ok // to avoid unexpected interleaving with basic.publish frames if // publishing is happening concurrently ch.m.Lock() ch.send(&channelCloseOk{}) ch.m.Unlock() ch.connection.closeChannel(ch, newError(m.ReplyCode, m.ReplyText)) case *channelFlow: ch.notifyM.RLock() for _, c := range ch.flows { c <- m.Active } ch.notifyM.RUnlock() ch.send(&channelFlowOk{Active: m.Active}) case *basicCancel: ch.notifyM.RLock() for _, c := range ch.cancels { c <- m.ConsumerTag } ch.notifyM.RUnlock() ch.consumers.cancel(m.ConsumerTag) case *basicReturn: ret := newReturn(*m) ch.notifyM.RLock() for _, c := range ch.returns { c <- *ret } ch.notifyM.RUnlock() case *basicAck: if ch.confirming { if m.Multiple { ch.confirms.Multiple(Confirmation{m.DeliveryTag, true}) } else { ch.confirms.One(Confirmation{m.DeliveryTag, true}) } } case *basicNack: if ch.confirming { if m.Multiple { ch.confirms.Multiple(Confirmation{m.DeliveryTag, false}) } else { ch.confirms.One(Confirmation{m.DeliveryTag, false}) } } case *basicDeliver: ch.consumers.send(m.ConsumerTag, newDelivery(ch, m)) // TODO log failed consumer and close channel, this can happen when // deliveries are in flight and a no-wait cancel has happened default: ch.rpc <- msg } }
go
func (ch *Channel) dispatch(msg message) { switch m := msg.(type) { case *channelClose: // lock before sending connection.close-ok // to avoid unexpected interleaving with basic.publish frames if // publishing is happening concurrently ch.m.Lock() ch.send(&channelCloseOk{}) ch.m.Unlock() ch.connection.closeChannel(ch, newError(m.ReplyCode, m.ReplyText)) case *channelFlow: ch.notifyM.RLock() for _, c := range ch.flows { c <- m.Active } ch.notifyM.RUnlock() ch.send(&channelFlowOk{Active: m.Active}) case *basicCancel: ch.notifyM.RLock() for _, c := range ch.cancels { c <- m.ConsumerTag } ch.notifyM.RUnlock() ch.consumers.cancel(m.ConsumerTag) case *basicReturn: ret := newReturn(*m) ch.notifyM.RLock() for _, c := range ch.returns { c <- *ret } ch.notifyM.RUnlock() case *basicAck: if ch.confirming { if m.Multiple { ch.confirms.Multiple(Confirmation{m.DeliveryTag, true}) } else { ch.confirms.One(Confirmation{m.DeliveryTag, true}) } } case *basicNack: if ch.confirming { if m.Multiple { ch.confirms.Multiple(Confirmation{m.DeliveryTag, false}) } else { ch.confirms.One(Confirmation{m.DeliveryTag, false}) } } case *basicDeliver: ch.consumers.send(m.ConsumerTag, newDelivery(ch, m)) // TODO log failed consumer and close channel, this can happen when // deliveries are in flight and a no-wait cancel has happened default: ch.rpc <- msg } }
[ "func", "(", "ch", "*", "Channel", ")", "dispatch", "(", "msg", "message", ")", "{", "switch", "m", ":=", "msg", ".", "(", "type", ")", "{", "case", "*", "channelClose", ":", "// lock before sending connection.close-ok", "// to avoid unexpected interleaving with basic.publish frames if", "// publishing is happening concurrently", "ch", ".", "m", ".", "Lock", "(", ")", "\n", "ch", ".", "send", "(", "&", "channelCloseOk", "{", "}", ")", "\n", "ch", ".", "m", ".", "Unlock", "(", ")", "\n", "ch", ".", "connection", ".", "closeChannel", "(", "ch", ",", "newError", "(", "m", ".", "ReplyCode", ",", "m", ".", "ReplyText", ")", ")", "\n\n", "case", "*", "channelFlow", ":", "ch", ".", "notifyM", ".", "RLock", "(", ")", "\n", "for", "_", ",", "c", ":=", "range", "ch", ".", "flows", "{", "c", "<-", "m", ".", "Active", "\n", "}", "\n", "ch", ".", "notifyM", ".", "RUnlock", "(", ")", "\n", "ch", ".", "send", "(", "&", "channelFlowOk", "{", "Active", ":", "m", ".", "Active", "}", ")", "\n\n", "case", "*", "basicCancel", ":", "ch", ".", "notifyM", ".", "RLock", "(", ")", "\n", "for", "_", ",", "c", ":=", "range", "ch", ".", "cancels", "{", "c", "<-", "m", ".", "ConsumerTag", "\n", "}", "\n", "ch", ".", "notifyM", ".", "RUnlock", "(", ")", "\n", "ch", ".", "consumers", ".", "cancel", "(", "m", ".", "ConsumerTag", ")", "\n\n", "case", "*", "basicReturn", ":", "ret", ":=", "newReturn", "(", "*", "m", ")", "\n", "ch", ".", "notifyM", ".", "RLock", "(", ")", "\n", "for", "_", ",", "c", ":=", "range", "ch", ".", "returns", "{", "c", "<-", "*", "ret", "\n", "}", "\n", "ch", ".", "notifyM", ".", "RUnlock", "(", ")", "\n\n", "case", "*", "basicAck", ":", "if", "ch", ".", "confirming", "{", "if", "m", ".", "Multiple", "{", "ch", ".", "confirms", ".", "Multiple", "(", "Confirmation", "{", "m", ".", "DeliveryTag", ",", "true", "}", ")", "\n", "}", "else", "{", "ch", ".", "confirms", ".", "One", "(", "Confirmation", "{", "m", ".", "DeliveryTag", ",", "true", "}", ")", "\n", "}", "\n", "}", "\n\n", "case", "*", "basicNack", ":", "if", "ch", ".", "confirming", "{", "if", "m", ".", "Multiple", "{", "ch", ".", "confirms", ".", "Multiple", "(", "Confirmation", "{", "m", ".", "DeliveryTag", ",", "false", "}", ")", "\n", "}", "else", "{", "ch", ".", "confirms", ".", "One", "(", "Confirmation", "{", "m", ".", "DeliveryTag", ",", "false", "}", ")", "\n", "}", "\n", "}", "\n\n", "case", "*", "basicDeliver", ":", "ch", ".", "consumers", ".", "send", "(", "m", ".", "ConsumerTag", ",", "newDelivery", "(", "ch", ",", "m", ")", ")", "\n", "// TODO log failed consumer and close channel, this can happen when", "// deliveries are in flight and a no-wait cancel has happened", "default", ":", "ch", ".", "rpc", "<-", "msg", "\n", "}", "\n", "}" ]
// Eventually called via the state machine from the connection's reader // goroutine, so assumes serialized access.
[ "Eventually", "called", "via", "the", "state", "machine", "from", "the", "connection", "s", "reader", "goroutine", "so", "assumes", "serialized", "access", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/channel.go#L274-L335
167,052
streadway/amqp
channel.go
recvContent
func (ch *Channel) recvContent(f frame) error { switch frame := f.(type) { case *methodFrame: // interrupt content and handle method return ch.recvMethod(f) case *headerFrame: // drop and reset return ch.transition((*Channel).recvMethod) case *bodyFrame: ch.body = append(ch.body, frame.Body...) if uint64(len(ch.body)) >= ch.header.Size { ch.message.setContent(ch.header.Properties, ch.body) ch.dispatch(ch.message) // termination state return ch.transition((*Channel).recvMethod) } return ch.transition((*Channel).recvContent) } panic("unexpected frame type") }
go
func (ch *Channel) recvContent(f frame) error { switch frame := f.(type) { case *methodFrame: // interrupt content and handle method return ch.recvMethod(f) case *headerFrame: // drop and reset return ch.transition((*Channel).recvMethod) case *bodyFrame: ch.body = append(ch.body, frame.Body...) if uint64(len(ch.body)) >= ch.header.Size { ch.message.setContent(ch.header.Properties, ch.body) ch.dispatch(ch.message) // termination state return ch.transition((*Channel).recvMethod) } return ch.transition((*Channel).recvContent) } panic("unexpected frame type") }
[ "func", "(", "ch", "*", "Channel", ")", "recvContent", "(", "f", "frame", ")", "error", "{", "switch", "frame", ":=", "f", ".", "(", "type", ")", "{", "case", "*", "methodFrame", ":", "// interrupt content and handle method", "return", "ch", ".", "recvMethod", "(", "f", ")", "\n\n", "case", "*", "headerFrame", ":", "// drop and reset", "return", "ch", ".", "transition", "(", "(", "*", "Channel", ")", ".", "recvMethod", ")", "\n\n", "case", "*", "bodyFrame", ":", "ch", ".", "body", "=", "append", "(", "ch", ".", "body", ",", "frame", ".", "Body", "...", ")", "\n\n", "if", "uint64", "(", "len", "(", "ch", ".", "body", ")", ")", ">=", "ch", ".", "header", ".", "Size", "{", "ch", ".", "message", ".", "setContent", "(", "ch", ".", "header", ".", "Properties", ",", "ch", ".", "body", ")", "\n", "ch", ".", "dispatch", "(", "ch", ".", "message", ")", "// termination state", "\n", "return", "ch", ".", "transition", "(", "(", "*", "Channel", ")", ".", "recvMethod", ")", "\n", "}", "\n\n", "return", "ch", ".", "transition", "(", "(", "*", "Channel", ")", ".", "recvContent", ")", "\n", "}", "\n\n", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// state after method + header and before the length // defined by the header has been reached
[ "state", "after", "method", "+", "header", "and", "before", "the", "length", "defined", "by", "the", "header", "has", "been", "reached" ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/channel.go#L393-L416
167,053
streadway/amqp
_examples/simple-producer/producer.go
confirmOne
func confirmOne(confirms <-chan amqp.Confirmation) { log.Printf("waiting for confirmation of one publishing") if confirmed := <-confirms; confirmed.Ack { log.Printf("confirmed delivery with delivery tag: %d", confirmed.DeliveryTag) } else { log.Printf("failed delivery of delivery tag: %d", confirmed.DeliveryTag) } }
go
func confirmOne(confirms <-chan amqp.Confirmation) { log.Printf("waiting for confirmation of one publishing") if confirmed := <-confirms; confirmed.Ack { log.Printf("confirmed delivery with delivery tag: %d", confirmed.DeliveryTag) } else { log.Printf("failed delivery of delivery tag: %d", confirmed.DeliveryTag) } }
[ "func", "confirmOne", "(", "confirms", "<-", "chan", "amqp", ".", "Confirmation", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ")", "\n\n", "if", "confirmed", ":=", "<-", "confirms", ";", "confirmed", ".", "Ack", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "confirmed", ".", "DeliveryTag", ")", "\n", "}", "else", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "confirmed", ".", "DeliveryTag", ")", "\n", "}", "\n", "}" ]
// One would typically keep a channel of publishings, a sequence number, and a // set of unacknowledged sequence numbers and loop until the publishing channel // is closed.
[ "One", "would", "typically", "keep", "a", "channel", "of", "publishings", "a", "sequence", "number", "and", "a", "set", "of", "unacknowledged", "sequence", "numbers", "and", "loop", "until", "the", "publishing", "channel", "is", "closed", "." ]
75d898a42a940fbc854dfd1a4199eabdc00cf024
https://github.com/streadway/amqp/blob/75d898a42a940fbc854dfd1a4199eabdc00cf024/_examples/simple-producer/producer.go#L104-L112
167,054
gobwas/ws
wsutil/helper.go
WriteMessage
func WriteMessage(w io.Writer, s ws.State, op ws.OpCode, p []byte) error { return writeFrame(w, s, op, true, p) }
go
func WriteMessage(w io.Writer, s ws.State, op ws.OpCode, p []byte) error { return writeFrame(w, s, op, true, p) }
[ "func", "WriteMessage", "(", "w", "io", ".", "Writer", ",", "s", "ws", ".", "State", ",", "op", "ws", ".", "OpCode", ",", "p", "[", "]", "byte", ")", "error", "{", "return", "writeFrame", "(", "w", ",", "s", ",", "op", ",", "true", ",", "p", ")", "\n", "}" ]
// WriteMessage is a helper function that writes message to the w. It // constructs single frame with given operation code and payload. // It uses given state to prepare side-dependtend things, like cipher // payload bytes from client to server. It will not mutate p bytes if // cipher must be made. // // If you want to write message in fragmented frames, use Writer instead.
[ "WriteMessage", "is", "a", "helper", "function", "that", "writes", "message", "to", "the", "w", ".", "It", "constructs", "single", "frame", "with", "given", "operation", "code", "and", "payload", ".", "It", "uses", "given", "state", "to", "prepare", "side", "-", "dependtend", "things", "like", "cipher", "payload", "bytes", "from", "client", "to", "server", ".", "It", "will", "not", "mutate", "p", "bytes", "if", "cipher", "must", "be", "made", ".", "If", "you", "want", "to", "write", "message", "in", "fragmented", "frames", "use", "Writer", "instead", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L160-L162
167,055
gobwas/ws
wsutil/helper.go
WriteServerMessage
func WriteServerMessage(w io.Writer, op ws.OpCode, p []byte) error { return WriteMessage(w, ws.StateServerSide, op, p) }
go
func WriteServerMessage(w io.Writer, op ws.OpCode, p []byte) error { return WriteMessage(w, ws.StateServerSide, op, p) }
[ "func", "WriteServerMessage", "(", "w", "io", ".", "Writer", ",", "op", "ws", ".", "OpCode", ",", "p", "[", "]", "byte", ")", "error", "{", "return", "WriteMessage", "(", "w", ",", "ws", ".", "StateServerSide", ",", "op", ",", "p", ")", "\n", "}" ]
// WriteServerMessage writes message to w, considering that caller // represents server side.
[ "WriteServerMessage", "writes", "message", "to", "w", "considering", "that", "caller", "represents", "server", "side", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L166-L168
167,056
gobwas/ws
wsutil/helper.go
WriteServerText
func WriteServerText(w io.Writer, p []byte) error { return WriteServerMessage(w, ws.OpText, p) }
go
func WriteServerText(w io.Writer, p []byte) error { return WriteServerMessage(w, ws.OpText, p) }
[ "func", "WriteServerText", "(", "w", "io", ".", "Writer", ",", "p", "[", "]", "byte", ")", "error", "{", "return", "WriteServerMessage", "(", "w", ",", "ws", ".", "OpText", ",", "p", ")", "\n", "}" ]
// WriteServerText is the same as WriteServerMessage with // ws.OpText.
[ "WriteServerText", "is", "the", "same", "as", "WriteServerMessage", "with", "ws", ".", "OpText", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L172-L174
167,057
gobwas/ws
wsutil/helper.go
WriteServerBinary
func WriteServerBinary(w io.Writer, p []byte) error { return WriteServerMessage(w, ws.OpBinary, p) }
go
func WriteServerBinary(w io.Writer, p []byte) error { return WriteServerMessage(w, ws.OpBinary, p) }
[ "func", "WriteServerBinary", "(", "w", "io", ".", "Writer", ",", "p", "[", "]", "byte", ")", "error", "{", "return", "WriteServerMessage", "(", "w", ",", "ws", ".", "OpBinary", ",", "p", ")", "\n", "}" ]
// WriteServerBinary is the same as WriteServerMessage with // ws.OpBinary.
[ "WriteServerBinary", "is", "the", "same", "as", "WriteServerMessage", "with", "ws", ".", "OpBinary", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L178-L180
167,058
gobwas/ws
wsutil/helper.go
WriteClientMessage
func WriteClientMessage(w io.Writer, op ws.OpCode, p []byte) error { return WriteMessage(w, ws.StateClientSide, op, p) }
go
func WriteClientMessage(w io.Writer, op ws.OpCode, p []byte) error { return WriteMessage(w, ws.StateClientSide, op, p) }
[ "func", "WriteClientMessage", "(", "w", "io", ".", "Writer", ",", "op", "ws", ".", "OpCode", ",", "p", "[", "]", "byte", ")", "error", "{", "return", "WriteMessage", "(", "w", ",", "ws", ".", "StateClientSide", ",", "op", ",", "p", ")", "\n", "}" ]
// WriteClientMessage writes message to w, considering that caller // represents client side.
[ "WriteClientMessage", "writes", "message", "to", "w", "considering", "that", "caller", "represents", "client", "side", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L184-L186
167,059
gobwas/ws
wsutil/helper.go
WriteClientText
func WriteClientText(w io.Writer, p []byte) error { return WriteClientMessage(w, ws.OpText, p) }
go
func WriteClientText(w io.Writer, p []byte) error { return WriteClientMessage(w, ws.OpText, p) }
[ "func", "WriteClientText", "(", "w", "io", ".", "Writer", ",", "p", "[", "]", "byte", ")", "error", "{", "return", "WriteClientMessage", "(", "w", ",", "ws", ".", "OpText", ",", "p", ")", "\n", "}" ]
// WriteClientText is the same as WriteClientMessage with // ws.OpText.
[ "WriteClientText", "is", "the", "same", "as", "WriteClientMessage", "with", "ws", ".", "OpText", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L190-L192
167,060
gobwas/ws
wsutil/helper.go
WriteClientBinary
func WriteClientBinary(w io.Writer, p []byte) error { return WriteClientMessage(w, ws.OpBinary, p) }
go
func WriteClientBinary(w io.Writer, p []byte) error { return WriteClientMessage(w, ws.OpBinary, p) }
[ "func", "WriteClientBinary", "(", "w", "io", ".", "Writer", ",", "p", "[", "]", "byte", ")", "error", "{", "return", "WriteClientMessage", "(", "w", ",", "ws", ".", "OpBinary", ",", "p", ")", "\n", "}" ]
// WriteClientBinary is the same as WriteClientMessage with // ws.OpBinary.
[ "WriteClientBinary", "is", "the", "same", "as", "WriteClientMessage", "with", "ws", ".", "OpBinary", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L196-L198
167,061
gobwas/ws
wsutil/helper.go
HandleClientControlMessage
func HandleClientControlMessage(conn io.Writer, msg Message) error { return HandleControlMessage(conn, ws.StateServerSide, msg) }
go
func HandleClientControlMessage(conn io.Writer, msg Message) error { return HandleControlMessage(conn, ws.StateServerSide, msg) }
[ "func", "HandleClientControlMessage", "(", "conn", "io", ".", "Writer", ",", "msg", "Message", ")", "error", "{", "return", "HandleControlMessage", "(", "conn", ",", "ws", ".", "StateServerSide", ",", "msg", ")", "\n", "}" ]
// HandleClientControlMessage handles control frame from conn and writes // response when needed. // // It considers that caller represents server side.
[ "HandleClientControlMessage", "handles", "control", "frame", "from", "conn", "and", "writes", "response", "when", "needed", ".", "It", "considers", "that", "caller", "represents", "server", "side", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L204-L206
167,062
gobwas/ws
wsutil/helper.go
HandleServerControlMessage
func HandleServerControlMessage(conn io.Writer, msg Message) error { return HandleControlMessage(conn, ws.StateClientSide, msg) }
go
func HandleServerControlMessage(conn io.Writer, msg Message) error { return HandleControlMessage(conn, ws.StateClientSide, msg) }
[ "func", "HandleServerControlMessage", "(", "conn", "io", ".", "Writer", ",", "msg", "Message", ")", "error", "{", "return", "HandleControlMessage", "(", "conn", ",", "ws", ".", "StateClientSide", ",", "msg", ")", "\n", "}" ]
// HandleServerControlMessage handles control frame from conn and writes // response when needed. // // It considers that caller represents client side.
[ "HandleServerControlMessage", "handles", "control", "frame", "from", "conn", "and", "writes", "response", "when", "needed", ".", "It", "considers", "that", "caller", "represents", "client", "side", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L212-L214
167,063
gobwas/ws
wsutil/helper.go
ControlFrameHandler
func ControlFrameHandler(w io.Writer, state ws.State) FrameHandlerFunc { return func(h ws.Header, r io.Reader) error { return (ControlHandler{ DisableSrcCiphering: true, Src: r, Dst: w, State: state, }).Handle(h) } }
go
func ControlFrameHandler(w io.Writer, state ws.State) FrameHandlerFunc { return func(h ws.Header, r io.Reader) error { return (ControlHandler{ DisableSrcCiphering: true, Src: r, Dst: w, State: state, }).Handle(h) } }
[ "func", "ControlFrameHandler", "(", "w", "io", ".", "Writer", ",", "state", "ws", ".", "State", ")", "FrameHandlerFunc", "{", "return", "func", "(", "h", "ws", ".", "Header", ",", "r", "io", ".", "Reader", ")", "error", "{", "return", "(", "ControlHandler", "{", "DisableSrcCiphering", ":", "true", ",", "Src", ":", "r", ",", "Dst", ":", "w", ",", "State", ":", "state", ",", "}", ")", ".", "Handle", "(", "h", ")", "\n", "}", "\n", "}" ]
// ControlFrameHandler returns FrameHandlerFunc for handling control frames. // For more info see ControlHandler docs.
[ "ControlFrameHandler", "returns", "FrameHandlerFunc", "for", "handling", "control", "frames", ".", "For", "more", "info", "see", "ControlHandler", "docs", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/helper.go#L237-L246
167,064
gobwas/ws
nonce.go
initNonce
func initNonce(dst []byte) { // NOTE: bts does not escapes. bts := make([]byte, nonceKeySize) if _, err := rand.Read(bts); err != nil { panic(fmt.Sprintf("rand read error: %s", err)) } base64.StdEncoding.Encode(dst, bts) }
go
func initNonce(dst []byte) { // NOTE: bts does not escapes. bts := make([]byte, nonceKeySize) if _, err := rand.Read(bts); err != nil { panic(fmt.Sprintf("rand read error: %s", err)) } base64.StdEncoding.Encode(dst, bts) }
[ "func", "initNonce", "(", "dst", "[", "]", "byte", ")", "{", "// NOTE: bts does not escapes.", "bts", ":=", "make", "(", "[", "]", "byte", ",", "nonceKeySize", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "bts", ")", ";", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "base64", ".", "StdEncoding", ".", "Encode", "(", "dst", ",", "bts", ")", "\n", "}" ]
// initNonce fills given slice with random base64-encoded nonce bytes.
[ "initNonce", "fills", "given", "slice", "with", "random", "base64", "-", "encoded", "nonce", "bytes", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/nonce.go#L59-L66
167,065
gobwas/ws
nonce.go
checkAcceptFromNonce
func checkAcceptFromNonce(accept, nonce []byte) bool { if len(accept) != acceptSize { return false } // NOTE: expect does not escapes. expect := make([]byte, acceptSize) initAcceptFromNonce(expect, nonce) return bytes.Equal(expect, accept) }
go
func checkAcceptFromNonce(accept, nonce []byte) bool { if len(accept) != acceptSize { return false } // NOTE: expect does not escapes. expect := make([]byte, acceptSize) initAcceptFromNonce(expect, nonce) return bytes.Equal(expect, accept) }
[ "func", "checkAcceptFromNonce", "(", "accept", ",", "nonce", "[", "]", "byte", ")", "bool", "{", "if", "len", "(", "accept", ")", "!=", "acceptSize", "{", "return", "false", "\n", "}", "\n", "// NOTE: expect does not escapes.", "expect", ":=", "make", "(", "[", "]", "byte", ",", "acceptSize", ")", "\n", "initAcceptFromNonce", "(", "expect", ",", "nonce", ")", "\n", "return", "bytes", ".", "Equal", "(", "expect", ",", "accept", ")", "\n", "}" ]
// checkAcceptFromNonce reports whether given accept bytes are valid for given // nonce bytes.
[ "checkAcceptFromNonce", "reports", "whether", "given", "accept", "bytes", "are", "valid", "for", "given", "nonce", "bytes", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/nonce.go#L70-L78
167,066
gobwas/ws
nonce.go
initAcceptFromNonce
func initAcceptFromNonce(dst, nonce []byte) { if len(dst) != acceptSize { panic("accept buffer is invalid") } if len(nonce) != nonceSize { panic("nonce is invalid") } sha := acquireSha1() defer releaseSha1(sha) sha.Write(nonce) sha.Write(webSocketMagic) var sb [sha1.Size]byte sh := uintptr(unsafe.Pointer(&sb)) sum := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ Data: sh, Len: 0, Cap: sha1.Size, })) sum = sha.Sum(sum) base64.StdEncoding.Encode(dst, sum) }
go
func initAcceptFromNonce(dst, nonce []byte) { if len(dst) != acceptSize { panic("accept buffer is invalid") } if len(nonce) != nonceSize { panic("nonce is invalid") } sha := acquireSha1() defer releaseSha1(sha) sha.Write(nonce) sha.Write(webSocketMagic) var sb [sha1.Size]byte sh := uintptr(unsafe.Pointer(&sb)) sum := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ Data: sh, Len: 0, Cap: sha1.Size, })) sum = sha.Sum(sum) base64.StdEncoding.Encode(dst, sum) }
[ "func", "initAcceptFromNonce", "(", "dst", ",", "nonce", "[", "]", "byte", ")", "{", "if", "len", "(", "dst", ")", "!=", "acceptSize", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "nonce", ")", "!=", "nonceSize", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "sha", ":=", "acquireSha1", "(", ")", "\n", "defer", "releaseSha1", "(", "sha", ")", "\n\n", "sha", ".", "Write", "(", "nonce", ")", "\n", "sha", ".", "Write", "(", "webSocketMagic", ")", "\n\n", "var", "sb", "[", "sha1", ".", "Size", "]", "byte", "\n", "sh", ":=", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "sb", ")", ")", "\n", "sum", ":=", "*", "(", "*", "[", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "&", "reflect", ".", "SliceHeader", "{", "Data", ":", "sh", ",", "Len", ":", "0", ",", "Cap", ":", "sha1", ".", "Size", ",", "}", ")", ")", "\n", "sum", "=", "sha", ".", "Sum", "(", "sum", ")", "\n\n", "base64", ".", "StdEncoding", ".", "Encode", "(", "dst", ",", "sum", ")", "\n", "}" ]
// initAcceptFromNonce fills given slice with accept bytes generated from given // nonce bytes. Given buffer should be exactly acceptSize bytes.
[ "initAcceptFromNonce", "fills", "given", "slice", "with", "accept", "bytes", "generated", "from", "given", "nonce", "bytes", ".", "Given", "buffer", "should", "be", "exactly", "acceptSize", "bytes", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/nonce.go#L82-L106
167,067
gobwas/ws
write.go
HeaderSize
func HeaderSize(h Header) (n int) { switch { case h.Length < 126: n = 2 case h.Length <= len16: n = 4 case h.Length <= len64: n = 10 default: return -1 } if h.Masked { n += len(h.Mask) } return n }
go
func HeaderSize(h Header) (n int) { switch { case h.Length < 126: n = 2 case h.Length <= len16: n = 4 case h.Length <= len64: n = 10 default: return -1 } if h.Masked { n += len(h.Mask) } return n }
[ "func", "HeaderSize", "(", "h", "Header", ")", "(", "n", "int", ")", "{", "switch", "{", "case", "h", ".", "Length", "<", "126", ":", "n", "=", "2", "\n", "case", "h", ".", "Length", "<=", "len16", ":", "n", "=", "4", "\n", "case", "h", ".", "Length", "<=", "len64", ":", "n", "=", "10", "\n", "default", ":", "return", "-", "1", "\n", "}", "\n", "if", "h", ".", "Masked", "{", "n", "+=", "len", "(", "h", ".", "Mask", ")", "\n", "}", "\n", "return", "n", "\n", "}" ]
// HeaderSize returns number of bytes that are needed to encode given header. // It returns -1 if header is malformed.
[ "HeaderSize", "returns", "number", "of", "bytes", "that", "are", "needed", "to", "encode", "given", "header", ".", "It", "returns", "-", "1", "if", "header", "is", "malformed", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/write.go#L33-L48
167,068
gobwas/ws
write.go
WriteHeader
func WriteHeader(w io.Writer, h Header) error { // Make slice of bytes with capacity 14 that could hold any header. // // We use unsafe to stick bts to stack and avoid allocations. // // Using stack based slice is safe here, cause golang docs for io.Writer // says that "Implementations must not retain p". // See https://golang.org/pkg/io/#Writer var b [MaxHeaderSize]byte bp := uintptr(unsafe.Pointer(&b)) bh := &reflect.SliceHeader{ Data: bp, Len: MaxHeaderSize, Cap: MaxHeaderSize, } bts := *(*[]byte)(unsafe.Pointer(bh)) _ = bts[MaxHeaderSize-1] // bounds check hint to compiler. if h.Fin { bts[0] |= bit0 } bts[0] |= h.Rsv << 4 bts[0] |= byte(h.OpCode) var n int switch { case h.Length <= len7: bts[1] = byte(h.Length) n = 2 case h.Length <= len16: bts[1] = 126 binary.BigEndian.PutUint16(bts[2:4], uint16(h.Length)) n = 4 case h.Length <= len64: bts[1] = 127 binary.BigEndian.PutUint64(bts[2:10], uint64(h.Length)) n = 10 default: return ErrHeaderLengthUnexpected } if h.Masked { bts[1] |= bit0 n += copy(bts[n:], h.Mask[:]) } _, err := w.Write(bts[:n]) return err }
go
func WriteHeader(w io.Writer, h Header) error { // Make slice of bytes with capacity 14 that could hold any header. // // We use unsafe to stick bts to stack and avoid allocations. // // Using stack based slice is safe here, cause golang docs for io.Writer // says that "Implementations must not retain p". // See https://golang.org/pkg/io/#Writer var b [MaxHeaderSize]byte bp := uintptr(unsafe.Pointer(&b)) bh := &reflect.SliceHeader{ Data: bp, Len: MaxHeaderSize, Cap: MaxHeaderSize, } bts := *(*[]byte)(unsafe.Pointer(bh)) _ = bts[MaxHeaderSize-1] // bounds check hint to compiler. if h.Fin { bts[0] |= bit0 } bts[0] |= h.Rsv << 4 bts[0] |= byte(h.OpCode) var n int switch { case h.Length <= len7: bts[1] = byte(h.Length) n = 2 case h.Length <= len16: bts[1] = 126 binary.BigEndian.PutUint16(bts[2:4], uint16(h.Length)) n = 4 case h.Length <= len64: bts[1] = 127 binary.BigEndian.PutUint64(bts[2:10], uint64(h.Length)) n = 10 default: return ErrHeaderLengthUnexpected } if h.Masked { bts[1] |= bit0 n += copy(bts[n:], h.Mask[:]) } _, err := w.Write(bts[:n]) return err }
[ "func", "WriteHeader", "(", "w", "io", ".", "Writer", ",", "h", "Header", ")", "error", "{", "// Make slice of bytes with capacity 14 that could hold any header.", "//", "// We use unsafe to stick bts to stack and avoid allocations.", "//", "// Using stack based slice is safe here, cause golang docs for io.Writer", "// says that \"Implementations must not retain p\".", "// See https://golang.org/pkg/io/#Writer", "var", "b", "[", "MaxHeaderSize", "]", "byte", "\n", "bp", ":=", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "b", ")", ")", "\n", "bh", ":=", "&", "reflect", ".", "SliceHeader", "{", "Data", ":", "bp", ",", "Len", ":", "MaxHeaderSize", ",", "Cap", ":", "MaxHeaderSize", ",", "}", "\n", "bts", ":=", "*", "(", "*", "[", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "bh", ")", ")", "\n", "_", "=", "bts", "[", "MaxHeaderSize", "-", "1", "]", "// bounds check hint to compiler.", "\n\n", "if", "h", ".", "Fin", "{", "bts", "[", "0", "]", "|=", "bit0", "\n", "}", "\n", "bts", "[", "0", "]", "|=", "h", ".", "Rsv", "<<", "4", "\n", "bts", "[", "0", "]", "|=", "byte", "(", "h", ".", "OpCode", ")", "\n\n", "var", "n", "int", "\n", "switch", "{", "case", "h", ".", "Length", "<=", "len7", ":", "bts", "[", "1", "]", "=", "byte", "(", "h", ".", "Length", ")", "\n", "n", "=", "2", "\n\n", "case", "h", ".", "Length", "<=", "len16", ":", "bts", "[", "1", "]", "=", "126", "\n", "binary", ".", "BigEndian", ".", "PutUint16", "(", "bts", "[", "2", ":", "4", "]", ",", "uint16", "(", "h", ".", "Length", ")", ")", "\n", "n", "=", "4", "\n\n", "case", "h", ".", "Length", "<=", "len64", ":", "bts", "[", "1", "]", "=", "127", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "bts", "[", "2", ":", "10", "]", ",", "uint64", "(", "h", ".", "Length", ")", ")", "\n", "n", "=", "10", "\n\n", "default", ":", "return", "ErrHeaderLengthUnexpected", "\n", "}", "\n\n", "if", "h", ".", "Masked", "{", "bts", "[", "1", "]", "|=", "bit0", "\n", "n", "+=", "copy", "(", "bts", "[", "n", ":", "]", ",", "h", ".", "Mask", "[", ":", "]", ")", "\n", "}", "\n\n", "_", ",", "err", ":=", "w", ".", "Write", "(", "bts", "[", ":", "n", "]", ")", "\n\n", "return", "err", "\n", "}" ]
// WriteHeader writes header binary representation into w.
[ "WriteHeader", "writes", "header", "binary", "representation", "into", "w", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/write.go#L51-L103
167,069
gobwas/ws
write.go
WriteFrame
func WriteFrame(w io.Writer, f Frame) error { err := WriteHeader(w, f.Header) if err != nil { return err } _, err = w.Write(f.Payload) return err }
go
func WriteFrame(w io.Writer, f Frame) error { err := WriteHeader(w, f.Header) if err != nil { return err } _, err = w.Write(f.Payload) return err }
[ "func", "WriteFrame", "(", "w", "io", ".", "Writer", ",", "f", "Frame", ")", "error", "{", "err", ":=", "WriteHeader", "(", "w", ",", "f", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "w", ".", "Write", "(", "f", ".", "Payload", ")", "\n", "return", "err", "\n", "}" ]
// WriteFrame writes frame binary representation into w.
[ "WriteFrame", "writes", "frame", "binary", "representation", "into", "w", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/write.go#L106-L113
167,070
gobwas/ws
write.go
MustWriteFrame
func MustWriteFrame(w io.Writer, f Frame) { if err := WriteFrame(w, f); err != nil { panic(err) } }
go
func MustWriteFrame(w io.Writer, f Frame) { if err := WriteFrame(w, f); err != nil { panic(err) } }
[ "func", "MustWriteFrame", "(", "w", "io", ".", "Writer", ",", "f", "Frame", ")", "{", "if", "err", ":=", "WriteFrame", "(", "w", ",", "f", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// MustWriteFrame is like WriteFrame but panics if frame can not be read.
[ "MustWriteFrame", "is", "like", "WriteFrame", "but", "panics", "if", "frame", "can", "not", "be", "read", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/write.go#L116-L120
167,071
gobwas/ws
wsutil/writer.go
NewControlWriter
func NewControlWriter(dest io.Writer, state ws.State, op ws.OpCode) *ControlWriter { return &ControlWriter{ w: NewWriterSize(dest, state, op, ws.MaxControlFramePayloadSize), limit: ws.MaxControlFramePayloadSize, } }
go
func NewControlWriter(dest io.Writer, state ws.State, op ws.OpCode) *ControlWriter { return &ControlWriter{ w: NewWriterSize(dest, state, op, ws.MaxControlFramePayloadSize), limit: ws.MaxControlFramePayloadSize, } }
[ "func", "NewControlWriter", "(", "dest", "io", ".", "Writer", ",", "state", "ws", ".", "State", ",", "op", "ws", ".", "OpCode", ")", "*", "ControlWriter", "{", "return", "&", "ControlWriter", "{", "w", ":", "NewWriterSize", "(", "dest", ",", "state", ",", "op", ",", "ws", ".", "MaxControlFramePayloadSize", ")", ",", "limit", ":", "ws", ".", "MaxControlFramePayloadSize", ",", "}", "\n", "}" ]
// NewControlWriter contains ControlWriter with Writer inside whose buffer size // is at most ws.MaxControlFramePayloadSize + ws.MaxHeaderSize.
[ "NewControlWriter", "contains", "ControlWriter", "with", "Writer", "inside", "whose", "buffer", "size", "is", "at", "most", "ws", ".", "MaxControlFramePayloadSize", "+", "ws", ".", "MaxHeaderSize", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/writer.go#L45-L50
167,072
gobwas/ws
wsutil/writer.go
Write
func (c *ControlWriter) Write(p []byte) (n int, err error) { if c.n+len(p) > c.limit { return 0, ErrControlOverflow } return c.w.Write(p) }
go
func (c *ControlWriter) Write(p []byte) (n int, err error) { if c.n+len(p) > c.limit { return 0, ErrControlOverflow } return c.w.Write(p) }
[ "func", "(", "c", "*", "ControlWriter", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "c", ".", "n", "+", "len", "(", "p", ")", ">", "c", ".", "limit", "{", "return", "0", ",", "ErrControlOverflow", "\n", "}", "\n", "return", "c", ".", "w", ".", "Write", "(", "p", ")", "\n", "}" ]
// Write implements io.Writer. It writes to the underlying Writer until it // returns error or until ControlWriter write limit will be exceeded.
[ "Write", "implements", "io", ".", "Writer", ".", "It", "writes", "to", "the", "underlying", "Writer", "until", "it", "returns", "error", "or", "until", "ControlWriter", "write", "limit", "will", "be", "exceeded", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/writer.go#L75-L80
167,073
gobwas/ws
wsutil/writer.go
NewWriter
func NewWriter(dest io.Writer, state ws.State, op ws.OpCode) *Writer { return NewWriterBufferSize(dest, state, op, 0) }
go
func NewWriter(dest io.Writer, state ws.State, op ws.OpCode) *Writer { return NewWriterBufferSize(dest, state, op, 0) }
[ "func", "NewWriter", "(", "dest", "io", ".", "Writer", ",", "state", "ws", ".", "State", ",", "op", "ws", ".", "OpCode", ")", "*", "Writer", "{", "return", "NewWriterBufferSize", "(", "dest", ",", "state", ",", "op", ",", "0", ")", "\n", "}" ]
// NewWriter returns a new Writer whose buffer has the DefaultWriteBuffer size.
[ "NewWriter", "returns", "a", "new", "Writer", "whose", "buffer", "has", "the", "DefaultWriteBuffer", "size", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/writer.go#L149-L151
167,074
gobwas/ws
wsutil/writer.go
headerSize
func headerSize(s ws.State, n int) int { return ws.HeaderSize(ws.Header{ Length: int64(n), Masked: s.ClientSide(), }) }
go
func headerSize(s ws.State, n int) int { return ws.HeaderSize(ws.Header{ Length: int64(n), Masked: s.ClientSide(), }) }
[ "func", "headerSize", "(", "s", "ws", ".", "State", ",", "n", "int", ")", "int", "{", "return", "ws", ".", "HeaderSize", "(", "ws", ".", "Header", "{", "Length", ":", "int64", "(", "n", ")", ",", "Masked", ":", "s", ".", "ClientSide", "(", ")", ",", "}", ")", "\n", "}" ]
// headerSize returns number of bytes needed to encode header of a frame with // given state and length.
[ "headerSize", "returns", "number", "of", "bytes", "needed", "to", "encode", "header", "of", "a", "frame", "with", "given", "state", "and", "length", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/writer.go#L221-L226
167,075
gobwas/ws
wsutil/writer.go
Reset
func (w *Writer) Reset(dest io.Writer, state ws.State, op ws.OpCode) { w.n = 0 w.dirty = false w.fragmented = false w.dest = dest w.state = state w.op = op }
go
func (w *Writer) Reset(dest io.Writer, state ws.State, op ws.OpCode) { w.n = 0 w.dirty = false w.fragmented = false w.dest = dest w.state = state w.op = op }
[ "func", "(", "w", "*", "Writer", ")", "Reset", "(", "dest", "io", ".", "Writer", ",", "state", "ws", ".", "State", ",", "op", "ws", ".", "OpCode", ")", "{", "w", ".", "n", "=", "0", "\n", "w", ".", "dirty", "=", "false", "\n", "w", ".", "fragmented", "=", "false", "\n", "w", ".", "dest", "=", "dest", "\n", "w", ".", "state", "=", "state", "\n", "w", ".", "op", "=", "op", "\n", "}" ]
// Reset discards any buffered data, clears error, and resets w to have given // state and write frames with given OpCode to dest.
[ "Reset", "discards", "any", "buffered", "data", "clears", "error", "and", "resets", "w", "to", "have", "given", "state", "and", "write", "frames", "with", "given", "OpCode", "to", "dest", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/writer.go#L230-L237
167,076
gobwas/ws
wsutil/writer.go
ReadFrom
func (w *Writer) ReadFrom(src io.Reader) (n int64, err error) { var nn int for err == nil { if w.Available() == 0 { err = w.FlushFragment() continue } // We copy the behavior of bufio.Writer here. // Also, from the docs on io.ReaderFrom: // ReadFrom reads data from r until EOF or error. // // See https://codereview.appspot.com/76400048/#ps1 const maxEmptyReads = 100 var nr int for nr < maxEmptyReads { nn, err = src.Read(w.buf[w.n:]) if nn != 0 || err != nil { break } nr++ } if nr == maxEmptyReads { return n, io.ErrNoProgress } w.n += nn n += int64(nn) } if err == io.EOF { // NOTE: Do not flush preemtively. // See the Write() sources for more info. err = nil w.dirty = true } return n, err }
go
func (w *Writer) ReadFrom(src io.Reader) (n int64, err error) { var nn int for err == nil { if w.Available() == 0 { err = w.FlushFragment() continue } // We copy the behavior of bufio.Writer here. // Also, from the docs on io.ReaderFrom: // ReadFrom reads data from r until EOF or error. // // See https://codereview.appspot.com/76400048/#ps1 const maxEmptyReads = 100 var nr int for nr < maxEmptyReads { nn, err = src.Read(w.buf[w.n:]) if nn != 0 || err != nil { break } nr++ } if nr == maxEmptyReads { return n, io.ErrNoProgress } w.n += nn n += int64(nn) } if err == io.EOF { // NOTE: Do not flush preemtively. // See the Write() sources for more info. err = nil w.dirty = true } return n, err }
[ "func", "(", "w", "*", "Writer", ")", "ReadFrom", "(", "src", "io", ".", "Reader", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "var", "nn", "int", "\n", "for", "err", "==", "nil", "{", "if", "w", ".", "Available", "(", ")", "==", "0", "{", "err", "=", "w", ".", "FlushFragment", "(", ")", "\n", "continue", "\n", "}", "\n\n", "// We copy the behavior of bufio.Writer here.", "// Also, from the docs on io.ReaderFrom:", "// ReadFrom reads data from r until EOF or error.", "//", "// See https://codereview.appspot.com/76400048/#ps1", "const", "maxEmptyReads", "=", "100", "\n", "var", "nr", "int", "\n", "for", "nr", "<", "maxEmptyReads", "{", "nn", ",", "err", "=", "src", ".", "Read", "(", "w", ".", "buf", "[", "w", ".", "n", ":", "]", ")", "\n", "if", "nn", "!=", "0", "||", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "nr", "++", "\n", "}", "\n", "if", "nr", "==", "maxEmptyReads", "{", "return", "n", ",", "io", ".", "ErrNoProgress", "\n", "}", "\n\n", "w", ".", "n", "+=", "nn", "\n", "n", "+=", "int64", "(", "nn", ")", "\n", "}", "\n", "if", "err", "==", "io", ".", "EOF", "{", "// NOTE: Do not flush preemtively.", "// See the Write() sources for more info.", "err", "=", "nil", "\n", "w", ".", "dirty", "=", "true", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// ReadFrom implements io.ReaderFrom.
[ "ReadFrom", "implements", "io", ".", "ReaderFrom", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/writer.go#L320-L356
167,077
gobwas/ws
wsutil/writer.go
FlushFragment
func (w *Writer) FlushFragment() error { if w.Buffered() == 0 || w.err != nil { return w.err } w.err = w.flushFragment(false) w.n = 0 w.fragmented = true return w.err }
go
func (w *Writer) FlushFragment() error { if w.Buffered() == 0 || w.err != nil { return w.err } w.err = w.flushFragment(false) w.n = 0 w.fragmented = true return w.err }
[ "func", "(", "w", "*", "Writer", ")", "FlushFragment", "(", ")", "error", "{", "if", "w", ".", "Buffered", "(", ")", "==", "0", "||", "w", ".", "err", "!=", "nil", "{", "return", "w", ".", "err", "\n", "}", "\n\n", "w", ".", "err", "=", "w", ".", "flushFragment", "(", "false", ")", "\n", "w", ".", "n", "=", "0", "\n", "w", ".", "fragmented", "=", "true", "\n\n", "return", "w", ".", "err", "\n", "}" ]
// FlushFragment writes any buffered data to the underlying io.Writer. // It sends the frame with "fin" flag set to false.
[ "FlushFragment", "writes", "any", "buffered", "data", "to", "the", "underlying", "io", ".", "Writer", ".", "It", "sends", "the", "frame", "with", "fin", "flag", "set", "to", "false", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/writer.go#L377-L387
167,078
gobwas/ws
wsutil/handler.go
Handle
func (c ControlHandler) Handle(h ws.Header) error { switch h.OpCode { case ws.OpPing: return c.HandlePing(h) case ws.OpPong: return c.HandlePong(h) case ws.OpClose: return c.HandleClose(h) } return ErrNotControlFrame }
go
func (c ControlHandler) Handle(h ws.Header) error { switch h.OpCode { case ws.OpPing: return c.HandlePing(h) case ws.OpPong: return c.HandlePong(h) case ws.OpClose: return c.HandleClose(h) } return ErrNotControlFrame }
[ "func", "(", "c", "ControlHandler", ")", "Handle", "(", "h", "ws", ".", "Header", ")", "error", "{", "switch", "h", ".", "OpCode", "{", "case", "ws", ".", "OpPing", ":", "return", "c", ".", "HandlePing", "(", "h", ")", "\n", "case", "ws", ".", "OpPong", ":", "return", "c", ".", "HandlePong", "(", "h", ")", "\n", "case", "ws", ".", "OpClose", ":", "return", "c", ".", "HandleClose", "(", "h", ")", "\n", "}", "\n", "return", "ErrNotControlFrame", "\n", "}" ]
// Handle handles control framse regarding to the c.State and writes responses // to the c.Dst when needed. // // It returns ErrNotControlFrame when given header is not of ws.OpClose, // ws.OpPing or ws.OpPong operation code.
[ "Handle", "handles", "control", "framse", "regarding", "to", "the", "c", ".", "State", "and", "writes", "responses", "to", "the", "c", ".", "Dst", "when", "needed", ".", "It", "returns", "ErrNotControlFrame", "when", "given", "header", "is", "not", "of", "ws", ".", "OpClose", "ws", ".", "OpPing", "or", "ws", ".", "OpPong", "operation", "code", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/handler.go#L57-L67
167,079
gobwas/ws
wsutil/handler.go
HandlePing
func (c ControlHandler) HandlePing(h ws.Header) error { if h.Length == 0 { // The most common case when ping is empty. // Note that when sending masked frame the mask for empty payload is // just four zero bytes. return ws.WriteHeader(c.Dst, ws.Header{ Fin: true, OpCode: ws.OpPong, Masked: c.State.ClientSide(), }) } // In other way reply with Pong frame with copied payload. p := pbytes.GetLen(int(h.Length) + ws.HeaderSize(ws.Header{ Length: h.Length, Masked: c.State.ClientSide(), })) defer pbytes.Put(p) // Deal with ciphering i/o: // Masking key is used to mask the "Payload data" defined in the same // section as frame-payload-data, which includes "Extension data" and // "Application data". // // See https://tools.ietf.org/html/rfc6455#section-5.3 // // NOTE: We prefer ControlWriter with preallocated buffer to // ws.WriteHeader because it performs one syscall instead of two. w := NewControlWriterBuffer(c.Dst, c.State, ws.OpPong, p) r := c.Src if c.State.ServerSide() && !c.DisableSrcCiphering { r = NewCipherReader(r, h.Mask) } _, err := io.Copy(w, r) if err == nil { err = w.Flush() } return err }
go
func (c ControlHandler) HandlePing(h ws.Header) error { if h.Length == 0 { // The most common case when ping is empty. // Note that when sending masked frame the mask for empty payload is // just four zero bytes. return ws.WriteHeader(c.Dst, ws.Header{ Fin: true, OpCode: ws.OpPong, Masked: c.State.ClientSide(), }) } // In other way reply with Pong frame with copied payload. p := pbytes.GetLen(int(h.Length) + ws.HeaderSize(ws.Header{ Length: h.Length, Masked: c.State.ClientSide(), })) defer pbytes.Put(p) // Deal with ciphering i/o: // Masking key is used to mask the "Payload data" defined in the same // section as frame-payload-data, which includes "Extension data" and // "Application data". // // See https://tools.ietf.org/html/rfc6455#section-5.3 // // NOTE: We prefer ControlWriter with preallocated buffer to // ws.WriteHeader because it performs one syscall instead of two. w := NewControlWriterBuffer(c.Dst, c.State, ws.OpPong, p) r := c.Src if c.State.ServerSide() && !c.DisableSrcCiphering { r = NewCipherReader(r, h.Mask) } _, err := io.Copy(w, r) if err == nil { err = w.Flush() } return err }
[ "func", "(", "c", "ControlHandler", ")", "HandlePing", "(", "h", "ws", ".", "Header", ")", "error", "{", "if", "h", ".", "Length", "==", "0", "{", "// The most common case when ping is empty.", "// Note that when sending masked frame the mask for empty payload is", "// just four zero bytes.", "return", "ws", ".", "WriteHeader", "(", "c", ".", "Dst", ",", "ws", ".", "Header", "{", "Fin", ":", "true", ",", "OpCode", ":", "ws", ".", "OpPong", ",", "Masked", ":", "c", ".", "State", ".", "ClientSide", "(", ")", ",", "}", ")", "\n", "}", "\n\n", "// In other way reply with Pong frame with copied payload.", "p", ":=", "pbytes", ".", "GetLen", "(", "int", "(", "h", ".", "Length", ")", "+", "ws", ".", "HeaderSize", "(", "ws", ".", "Header", "{", "Length", ":", "h", ".", "Length", ",", "Masked", ":", "c", ".", "State", ".", "ClientSide", "(", ")", ",", "}", ")", ")", "\n", "defer", "pbytes", ".", "Put", "(", "p", ")", "\n\n", "// Deal with ciphering i/o:", "// Masking key is used to mask the \"Payload data\" defined in the same", "// section as frame-payload-data, which includes \"Extension data\" and", "// \"Application data\".", "//", "// See https://tools.ietf.org/html/rfc6455#section-5.3", "//", "// NOTE: We prefer ControlWriter with preallocated buffer to", "// ws.WriteHeader because it performs one syscall instead of two.", "w", ":=", "NewControlWriterBuffer", "(", "c", ".", "Dst", ",", "c", ".", "State", ",", "ws", ".", "OpPong", ",", "p", ")", "\n", "r", ":=", "c", ".", "Src", "\n", "if", "c", ".", "State", ".", "ServerSide", "(", ")", "&&", "!", "c", ".", "DisableSrcCiphering", "{", "r", "=", "NewCipherReader", "(", "r", ",", "h", ".", "Mask", ")", "\n", "}", "\n\n", "_", ",", "err", ":=", "io", ".", "Copy", "(", "w", ",", "r", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "w", ".", "Flush", "(", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// HandlePing handles ping frame and writes specification compatible response // to the c.Dst.
[ "HandlePing", "handles", "ping", "frame", "and", "writes", "specification", "compatible", "response", "to", "the", "c", ".", "Dst", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/handler.go#L71-L111
167,080
gobwas/ws
wsutil/handler.go
HandlePong
func (c ControlHandler) HandlePong(h ws.Header) error { if h.Length == 0 { return nil } buf := pbytes.GetLen(int(h.Length)) defer pbytes.Put(buf) // Discard pong message according to the RFC6455: // A Pong frame MAY be sent unsolicited. This serves as a // unidirectional heartbeat. A response to an unsolicited Pong frame // is not expected. _, err := io.CopyBuffer(ioutil.Discard, c.Src, buf) return err }
go
func (c ControlHandler) HandlePong(h ws.Header) error { if h.Length == 0 { return nil } buf := pbytes.GetLen(int(h.Length)) defer pbytes.Put(buf) // Discard pong message according to the RFC6455: // A Pong frame MAY be sent unsolicited. This serves as a // unidirectional heartbeat. A response to an unsolicited Pong frame // is not expected. _, err := io.CopyBuffer(ioutil.Discard, c.Src, buf) return err }
[ "func", "(", "c", "ControlHandler", ")", "HandlePong", "(", "h", "ws", ".", "Header", ")", "error", "{", "if", "h", ".", "Length", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "buf", ":=", "pbytes", ".", "GetLen", "(", "int", "(", "h", ".", "Length", ")", ")", "\n", "defer", "pbytes", ".", "Put", "(", "buf", ")", "\n\n", "// Discard pong message according to the RFC6455:", "// A Pong frame MAY be sent unsolicited. This serves as a", "// unidirectional heartbeat. A response to an unsolicited Pong frame", "// is not expected.", "_", ",", "err", ":=", "io", ".", "CopyBuffer", "(", "ioutil", ".", "Discard", ",", "c", ".", "Src", ",", "buf", ")", "\n\n", "return", "err", "\n", "}" ]
// HandlePong handles pong frame by discarding it.
[ "HandlePong", "handles", "pong", "frame", "by", "discarding", "it", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/handler.go#L114-L129
167,081
gobwas/ws
wsutil/handler.go
HandleClose
func (c ControlHandler) HandleClose(h ws.Header) error { if h.Length == 0 { err := ws.WriteHeader(c.Dst, ws.Header{ Fin: true, OpCode: ws.OpClose, Masked: c.State.ClientSide(), }) if err != nil { return err } // Due to RFC, we should interpret the code as no status code // received: // If this Close control frame contains no status code, _The WebSocket // Connection Close Code_ is considered to be 1005. // // See https://tools.ietf.org/html/rfc6455#section-7.1.5 return ClosedError{ Code: ws.StatusNoStatusRcvd, } } // Prepare bytes both for reading reason and sending response. p := pbytes.GetLen(int(h.Length) + ws.HeaderSize(ws.Header{ Length: h.Length, Masked: c.State.ClientSide(), })) defer pbytes.Put(p) // Get the subslice to read the frame payload out. subp := p[:h.Length] r := c.Src if c.State.ServerSide() && !c.DisableSrcCiphering { r = NewCipherReader(r, h.Mask) } if _, err := io.ReadFull(r, subp); err != nil { return err } code, reason := ws.ParseCloseFrameData(subp) if err := ws.CheckCloseFrameData(code, reason); err != nil { // Here we could not use the prepared bytes because there is no // guarantee that it may fit our protocol error closure code and a // reason. c.closeWithProtocolError(err) return err } // Deal with ciphering i/o: // Masking key is used to mask the "Payload data" defined in the same // section as frame-payload-data, which includes "Extension data" and // "Application data". // // See https://tools.ietf.org/html/rfc6455#section-5.3 // // NOTE: We prefer ControlWriter with preallocated buffer to // ws.WriteHeader because it performs one syscall instead of two. w := NewControlWriterBuffer(c.Dst, c.State, ws.OpClose, p) // RFC6455#5.5.1: // If an endpoint receives a Close frame and did not previously // send a Close frame, the endpoint MUST send a Close frame in // response. (When sending a Close frame in response, the endpoint // typically echos the status code it received.) _, err := w.Write(p[:2]) if err != nil { return err } if err = w.Flush(); err != nil { return err } return ClosedError{ Code: code, Reason: reason, } }
go
func (c ControlHandler) HandleClose(h ws.Header) error { if h.Length == 0 { err := ws.WriteHeader(c.Dst, ws.Header{ Fin: true, OpCode: ws.OpClose, Masked: c.State.ClientSide(), }) if err != nil { return err } // Due to RFC, we should interpret the code as no status code // received: // If this Close control frame contains no status code, _The WebSocket // Connection Close Code_ is considered to be 1005. // // See https://tools.ietf.org/html/rfc6455#section-7.1.5 return ClosedError{ Code: ws.StatusNoStatusRcvd, } } // Prepare bytes both for reading reason and sending response. p := pbytes.GetLen(int(h.Length) + ws.HeaderSize(ws.Header{ Length: h.Length, Masked: c.State.ClientSide(), })) defer pbytes.Put(p) // Get the subslice to read the frame payload out. subp := p[:h.Length] r := c.Src if c.State.ServerSide() && !c.DisableSrcCiphering { r = NewCipherReader(r, h.Mask) } if _, err := io.ReadFull(r, subp); err != nil { return err } code, reason := ws.ParseCloseFrameData(subp) if err := ws.CheckCloseFrameData(code, reason); err != nil { // Here we could not use the prepared bytes because there is no // guarantee that it may fit our protocol error closure code and a // reason. c.closeWithProtocolError(err) return err } // Deal with ciphering i/o: // Masking key is used to mask the "Payload data" defined in the same // section as frame-payload-data, which includes "Extension data" and // "Application data". // // See https://tools.ietf.org/html/rfc6455#section-5.3 // // NOTE: We prefer ControlWriter with preallocated buffer to // ws.WriteHeader because it performs one syscall instead of two. w := NewControlWriterBuffer(c.Dst, c.State, ws.OpClose, p) // RFC6455#5.5.1: // If an endpoint receives a Close frame and did not previously // send a Close frame, the endpoint MUST send a Close frame in // response. (When sending a Close frame in response, the endpoint // typically echos the status code it received.) _, err := w.Write(p[:2]) if err != nil { return err } if err = w.Flush(); err != nil { return err } return ClosedError{ Code: code, Reason: reason, } }
[ "func", "(", "c", "ControlHandler", ")", "HandleClose", "(", "h", "ws", ".", "Header", ")", "error", "{", "if", "h", ".", "Length", "==", "0", "{", "err", ":=", "ws", ".", "WriteHeader", "(", "c", ".", "Dst", ",", "ws", ".", "Header", "{", "Fin", ":", "true", ",", "OpCode", ":", "ws", ".", "OpClose", ",", "Masked", ":", "c", ".", "State", ".", "ClientSide", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Due to RFC, we should interpret the code as no status code", "// received:", "// If this Close control frame contains no status code, _The WebSocket", "// Connection Close Code_ is considered to be 1005.", "//", "// See https://tools.ietf.org/html/rfc6455#section-7.1.5", "return", "ClosedError", "{", "Code", ":", "ws", ".", "StatusNoStatusRcvd", ",", "}", "\n", "}", "\n\n", "// Prepare bytes both for reading reason and sending response.", "p", ":=", "pbytes", ".", "GetLen", "(", "int", "(", "h", ".", "Length", ")", "+", "ws", ".", "HeaderSize", "(", "ws", ".", "Header", "{", "Length", ":", "h", ".", "Length", ",", "Masked", ":", "c", ".", "State", ".", "ClientSide", "(", ")", ",", "}", ")", ")", "\n", "defer", "pbytes", ".", "Put", "(", "p", ")", "\n\n", "// Get the subslice to read the frame payload out.", "subp", ":=", "p", "[", ":", "h", ".", "Length", "]", "\n\n", "r", ":=", "c", ".", "Src", "\n", "if", "c", ".", "State", ".", "ServerSide", "(", ")", "&&", "!", "c", ".", "DisableSrcCiphering", "{", "r", "=", "NewCipherReader", "(", "r", ",", "h", ".", "Mask", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "subp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "code", ",", "reason", ":=", "ws", ".", "ParseCloseFrameData", "(", "subp", ")", "\n", "if", "err", ":=", "ws", ".", "CheckCloseFrameData", "(", "code", ",", "reason", ")", ";", "err", "!=", "nil", "{", "// Here we could not use the prepared bytes because there is no", "// guarantee that it may fit our protocol error closure code and a", "// reason.", "c", ".", "closeWithProtocolError", "(", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "// Deal with ciphering i/o:", "// Masking key is used to mask the \"Payload data\" defined in the same", "// section as frame-payload-data, which includes \"Extension data\" and", "// \"Application data\".", "//", "// See https://tools.ietf.org/html/rfc6455#section-5.3", "//", "// NOTE: We prefer ControlWriter with preallocated buffer to", "// ws.WriteHeader because it performs one syscall instead of two.", "w", ":=", "NewControlWriterBuffer", "(", "c", ".", "Dst", ",", "c", ".", "State", ",", "ws", ".", "OpClose", ",", "p", ")", "\n\n", "// RFC6455#5.5.1:", "// If an endpoint receives a Close frame and did not previously", "// send a Close frame, the endpoint MUST send a Close frame in", "// response. (When sending a Close frame in response, the endpoint", "// typically echos the status code it received.)", "_", ",", "err", ":=", "w", ".", "Write", "(", "p", "[", ":", "2", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "w", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ClosedError", "{", "Code", ":", "code", ",", "Reason", ":", "reason", ",", "}", "\n", "}" ]
// HandleClose handles close frame, makes protocol validity checks and writes // specification compatible response to the c.Dst.
[ "HandleClose", "handles", "close", "frame", "makes", "protocol", "validity", "checks", "and", "writes", "specification", "compatible", "response", "to", "the", "c", ".", "Dst", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/handler.go#L133-L209
167,082
gobwas/ws
errors.go
RejectConnectionError
func RejectConnectionError(options ...RejectOption) error { err := new(rejectConnectionError) for _, opt := range options { opt(err) } return err }
go
func RejectConnectionError(options ...RejectOption) error { err := new(rejectConnectionError) for _, opt := range options { opt(err) } return err }
[ "func", "RejectConnectionError", "(", "options", "...", "RejectOption", ")", "error", "{", "err", ":=", "new", "(", "rejectConnectionError", ")", "\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "opt", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// RejectConnectionError constructs an error that could be used to control the way // handshake is rejected by Upgrader.
[ "RejectConnectionError", "constructs", "an", "error", "that", "could", "be", "used", "to", "control", "the", "way", "handshake", "is", "rejected", "by", "Upgrader", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/errors.go#L33-L39
167,083
gobwas/ws
util.go
asciiToInt
func asciiToInt(bts []byte) (ret int, err error) { // ASCII numbers all start with the high-order bits 0011. // If you see that, and the next bits are 0-9 (0000 - 1001) you can grab those // bits and interpret them directly as an integer. var n int if n = len(bts); n < 1 { return 0, fmt.Errorf("converting empty bytes to int") } for i := 0; i < n; i++ { if bts[i]&0xf0 != 0x30 { return 0, fmt.Errorf("%s is not a numeric character", string(bts[i])) } ret += int(bts[i]&0xf) * pow(10, n-i-1) } return ret, nil }
go
func asciiToInt(bts []byte) (ret int, err error) { // ASCII numbers all start with the high-order bits 0011. // If you see that, and the next bits are 0-9 (0000 - 1001) you can grab those // bits and interpret them directly as an integer. var n int if n = len(bts); n < 1 { return 0, fmt.Errorf("converting empty bytes to int") } for i := 0; i < n; i++ { if bts[i]&0xf0 != 0x30 { return 0, fmt.Errorf("%s is not a numeric character", string(bts[i])) } ret += int(bts[i]&0xf) * pow(10, n-i-1) } return ret, nil }
[ "func", "asciiToInt", "(", "bts", "[", "]", "byte", ")", "(", "ret", "int", ",", "err", "error", ")", "{", "// ASCII numbers all start with the high-order bits 0011.", "// If you see that, and the next bits are 0-9 (0000 - 1001) you can grab those", "// bits and interpret them directly as an integer.", "var", "n", "int", "\n", "if", "n", "=", "len", "(", "bts", ")", ";", "n", "<", "1", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "if", "bts", "[", "i", "]", "&", "0xf0", "!=", "0x30", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "bts", "[", "i", "]", ")", ")", "\n", "}", "\n", "ret", "+=", "int", "(", "bts", "[", "i", "]", "&", "0xf", ")", "*", "pow", "(", "10", ",", "n", "-", "i", "-", "1", ")", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// asciiToInt converts bytes to int.
[ "asciiToInt", "converts", "bytes", "to", "int", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/util.go#L57-L72
167,084
gobwas/ws
util.go
pow
func pow(a, b int) int { p := 1 for b > 0 { if b&1 != 0 { p *= a } b >>= 1 a *= a } return p }
go
func pow(a, b int) int { p := 1 for b > 0 { if b&1 != 0 { p *= a } b >>= 1 a *= a } return p }
[ "func", "pow", "(", "a", ",", "b", "int", ")", "int", "{", "p", ":=", "1", "\n", "for", "b", ">", "0", "{", "if", "b", "&", "1", "!=", "0", "{", "p", "*=", "a", "\n", "}", "\n", "b", ">>=", "1", "\n", "a", "*=", "a", "\n", "}", "\n", "return", "p", "\n", "}" ]
// pow for integers implementation. // See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3
[ "pow", "for", "integers", "implementation", ".", "See", "Donald", "Knuth", "The", "Art", "of", "Computer", "Programming", "Volume", "2", "Section", "4", ".", "6", ".", "3" ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/util.go#L76-L86
167,085
gobwas/ws
frame.go
In
func (s StatusCode) In(r StatusCodeRange) bool { return r.Min <= s && s <= r.Max }
go
func (s StatusCode) In(r StatusCodeRange) bool { return r.Min <= s && s <= r.Max }
[ "func", "(", "s", "StatusCode", ")", "In", "(", "r", "StatusCodeRange", ")", "bool", "{", "return", "r", ".", "Min", "<=", "s", "&&", "s", "<=", "r", ".", "Max", "\n", "}" ]
// In reports whether the code is defined in given range.
[ "In", "reports", "whether", "the", "code", "is", "defined", "in", "given", "range", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L104-L106
167,086
gobwas/ws
frame.go
IsProtocolDefined
func (s StatusCode) IsProtocolDefined() bool { switch s { case StatusNormalClosure, StatusGoingAway, StatusProtocolError, StatusUnsupportedData, StatusInvalidFramePayloadData, StatusPolicyViolation, StatusMessageTooBig, StatusMandatoryExt, StatusInternalServerError, StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: return true } return false }
go
func (s StatusCode) IsProtocolDefined() bool { switch s { case StatusNormalClosure, StatusGoingAway, StatusProtocolError, StatusUnsupportedData, StatusInvalidFramePayloadData, StatusPolicyViolation, StatusMessageTooBig, StatusMandatoryExt, StatusInternalServerError, StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: return true } return false }
[ "func", "(", "s", "StatusCode", ")", "IsProtocolDefined", "(", ")", "bool", "{", "switch", "s", "{", "case", "StatusNormalClosure", ",", "StatusGoingAway", ",", "StatusProtocolError", ",", "StatusUnsupportedData", ",", "StatusInvalidFramePayloadData", ",", "StatusPolicyViolation", ",", "StatusMessageTooBig", ",", "StatusMandatoryExt", ",", "StatusInternalServerError", ",", "StatusNoStatusRcvd", ",", "StatusAbnormalClosure", ",", "StatusTLSHandshake", ":", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsProtocolDefined reports whether the code is already defined by protocol specification.
[ "IsProtocolDefined", "reports", "whether", "the", "code", "is", "already", "defined", "by", "protocol", "specification", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L137-L154
167,087
gobwas/ws
frame.go
IsProtocolReserved
func (s StatusCode) IsProtocolReserved() bool { switch s { // [RFC6455]: {1005,1006,1015} is a reserved value and MUST NOT be set as a status code in a // Close control frame by an endpoint. case StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: return true default: return false } }
go
func (s StatusCode) IsProtocolReserved() bool { switch s { // [RFC6455]: {1005,1006,1015} is a reserved value and MUST NOT be set as a status code in a // Close control frame by an endpoint. case StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: return true default: return false } }
[ "func", "(", "s", "StatusCode", ")", "IsProtocolReserved", "(", ")", "bool", "{", "switch", "s", "{", "// [RFC6455]: {1005,1006,1015} is a reserved value and MUST NOT be set as a status code in a", "// Close control frame by an endpoint.", "case", "StatusNoStatusRcvd", ",", "StatusAbnormalClosure", ",", "StatusTLSHandshake", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsProtocolReserved reports whether the code is defined by protocol specification // to be reserved only for application usage purpose.
[ "IsProtocolReserved", "reports", "whether", "the", "code", "is", "defined", "by", "protocol", "specification", "to", "be", "reserved", "only", "for", "application", "usage", "purpose", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L158-L167
167,088
gobwas/ws
frame.go
NewFrame
func NewFrame(op OpCode, fin bool, p []byte) Frame { return Frame{ Header: Header{ Fin: fin, OpCode: op, Length: int64(len(p)), }, Payload: p, } }
go
func NewFrame(op OpCode, fin bool, p []byte) Frame { return Frame{ Header: Header{ Fin: fin, OpCode: op, Length: int64(len(p)), }, Payload: p, } }
[ "func", "NewFrame", "(", "op", "OpCode", ",", "fin", "bool", ",", "p", "[", "]", "byte", ")", "Frame", "{", "return", "Frame", "{", "Header", ":", "Header", "{", "Fin", ":", "fin", ",", "OpCode", ":", "op", ",", "Length", ":", "int64", "(", "len", "(", "p", ")", ")", ",", "}", ",", "Payload", ":", "p", ",", "}", "\n", "}" ]
// NewFrame creates frame with given operation code, // flag of completeness and payload bytes.
[ "NewFrame", "creates", "frame", "with", "given", "operation", "code", "flag", "of", "completeness", "and", "payload", "bytes", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L218-L227
167,089
gobwas/ws
frame.go
PutCloseFrameBody
func PutCloseFrameBody(p []byte, code StatusCode, reason string) { _ = p[1+len(reason)] binary.BigEndian.PutUint16(p, uint16(code)) copy(p[2:], reason) }
go
func PutCloseFrameBody(p []byte, code StatusCode, reason string) { _ = p[1+len(reason)] binary.BigEndian.PutUint16(p, uint16(code)) copy(p[2:], reason) }
[ "func", "PutCloseFrameBody", "(", "p", "[", "]", "byte", ",", "code", "StatusCode", ",", "reason", "string", ")", "{", "_", "=", "p", "[", "1", "+", "len", "(", "reason", ")", "]", "\n", "binary", ".", "BigEndian", ".", "PutUint16", "(", "p", ",", "uint16", "(", "code", ")", ")", "\n", "copy", "(", "p", "[", "2", ":", "]", ",", "reason", ")", "\n", "}" ]
// PutCloseFrameBody encodes code and reason into buf. // // It will panic if the buffer is too small to accommodate a code or a reason. // // PutCloseFrameBody does not check buffer to be RFC compliant, but note that // by RFC it must be at most MaxControlFramePayloadSize.
[ "PutCloseFrameBody", "encodes", "code", "and", "reason", "into", "buf", ".", "It", "will", "panic", "if", "the", "buffer", "is", "too", "small", "to", "accommodate", "a", "code", "or", "a", "reason", ".", "PutCloseFrameBody", "does", "not", "check", "buffer", "to", "be", "RFC", "compliant", "but", "note", "that", "by", "RFC", "it", "must", "be", "at", "most", "MaxControlFramePayloadSize", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L289-L293
167,090
gobwas/ws
frame.go
MaskFrameWith
func MaskFrameWith(f Frame, mask [4]byte) Frame { // TODO(gobwas): check CopyCipher ws copy() Cipher(). p := make([]byte, len(f.Payload)) copy(p, f.Payload) f.Payload = p return MaskFrameInPlaceWith(f, mask) }
go
func MaskFrameWith(f Frame, mask [4]byte) Frame { // TODO(gobwas): check CopyCipher ws copy() Cipher(). p := make([]byte, len(f.Payload)) copy(p, f.Payload) f.Payload = p return MaskFrameInPlaceWith(f, mask) }
[ "func", "MaskFrameWith", "(", "f", "Frame", ",", "mask", "[", "4", "]", "byte", ")", "Frame", "{", "// TODO(gobwas): check CopyCipher ws copy() Cipher().", "p", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "f", ".", "Payload", ")", ")", "\n", "copy", "(", "p", ",", "f", ".", "Payload", ")", "\n", "f", ".", "Payload", "=", "p", "\n", "return", "MaskFrameInPlaceWith", "(", "f", ",", "mask", ")", "\n", "}" ]
// MaskFrameWith masks frame with given mask and returns frame // with masked payload and Mask header's field set. // Note that it copies f payload to prevent collisions. // For less allocations you could use MaskFrameInPlaceWith or construct frame manually.
[ "MaskFrameWith", "masks", "frame", "with", "given", "mask", "and", "returns", "frame", "with", "masked", "payload", "and", "Mask", "header", "s", "field", "set", ".", "Note", "that", "it", "copies", "f", "payload", "to", "prevent", "collisions", ".", "For", "less", "allocations", "you", "could", "use", "MaskFrameInPlaceWith", "or", "construct", "frame", "manually", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L306-L312
167,091
gobwas/ws
frame.go
MaskFrameInPlaceWith
func MaskFrameInPlaceWith(f Frame, m [4]byte) Frame { f.Header.Masked = true f.Header.Mask = m Cipher(f.Payload, m, 0) return f }
go
func MaskFrameInPlaceWith(f Frame, m [4]byte) Frame { f.Header.Masked = true f.Header.Mask = m Cipher(f.Payload, m, 0) return f }
[ "func", "MaskFrameInPlaceWith", "(", "f", "Frame", ",", "m", "[", "4", "]", "byte", ")", "Frame", "{", "f", ".", "Header", ".", "Masked", "=", "true", "\n", "f", ".", "Header", ".", "Mask", "=", "m", "\n", "Cipher", "(", "f", ".", "Payload", ",", "m", ",", "0", ")", "\n", "return", "f", "\n", "}" ]
// MaskFrameInPlaceWith masks frame with given mask and returns frame // with masked payload and Mask header's field set. // Note that it applies xor cipher to f.Payload without copying, that is, it // modifies f.Payload inplace.
[ "MaskFrameInPlaceWith", "masks", "frame", "with", "given", "mask", "and", "returns", "frame", "with", "masked", "payload", "and", "Mask", "header", "s", "field", "set", ".", "Note", "that", "it", "applies", "xor", "cipher", "to", "f", ".", "Payload", "without", "copying", "that", "is", "it", "modifies", "f", ".", "Payload", "inplace", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L326-L331
167,092
gobwas/ws
frame.go
CompileFrame
func CompileFrame(f Frame) (bts []byte, err error) { buf := bytes.NewBuffer(make([]byte, 0, 16)) err = WriteFrame(buf, f) bts = buf.Bytes() return }
go
func CompileFrame(f Frame) (bts []byte, err error) { buf := bytes.NewBuffer(make([]byte, 0, 16)) err = WriteFrame(buf, f) bts = buf.Bytes() return }
[ "func", "CompileFrame", "(", "f", "Frame", ")", "(", "bts", "[", "]", "byte", ",", "err", "error", ")", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "16", ")", ")", "\n", "err", "=", "WriteFrame", "(", "buf", ",", "f", ")", "\n", "bts", "=", "buf", ".", "Bytes", "(", ")", "\n", "return", "\n", "}" ]
// CompileFrame returns byte representation of given frame. // In terms of memory consumption it is useful to precompile static frames // which are often used.
[ "CompileFrame", "returns", "byte", "representation", "of", "given", "frame", ".", "In", "terms", "of", "memory", "consumption", "it", "is", "useful", "to", "precompile", "static", "frames", "which", "are", "often", "used", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L342-L347
167,093
gobwas/ws
frame.go
MustCompileFrame
func MustCompileFrame(f Frame) []byte { bts, err := CompileFrame(f) if err != nil { panic(err) } return bts }
go
func MustCompileFrame(f Frame) []byte { bts, err := CompileFrame(f) if err != nil { panic(err) } return bts }
[ "func", "MustCompileFrame", "(", "f", "Frame", ")", "[", "]", "byte", "{", "bts", ",", "err", ":=", "CompileFrame", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "bts", "\n", "}" ]
// MustCompileFrame is like CompileFrame but panics if frame can not be // encoded.
[ "MustCompileFrame", "is", "like", "CompileFrame", "but", "panics", "if", "frame", "can", "not", "be", "encoded", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L351-L357
167,094
gobwas/ws
frame.go
Rsv
func Rsv(r1, r2, r3 bool) (rsv byte) { if r1 { rsv |= bit5 } if r2 { rsv |= bit6 } if r3 { rsv |= bit7 } return rsv }
go
func Rsv(r1, r2, r3 bool) (rsv byte) { if r1 { rsv |= bit5 } if r2 { rsv |= bit6 } if r3 { rsv |= bit7 } return rsv }
[ "func", "Rsv", "(", "r1", ",", "r2", ",", "r3", "bool", ")", "(", "rsv", "byte", ")", "{", "if", "r1", "{", "rsv", "|=", "bit5", "\n", "}", "\n", "if", "r2", "{", "rsv", "|=", "bit6", "\n", "}", "\n", "if", "r3", "{", "rsv", "|=", "bit7", "\n", "}", "\n", "return", "rsv", "\n", "}" ]
// Rsv creates rsv byte representation.
[ "Rsv", "creates", "rsv", "byte", "representation", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/frame.go#L360-L371
167,095
gobwas/ws
read.go
ReadHeader
func ReadHeader(r io.Reader) (h Header, err error) { // Make slice of bytes with capacity 12 that could hold any header. // // The maximum header size is 14, but due to the 2 hop reads, // after first hop that reads first 2 constant bytes, we could reuse 2 bytes. // So 14 - 2 = 12. // // We use unsafe to stick bts to stack and avoid allocations. // // Using stack based slice is safe here, cause golang docs for io.Reader // says that "Implementations must not retain p". // See https://golang.org/pkg/io/#Reader var b [MaxHeaderSize - 2]byte bp := uintptr(unsafe.Pointer(&b)) bh := &reflect.SliceHeader{Data: bp, Len: 2, Cap: MaxHeaderSize - 2} bts := *(*[]byte)(unsafe.Pointer(bh)) // Prepare to hold first 2 bytes to choose size of next read. _, err = io.ReadFull(r, bts) if err != nil { return } h.Fin = bts[0]&bit0 != 0 h.Rsv = (bts[0] & 0x70) >> 4 h.OpCode = OpCode(bts[0] & 0x0f) var extra int if bts[1]&bit0 != 0 { h.Masked = true extra += 4 } length := bts[1] & 0x7f switch { case length < 126: h.Length = int64(length) case length == 126: extra += 2 case length == 127: extra += 8 default: err = ErrHeaderLengthUnexpected return } if extra == 0 { return } // Increase len of bts to extra bytes need to read. // Overwrite frist 2 bytes read before. bts = bts[:extra] _, err = io.ReadFull(r, bts) if err != nil { return } switch { case length == 126: h.Length = int64(binary.BigEndian.Uint16(bts[:2])) bts = bts[2:] case length == 127: if bts[0]&0x80 != 0 { err = ErrHeaderLengthMSB return } h.Length = int64(binary.BigEndian.Uint64(bts[:8])) bts = bts[8:] } if h.Masked { copy(h.Mask[:], bts) } return }
go
func ReadHeader(r io.Reader) (h Header, err error) { // Make slice of bytes with capacity 12 that could hold any header. // // The maximum header size is 14, but due to the 2 hop reads, // after first hop that reads first 2 constant bytes, we could reuse 2 bytes. // So 14 - 2 = 12. // // We use unsafe to stick bts to stack and avoid allocations. // // Using stack based slice is safe here, cause golang docs for io.Reader // says that "Implementations must not retain p". // See https://golang.org/pkg/io/#Reader var b [MaxHeaderSize - 2]byte bp := uintptr(unsafe.Pointer(&b)) bh := &reflect.SliceHeader{Data: bp, Len: 2, Cap: MaxHeaderSize - 2} bts := *(*[]byte)(unsafe.Pointer(bh)) // Prepare to hold first 2 bytes to choose size of next read. _, err = io.ReadFull(r, bts) if err != nil { return } h.Fin = bts[0]&bit0 != 0 h.Rsv = (bts[0] & 0x70) >> 4 h.OpCode = OpCode(bts[0] & 0x0f) var extra int if bts[1]&bit0 != 0 { h.Masked = true extra += 4 } length := bts[1] & 0x7f switch { case length < 126: h.Length = int64(length) case length == 126: extra += 2 case length == 127: extra += 8 default: err = ErrHeaderLengthUnexpected return } if extra == 0 { return } // Increase len of bts to extra bytes need to read. // Overwrite frist 2 bytes read before. bts = bts[:extra] _, err = io.ReadFull(r, bts) if err != nil { return } switch { case length == 126: h.Length = int64(binary.BigEndian.Uint16(bts[:2])) bts = bts[2:] case length == 127: if bts[0]&0x80 != 0 { err = ErrHeaderLengthMSB return } h.Length = int64(binary.BigEndian.Uint64(bts[:8])) bts = bts[8:] } if h.Masked { copy(h.Mask[:], bts) } return }
[ "func", "ReadHeader", "(", "r", "io", ".", "Reader", ")", "(", "h", "Header", ",", "err", "error", ")", "{", "// Make slice of bytes with capacity 12 that could hold any header.", "//", "// The maximum header size is 14, but due to the 2 hop reads,", "// after first hop that reads first 2 constant bytes, we could reuse 2 bytes.", "// So 14 - 2 = 12.", "//", "// We use unsafe to stick bts to stack and avoid allocations.", "//", "// Using stack based slice is safe here, cause golang docs for io.Reader", "// says that \"Implementations must not retain p\".", "// See https://golang.org/pkg/io/#Reader", "var", "b", "[", "MaxHeaderSize", "-", "2", "]", "byte", "\n", "bp", ":=", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "b", ")", ")", "\n", "bh", ":=", "&", "reflect", ".", "SliceHeader", "{", "Data", ":", "bp", ",", "Len", ":", "2", ",", "Cap", ":", "MaxHeaderSize", "-", "2", "}", "\n", "bts", ":=", "*", "(", "*", "[", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "bh", ")", ")", "\n\n", "// Prepare to hold first 2 bytes to choose size of next read.", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "bts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "h", ".", "Fin", "=", "bts", "[", "0", "]", "&", "bit0", "!=", "0", "\n", "h", ".", "Rsv", "=", "(", "bts", "[", "0", "]", "&", "0x70", ")", ">>", "4", "\n", "h", ".", "OpCode", "=", "OpCode", "(", "bts", "[", "0", "]", "&", "0x0f", ")", "\n\n", "var", "extra", "int", "\n\n", "if", "bts", "[", "1", "]", "&", "bit0", "!=", "0", "{", "h", ".", "Masked", "=", "true", "\n", "extra", "+=", "4", "\n", "}", "\n\n", "length", ":=", "bts", "[", "1", "]", "&", "0x7f", "\n", "switch", "{", "case", "length", "<", "126", ":", "h", ".", "Length", "=", "int64", "(", "length", ")", "\n\n", "case", "length", "==", "126", ":", "extra", "+=", "2", "\n\n", "case", "length", "==", "127", ":", "extra", "+=", "8", "\n\n", "default", ":", "err", "=", "ErrHeaderLengthUnexpected", "\n", "return", "\n", "}", "\n\n", "if", "extra", "==", "0", "{", "return", "\n", "}", "\n\n", "// Increase len of bts to extra bytes need to read.", "// Overwrite frist 2 bytes read before.", "bts", "=", "bts", "[", ":", "extra", "]", "\n", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "bts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "switch", "{", "case", "length", "==", "126", ":", "h", ".", "Length", "=", "int64", "(", "binary", ".", "BigEndian", ".", "Uint16", "(", "bts", "[", ":", "2", "]", ")", ")", "\n", "bts", "=", "bts", "[", "2", ":", "]", "\n\n", "case", "length", "==", "127", ":", "if", "bts", "[", "0", "]", "&", "0x80", "!=", "0", "{", "err", "=", "ErrHeaderLengthMSB", "\n", "return", "\n", "}", "\n", "h", ".", "Length", "=", "int64", "(", "binary", ".", "BigEndian", ".", "Uint64", "(", "bts", "[", ":", "8", "]", ")", ")", "\n", "bts", "=", "bts", "[", "8", ":", "]", "\n", "}", "\n\n", "if", "h", ".", "Masked", "{", "copy", "(", "h", ".", "Mask", "[", ":", "]", ",", "bts", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// ReadHeader reads a frame header from r.
[ "ReadHeader", "reads", "a", "frame", "header", "from", "r", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/read.go#L18-L99
167,096
gobwas/ws
read.go
ReadFrame
func ReadFrame(r io.Reader) (f Frame, err error) { f.Header, err = ReadHeader(r) if err != nil { return } if f.Header.Length > 0 { // int(f.Header.Length) is safe here cause we have // checked it for overflow above in ReadHeader. f.Payload = make([]byte, int(f.Header.Length)) _, err = io.ReadFull(r, f.Payload) } return }
go
func ReadFrame(r io.Reader) (f Frame, err error) { f.Header, err = ReadHeader(r) if err != nil { return } if f.Header.Length > 0 { // int(f.Header.Length) is safe here cause we have // checked it for overflow above in ReadHeader. f.Payload = make([]byte, int(f.Header.Length)) _, err = io.ReadFull(r, f.Payload) } return }
[ "func", "ReadFrame", "(", "r", "io", ".", "Reader", ")", "(", "f", "Frame", ",", "err", "error", ")", "{", "f", ".", "Header", ",", "err", "=", "ReadHeader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "f", ".", "Header", ".", "Length", ">", "0", "{", "// int(f.Header.Length) is safe here cause we have", "// checked it for overflow above in ReadHeader.", "f", ".", "Payload", "=", "make", "(", "[", "]", "byte", ",", "int", "(", "f", ".", "Header", ".", "Length", ")", ")", "\n", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "f", ".", "Payload", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// ReadFrame reads a frame from r. // It is not designed for high optimized use case cause it makes allocation // for frame.Header.Length size inside to read frame payload into. // // Note that ReadFrame does not unmask payload.
[ "ReadFrame", "reads", "a", "frame", "from", "r", ".", "It", "is", "not", "designed", "for", "high", "optimized", "use", "case", "cause", "it", "makes", "allocation", "for", "frame", ".", "Header", ".", "Length", "size", "inside", "to", "read", "frame", "payload", "into", ".", "Note", "that", "ReadFrame", "does", "not", "unmask", "payload", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/read.go#L106-L120
167,097
gobwas/ws
read.go
MustReadFrame
func MustReadFrame(r io.Reader) Frame { f, err := ReadFrame(r) if err != nil { panic(err) } return f }
go
func MustReadFrame(r io.Reader) Frame { f, err := ReadFrame(r) if err != nil { panic(err) } return f }
[ "func", "MustReadFrame", "(", "r", "io", ".", "Reader", ")", "Frame", "{", "f", ",", "err", ":=", "ReadFrame", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "f", "\n", "}" ]
// MustReadFrame is like ReadFrame but panics if frame can not be read.
[ "MustReadFrame", "is", "like", "ReadFrame", "but", "panics", "if", "frame", "can", "not", "be", "read", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/read.go#L123-L129
167,098
gobwas/ws
read.go
ParseCloseFrameDataUnsafe
func ParseCloseFrameDataUnsafe(payload []byte) (code StatusCode, reason string) { if len(payload) < 2 { return } code = StatusCode(binary.BigEndian.Uint16(payload)) reason = btsToString(payload[2:]) return }
go
func ParseCloseFrameDataUnsafe(payload []byte) (code StatusCode, reason string) { if len(payload) < 2 { return } code = StatusCode(binary.BigEndian.Uint16(payload)) reason = btsToString(payload[2:]) return }
[ "func", "ParseCloseFrameDataUnsafe", "(", "payload", "[", "]", "byte", ")", "(", "code", "StatusCode", ",", "reason", "string", ")", "{", "if", "len", "(", "payload", ")", "<", "2", "{", "return", "\n", "}", "\n", "code", "=", "StatusCode", "(", "binary", ".", "BigEndian", ".", "Uint16", "(", "payload", ")", ")", "\n", "reason", "=", "btsToString", "(", "payload", "[", "2", ":", "]", ")", "\n", "return", "\n", "}" ]
// ParseCloseFrameDataUnsafe is like ParseCloseFrameData except the thing // that it does not copies payload bytes into reason, but prepares unsafe cast.
[ "ParseCloseFrameDataUnsafe", "is", "like", "ParseCloseFrameData", "except", "the", "thing", "that", "it", "does", "not", "copies", "payload", "bytes", "into", "reason", "but", "prepares", "unsafe", "cast", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/read.go#L151-L158
167,099
gobwas/ws
wsutil/utf8.go
Reset
func (u *UTF8Reader) Reset(r io.Reader) { u.Source = r u.state = 0 u.codep = 0 }
go
func (u *UTF8Reader) Reset(r io.Reader) { u.Source = r u.state = 0 u.codep = 0 }
[ "func", "(", "u", "*", "UTF8Reader", ")", "Reset", "(", "r", "io", ".", "Reader", ")", "{", "u", ".", "Source", "=", "r", "\n", "u", ".", "state", "=", "0", "\n", "u", ".", "codep", "=", "0", "\n", "}" ]
// Reset resets utf8 reader to read from r.
[ "Reset", "resets", "utf8", "reader", "to", "read", "from", "r", "." ]
7338e265e1ab4ea2403da5ce80d934ef5f976923
https://github.com/gobwas/ws/blob/7338e265e1ab4ea2403da5ce80d934ef5f976923/wsutil/utf8.go#L43-L47