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
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
142,600 |
trivago/gollum
|
core/pluginconfig.go
|
NewPluginConfig
|
func NewPluginConfig(pluginID string, defaultTypename string) PluginConfig {
return PluginConfig{
Enable: true,
ID: pluginID,
Typename: defaultTypename,
Settings: tcontainer.NewMarshalMap(),
validKeys: make(map[string]bool),
}
}
|
go
|
func NewPluginConfig(pluginID string, defaultTypename string) PluginConfig {
return PluginConfig{
Enable: true,
ID: pluginID,
Typename: defaultTypename,
Settings: tcontainer.NewMarshalMap(),
validKeys: make(map[string]bool),
}
}
|
[
"func",
"NewPluginConfig",
"(",
"pluginID",
"string",
",",
"defaultTypename",
"string",
")",
"PluginConfig",
"{",
"return",
"PluginConfig",
"{",
"Enable",
":",
"true",
",",
"ID",
":",
"pluginID",
",",
"Typename",
":",
"defaultTypename",
",",
"Settings",
":",
"tcontainer",
".",
"NewMarshalMap",
"(",
")",
",",
"validKeys",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
",",
"}",
"\n",
"}"
] |
// NewPluginConfig creates a new plugin config with default values.
// By default the plugin is enabled, has one instance and has no additional settings.
// Passing an empty pluginID makes the plugin anonymous.
// The defaultTypename may be overridden by a later call to read.
|
[
"NewPluginConfig",
"creates",
"a",
"new",
"plugin",
"config",
"with",
"default",
"values",
".",
"By",
"default",
"the",
"plugin",
"is",
"enabled",
"has",
"one",
"instance",
"and",
"has",
"no",
"additional",
"settings",
".",
"Passing",
"an",
"empty",
"pluginID",
"makes",
"the",
"plugin",
"anonymous",
".",
"The",
"defaultTypename",
"may",
"be",
"overridden",
"by",
"a",
"later",
"call",
"to",
"read",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L38-L46
|
142,601 |
trivago/gollum
|
core/pluginconfig.go
|
NewNestedPluginConfig
|
func NewNestedPluginConfig(defaultTypename string, values tcontainer.MarshalMap) (PluginConfig, error) {
conf := NewPluginConfig("", defaultTypename)
err := conf.Read(values)
return conf, err
}
|
go
|
func NewNestedPluginConfig(defaultTypename string, values tcontainer.MarshalMap) (PluginConfig, error) {
conf := NewPluginConfig("", defaultTypename)
err := conf.Read(values)
return conf, err
}
|
[
"func",
"NewNestedPluginConfig",
"(",
"defaultTypename",
"string",
",",
"values",
"tcontainer",
".",
"MarshalMap",
")",
"(",
"PluginConfig",
",",
"error",
")",
"{",
"conf",
":=",
"NewPluginConfig",
"(",
"\"",
"\"",
",",
"defaultTypename",
")",
"\n",
"err",
":=",
"conf",
".",
"Read",
"(",
"values",
")",
"\n",
"return",
"conf",
",",
"err",
"\n",
"}"
] |
// NewNestedPluginConfig creates a pluginconfig based on a given set of config
// values. The plugin created does not have an id, i.e. it is considered
// anonymous.
|
[
"NewNestedPluginConfig",
"creates",
"a",
"pluginconfig",
"based",
"on",
"a",
"given",
"set",
"of",
"config",
"values",
".",
"The",
"plugin",
"created",
"does",
"not",
"have",
"an",
"id",
"i",
".",
"e",
".",
"it",
"is",
"considered",
"anonymous",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L51-L55
|
142,602 |
trivago/gollum
|
core/pluginconfig.go
|
registerKey
|
func (conf *PluginConfig) registerKey(key string) string {
if _, exists := conf.validKeys[key]; exists {
return key // ### return, already registered ###
}
// Remove array notation from path
path := key
startIdx := strings.IndexRune(path, tcontainer.MarshalMapArrayBegin)
for startIdx > -1 {
if endIdx := strings.IndexRune(path[startIdx:], tcontainer.MarshalMapArrayEnd); endIdx > -1 {
path = path[0:startIdx] + path[startIdx+endIdx+1:]
startIdx = strings.IndexRune(path, tcontainer.MarshalMapArrayBegin)
} else {
startIdx = -1
}
}
if _, exists := conf.validKeys[path]; exists {
return key // ### return, already registered (without array notation) ###
}
// Register all parts of the path
startIdx = strings.IndexRune(path, tcontainer.MarshalMapSeparator)
cutIdx := startIdx
for startIdx > -1 {
conf.validKeys[path[:cutIdx]] = true
startIdx = strings.IndexRune(path[startIdx+1:], tcontainer.MarshalMapSeparator)
cutIdx += startIdx
}
conf.validKeys[path] = true
return key
}
|
go
|
func (conf *PluginConfig) registerKey(key string) string {
if _, exists := conf.validKeys[key]; exists {
return key // ### return, already registered ###
}
// Remove array notation from path
path := key
startIdx := strings.IndexRune(path, tcontainer.MarshalMapArrayBegin)
for startIdx > -1 {
if endIdx := strings.IndexRune(path[startIdx:], tcontainer.MarshalMapArrayEnd); endIdx > -1 {
path = path[0:startIdx] + path[startIdx+endIdx+1:]
startIdx = strings.IndexRune(path, tcontainer.MarshalMapArrayBegin)
} else {
startIdx = -1
}
}
if _, exists := conf.validKeys[path]; exists {
return key // ### return, already registered (without array notation) ###
}
// Register all parts of the path
startIdx = strings.IndexRune(path, tcontainer.MarshalMapSeparator)
cutIdx := startIdx
for startIdx > -1 {
conf.validKeys[path[:cutIdx]] = true
startIdx = strings.IndexRune(path[startIdx+1:], tcontainer.MarshalMapSeparator)
cutIdx += startIdx
}
conf.validKeys[path] = true
return key
}
|
[
"func",
"(",
"conf",
"*",
"PluginConfig",
")",
"registerKey",
"(",
"key",
"string",
")",
"string",
"{",
"if",
"_",
",",
"exists",
":=",
"conf",
".",
"validKeys",
"[",
"key",
"]",
";",
"exists",
"{",
"return",
"key",
"// ### return, already registered ###",
"\n",
"}",
"\n\n",
"// Remove array notation from path",
"path",
":=",
"key",
"\n",
"startIdx",
":=",
"strings",
".",
"IndexRune",
"(",
"path",
",",
"tcontainer",
".",
"MarshalMapArrayBegin",
")",
"\n",
"for",
"startIdx",
">",
"-",
"1",
"{",
"if",
"endIdx",
":=",
"strings",
".",
"IndexRune",
"(",
"path",
"[",
"startIdx",
":",
"]",
",",
"tcontainer",
".",
"MarshalMapArrayEnd",
")",
";",
"endIdx",
">",
"-",
"1",
"{",
"path",
"=",
"path",
"[",
"0",
":",
"startIdx",
"]",
"+",
"path",
"[",
"startIdx",
"+",
"endIdx",
"+",
"1",
":",
"]",
"\n",
"startIdx",
"=",
"strings",
".",
"IndexRune",
"(",
"path",
",",
"tcontainer",
".",
"MarshalMapArrayBegin",
")",
"\n",
"}",
"else",
"{",
"startIdx",
"=",
"-",
"1",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"exists",
":=",
"conf",
".",
"validKeys",
"[",
"path",
"]",
";",
"exists",
"{",
"return",
"key",
"// ### return, already registered (without array notation) ###",
"\n",
"}",
"\n\n",
"// Register all parts of the path",
"startIdx",
"=",
"strings",
".",
"IndexRune",
"(",
"path",
",",
"tcontainer",
".",
"MarshalMapSeparator",
")",
"\n",
"cutIdx",
":=",
"startIdx",
"\n",
"for",
"startIdx",
">",
"-",
"1",
"{",
"conf",
".",
"validKeys",
"[",
"path",
"[",
":",
"cutIdx",
"]",
"]",
"=",
"true",
"\n",
"startIdx",
"=",
"strings",
".",
"IndexRune",
"(",
"path",
"[",
"startIdx",
"+",
"1",
":",
"]",
",",
"tcontainer",
".",
"MarshalMapSeparator",
")",
"\n",
"cutIdx",
"+=",
"startIdx",
"\n",
"}",
"\n\n",
"conf",
".",
"validKeys",
"[",
"path",
"]",
"=",
"true",
"\n",
"return",
"key",
"\n",
"}"
] |
// registerKey registers a key to the validKeys map as lowercase and returns
// the lowercase key
|
[
"registerKey",
"registers",
"a",
"key",
"to",
"the",
"validKeys",
"map",
"as",
"lowercase",
"and",
"returns",
"the",
"lowercase",
"key"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L59-L91
|
142,603 |
trivago/gollum
|
core/pluginconfig.go
|
Validate
|
func (conf PluginConfig) Validate() error {
errors := tgo.NewErrorStack()
errors.SetFormat(tgo.ErrorStackFormatCSV)
for key := range conf.Settings {
if _, exists := conf.validKeys[key]; !exists {
if suggestion := conf.suggestKey(key); suggestion != "" {
errors.Pushf("Unknown configuration key '%s' in '%s'. Did you mean '%s'?", key, conf.Typename, suggestion)
} else {
errors.Pushf("Unknown configuration key '%s' in '%s", key, conf.Typename)
}
}
}
return errors.OrNil()
}
|
go
|
func (conf PluginConfig) Validate() error {
errors := tgo.NewErrorStack()
errors.SetFormat(tgo.ErrorStackFormatCSV)
for key := range conf.Settings {
if _, exists := conf.validKeys[key]; !exists {
if suggestion := conf.suggestKey(key); suggestion != "" {
errors.Pushf("Unknown configuration key '%s' in '%s'. Did you mean '%s'?", key, conf.Typename, suggestion)
} else {
errors.Pushf("Unknown configuration key '%s' in '%s", key, conf.Typename)
}
}
}
return errors.OrNil()
}
|
[
"func",
"(",
"conf",
"PluginConfig",
")",
"Validate",
"(",
")",
"error",
"{",
"errors",
":=",
"tgo",
".",
"NewErrorStack",
"(",
")",
"\n",
"errors",
".",
"SetFormat",
"(",
"tgo",
".",
"ErrorStackFormatCSV",
")",
"\n",
"for",
"key",
":=",
"range",
"conf",
".",
"Settings",
"{",
"if",
"_",
",",
"exists",
":=",
"conf",
".",
"validKeys",
"[",
"key",
"]",
";",
"!",
"exists",
"{",
"if",
"suggestion",
":=",
"conf",
".",
"suggestKey",
"(",
"key",
")",
";",
"suggestion",
"!=",
"\"",
"\"",
"{",
"errors",
".",
"Pushf",
"(",
"\"",
"\"",
",",
"key",
",",
"conf",
".",
"Typename",
",",
"suggestion",
")",
"\n",
"}",
"else",
"{",
"errors",
".",
"Pushf",
"(",
"\"",
"\"",
",",
"key",
",",
"conf",
".",
"Typename",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"errors",
".",
"OrNil",
"(",
")",
"\n",
"}"
] |
// Validate should be called after a configuration has been processed. It will
// check the keys read from the config files against the keys requested up to
// this point. Unknown keys will be returned as errors
|
[
"Validate",
"should",
"be",
"called",
"after",
"a",
"configuration",
"has",
"been",
"processed",
".",
"It",
"will",
"check",
"the",
"keys",
"read",
"from",
"the",
"config",
"files",
"against",
"the",
"keys",
"requested",
"up",
"to",
"this",
"point",
".",
"Unknown",
"keys",
"will",
"be",
"returned",
"as",
"errors"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L116-L129
|
142,604 |
trivago/gollum
|
core/pluginconfig.go
|
Override
|
func (conf *PluginConfig) Override(key string, value interface{}) {
key = conf.registerKey(key)
conf.Settings[key] = value
}
|
go
|
func (conf *PluginConfig) Override(key string, value interface{}) {
key = conf.registerKey(key)
conf.Settings[key] = value
}
|
[
"func",
"(",
"conf",
"*",
"PluginConfig",
")",
"Override",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"key",
"=",
"conf",
".",
"registerKey",
"(",
"key",
")",
"\n",
"conf",
".",
"Settings",
"[",
"key",
"]",
"=",
"value",
"\n",
"}"
] |
// Override sets or override a configuration value for non-predefined options.
|
[
"Override",
"sets",
"or",
"override",
"a",
"configuration",
"value",
"for",
"non",
"-",
"predefined",
"options",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L206-L209
|
142,605 |
trivago/gollum
|
router/distribute.go
|
Start
|
func (router *Distribute) Start() error {
for _, streamID := range router.boundStreamIDs {
targetRouter := core.StreamRegistry.GetRouterOrFallback(streamID)
router.routers = append(router.routers, targetRouter)
}
return nil
}
|
go
|
func (router *Distribute) Start() error {
for _, streamID := range router.boundStreamIDs {
targetRouter := core.StreamRegistry.GetRouterOrFallback(streamID)
router.routers = append(router.routers, targetRouter)
}
return nil
}
|
[
"func",
"(",
"router",
"*",
"Distribute",
")",
"Start",
"(",
")",
"error",
"{",
"for",
"_",
",",
"streamID",
":=",
"range",
"router",
".",
"boundStreamIDs",
"{",
"targetRouter",
":=",
"core",
".",
"StreamRegistry",
".",
"GetRouterOrFallback",
"(",
"streamID",
")",
"\n",
"router",
".",
"routers",
"=",
"append",
"(",
"router",
".",
"routers",
",",
"targetRouter",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Start the router
|
[
"Start",
"the",
"router"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/router/distribute.go#L66-L72
|
142,606 |
trivago/gollum
|
core/streamregistry.go
|
GetStreamID
|
func (registry *streamRegistry) GetStreamID(stream string) MessageStreamID {
hash := fnv.New64a()
hash.Write([]byte(stream))
streamID := MessageStreamID(hash.Sum64())
registry.nameGuard.Lock()
registry.name[streamID] = stream
registry.nameGuard.Unlock()
return streamID
}
|
go
|
func (registry *streamRegistry) GetStreamID(stream string) MessageStreamID {
hash := fnv.New64a()
hash.Write([]byte(stream))
streamID := MessageStreamID(hash.Sum64())
registry.nameGuard.Lock()
registry.name[streamID] = stream
registry.nameGuard.Unlock()
return streamID
}
|
[
"func",
"(",
"registry",
"*",
"streamRegistry",
")",
"GetStreamID",
"(",
"stream",
"string",
")",
"MessageStreamID",
"{",
"hash",
":=",
"fnv",
".",
"New64a",
"(",
")",
"\n",
"hash",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"stream",
")",
")",
"\n",
"streamID",
":=",
"MessageStreamID",
"(",
"hash",
".",
"Sum64",
"(",
")",
")",
"\n\n",
"registry",
".",
"nameGuard",
".",
"Lock",
"(",
")",
"\n",
"registry",
".",
"name",
"[",
"streamID",
"]",
"=",
"stream",
"\n",
"registry",
".",
"nameGuard",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"streamID",
"\n",
"}"
] |
// GetStreamID returns the integer representation of a given stream name.
|
[
"GetStreamID",
"returns",
"the",
"integer",
"representation",
"of",
"a",
"given",
"stream",
"name",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L59-L69
|
142,607 |
trivago/gollum
|
core/streamregistry.go
|
GetStreamName
|
func (registry streamRegistry) GetStreamName(streamID MessageStreamID) string {
switch streamID {
case LogInternalStreamID:
return LogInternalStream
case WildcardStreamID:
return WildcardStream
case InvalidStreamID:
return InvalidStream
case TraceInternalStreamID:
return TraceInternalStream
default:
registry.nameGuard.RLock()
name, exists := registry.name[streamID]
registry.nameGuard.RUnlock()
if exists {
return name // ### return, found ###
}
}
return ""
}
|
go
|
func (registry streamRegistry) GetStreamName(streamID MessageStreamID) string {
switch streamID {
case LogInternalStreamID:
return LogInternalStream
case WildcardStreamID:
return WildcardStream
case InvalidStreamID:
return InvalidStream
case TraceInternalStreamID:
return TraceInternalStream
default:
registry.nameGuard.RLock()
name, exists := registry.name[streamID]
registry.nameGuard.RUnlock()
if exists {
return name // ### return, found ###
}
}
return ""
}
|
[
"func",
"(",
"registry",
"streamRegistry",
")",
"GetStreamName",
"(",
"streamID",
"MessageStreamID",
")",
"string",
"{",
"switch",
"streamID",
"{",
"case",
"LogInternalStreamID",
":",
"return",
"LogInternalStream",
"\n\n",
"case",
"WildcardStreamID",
":",
"return",
"WildcardStream",
"\n\n",
"case",
"InvalidStreamID",
":",
"return",
"InvalidStream",
"\n\n",
"case",
"TraceInternalStreamID",
":",
"return",
"TraceInternalStream",
"\n\n",
"default",
":",
"registry",
".",
"nameGuard",
".",
"RLock",
"(",
")",
"\n",
"name",
",",
"exists",
":=",
"registry",
".",
"name",
"[",
"streamID",
"]",
"\n",
"registry",
".",
"nameGuard",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"exists",
"{",
"return",
"name",
"// ### return, found ###",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// GetStreamName does a reverse lookup for a given MessageStreamID and returns
// the corresponding name. If the MessageStreamID is not registered, an empty
// string is returned.
|
[
"GetStreamName",
"does",
"a",
"reverse",
"lookup",
"for",
"a",
"given",
"MessageStreamID",
"and",
"returns",
"the",
"corresponding",
"name",
".",
"If",
"the",
"MessageStreamID",
"is",
"not",
"registered",
"an",
"empty",
"string",
"is",
"returned",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L74-L98
|
142,608 |
trivago/gollum
|
core/streamregistry.go
|
GetRouterByStreamName
|
func (registry streamRegistry) GetRouterByStreamName(name string) Router {
streamID := registry.GetStreamID(name)
return registry.GetRouter(streamID)
}
|
go
|
func (registry streamRegistry) GetRouterByStreamName(name string) Router {
streamID := registry.GetStreamID(name)
return registry.GetRouter(streamID)
}
|
[
"func",
"(",
"registry",
"streamRegistry",
")",
"GetRouterByStreamName",
"(",
"name",
"string",
")",
"Router",
"{",
"streamID",
":=",
"registry",
".",
"GetStreamID",
"(",
"name",
")",
"\n",
"return",
"registry",
".",
"GetRouter",
"(",
"streamID",
")",
"\n",
"}"
] |
// GetRouterByStreamName returns a registered stream by name. See GetRouter.
|
[
"GetRouterByStreamName",
"returns",
"a",
"registered",
"stream",
"by",
"name",
".",
"See",
"GetRouter",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L101-L104
|
142,609 |
trivago/gollum
|
core/streamregistry.go
|
GetRouter
|
func (registry streamRegistry) GetRouter(id MessageStreamID) Router {
registry.streamGuard.RLock()
stream, exists := registry.routers[id]
registry.streamGuard.RUnlock()
if exists {
return stream
}
return nil
}
|
go
|
func (registry streamRegistry) GetRouter(id MessageStreamID) Router {
registry.streamGuard.RLock()
stream, exists := registry.routers[id]
registry.streamGuard.RUnlock()
if exists {
return stream
}
return nil
}
|
[
"func",
"(",
"registry",
"streamRegistry",
")",
"GetRouter",
"(",
"id",
"MessageStreamID",
")",
"Router",
"{",
"registry",
".",
"streamGuard",
".",
"RLock",
"(",
")",
"\n",
"stream",
",",
"exists",
":=",
"registry",
".",
"routers",
"[",
"id",
"]",
"\n",
"registry",
".",
"streamGuard",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"exists",
"{",
"return",
"stream",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// GetRouter returns a registered stream or nil
|
[
"GetRouter",
"returns",
"a",
"registered",
"stream",
"or",
"nil"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L107-L116
|
142,610 |
trivago/gollum
|
core/streamregistry.go
|
IsStreamRegistered
|
func (registry streamRegistry) IsStreamRegistered(id MessageStreamID) bool {
registry.streamGuard.RLock()
_, exists := registry.routers[id]
registry.streamGuard.RUnlock()
return exists
}
|
go
|
func (registry streamRegistry) IsStreamRegistered(id MessageStreamID) bool {
registry.streamGuard.RLock()
_, exists := registry.routers[id]
registry.streamGuard.RUnlock()
return exists
}
|
[
"func",
"(",
"registry",
"streamRegistry",
")",
"IsStreamRegistered",
"(",
"id",
"MessageStreamID",
")",
"bool",
"{",
"registry",
".",
"streamGuard",
".",
"RLock",
"(",
")",
"\n",
"_",
",",
"exists",
":=",
"registry",
".",
"routers",
"[",
"id",
"]",
"\n",
"registry",
".",
"streamGuard",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"exists",
"\n",
"}"
] |
// IsStreamRegistered returns true if the stream for the given id is registered.
|
[
"IsStreamRegistered",
"returns",
"true",
"if",
"the",
"stream",
"for",
"the",
"given",
"id",
"is",
"registered",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L119-L125
|
142,611 |
trivago/gollum
|
core/streamregistry.go
|
ForEachStream
|
func (registry streamRegistry) ForEachStream(callback func(streamID MessageStreamID, stream Router)) {
registry.streamGuard.RLock()
defer registry.streamGuard.RUnlock()
for streamID, router := range registry.routers {
callback(streamID, router)
}
}
|
go
|
func (registry streamRegistry) ForEachStream(callback func(streamID MessageStreamID, stream Router)) {
registry.streamGuard.RLock()
defer registry.streamGuard.RUnlock()
for streamID, router := range registry.routers {
callback(streamID, router)
}
}
|
[
"func",
"(",
"registry",
"streamRegistry",
")",
"ForEachStream",
"(",
"callback",
"func",
"(",
"streamID",
"MessageStreamID",
",",
"stream",
"Router",
")",
")",
"{",
"registry",
".",
"streamGuard",
".",
"RLock",
"(",
")",
"\n",
"defer",
"registry",
".",
"streamGuard",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"streamID",
",",
"router",
":=",
"range",
"registry",
".",
"routers",
"{",
"callback",
"(",
"streamID",
",",
"router",
")",
"\n",
"}",
"\n",
"}"
] |
// ForEachStream loops over all registered routers and calls the given function.
|
[
"ForEachStream",
"loops",
"over",
"all",
"registered",
"routers",
"and",
"calls",
"the",
"given",
"function",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L128-L135
|
142,612 |
trivago/gollum
|
core/streamregistry.go
|
AddWildcardProducersToRouter
|
func (registry streamRegistry) AddWildcardProducersToRouter(router Router) {
streamID := router.GetStreamID()
if streamID != LogInternalStreamID {
router.AddProducer(registry.wildcard...)
}
}
|
go
|
func (registry streamRegistry) AddWildcardProducersToRouter(router Router) {
streamID := router.GetStreamID()
if streamID != LogInternalStreamID {
router.AddProducer(registry.wildcard...)
}
}
|
[
"func",
"(",
"registry",
"streamRegistry",
")",
"AddWildcardProducersToRouter",
"(",
"router",
"Router",
")",
"{",
"streamID",
":=",
"router",
".",
"GetStreamID",
"(",
")",
"\n",
"if",
"streamID",
"!=",
"LogInternalStreamID",
"{",
"router",
".",
"AddProducer",
"(",
"registry",
".",
"wildcard",
"...",
")",
"\n",
"}",
"\n",
"}"
] |
// AddWildcardProducersToRouter adds all known wildcard producers to a given
// router. The state of the wildcard list is undefined during the configuration
// phase.
|
[
"AddWildcardProducersToRouter",
"adds",
"all",
"known",
"wildcard",
"producers",
"to",
"a",
"given",
"router",
".",
"The",
"state",
"of",
"the",
"wildcard",
"list",
"is",
"undefined",
"during",
"the",
"configuration",
"phase",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L163-L168
|
142,613 |
trivago/gollum
|
core/streamregistry.go
|
AddAllWildcardProducersToAllRouters
|
func (registry *streamRegistry) AddAllWildcardProducersToAllRouters() {
registry.ForEachStream(
func(streamID MessageStreamID, router Router) {
registry.AddWildcardProducersToRouter(router)
})
}
|
go
|
func (registry *streamRegistry) AddAllWildcardProducersToAllRouters() {
registry.ForEachStream(
func(streamID MessageStreamID, router Router) {
registry.AddWildcardProducersToRouter(router)
})
}
|
[
"func",
"(",
"registry",
"*",
"streamRegistry",
")",
"AddAllWildcardProducersToAllRouters",
"(",
")",
"{",
"registry",
".",
"ForEachStream",
"(",
"func",
"(",
"streamID",
"MessageStreamID",
",",
"router",
"Router",
")",
"{",
"registry",
".",
"AddWildcardProducersToRouter",
"(",
"router",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// AddAllWildcardProducersToAllRouters executes AddWildcardProducersToRouter on
// all currently registered routers
|
[
"AddAllWildcardProducersToAllRouters",
"executes",
"AddWildcardProducersToRouter",
"on",
"all",
"currently",
"registered",
"routers"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L172-L177
|
142,614 |
trivago/gollum
|
core/streamregistry.go
|
Register
|
func (registry *streamRegistry) Register(router Router, streamID MessageStreamID) {
registry.streamGuard.RLock()
_, exists := registry.routers[streamID]
registry.streamGuard.RUnlock()
if exists {
logrus.Warningf("%T attaches to an already occupied router (%s)", router, registry.GetStreamName(streamID))
return // ### return, double registration ###
}
registry.streamGuard.Lock()
defer registry.streamGuard.Unlock()
// Test again inside critical section to avoid races
if _, exists := registry.routers[streamID]; !exists {
registry.routers[streamID] = router
MetricRouters.Inc(1)
}
}
|
go
|
func (registry *streamRegistry) Register(router Router, streamID MessageStreamID) {
registry.streamGuard.RLock()
_, exists := registry.routers[streamID]
registry.streamGuard.RUnlock()
if exists {
logrus.Warningf("%T attaches to an already occupied router (%s)", router, registry.GetStreamName(streamID))
return // ### return, double registration ###
}
registry.streamGuard.Lock()
defer registry.streamGuard.Unlock()
// Test again inside critical section to avoid races
if _, exists := registry.routers[streamID]; !exists {
registry.routers[streamID] = router
MetricRouters.Inc(1)
}
}
|
[
"func",
"(",
"registry",
"*",
"streamRegistry",
")",
"Register",
"(",
"router",
"Router",
",",
"streamID",
"MessageStreamID",
")",
"{",
"registry",
".",
"streamGuard",
".",
"RLock",
"(",
")",
"\n",
"_",
",",
"exists",
":=",
"registry",
".",
"routers",
"[",
"streamID",
"]",
"\n",
"registry",
".",
"streamGuard",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"exists",
"{",
"logrus",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"router",
",",
"registry",
".",
"GetStreamName",
"(",
"streamID",
")",
")",
"\n",
"return",
"// ### return, double registration ###",
"\n",
"}",
"\n\n",
"registry",
".",
"streamGuard",
".",
"Lock",
"(",
")",
"\n",
"defer",
"registry",
".",
"streamGuard",
".",
"Unlock",
"(",
")",
"\n\n",
"// Test again inside critical section to avoid races",
"if",
"_",
",",
"exists",
":=",
"registry",
".",
"routers",
"[",
"streamID",
"]",
";",
"!",
"exists",
"{",
"registry",
".",
"routers",
"[",
"streamID",
"]",
"=",
"router",
"\n",
"MetricRouters",
".",
"Inc",
"(",
"1",
")",
"\n",
"}",
"\n",
"}"
] |
// Register registers a router plugin to a given stream id
|
[
"Register",
"registers",
"a",
"router",
"plugin",
"to",
"a",
"given",
"stream",
"id"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L180-L198
|
142,615 |
trivago/gollum
|
core/streamregistry.go
|
GetRouterOrFallback
|
func (registry *streamRegistry) GetRouterOrFallback(streamID MessageStreamID) Router {
if streamID == InvalidStreamID {
return nil // ### return, invalid stream does not have a router ###
}
registry.streamGuard.RLock()
router, exists := registry.routers[streamID]
registry.streamGuard.RUnlock()
if exists {
return router // ### return, already registered ###
}
registry.streamGuard.Lock()
defer registry.streamGuard.Unlock()
// Create router, avoid race conditions by check again in ciritical section
if router, exists = registry.routers[streamID]; exists {
return router // ### return, lost the race ###
}
defaultRouter := registry.createFallback(streamID)
registry.AddWildcardProducersToRouter(defaultRouter)
registry.routers[streamID] = defaultRouter
MetricRouters.Inc(1)
MetricFallbackRouters.Inc(1)
return defaultRouter
}
|
go
|
func (registry *streamRegistry) GetRouterOrFallback(streamID MessageStreamID) Router {
if streamID == InvalidStreamID {
return nil // ### return, invalid stream does not have a router ###
}
registry.streamGuard.RLock()
router, exists := registry.routers[streamID]
registry.streamGuard.RUnlock()
if exists {
return router // ### return, already registered ###
}
registry.streamGuard.Lock()
defer registry.streamGuard.Unlock()
// Create router, avoid race conditions by check again in ciritical section
if router, exists = registry.routers[streamID]; exists {
return router // ### return, lost the race ###
}
defaultRouter := registry.createFallback(streamID)
registry.AddWildcardProducersToRouter(defaultRouter)
registry.routers[streamID] = defaultRouter
MetricRouters.Inc(1)
MetricFallbackRouters.Inc(1)
return defaultRouter
}
|
[
"func",
"(",
"registry",
"*",
"streamRegistry",
")",
"GetRouterOrFallback",
"(",
"streamID",
"MessageStreamID",
")",
"Router",
"{",
"if",
"streamID",
"==",
"InvalidStreamID",
"{",
"return",
"nil",
"// ### return, invalid stream does not have a router ###",
"\n",
"}",
"\n\n",
"registry",
".",
"streamGuard",
".",
"RLock",
"(",
")",
"\n",
"router",
",",
"exists",
":=",
"registry",
".",
"routers",
"[",
"streamID",
"]",
"\n",
"registry",
".",
"streamGuard",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"exists",
"{",
"return",
"router",
"// ### return, already registered ###",
"\n",
"}",
"\n\n",
"registry",
".",
"streamGuard",
".",
"Lock",
"(",
")",
"\n",
"defer",
"registry",
".",
"streamGuard",
".",
"Unlock",
"(",
")",
"\n\n",
"// Create router, avoid race conditions by check again in ciritical section",
"if",
"router",
",",
"exists",
"=",
"registry",
".",
"routers",
"[",
"streamID",
"]",
";",
"exists",
"{",
"return",
"router",
"// ### return, lost the race ###",
"\n",
"}",
"\n\n",
"defaultRouter",
":=",
"registry",
".",
"createFallback",
"(",
"streamID",
")",
"\n",
"registry",
".",
"AddWildcardProducersToRouter",
"(",
"defaultRouter",
")",
"\n",
"registry",
".",
"routers",
"[",
"streamID",
"]",
"=",
"defaultRouter",
"\n\n",
"MetricRouters",
".",
"Inc",
"(",
"1",
")",
"\n",
"MetricFallbackRouters",
".",
"Inc",
"(",
"1",
")",
"\n\n",
"return",
"defaultRouter",
"\n",
"}"
] |
// GetRouterOrFallback returns the router for the given streamID if it is registered.
// If no router is registered for the given streamID the default router is used.
// The default router is equivalent to an unconfigured router.Broadcast with
// all wildcard producers already added.
|
[
"GetRouterOrFallback",
"returns",
"the",
"router",
"for",
"the",
"given",
"streamID",
"if",
"it",
"is",
"registered",
".",
"If",
"no",
"router",
"is",
"registered",
"for",
"the",
"given",
"streamID",
"the",
"default",
"router",
"is",
"used",
".",
"The",
"default",
"router",
"is",
"equivalent",
"to",
"an",
"unconfigured",
"router",
".",
"Broadcast",
"with",
"all",
"wildcard",
"producers",
"already",
"added",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L204-L232
|
142,616 |
trivago/gollum
|
core/metadata.go
|
SetValue
|
func (meta Metadata) SetValue(key string, value []byte) {
meta[key] = value
}
|
go
|
func (meta Metadata) SetValue(key string, value []byte) {
meta[key] = value
}
|
[
"func",
"(",
"meta",
"Metadata",
")",
"SetValue",
"(",
"key",
"string",
",",
"value",
"[",
"]",
"byte",
")",
"{",
"meta",
"[",
"key",
"]",
"=",
"value",
"\n",
"}"
] |
// SetValue set a key value pair at meta data
|
[
"SetValue",
"set",
"a",
"key",
"value",
"pair",
"at",
"meta",
"data"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L21-L23
|
142,617 |
trivago/gollum
|
core/metadata.go
|
TrySetValue
|
func (meta Metadata) TrySetValue(key string, value []byte) bool {
if _, exists := meta[key]; exists {
meta[key] = value
return true
}
return false
}
|
go
|
func (meta Metadata) TrySetValue(key string, value []byte) bool {
if _, exists := meta[key]; exists {
meta[key] = value
return true
}
return false
}
|
[
"func",
"(",
"meta",
"Metadata",
")",
"TrySetValue",
"(",
"key",
"string",
",",
"value",
"[",
"]",
"byte",
")",
"bool",
"{",
"if",
"_",
",",
"exists",
":=",
"meta",
"[",
"key",
"]",
";",
"exists",
"{",
"meta",
"[",
"key",
"]",
"=",
"value",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// TrySetValue sets a key value pair only if the key is already existing
|
[
"TrySetValue",
"sets",
"a",
"key",
"value",
"pair",
"only",
"if",
"the",
"key",
"is",
"already",
"existing"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L26-L32
|
142,618 |
trivago/gollum
|
core/metadata.go
|
GetValue
|
func (meta Metadata) GetValue(key string) []byte {
if value, isSet := meta[key]; isSet {
return value
}
return []byte{}
}
|
go
|
func (meta Metadata) GetValue(key string) []byte {
if value, isSet := meta[key]; isSet {
return value
}
return []byte{}
}
|
[
"func",
"(",
"meta",
"Metadata",
")",
"GetValue",
"(",
"key",
"string",
")",
"[",
"]",
"byte",
"{",
"if",
"value",
",",
"isSet",
":=",
"meta",
"[",
"key",
"]",
";",
"isSet",
"{",
"return",
"value",
"\n",
"}",
"\n\n",
"return",
"[",
"]",
"byte",
"{",
"}",
"\n",
"}"
] |
// GetValue returns a meta data value by key. This function returns a value if
// key is not set, too. In that case it will return an empty byte array.
|
[
"GetValue",
"returns",
"a",
"meta",
"data",
"value",
"by",
"key",
".",
"This",
"function",
"returns",
"a",
"value",
"if",
"key",
"is",
"not",
"set",
"too",
".",
"In",
"that",
"case",
"it",
"will",
"return",
"an",
"empty",
"byte",
"array",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L36-L42
|
142,619 |
trivago/gollum
|
core/metadata.go
|
TryGetValue
|
func (meta Metadata) TryGetValue(key string) ([]byte, bool) {
if value, isSet := meta[key]; isSet {
return value, true
}
return []byte{}, false
}
|
go
|
func (meta Metadata) TryGetValue(key string) ([]byte, bool) {
if value, isSet := meta[key]; isSet {
return value, true
}
return []byte{}, false
}
|
[
"func",
"(",
"meta",
"Metadata",
")",
"TryGetValue",
"(",
"key",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
")",
"{",
"if",
"value",
",",
"isSet",
":=",
"meta",
"[",
"key",
"]",
";",
"isSet",
"{",
"return",
"value",
",",
"true",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"false",
"\n",
"}"
] |
// TryGetValue behaves like GetValue but returns a second value which denotes
// if the key was set or not.
|
[
"TryGetValue",
"behaves",
"like",
"GetValue",
"but",
"returns",
"a",
"second",
"value",
"which",
"denotes",
"if",
"the",
"key",
"was",
"set",
"or",
"not",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L46-L51
|
142,620 |
trivago/gollum
|
core/metadata.go
|
GetValueString
|
func (meta Metadata) GetValueString(key string) string {
return string(meta.GetValue(key))
}
|
go
|
func (meta Metadata) GetValueString(key string) string {
return string(meta.GetValue(key))
}
|
[
"func",
"(",
"meta",
"Metadata",
")",
"GetValueString",
"(",
"key",
"string",
")",
"string",
"{",
"return",
"string",
"(",
"meta",
".",
"GetValue",
"(",
"key",
")",
")",
"\n",
"}"
] |
// GetValueString casts the results of GetValue to a string
|
[
"GetValueString",
"casts",
"the",
"results",
"of",
"GetValue",
"to",
"a",
"string"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L54-L56
|
142,621 |
trivago/gollum
|
core/metadata.go
|
TryGetValueString
|
func (meta Metadata) TryGetValueString(key string) (string, bool) {
data, exists := meta.TryGetValue(key)
return string(data), exists
}
|
go
|
func (meta Metadata) TryGetValueString(key string) (string, bool) {
data, exists := meta.TryGetValue(key)
return string(data), exists
}
|
[
"func",
"(",
"meta",
"Metadata",
")",
"TryGetValueString",
"(",
"key",
"string",
")",
"(",
"string",
",",
"bool",
")",
"{",
"data",
",",
"exists",
":=",
"meta",
".",
"TryGetValue",
"(",
"key",
")",
"\n",
"return",
"string",
"(",
"data",
")",
",",
"exists",
"\n",
"}"
] |
// TryGetValueString casts the data result of TryGetValue to string
|
[
"TryGetValueString",
"casts",
"the",
"data",
"result",
"of",
"TryGetValue",
"to",
"string"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L59-L62
|
142,622 |
trivago/gollum
|
core/metadata.go
|
Clone
|
func (meta Metadata) Clone() (clone Metadata) {
clone = Metadata{}
for k, v := range meta {
vCopy := make([]byte, len(v))
copy(vCopy, v)
clone[k] = vCopy
}
return
}
|
go
|
func (meta Metadata) Clone() (clone Metadata) {
clone = Metadata{}
for k, v := range meta {
vCopy := make([]byte, len(v))
copy(vCopy, v)
clone[k] = vCopy
}
return
}
|
[
"func",
"(",
"meta",
"Metadata",
")",
"Clone",
"(",
")",
"(",
"clone",
"Metadata",
")",
"{",
"clone",
"=",
"Metadata",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"meta",
"{",
"vCopy",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"v",
")",
")",
"\n",
"copy",
"(",
"vCopy",
",",
"v",
")",
"\n",
"clone",
"[",
"k",
"]",
"=",
"vCopy",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Clone creates an exact copy of this metadata map.
|
[
"Clone",
"creates",
"an",
"exact",
"copy",
"of",
"this",
"metadata",
"map",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L70-L78
|
142,623 |
trivago/gollum
|
core/simpleproducer.go
|
Modulate
|
func (prod *SimpleProducer) Modulate(msg *Message) ModulateResult {
if len(prod.modulators) > 0 {
msg.FreezeOriginal()
return prod.modulators.Modulate(msg)
}
return ModulateResultContinue
}
|
go
|
func (prod *SimpleProducer) Modulate(msg *Message) ModulateResult {
if len(prod.modulators) > 0 {
msg.FreezeOriginal()
return prod.modulators.Modulate(msg)
}
return ModulateResultContinue
}
|
[
"func",
"(",
"prod",
"*",
"SimpleProducer",
")",
"Modulate",
"(",
"msg",
"*",
"Message",
")",
"ModulateResult",
"{",
"if",
"len",
"(",
"prod",
".",
"modulators",
")",
">",
"0",
"{",
"msg",
".",
"FreezeOriginal",
"(",
")",
"\n",
"return",
"prod",
".",
"modulators",
".",
"Modulate",
"(",
"msg",
")",
"\n",
"}",
"\n",
"return",
"ModulateResultContinue",
"\n",
"}"
] |
// Modulate applies all modulators from this producer to a given message.
// This implementation handles routing and discarding of messages.
|
[
"Modulate",
"applies",
"all",
"modulators",
"from",
"this",
"producer",
"to",
"a",
"given",
"message",
".",
"This",
"implementation",
"handles",
"routing",
"and",
"discarding",
"of",
"messages",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L191-L197
|
142,624 |
trivago/gollum
|
core/simpleproducer.go
|
HasContinueAfterModulate
|
func (prod *SimpleProducer) HasContinueAfterModulate(msg *Message) bool {
switch result := prod.Modulate(msg); result {
case ModulateResultDiscard:
DiscardMessage(msg, prod.GetID(), "Producer discarded")
return false
case ModulateResultFallback:
if err := Route(msg, msg.GetRouter()); err != nil {
prod.Logger.WithError(err).Error("Failed to route to fallback")
}
return false
case ModulateResultContinue:
// OK
return true
default:
prod.Logger.Error("Modulator result not supported:", result)
return false
}
}
|
go
|
func (prod *SimpleProducer) HasContinueAfterModulate(msg *Message) bool {
switch result := prod.Modulate(msg); result {
case ModulateResultDiscard:
DiscardMessage(msg, prod.GetID(), "Producer discarded")
return false
case ModulateResultFallback:
if err := Route(msg, msg.GetRouter()); err != nil {
prod.Logger.WithError(err).Error("Failed to route to fallback")
}
return false
case ModulateResultContinue:
// OK
return true
default:
prod.Logger.Error("Modulator result not supported:", result)
return false
}
}
|
[
"func",
"(",
"prod",
"*",
"SimpleProducer",
")",
"HasContinueAfterModulate",
"(",
"msg",
"*",
"Message",
")",
"bool",
"{",
"switch",
"result",
":=",
"prod",
".",
"Modulate",
"(",
"msg",
")",
";",
"result",
"{",
"case",
"ModulateResultDiscard",
":",
"DiscardMessage",
"(",
"msg",
",",
"prod",
".",
"GetID",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"false",
"\n\n",
"case",
"ModulateResultFallback",
":",
"if",
"err",
":=",
"Route",
"(",
"msg",
",",
"msg",
".",
"GetRouter",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"prod",
".",
"Logger",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n\n",
"case",
"ModulateResultContinue",
":",
"// OK",
"return",
"true",
"\n\n",
"default",
":",
"prod",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"result",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}"
] |
// HasContinueAfterModulate applies all modulators by Modulate, handle the ModulateResult
// and return if you have to continue the message process.
// This method is a default producer modulate handling.
|
[
"HasContinueAfterModulate",
"applies",
"all",
"modulators",
"by",
"Modulate",
"handle",
"the",
"ModulateResult",
"and",
"return",
"if",
"you",
"have",
"to",
"continue",
"the",
"message",
"process",
".",
"This",
"method",
"is",
"a",
"default",
"producer",
"modulate",
"handling",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L202-L222
|
142,625 |
trivago/gollum
|
core/simpleproducer.go
|
TryFallback
|
func (prod *SimpleProducer) TryFallback(msg *Message) {
if err := RouteOriginal(msg, prod.fallbackStream); err != nil {
prod.Logger.WithError(err).Error("Failed to route to fallback")
}
}
|
go
|
func (prod *SimpleProducer) TryFallback(msg *Message) {
if err := RouteOriginal(msg, prod.fallbackStream); err != nil {
prod.Logger.WithError(err).Error("Failed to route to fallback")
}
}
|
[
"func",
"(",
"prod",
"*",
"SimpleProducer",
")",
"TryFallback",
"(",
"msg",
"*",
"Message",
")",
"{",
"if",
"err",
":=",
"RouteOriginal",
"(",
"msg",
",",
"prod",
".",
"fallbackStream",
")",
";",
"err",
"!=",
"nil",
"{",
"prod",
".",
"Logger",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] |
// TryFallback routes the message to the configured fallback stream.
|
[
"TryFallback",
"routes",
"the",
"message",
"to",
"the",
"configured",
"fallback",
"stream",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L225-L229
|
142,626 |
trivago/gollum
|
core/simpleproducer.go
|
ControlLoop
|
func (prod *SimpleProducer) ControlLoop() {
prod.setState(PluginStateActive)
defer prod.setState(PluginStateDead)
defer prod.Logger.Debug("Stopped")
for {
command := <-prod.control
switch command {
default:
prod.Logger.Debug("Received untracked command")
// Do nothing
case PluginControlStopProducer:
prod.Logger.Debug("Preparing for stop")
prod.setState(PluginStatePrepareStop)
if prod.onPrepareStop != nil {
if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onPrepareStop) {
prod.Logger.Error("Timeout during onPrepareStop.")
}
}
prod.Logger.Debug("Executing stop command")
prod.setState(PluginStateStopping)
if prod.onStop != nil {
if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onStop) {
prod.Logger.Error("Timeout during onStop.")
}
}
return // ### return ###
case PluginControlRoll:
prod.Logger.Debug("Received roll command")
if prod.onRoll != nil {
prod.onRoll()
}
}
}
}
|
go
|
func (prod *SimpleProducer) ControlLoop() {
prod.setState(PluginStateActive)
defer prod.setState(PluginStateDead)
defer prod.Logger.Debug("Stopped")
for {
command := <-prod.control
switch command {
default:
prod.Logger.Debug("Received untracked command")
// Do nothing
case PluginControlStopProducer:
prod.Logger.Debug("Preparing for stop")
prod.setState(PluginStatePrepareStop)
if prod.onPrepareStop != nil {
if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onPrepareStop) {
prod.Logger.Error("Timeout during onPrepareStop.")
}
}
prod.Logger.Debug("Executing stop command")
prod.setState(PluginStateStopping)
if prod.onStop != nil {
if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onStop) {
prod.Logger.Error("Timeout during onStop.")
}
}
return // ### return ###
case PluginControlRoll:
prod.Logger.Debug("Received roll command")
if prod.onRoll != nil {
prod.onRoll()
}
}
}
}
|
[
"func",
"(",
"prod",
"*",
"SimpleProducer",
")",
"ControlLoop",
"(",
")",
"{",
"prod",
".",
"setState",
"(",
"PluginStateActive",
")",
"\n",
"defer",
"prod",
".",
"setState",
"(",
"PluginStateDead",
")",
"\n",
"defer",
"prod",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"for",
"{",
"command",
":=",
"<-",
"prod",
".",
"control",
"\n",
"switch",
"command",
"{",
"default",
":",
"prod",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"// Do nothing",
"case",
"PluginControlStopProducer",
":",
"prod",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"prod",
".",
"setState",
"(",
"PluginStatePrepareStop",
")",
"\n\n",
"if",
"prod",
".",
"onPrepareStop",
"!=",
"nil",
"{",
"if",
"!",
"tgo",
".",
"ReturnAfter",
"(",
"prod",
".",
"shutdownTimeout",
"*",
"5",
",",
"prod",
".",
"onPrepareStop",
")",
"{",
"prod",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"prod",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"prod",
".",
"setState",
"(",
"PluginStateStopping",
")",
"\n\n",
"if",
"prod",
".",
"onStop",
"!=",
"nil",
"{",
"if",
"!",
"tgo",
".",
"ReturnAfter",
"(",
"prod",
".",
"shutdownTimeout",
"*",
"5",
",",
"prod",
".",
"onStop",
")",
"{",
"prod",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"// ### return ###",
"\n\n",
"case",
"PluginControlRoll",
":",
"prod",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"if",
"prod",
".",
"onRoll",
"!=",
"nil",
"{",
"prod",
".",
"onRoll",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// ControlLoop listens to the control channel and triggers callbacks for these
// messags. Upon stop control message doExit will be set to true.
|
[
"ControlLoop",
"listens",
"to",
"the",
"control",
"channel",
"and",
"triggers",
"callbacks",
"for",
"these",
"messags",
".",
"Upon",
"stop",
"control",
"message",
"doExit",
"will",
"be",
"set",
"to",
"true",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L233-L272
|
142,627 |
trivago/gollum
|
core/simpleproducer.go
|
TickerControlLoop
|
func (prod *SimpleProducer) TickerControlLoop(interval time.Duration, onTimeOut func()) {
prod.setState(PluginStateActive)
go prod.ControlLoop()
prod.tickerLoop(interval, onTimeOut)
}
|
go
|
func (prod *SimpleProducer) TickerControlLoop(interval time.Duration, onTimeOut func()) {
prod.setState(PluginStateActive)
go prod.ControlLoop()
prod.tickerLoop(interval, onTimeOut)
}
|
[
"func",
"(",
"prod",
"*",
"SimpleProducer",
")",
"TickerControlLoop",
"(",
"interval",
"time",
".",
"Duration",
",",
"onTimeOut",
"func",
"(",
")",
")",
"{",
"prod",
".",
"setState",
"(",
"PluginStateActive",
")",
"\n",
"go",
"prod",
".",
"ControlLoop",
"(",
")",
"\n",
"prod",
".",
"tickerLoop",
"(",
"interval",
",",
"onTimeOut",
")",
"\n",
"}"
] |
// TickerControlLoop is like ControlLoop but executes a given function at
// every given interval tick, too. If the onTick function takes longer than
// interval, the next tick will be delayed until onTick finishes.
|
[
"TickerControlLoop",
"is",
"like",
"ControlLoop",
"but",
"executes",
"a",
"given",
"function",
"at",
"every",
"given",
"interval",
"tick",
"too",
".",
"If",
"the",
"onTick",
"function",
"takes",
"longer",
"than",
"interval",
"the",
"next",
"tick",
"will",
"be",
"delayed",
"until",
"onTick",
"finishes",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L277-L281
|
142,628 |
trivago/gollum
|
producer/proxy.go
|
Produce
|
func (prod *Proxy) Produce(workers *sync.WaitGroup) {
prod.AddMainWorker(workers)
prod.MessageControlLoop(prod.sendMessage)
}
|
go
|
func (prod *Proxy) Produce(workers *sync.WaitGroup) {
prod.AddMainWorker(workers)
prod.MessageControlLoop(prod.sendMessage)
}
|
[
"func",
"(",
"prod",
"*",
"Proxy",
")",
"Produce",
"(",
"workers",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"prod",
".",
"AddMainWorker",
"(",
"workers",
")",
"\n",
"prod",
".",
"MessageControlLoop",
"(",
"prod",
".",
"sendMessage",
")",
"\n",
"}"
] |
// Produce writes to a buffer that is sent to a given Proxy.
|
[
"Produce",
"writes",
"to",
"a",
"buffer",
"that",
"is",
"sent",
"to",
"a",
"given",
"Proxy",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/proxy.go#L213-L216
|
142,629 |
trivago/gollum
|
consumer/http.go
|
requestHandler
|
func (cons *HTTP) requestHandler(resp http.ResponseWriter, req *http.Request) {
if cons.htpasswd != "" {
if !cons.checkAuth(req) {
resp.WriteHeader(http.StatusUnauthorized)
return
}
}
if cons.withHeaders {
// Read the whole package
requestBuffer := bytes.NewBuffer(nil)
if err := req.Write(requestBuffer); err != nil {
resp.WriteHeader(http.StatusBadRequest)
cons.Logger.Error(err)
return // ### return, missing body or bad write ###
}
cons.Enqueue(requestBuffer.Bytes())
resp.WriteHeader(http.StatusOK)
} else {
// Read only the message body
if req.Body == nil {
resp.WriteHeader(http.StatusBadRequest)
return // ### return, missing body ###
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
resp.WriteHeader(http.StatusBadRequest)
cons.Logger.Error(err)
return // ### return, missing body or bad write ###
}
defer req.Body.Close()
cons.Enqueue(body)
resp.WriteHeader(http.StatusOK)
}
}
|
go
|
func (cons *HTTP) requestHandler(resp http.ResponseWriter, req *http.Request) {
if cons.htpasswd != "" {
if !cons.checkAuth(req) {
resp.WriteHeader(http.StatusUnauthorized)
return
}
}
if cons.withHeaders {
// Read the whole package
requestBuffer := bytes.NewBuffer(nil)
if err := req.Write(requestBuffer); err != nil {
resp.WriteHeader(http.StatusBadRequest)
cons.Logger.Error(err)
return // ### return, missing body or bad write ###
}
cons.Enqueue(requestBuffer.Bytes())
resp.WriteHeader(http.StatusOK)
} else {
// Read only the message body
if req.Body == nil {
resp.WriteHeader(http.StatusBadRequest)
return // ### return, missing body ###
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
resp.WriteHeader(http.StatusBadRequest)
cons.Logger.Error(err)
return // ### return, missing body or bad write ###
}
defer req.Body.Close()
cons.Enqueue(body)
resp.WriteHeader(http.StatusOK)
}
}
|
[
"func",
"(",
"cons",
"*",
"HTTP",
")",
"requestHandler",
"(",
"resp",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"cons",
".",
"htpasswd",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"cons",
".",
"checkAuth",
"(",
"req",
")",
"{",
"resp",
".",
"WriteHeader",
"(",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"cons",
".",
"withHeaders",
"{",
"// Read the whole package",
"requestBuffer",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"if",
"err",
":=",
"req",
".",
"Write",
"(",
"requestBuffer",
")",
";",
"err",
"!=",
"nil",
"{",
"resp",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"cons",
".",
"Logger",
".",
"Error",
"(",
"err",
")",
"\n",
"return",
"// ### return, missing body or bad write ###",
"\n",
"}",
"\n\n",
"cons",
".",
"Enqueue",
"(",
"requestBuffer",
".",
"Bytes",
"(",
")",
")",
"\n",
"resp",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"else",
"{",
"// Read only the message body",
"if",
"req",
".",
"Body",
"==",
"nil",
"{",
"resp",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"// ### return, missing body ###",
"\n",
"}",
"\n\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"req",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"resp",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"cons",
".",
"Logger",
".",
"Error",
"(",
"err",
")",
"\n",
"return",
"// ### return, missing body or bad write ###",
"\n",
"}",
"\n",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"cons",
".",
"Enqueue",
"(",
"body",
")",
"\n",
"resp",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n",
"}"
] |
// requestHandler will handle a single web request.
|
[
"requestHandler",
"will",
"handle",
"a",
"single",
"web",
"request",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/http.go#L124-L161
|
142,630 |
trivago/gollum
|
producer/InfluxDBWriter10.go
|
configure
|
func (writer *influxDBWriter10) configure(conf core.PluginConfigReader, prod *InfluxDB) error {
writer.host = conf.GetString("Host", "localhost:8086")
writer.username = conf.GetString("User", "")
writer.password = conf.GetString("Password", "")
writer.databaseTemplate = conf.GetString("Database", "default")
writer.buffer = tio.NewByteStream(4096)
writer.connectionUp = false
writer.timeBasedDBName = conf.GetBool("TimeBasedName", true)
writer.Control = prod.Control
writer.logger = prod.Logger
writer.writeURL = fmt.Sprintf("http://%s/write", writer.host)
writer.queryURL = fmt.Sprintf("http://%s/query", writer.host)
writer.pingURL = fmt.Sprintf("http://%s/ping", writer.host)
writer.separator = '?'
if writer.username != "" {
credentials := fmt.Sprintf("?u=%s&p=%s", url.QueryEscape(writer.username), url.QueryEscape(writer.password))
writer.writeURL += credentials
writer.queryURL += credentials
writer.separator = '&'
}
writer.writeURL = fmt.Sprintf("%s%cprecision=ms", writer.writeURL, writer.separator)
return conf.Errors.OrNil()
}
|
go
|
func (writer *influxDBWriter10) configure(conf core.PluginConfigReader, prod *InfluxDB) error {
writer.host = conf.GetString("Host", "localhost:8086")
writer.username = conf.GetString("User", "")
writer.password = conf.GetString("Password", "")
writer.databaseTemplate = conf.GetString("Database", "default")
writer.buffer = tio.NewByteStream(4096)
writer.connectionUp = false
writer.timeBasedDBName = conf.GetBool("TimeBasedName", true)
writer.Control = prod.Control
writer.logger = prod.Logger
writer.writeURL = fmt.Sprintf("http://%s/write", writer.host)
writer.queryURL = fmt.Sprintf("http://%s/query", writer.host)
writer.pingURL = fmt.Sprintf("http://%s/ping", writer.host)
writer.separator = '?'
if writer.username != "" {
credentials := fmt.Sprintf("?u=%s&p=%s", url.QueryEscape(writer.username), url.QueryEscape(writer.password))
writer.writeURL += credentials
writer.queryURL += credentials
writer.separator = '&'
}
writer.writeURL = fmt.Sprintf("%s%cprecision=ms", writer.writeURL, writer.separator)
return conf.Errors.OrNil()
}
|
[
"func",
"(",
"writer",
"*",
"influxDBWriter10",
")",
"configure",
"(",
"conf",
"core",
".",
"PluginConfigReader",
",",
"prod",
"*",
"InfluxDB",
")",
"error",
"{",
"writer",
".",
"host",
"=",
"conf",
".",
"GetString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"writer",
".",
"username",
"=",
"conf",
".",
"GetString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"writer",
".",
"password",
"=",
"conf",
".",
"GetString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"writer",
".",
"databaseTemplate",
"=",
"conf",
".",
"GetString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"writer",
".",
"buffer",
"=",
"tio",
".",
"NewByteStream",
"(",
"4096",
")",
"\n",
"writer",
".",
"connectionUp",
"=",
"false",
"\n",
"writer",
".",
"timeBasedDBName",
"=",
"conf",
".",
"GetBool",
"(",
"\"",
"\"",
",",
"true",
")",
"\n",
"writer",
".",
"Control",
"=",
"prod",
".",
"Control",
"\n",
"writer",
".",
"logger",
"=",
"prod",
".",
"Logger",
"\n\n",
"writer",
".",
"writeURL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"writer",
".",
"host",
")",
"\n",
"writer",
".",
"queryURL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"writer",
".",
"host",
")",
"\n",
"writer",
".",
"pingURL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"writer",
".",
"host",
")",
"\n",
"writer",
".",
"separator",
"=",
"'?'",
"\n\n",
"if",
"writer",
".",
"username",
"!=",
"\"",
"\"",
"{",
"credentials",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"url",
".",
"QueryEscape",
"(",
"writer",
".",
"username",
")",
",",
"url",
".",
"QueryEscape",
"(",
"writer",
".",
"password",
")",
")",
"\n",
"writer",
".",
"writeURL",
"+=",
"credentials",
"\n",
"writer",
".",
"queryURL",
"+=",
"credentials",
"\n",
"writer",
".",
"separator",
"=",
"'&'",
"\n",
"}",
"\n\n",
"writer",
".",
"writeURL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"writer",
".",
"writeURL",
",",
"writer",
".",
"separator",
")",
"\n",
"return",
"conf",
".",
"Errors",
".",
"OrNil",
"(",
")",
"\n",
"}"
] |
// Configure sets the database connection values
|
[
"Configure",
"sets",
"the",
"database",
"connection",
"values"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/InfluxDBWriter10.go#L49-L74
|
142,631 |
trivago/gollum
|
producer/awsS3.go
|
Produce
|
func (prod *AwsS3) Produce(workers *sync.WaitGroup) {
prod.initS3Client()
prod.AddMainWorker(workers)
prod.TickerMessageControlLoop(prod.writeMessage, prod.BatchConfig.BatchTimeout, prod.writeBatchOnTimeOut)
}
|
go
|
func (prod *AwsS3) Produce(workers *sync.WaitGroup) {
prod.initS3Client()
prod.AddMainWorker(workers)
prod.TickerMessageControlLoop(prod.writeMessage, prod.BatchConfig.BatchTimeout, prod.writeBatchOnTimeOut)
}
|
[
"func",
"(",
"prod",
"*",
"AwsS3",
")",
"Produce",
"(",
"workers",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"prod",
".",
"initS3Client",
"(",
")",
"\n\n",
"prod",
".",
"AddMainWorker",
"(",
"workers",
")",
"\n",
"prod",
".",
"TickerMessageControlLoop",
"(",
"prod",
".",
"writeMessage",
",",
"prod",
".",
"BatchConfig",
".",
"BatchTimeout",
",",
"prod",
".",
"writeBatchOnTimeOut",
")",
"\n",
"}"
] |
// Produce writes to a buffer that is send to S3 as a multipart upload.
|
[
"Produce",
"writes",
"to",
"a",
"buffer",
"that",
"is",
"send",
"to",
"S3",
"as",
"a",
"multipart",
"upload",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsS3.go#L118-L123
|
142,632 |
trivago/gollum
|
core/pluginstructtag.go
|
GetBool
|
func (tag PluginStructTag) GetBool() bool {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet || tagValue == "" {
return false
}
value, err := strconv.ParseBool(tagValue)
if err != nil {
panic(err)
}
return value
}
|
go
|
func (tag PluginStructTag) GetBool() bool {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet || tagValue == "" {
return false
}
value, err := strconv.ParseBool(tagValue)
if err != nil {
panic(err)
}
return value
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetBool",
"(",
")",
"bool",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagDefault",
")",
"\n",
"if",
"!",
"tagSet",
"||",
"tagValue",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"value",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"tagValue",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"value",
"\n",
"}"
] |
// GetBool returns the default boolean value for an auto configured field.
// When not set, false is returned.
|
[
"GetBool",
"returns",
"the",
"default",
"boolean",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"false",
"is",
"returned",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L38-L48
|
142,633 |
trivago/gollum
|
core/pluginstructtag.go
|
GetInt
|
func (tag PluginStructTag) GetInt() int64 {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet || len(tagValue) == 0 {
return 0
}
value, err := tstrings.AtoI64(tagValue)
if err != nil {
panic(err)
}
return value
}
|
go
|
func (tag PluginStructTag) GetInt() int64 {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet || len(tagValue) == 0 {
return 0
}
value, err := tstrings.AtoI64(tagValue)
if err != nil {
panic(err)
}
return value
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetInt",
"(",
")",
"int64",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagDefault",
")",
"\n",
"if",
"!",
"tagSet",
"||",
"len",
"(",
"tagValue",
")",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"value",
",",
"err",
":=",
"tstrings",
".",
"AtoI64",
"(",
"tagValue",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"value",
"\n",
"}"
] |
// GetInt returns the default integer value for an auto configured field.
// When not set, 0 is returned. Metrics are not applied to this value.
|
[
"GetInt",
"returns",
"the",
"default",
"integer",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"0",
"is",
"returned",
".",
"Metrics",
"are",
"not",
"applied",
"to",
"this",
"value",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L52-L63
|
142,634 |
trivago/gollum
|
core/pluginstructtag.go
|
GetUint
|
func (tag PluginStructTag) GetUint() uint64 {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet || len(tagValue) == 0 {
return 0
}
value, err := tstrings.AtoU64(tagValue)
if err != nil {
panic(err)
}
return value
}
|
go
|
func (tag PluginStructTag) GetUint() uint64 {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet || len(tagValue) == 0 {
return 0
}
value, err := tstrings.AtoU64(tagValue)
if err != nil {
panic(err)
}
return value
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetUint",
"(",
")",
"uint64",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagDefault",
")",
"\n",
"if",
"!",
"tagSet",
"||",
"len",
"(",
"tagValue",
")",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"value",
",",
"err",
":=",
"tstrings",
".",
"AtoU64",
"(",
"tagValue",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"value",
"\n",
"}"
] |
// GetUint returns the default unsigned integer value for an auto configured
// field. When not set, 0 is returned. Metrics are not applied to this value.
|
[
"GetUint",
"returns",
"the",
"default",
"unsigned",
"integer",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"0",
"is",
"returned",
".",
"Metrics",
"are",
"not",
"applied",
"to",
"this",
"value",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L67-L78
|
142,635 |
trivago/gollum
|
core/pluginstructtag.go
|
GetString
|
func (tag PluginStructTag) GetString() string {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return ""
}
return tstrings.Unescape(tagValue)
}
|
go
|
func (tag PluginStructTag) GetString() string {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return ""
}
return tstrings.Unescape(tagValue)
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetString",
"(",
")",
"string",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagDefault",
")",
"\n",
"if",
"!",
"tagSet",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"tstrings",
".",
"Unescape",
"(",
"tagValue",
")",
"\n",
"}"
] |
// GetString returns the default string value for an auto configured field.
// When not set, "" is returned.
|
[
"GetString",
"returns",
"the",
"default",
"string",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"is",
"returned",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L82-L88
|
142,636 |
trivago/gollum
|
core/pluginstructtag.go
|
GetStream
|
func (tag PluginStructTag) GetStream() MessageStreamID {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return InvalidStreamID
}
return GetStreamID(tagValue)
}
|
go
|
func (tag PluginStructTag) GetStream() MessageStreamID {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return InvalidStreamID
}
return GetStreamID(tagValue)
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetStream",
"(",
")",
"MessageStreamID",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagDefault",
")",
"\n",
"if",
"!",
"tagSet",
"{",
"return",
"InvalidStreamID",
"\n",
"}",
"\n",
"return",
"GetStreamID",
"(",
"tagValue",
")",
"\n",
"}"
] |
// GetStream returns the default message stream value for an auto configured
// field. When not set, InvalidStream is returned.
|
[
"GetStream",
"returns",
"the",
"default",
"message",
"stream",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"InvalidStream",
"is",
"returned",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L92-L98
|
142,637 |
trivago/gollum
|
core/pluginstructtag.go
|
GetStringArray
|
func (tag PluginStructTag) GetStringArray() []string {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return []string{}
}
return strings.Split(tagValue, ",")
}
|
go
|
func (tag PluginStructTag) GetStringArray() []string {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return []string{}
}
return strings.Split(tagValue, ",")
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetStringArray",
"(",
")",
"[",
"]",
"string",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagDefault",
")",
"\n",
"if",
"!",
"tagSet",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Split",
"(",
"tagValue",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// GetStringArray returns the default string array value for an auto configured
// field. When not set an empty array is returned.
|
[
"GetStringArray",
"returns",
"the",
"default",
"string",
"array",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"an",
"empty",
"array",
"is",
"returned",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L102-L108
|
142,638 |
trivago/gollum
|
core/pluginstructtag.go
|
GetByteArray
|
func (tag PluginStructTag) GetByteArray() []byte {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return []byte{}
}
return []byte(tagValue)
}
|
go
|
func (tag PluginStructTag) GetByteArray() []byte {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
if !tagSet {
return []byte{}
}
return []byte(tagValue)
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetByteArray",
"(",
")",
"[",
"]",
"byte",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagDefault",
")",
"\n",
"if",
"!",
"tagSet",
"{",
"return",
"[",
"]",
"byte",
"{",
"}",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"(",
"tagValue",
")",
"\n",
"}"
] |
// GetByteArray returns the default byte array value for an auto configured
// field. When not set an empty array is returned.
|
[
"GetByteArray",
"returns",
"the",
"default",
"byte",
"array",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"an",
"empty",
"array",
"is",
"returned",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L112-L118
|
142,639 |
trivago/gollum
|
core/pluginstructtag.go
|
GetStreamArray
|
func (tag PluginStructTag) GetStreamArray() []MessageStreamID {
streamNames := tag.GetStringArray()
streamIDs := make([]MessageStreamID, 0, len(streamNames))
for _, name := range streamNames {
streamIDs = append(streamIDs, GetStreamID(strings.TrimSpace(name)))
}
return streamIDs
}
|
go
|
func (tag PluginStructTag) GetStreamArray() []MessageStreamID {
streamNames := tag.GetStringArray()
streamIDs := make([]MessageStreamID, 0, len(streamNames))
for _, name := range streamNames {
streamIDs = append(streamIDs, GetStreamID(strings.TrimSpace(name)))
}
return streamIDs
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetStreamArray",
"(",
")",
"[",
"]",
"MessageStreamID",
"{",
"streamNames",
":=",
"tag",
".",
"GetStringArray",
"(",
")",
"\n",
"streamIDs",
":=",
"make",
"(",
"[",
"]",
"MessageStreamID",
",",
"0",
",",
"len",
"(",
"streamNames",
")",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"streamNames",
"{",
"streamIDs",
"=",
"append",
"(",
"streamIDs",
",",
"GetStreamID",
"(",
"strings",
".",
"TrimSpace",
"(",
"name",
")",
")",
")",
"\n",
"}",
"\n\n",
"return",
"streamIDs",
"\n",
"}"
] |
// GetStreamArray returns the default message stream array value for an auto
// configured field. When not set an empty array is returned.
|
[
"GetStreamArray",
"returns",
"the",
"default",
"message",
"stream",
"array",
"value",
"for",
"an",
"auto",
"configured",
"field",
".",
"When",
"not",
"set",
"an",
"empty",
"array",
"is",
"returned",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L122-L130
|
142,640 |
trivago/gollum
|
core/pluginstructtag.go
|
GetMetricScale
|
func (tag PluginStructTag) GetMetricScale() int64 {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagMetric)
if !tagSet {
return 1
}
return metricScale[strings.ToLower(tagValue)]
}
|
go
|
func (tag PluginStructTag) GetMetricScale() int64 {
tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagMetric)
if !tagSet {
return 1
}
return metricScale[strings.ToLower(tagValue)]
}
|
[
"func",
"(",
"tag",
"PluginStructTag",
")",
"GetMetricScale",
"(",
")",
"int64",
"{",
"tagValue",
",",
"tagSet",
":=",
"reflect",
".",
"StructTag",
"(",
"tag",
")",
".",
"Lookup",
"(",
"PluginStructTagMetric",
")",
"\n",
"if",
"!",
"tagSet",
"{",
"return",
"1",
"\n",
"}",
"\n\n",
"return",
"metricScale",
"[",
"strings",
".",
"ToLower",
"(",
"tagValue",
")",
"]",
"\n",
"}"
] |
// GetMetricScale returns the scale as defined by the "metric" tag as a number.
|
[
"GetMetricScale",
"returns",
"the",
"scale",
"as",
"defined",
"by",
"the",
"metric",
"tag",
"as",
"a",
"number",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L133-L140
|
142,641 |
trivago/gollum
|
format/groktojson.go
|
applyGrok
|
func (format *GrokToJSON) applyGrok(content string) (map[string]string, error) {
for _, exp := range format.exp {
values := exp.ParseString(content)
if len(values) > 0 {
return values, nil
}
}
format.Logger.Warningf("Message does not match any pattern: %s", content)
return nil, fmt.Errorf("grok parsing error")
}
|
go
|
func (format *GrokToJSON) applyGrok(content string) (map[string]string, error) {
for _, exp := range format.exp {
values := exp.ParseString(content)
if len(values) > 0 {
return values, nil
}
}
format.Logger.Warningf("Message does not match any pattern: %s", content)
return nil, fmt.Errorf("grok parsing error")
}
|
[
"func",
"(",
"format",
"*",
"GrokToJSON",
")",
"applyGrok",
"(",
"content",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"for",
"_",
",",
"exp",
":=",
"range",
"format",
".",
"exp",
"{",
"values",
":=",
"exp",
".",
"ParseString",
"(",
"content",
")",
"\n",
"if",
"len",
"(",
"values",
")",
">",
"0",
"{",
"return",
"values",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"format",
".",
"Logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"content",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// grok iterates over all defined patterns and parses the content based on the first match.
// It returns a map of the defined values.
|
[
"grok",
"iterates",
"over",
"all",
"defined",
"patterns",
"and",
"parses",
"the",
"content",
"based",
"on",
"the",
"first",
"match",
".",
"It",
"returns",
"a",
"map",
"of",
"the",
"defined",
"values",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/format/groktojson.go#L130-L139
|
142,642 |
trivago/gollum
|
consumer/console.go
|
Enqueue
|
func (cons *Console) Enqueue(data []byte) {
if cons.hasToSetMetadata {
metaData := core.Metadata{}
metaData.SetValue("pipe", []byte(cons.pipeName))
cons.EnqueueWithMetadata(data, metaData)
} else {
cons.SimpleConsumer.Enqueue(data)
}
}
|
go
|
func (cons *Console) Enqueue(data []byte) {
if cons.hasToSetMetadata {
metaData := core.Metadata{}
metaData.SetValue("pipe", []byte(cons.pipeName))
cons.EnqueueWithMetadata(data, metaData)
} else {
cons.SimpleConsumer.Enqueue(data)
}
}
|
[
"func",
"(",
"cons",
"*",
"Console",
")",
"Enqueue",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"if",
"cons",
".",
"hasToSetMetadata",
"{",
"metaData",
":=",
"core",
".",
"Metadata",
"{",
"}",
"\n",
"metaData",
".",
"SetValue",
"(",
"\"",
"\"",
",",
"[",
"]",
"byte",
"(",
"cons",
".",
"pipeName",
")",
")",
"\n\n",
"cons",
".",
"EnqueueWithMetadata",
"(",
"data",
",",
"metaData",
")",
"\n",
"}",
"else",
"{",
"cons",
".",
"SimpleConsumer",
".",
"Enqueue",
"(",
"data",
")",
"\n",
"}",
"\n",
"}"
] |
// Enqueue creates a new message
|
[
"Enqueue",
"creates",
"a",
"new",
"message"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/console.go#L96-L105
|
142,643 |
trivago/gollum
|
docs/generator/tree.go
|
NewTree
|
func NewTree(rootAstNode ast.Node) *TreeNode {
treeCursor := treeCursor{}
// Stub root
treeCursor.root = &TreeNode{
AstNode: nil,
Parent: nil,
Children: []*TreeNode{},
}
treeCursor.current = treeCursor.root
treeCursor.currentDepth = 0
// Populate the tree
ast.Inspect(rootAstNode, treeCursor.insert)
// Return the actual root
return treeCursor.root.Children[0]
}
|
go
|
func NewTree(rootAstNode ast.Node) *TreeNode {
treeCursor := treeCursor{}
// Stub root
treeCursor.root = &TreeNode{
AstNode: nil,
Parent: nil,
Children: []*TreeNode{},
}
treeCursor.current = treeCursor.root
treeCursor.currentDepth = 0
// Populate the tree
ast.Inspect(rootAstNode, treeCursor.insert)
// Return the actual root
return treeCursor.root.Children[0]
}
|
[
"func",
"NewTree",
"(",
"rootAstNode",
"ast",
".",
"Node",
")",
"*",
"TreeNode",
"{",
"treeCursor",
":=",
"treeCursor",
"{",
"}",
"\n\n",
"// Stub root",
"treeCursor",
".",
"root",
"=",
"&",
"TreeNode",
"{",
"AstNode",
":",
"nil",
",",
"Parent",
":",
"nil",
",",
"Children",
":",
"[",
"]",
"*",
"TreeNode",
"{",
"}",
",",
"}",
"\n",
"treeCursor",
".",
"current",
"=",
"treeCursor",
".",
"root",
"\n",
"treeCursor",
".",
"currentDepth",
"=",
"0",
"\n\n",
"// Populate the tree",
"ast",
".",
"Inspect",
"(",
"rootAstNode",
",",
"treeCursor",
".",
"insert",
")",
"\n\n",
"// Return the actual root",
"return",
"treeCursor",
".",
"root",
".",
"Children",
"[",
"0",
"]",
"\n",
"}"
] |
// NewTree creates a new tree of TreeNodes from the contents of the Go AST rooted at rootAstNode.
// Returns a pointer to the root TreeNode.
|
[
"NewTree",
"creates",
"a",
"new",
"tree",
"of",
"TreeNodes",
"from",
"the",
"contents",
"of",
"the",
"Go",
"AST",
"rooted",
"at",
"rootAstNode",
".",
"Returns",
"a",
"pointer",
"to",
"the",
"root",
"TreeNode",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/tree.go#L59-L76
|
142,644 |
trivago/gollum
|
docs/generator/tree.go
|
Search
|
func (treeNode *TreeNode) Search(patternNode PatternNode) []*TreeNode {
results := []*TreeNode{}
// Current node
if treeNode.compare(patternNode) {
results = append(results, treeNode)
}
// Current node's children
for _, child := range treeNode.Children {
for _, subResult := range child.Search(patternNode) {
results = append(results, subResult)
}
}
return results
}
|
go
|
func (treeNode *TreeNode) Search(patternNode PatternNode) []*TreeNode {
results := []*TreeNode{}
// Current node
if treeNode.compare(patternNode) {
results = append(results, treeNode)
}
// Current node's children
for _, child := range treeNode.Children {
for _, subResult := range child.Search(patternNode) {
results = append(results, subResult)
}
}
return results
}
|
[
"func",
"(",
"treeNode",
"*",
"TreeNode",
")",
"Search",
"(",
"patternNode",
"PatternNode",
")",
"[",
"]",
"*",
"TreeNode",
"{",
"results",
":=",
"[",
"]",
"*",
"TreeNode",
"{",
"}",
"\n\n",
"// Current node",
"if",
"treeNode",
".",
"compare",
"(",
"patternNode",
")",
"{",
"results",
"=",
"append",
"(",
"results",
",",
"treeNode",
")",
"\n",
"}",
"\n\n",
"// Current node's children",
"for",
"_",
",",
"child",
":=",
"range",
"treeNode",
".",
"Children",
"{",
"for",
"_",
",",
"subResult",
":=",
"range",
"child",
".",
"Search",
"(",
"patternNode",
")",
"{",
"results",
"=",
"append",
"(",
"results",
",",
"subResult",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"results",
"\n",
"}"
] |
// Search iterates recursively through all subtrees of TreeNode and compares them to
// the pattern three rooted at patternNode. It returns a flat list containing the
// matching subtrees' roots.
|
[
"Search",
"iterates",
"recursively",
"through",
"all",
"subtrees",
"of",
"TreeNode",
"and",
"compares",
"them",
"to",
"the",
"pattern",
"three",
"rooted",
"at",
"patternNode",
".",
"It",
"returns",
"a",
"flat",
"list",
"containing",
"the",
"matching",
"subtrees",
"roots",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/tree.go#L107-L123
|
142,645 |
trivago/gollum
|
docs/generator/tree.go
|
Dump
|
func (treeNode *TreeNode) Dump() {
fmt.Printf("%s<%p>%q\n", strings.Repeat(" ", 4*treeNode.Depth), treeNode, treeNode.astNodeDump())
for _, child := range treeNode.Children {
child.Dump()
}
}
|
go
|
func (treeNode *TreeNode) Dump() {
fmt.Printf("%s<%p>%q\n", strings.Repeat(" ", 4*treeNode.Depth), treeNode, treeNode.astNodeDump())
for _, child := range treeNode.Children {
child.Dump()
}
}
|
[
"func",
"(",
"treeNode",
"*",
"TreeNode",
")",
"Dump",
"(",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"strings",
".",
"Repeat",
"(",
"\"",
"\"",
",",
"4",
"*",
"treeNode",
".",
"Depth",
")",
",",
"treeNode",
",",
"treeNode",
".",
"astNodeDump",
"(",
")",
")",
"\n",
"for",
"_",
",",
"child",
":=",
"range",
"treeNode",
".",
"Children",
"{",
"child",
".",
"Dump",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Dump prints a dumpString of the tree rooted at `treeNode` to stdout
|
[
"Dump",
"prints",
"a",
"dumpString",
"of",
"the",
"tree",
"rooted",
"at",
"treeNode",
"to",
"stdout"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/tree.go#L168-L173
|
142,646 |
trivago/gollum
|
consumer/profiler.go
|
Consume
|
func (cons *Profiler) Consume(workers *sync.WaitGroup) {
cons.AddMainWorker(workers)
go tgo.WithRecoverShutdown(cons.profile)
cons.ControlLoop()
}
|
go
|
func (cons *Profiler) Consume(workers *sync.WaitGroup) {
cons.AddMainWorker(workers)
go tgo.WithRecoverShutdown(cons.profile)
cons.ControlLoop()
}
|
[
"func",
"(",
"cons",
"*",
"Profiler",
")",
"Consume",
"(",
"workers",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"cons",
".",
"AddMainWorker",
"(",
"workers",
")",
"\n\n",
"go",
"tgo",
".",
"WithRecoverShutdown",
"(",
"cons",
".",
"profile",
")",
"\n",
"cons",
".",
"ControlLoop",
"(",
")",
"\n",
"}"
] |
// Consume starts a profile run and exits gollum when done
|
[
"Consume",
"starts",
"a",
"profile",
"run",
"and",
"exits",
"gollum",
"when",
"done"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/profiler.go#L230-L235
|
142,647 |
trivago/gollum
|
producer/file/batchedFileWriter.go
|
IsAccessible
|
func (w *BatchedFileWriter) IsAccessible() bool {
_, err := w.getStats()
return err == nil
}
|
go
|
func (w *BatchedFileWriter) IsAccessible() bool {
_, err := w.getStats()
return err == nil
}
|
[
"func",
"(",
"w",
"*",
"BatchedFileWriter",
")",
"IsAccessible",
"(",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"w",
".",
"getStats",
"(",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsAccessible is part of the BatchedWriter interface and check if the writer can access his file
|
[
"IsAccessible",
"is",
"part",
"of",
"the",
"BatchedWriter",
"interface",
"and",
"check",
"if",
"the",
"writer",
"can",
"access",
"his",
"file"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/batchedFileWriter.go#L66-L69
|
142,648 |
trivago/gollum
|
contrib/native/pcap/pcapsession.go
|
newPcapSession
|
func newPcapSession(client string, logger logrus.FieldLogger) *pcapSession {
return &pcapSession{
client: client,
logger: logger,
}
}
|
go
|
func newPcapSession(client string, logger logrus.FieldLogger) *pcapSession {
return &pcapSession{
client: client,
logger: logger,
}
}
|
[
"func",
"newPcapSession",
"(",
"client",
"string",
",",
"logger",
"logrus",
".",
"FieldLogger",
")",
"*",
"pcapSession",
"{",
"return",
"&",
"pcapSession",
"{",
"client",
":",
"client",
",",
"logger",
":",
"logger",
",",
"}",
"\n",
"}"
] |
// create a new TCP session buffer
|
[
"create",
"a",
"new",
"TCP",
"session",
"buffer"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L57-L62
|
142,649 |
trivago/gollum
|
contrib/native/pcap/pcapsession.go
|
findPacketSlot
|
func findPacketSlot(seq uint32, list packetList) (int, bool) {
offset := 0
partLen := len(list)
for partLen > 1 {
median := partLen / 2
TCPHeader, _ := tcpFromPcap(list[offset+median])
switch {
case seq < TCPHeader.Seq:
partLen = median
case seq > TCPHeader.Seq:
offset += median + 1
partLen -= median + 1
default:
return offset, true // ### return, duplicate ###
}
}
if partLen == 0 {
return offset, false // ### return, out of range ###
}
TCPHeader, _ := tcpFromPcap(list[offset])
if seq > TCPHeader.Seq {
return offset + 1, false
}
return offset, seq == TCPHeader.Seq // ### return, duplicate ###
}
|
go
|
func findPacketSlot(seq uint32, list packetList) (int, bool) {
offset := 0
partLen := len(list)
for partLen > 1 {
median := partLen / 2
TCPHeader, _ := tcpFromPcap(list[offset+median])
switch {
case seq < TCPHeader.Seq:
partLen = median
case seq > TCPHeader.Seq:
offset += median + 1
partLen -= median + 1
default:
return offset, true // ### return, duplicate ###
}
}
if partLen == 0 {
return offset, false // ### return, out of range ###
}
TCPHeader, _ := tcpFromPcap(list[offset])
if seq > TCPHeader.Seq {
return offset + 1, false
}
return offset, seq == TCPHeader.Seq // ### return, duplicate ###
}
|
[
"func",
"findPacketSlot",
"(",
"seq",
"uint32",
",",
"list",
"packetList",
")",
"(",
"int",
",",
"bool",
")",
"{",
"offset",
":=",
"0",
"\n",
"partLen",
":=",
"len",
"(",
"list",
")",
"\n\n",
"for",
"partLen",
">",
"1",
"{",
"median",
":=",
"partLen",
"/",
"2",
"\n",
"TCPHeader",
",",
"_",
":=",
"tcpFromPcap",
"(",
"list",
"[",
"offset",
"+",
"median",
"]",
")",
"\n",
"switch",
"{",
"case",
"seq",
"<",
"TCPHeader",
".",
"Seq",
":",
"partLen",
"=",
"median",
"\n",
"case",
"seq",
">",
"TCPHeader",
".",
"Seq",
":",
"offset",
"+=",
"median",
"+",
"1",
"\n",
"partLen",
"-=",
"median",
"+",
"1",
"\n",
"default",
":",
"return",
"offset",
",",
"true",
"// ### return, duplicate ###",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"partLen",
"==",
"0",
"{",
"return",
"offset",
",",
"false",
"// ### return, out of range ###",
"\n",
"}",
"\n\n",
"TCPHeader",
",",
"_",
":=",
"tcpFromPcap",
"(",
"list",
"[",
"offset",
"]",
")",
"\n",
"if",
"seq",
">",
"TCPHeader",
".",
"Seq",
"{",
"return",
"offset",
"+",
"1",
",",
"false",
"\n",
"}",
"\n\n",
"return",
"offset",
",",
"seq",
"==",
"TCPHeader",
".",
"Seq",
"// ### return, duplicate ###",
"\n",
"}"
] |
// binary search for an insertion point in the packet list
|
[
"binary",
"search",
"for",
"an",
"insertion",
"point",
"in",
"the",
"packet",
"list"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L97-L125
|
142,650 |
trivago/gollum
|
contrib/native/pcap/pcapsession.go
|
insert
|
func (list packetList) insert(newPkt *pcap.Packet) packetList {
if len(list) == 0 {
return packetList{newPkt}
}
// 32-Bit integer overflow handling (stable for 65k blocks).
// If the smallest (leftmost) number in the stored packages is much smaller
// or much larger than the incoming number there is an overflow
TCPHeader, _ := tcpFromPcap(newPkt)
newPktSeq := TCPHeader.Seq
frontTCPHeader, _ := tcpFromPcap(list[0])
backTCPHeader, _ := tcpFromPcap(list[len(list)-1])
if newPktSeq < seqLow && frontTCPHeader.Seq > seqHigh {
// Overflow: add low value segment packet
for i, pkt := range list {
TCPHeader, _ = tcpFromPcap(pkt)
if TCPHeader.Seq > seqHigh {
continue // skip high value segment
}
if newPktSeq < TCPHeader.Seq {
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
if newPktSeq == TCPHeader.Seq {
list[i] = newPkt
return list // ### return, replaced ###
}
}
} else if newPktSeq > seqHigh && backTCPHeader.Seq < seqLow {
// Overflow: add high value segment packet
for i, pkt := range list {
TCPHeader, _ = tcpFromPcap(pkt)
if newPktSeq < TCPHeader.Seq || TCPHeader.Seq < seqLow {
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
if newPktSeq == TCPHeader.Seq {
list[i] = newPkt
return list // ### return, replaced ###
}
}
} else {
// Large package insert (binary search)
if len(list) > 10 {
i, duplicate := findPacketSlot(newPktSeq, list)
switch {
case duplicate:
list[i] = newPkt
return list // ### return, replaced ###
case i < 0:
return append(packetList{newPkt}, list...) // ### return, prepend ###
case i < len(list):
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
} else {
// Small package insert (linear Search)
for i, pkt := range list {
TCPHeader, _ = tcpFromPcap(pkt)
if newPktSeq < TCPHeader.Seq {
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
if newPktSeq == TCPHeader.Seq {
list[i] = newPkt
return list // ### return, replaced ###
}
}
}
}
return append(list, newPkt)
}
|
go
|
func (list packetList) insert(newPkt *pcap.Packet) packetList {
if len(list) == 0 {
return packetList{newPkt}
}
// 32-Bit integer overflow handling (stable for 65k blocks).
// If the smallest (leftmost) number in the stored packages is much smaller
// or much larger than the incoming number there is an overflow
TCPHeader, _ := tcpFromPcap(newPkt)
newPktSeq := TCPHeader.Seq
frontTCPHeader, _ := tcpFromPcap(list[0])
backTCPHeader, _ := tcpFromPcap(list[len(list)-1])
if newPktSeq < seqLow && frontTCPHeader.Seq > seqHigh {
// Overflow: add low value segment packet
for i, pkt := range list {
TCPHeader, _ = tcpFromPcap(pkt)
if TCPHeader.Seq > seqHigh {
continue // skip high value segment
}
if newPktSeq < TCPHeader.Seq {
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
if newPktSeq == TCPHeader.Seq {
list[i] = newPkt
return list // ### return, replaced ###
}
}
} else if newPktSeq > seqHigh && backTCPHeader.Seq < seqLow {
// Overflow: add high value segment packet
for i, pkt := range list {
TCPHeader, _ = tcpFromPcap(pkt)
if newPktSeq < TCPHeader.Seq || TCPHeader.Seq < seqLow {
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
if newPktSeq == TCPHeader.Seq {
list[i] = newPkt
return list // ### return, replaced ###
}
}
} else {
// Large package insert (binary search)
if len(list) > 10 {
i, duplicate := findPacketSlot(newPktSeq, list)
switch {
case duplicate:
list[i] = newPkt
return list // ### return, replaced ###
case i < 0:
return append(packetList{newPkt}, list...) // ### return, prepend ###
case i < len(list):
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
} else {
// Small package insert (linear Search)
for i, pkt := range list {
TCPHeader, _ = tcpFromPcap(pkt)
if newPktSeq < TCPHeader.Seq {
return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ###
}
if newPktSeq == TCPHeader.Seq {
list[i] = newPkt
return list // ### return, replaced ###
}
}
}
}
return append(list, newPkt)
}
|
[
"func",
"(",
"list",
"packetList",
")",
"insert",
"(",
"newPkt",
"*",
"pcap",
".",
"Packet",
")",
"packetList",
"{",
"if",
"len",
"(",
"list",
")",
"==",
"0",
"{",
"return",
"packetList",
"{",
"newPkt",
"}",
"\n",
"}",
"\n\n",
"// 32-Bit integer overflow handling (stable for 65k blocks).",
"// If the smallest (leftmost) number in the stored packages is much smaller",
"// or much larger than the incoming number there is an overflow",
"TCPHeader",
",",
"_",
":=",
"tcpFromPcap",
"(",
"newPkt",
")",
"\n",
"newPktSeq",
":=",
"TCPHeader",
".",
"Seq",
"\n",
"frontTCPHeader",
",",
"_",
":=",
"tcpFromPcap",
"(",
"list",
"[",
"0",
"]",
")",
"\n",
"backTCPHeader",
",",
"_",
":=",
"tcpFromPcap",
"(",
"list",
"[",
"len",
"(",
"list",
")",
"-",
"1",
"]",
")",
"\n\n",
"if",
"newPktSeq",
"<",
"seqLow",
"&&",
"frontTCPHeader",
".",
"Seq",
">",
"seqHigh",
"{",
"// Overflow: add low value segment packet",
"for",
"i",
",",
"pkt",
":=",
"range",
"list",
"{",
"TCPHeader",
",",
"_",
"=",
"tcpFromPcap",
"(",
"pkt",
")",
"\n",
"if",
"TCPHeader",
".",
"Seq",
">",
"seqHigh",
"{",
"continue",
"// skip high value segment",
"\n",
"}",
"\n",
"if",
"newPktSeq",
"<",
"TCPHeader",
".",
"Seq",
"{",
"return",
"append",
"(",
"list",
"[",
":",
"i",
"]",
",",
"append",
"(",
"packetList",
"{",
"newPkt",
"}",
",",
"list",
"[",
"i",
":",
"]",
"...",
")",
"...",
")",
"// ### return insert ###",
"\n",
"}",
"\n",
"if",
"newPktSeq",
"==",
"TCPHeader",
".",
"Seq",
"{",
"list",
"[",
"i",
"]",
"=",
"newPkt",
"\n",
"return",
"list",
"// ### return, replaced ###",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"newPktSeq",
">",
"seqHigh",
"&&",
"backTCPHeader",
".",
"Seq",
"<",
"seqLow",
"{",
"// Overflow: add high value segment packet",
"for",
"i",
",",
"pkt",
":=",
"range",
"list",
"{",
"TCPHeader",
",",
"_",
"=",
"tcpFromPcap",
"(",
"pkt",
")",
"\n",
"if",
"newPktSeq",
"<",
"TCPHeader",
".",
"Seq",
"||",
"TCPHeader",
".",
"Seq",
"<",
"seqLow",
"{",
"return",
"append",
"(",
"list",
"[",
":",
"i",
"]",
",",
"append",
"(",
"packetList",
"{",
"newPkt",
"}",
",",
"list",
"[",
"i",
":",
"]",
"...",
")",
"...",
")",
"// ### return insert ###",
"\n",
"}",
"\n",
"if",
"newPktSeq",
"==",
"TCPHeader",
".",
"Seq",
"{",
"list",
"[",
"i",
"]",
"=",
"newPkt",
"\n",
"return",
"list",
"// ### return, replaced ###",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Large package insert (binary search)",
"if",
"len",
"(",
"list",
")",
">",
"10",
"{",
"i",
",",
"duplicate",
":=",
"findPacketSlot",
"(",
"newPktSeq",
",",
"list",
")",
"\n",
"switch",
"{",
"case",
"duplicate",
":",
"list",
"[",
"i",
"]",
"=",
"newPkt",
"\n",
"return",
"list",
"// ### return, replaced ###",
"\n",
"case",
"i",
"<",
"0",
":",
"return",
"append",
"(",
"packetList",
"{",
"newPkt",
"}",
",",
"list",
"...",
")",
"// ### return, prepend ###",
"\n",
"case",
"i",
"<",
"len",
"(",
"list",
")",
":",
"return",
"append",
"(",
"list",
"[",
":",
"i",
"]",
",",
"append",
"(",
"packetList",
"{",
"newPkt",
"}",
",",
"list",
"[",
"i",
":",
"]",
"...",
")",
"...",
")",
"// ### return insert ###",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Small package insert (linear Search)",
"for",
"i",
",",
"pkt",
":=",
"range",
"list",
"{",
"TCPHeader",
",",
"_",
"=",
"tcpFromPcap",
"(",
"pkt",
")",
"\n",
"if",
"newPktSeq",
"<",
"TCPHeader",
".",
"Seq",
"{",
"return",
"append",
"(",
"list",
"[",
":",
"i",
"]",
",",
"append",
"(",
"packetList",
"{",
"newPkt",
"}",
",",
"list",
"[",
"i",
":",
"]",
"...",
")",
"...",
")",
"// ### return insert ###",
"\n",
"}",
"\n",
"if",
"newPktSeq",
"==",
"TCPHeader",
".",
"Seq",
"{",
"list",
"[",
"i",
"]",
"=",
"newPkt",
"\n",
"return",
"list",
"// ### return, replaced ###",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"append",
"(",
"list",
",",
"newPkt",
")",
"\n",
"}"
] |
// insertion sort for new packages by sequence number
|
[
"insertion",
"sort",
"for",
"new",
"packages",
"by",
"sequence",
"number"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L128-L198
|
142,651 |
trivago/gollum
|
contrib/native/pcap/pcapsession.go
|
isComplete
|
func (list packetList) isComplete() (bool, int) {
numPackets := len(list)
// Trivial cases
switch numPackets {
case 0:
return false, 0
case 1:
return true, len(list[0].Payload)
case 2:
TCPHeader0, _ := tcpFromPcap(list[0])
TCPHeader1, _ := tcpFromPcap(list[1])
size0 := len(list[0].Payload)
if TCPHeader0.Seq+uint32(size0) == TCPHeader1.Seq {
return true, size0 + len(list[1].Payload)
}
return false, 0
}
// More than 2 packets -> loop
TCPHeader, _ := tcpFromPcap(list[0])
payloadSize := len(list[0].Payload)
prevSeq := TCPHeader.Seq
prevSize := len(list[0].Payload)
for i := 1; i < numPackets; i++ {
TCPHeader, _ = tcpFromPcap(list[i])
if prevSeq+uint32(prevSize) != TCPHeader.Seq {
return false, 0
}
prevSeq = TCPHeader.Seq
prevSize = len(list[i].Payload)
payloadSize += prevSize
}
return true, payloadSize
}
|
go
|
func (list packetList) isComplete() (bool, int) {
numPackets := len(list)
// Trivial cases
switch numPackets {
case 0:
return false, 0
case 1:
return true, len(list[0].Payload)
case 2:
TCPHeader0, _ := tcpFromPcap(list[0])
TCPHeader1, _ := tcpFromPcap(list[1])
size0 := len(list[0].Payload)
if TCPHeader0.Seq+uint32(size0) == TCPHeader1.Seq {
return true, size0 + len(list[1].Payload)
}
return false, 0
}
// More than 2 packets -> loop
TCPHeader, _ := tcpFromPcap(list[0])
payloadSize := len(list[0].Payload)
prevSeq := TCPHeader.Seq
prevSize := len(list[0].Payload)
for i := 1; i < numPackets; i++ {
TCPHeader, _ = tcpFromPcap(list[i])
if prevSeq+uint32(prevSize) != TCPHeader.Seq {
return false, 0
}
prevSeq = TCPHeader.Seq
prevSize = len(list[i].Payload)
payloadSize += prevSize
}
return true, payloadSize
}
|
[
"func",
"(",
"list",
"packetList",
")",
"isComplete",
"(",
")",
"(",
"bool",
",",
"int",
")",
"{",
"numPackets",
":=",
"len",
"(",
"list",
")",
"\n\n",
"// Trivial cases",
"switch",
"numPackets",
"{",
"case",
"0",
":",
"return",
"false",
",",
"0",
"\n",
"case",
"1",
":",
"return",
"true",
",",
"len",
"(",
"list",
"[",
"0",
"]",
".",
"Payload",
")",
"\n",
"case",
"2",
":",
"TCPHeader0",
",",
"_",
":=",
"tcpFromPcap",
"(",
"list",
"[",
"0",
"]",
")",
"\n",
"TCPHeader1",
",",
"_",
":=",
"tcpFromPcap",
"(",
"list",
"[",
"1",
"]",
")",
"\n",
"size0",
":=",
"len",
"(",
"list",
"[",
"0",
"]",
".",
"Payload",
")",
"\n\n",
"if",
"TCPHeader0",
".",
"Seq",
"+",
"uint32",
"(",
"size0",
")",
"==",
"TCPHeader1",
".",
"Seq",
"{",
"return",
"true",
",",
"size0",
"+",
"len",
"(",
"list",
"[",
"1",
"]",
".",
"Payload",
")",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"0",
"\n",
"}",
"\n\n",
"// More than 2 packets -> loop",
"TCPHeader",
",",
"_",
":=",
"tcpFromPcap",
"(",
"list",
"[",
"0",
"]",
")",
"\n",
"payloadSize",
":=",
"len",
"(",
"list",
"[",
"0",
"]",
".",
"Payload",
")",
"\n",
"prevSeq",
":=",
"TCPHeader",
".",
"Seq",
"\n",
"prevSize",
":=",
"len",
"(",
"list",
"[",
"0",
"]",
".",
"Payload",
")",
"\n\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"numPackets",
";",
"i",
"++",
"{",
"TCPHeader",
",",
"_",
"=",
"tcpFromPcap",
"(",
"list",
"[",
"i",
"]",
")",
"\n",
"if",
"prevSeq",
"+",
"uint32",
"(",
"prevSize",
")",
"!=",
"TCPHeader",
".",
"Seq",
"{",
"return",
"false",
",",
"0",
"\n",
"}",
"\n\n",
"prevSeq",
"=",
"TCPHeader",
".",
"Seq",
"\n",
"prevSize",
"=",
"len",
"(",
"list",
"[",
"i",
"]",
".",
"Payload",
")",
"\n",
"payloadSize",
"+=",
"prevSize",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"payloadSize",
"\n",
"}"
] |
// check if all packets have consecutive sequence numbers and calculate the
// buffer size required for processing
|
[
"check",
"if",
"all",
"packets",
"have",
"consecutive",
"sequence",
"numbers",
"and",
"calculate",
"the",
"buffer",
"size",
"required",
"for",
"processing"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L202-L243
|
142,652 |
trivago/gollum
|
contrib/native/pcap/pcapsession.go
|
dropPackets
|
func (session *pcapSession) dropPackets(size int) {
chunkSize := 0
for i, pkt := range session.packets {
chunkSize += len(pkt.Payload)
if chunkSize > size {
session.packets = session.packets[i:]
}
}
session.packets = session.packets[:0]
}
|
go
|
func (session *pcapSession) dropPackets(size int) {
chunkSize := 0
for i, pkt := range session.packets {
chunkSize += len(pkt.Payload)
if chunkSize > size {
session.packets = session.packets[i:]
}
}
session.packets = session.packets[:0]
}
|
[
"func",
"(",
"session",
"*",
"pcapSession",
")",
"dropPackets",
"(",
"size",
"int",
")",
"{",
"chunkSize",
":=",
"0",
"\n",
"for",
"i",
",",
"pkt",
":=",
"range",
"session",
".",
"packets",
"{",
"chunkSize",
"+=",
"len",
"(",
"pkt",
".",
"Payload",
")",
"\n",
"if",
"chunkSize",
">",
"size",
"{",
"session",
".",
"packets",
"=",
"session",
".",
"packets",
"[",
"i",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"session",
".",
"packets",
"=",
"session",
".",
"packets",
"[",
":",
"0",
"]",
"\n",
"}"
] |
// remove processed packets from the list.
|
[
"remove",
"processed",
"packets",
"from",
"the",
"list",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L255-L264
|
142,653 |
trivago/gollum
|
contrib/native/pcap/pcapsession.go
|
addPacket
|
func (session *pcapSession) addPacket(cons *PcapHTTPConsumer, pkt *pcap.Packet) {
if len(pkt.Payload) == 0 {
return // ### return, no payload ###
}
session.packets = session.packets.insert(pkt)
if complete, size := session.packets.isComplete(); complete {
payload := bytes.NewBuffer(make([]byte, 0, size))
for _, pkt := range session.packets {
payload.Write(pkt.Payload)
}
payloadReader := bufio.NewReader(payload)
for {
request, err := http.ReadRequest(payloadReader)
if err != nil {
session.lastError = err
return // ### return, invalid request: packets pending? ###
}
request.Header.Add("X-Timestamp", strconv.FormatInt(time.Now().Unix(), 10))
request.Header.Add("X-Client-Ip", session.client)
extPayload := bytes.NewBuffer(nil)
if err := request.Write(extPayload); err != nil {
if err == io.ErrUnexpectedEOF {
session.lastError = err
return // ### return, invalid request: packets pending? ###
}
// Error: ignore this request
session.logger.Error("PcapHTTPConsumer request writer: ", err)
} else {
// Enqueue this request
cons.enqueueBuffer(extPayload.Bytes())
}
// Remove processed packets from list
if payload.Len() == 0 {
session.packets = session.packets[:0]
return // ### return, processed everything ###
}
numReadBytes := size - payload.Len()
size = payload.Len()
session.dropPackets(numReadBytes)
}
}
}
|
go
|
func (session *pcapSession) addPacket(cons *PcapHTTPConsumer, pkt *pcap.Packet) {
if len(pkt.Payload) == 0 {
return // ### return, no payload ###
}
session.packets = session.packets.insert(pkt)
if complete, size := session.packets.isComplete(); complete {
payload := bytes.NewBuffer(make([]byte, 0, size))
for _, pkt := range session.packets {
payload.Write(pkt.Payload)
}
payloadReader := bufio.NewReader(payload)
for {
request, err := http.ReadRequest(payloadReader)
if err != nil {
session.lastError = err
return // ### return, invalid request: packets pending? ###
}
request.Header.Add("X-Timestamp", strconv.FormatInt(time.Now().Unix(), 10))
request.Header.Add("X-Client-Ip", session.client)
extPayload := bytes.NewBuffer(nil)
if err := request.Write(extPayload); err != nil {
if err == io.ErrUnexpectedEOF {
session.lastError = err
return // ### return, invalid request: packets pending? ###
}
// Error: ignore this request
session.logger.Error("PcapHTTPConsumer request writer: ", err)
} else {
// Enqueue this request
cons.enqueueBuffer(extPayload.Bytes())
}
// Remove processed packets from list
if payload.Len() == 0 {
session.packets = session.packets[:0]
return // ### return, processed everything ###
}
numReadBytes := size - payload.Len()
size = payload.Len()
session.dropPackets(numReadBytes)
}
}
}
|
[
"func",
"(",
"session",
"*",
"pcapSession",
")",
"addPacket",
"(",
"cons",
"*",
"PcapHTTPConsumer",
",",
"pkt",
"*",
"pcap",
".",
"Packet",
")",
"{",
"if",
"len",
"(",
"pkt",
".",
"Payload",
")",
"==",
"0",
"{",
"return",
"// ### return, no payload ###",
"\n",
"}",
"\n\n",
"session",
".",
"packets",
"=",
"session",
".",
"packets",
".",
"insert",
"(",
"pkt",
")",
"\n\n",
"if",
"complete",
",",
"size",
":=",
"session",
".",
"packets",
".",
"isComplete",
"(",
")",
";",
"complete",
"{",
"payload",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"size",
")",
")",
"\n",
"for",
"_",
",",
"pkt",
":=",
"range",
"session",
".",
"packets",
"{",
"payload",
".",
"Write",
"(",
"pkt",
".",
"Payload",
")",
"\n",
"}",
"\n\n",
"payloadReader",
":=",
"bufio",
".",
"NewReader",
"(",
"payload",
")",
"\n",
"for",
"{",
"request",
",",
"err",
":=",
"http",
".",
"ReadRequest",
"(",
"payloadReader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"session",
".",
"lastError",
"=",
"err",
"\n",
"return",
"// ### return, invalid request: packets pending? ###",
"\n",
"}",
"\n\n",
"request",
".",
"Header",
".",
"Add",
"(",
"\"",
"\"",
",",
"strconv",
".",
"FormatInt",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
",",
"10",
")",
")",
"\n",
"request",
".",
"Header",
".",
"Add",
"(",
"\"",
"\"",
",",
"session",
".",
"client",
")",
"\n\n",
"extPayload",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"if",
"err",
":=",
"request",
".",
"Write",
"(",
"extPayload",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"io",
".",
"ErrUnexpectedEOF",
"{",
"session",
".",
"lastError",
"=",
"err",
"\n",
"return",
"// ### return, invalid request: packets pending? ###",
"\n",
"}",
"\n",
"// Error: ignore this request",
"session",
".",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"// Enqueue this request",
"cons",
".",
"enqueueBuffer",
"(",
"extPayload",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// Remove processed packets from list",
"if",
"payload",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"session",
".",
"packets",
"=",
"session",
".",
"packets",
"[",
":",
"0",
"]",
"\n",
"return",
"// ### return, processed everything ###",
"\n",
"}",
"\n\n",
"numReadBytes",
":=",
"size",
"-",
"payload",
".",
"Len",
"(",
")",
"\n",
"size",
"=",
"payload",
".",
"Len",
"(",
")",
"\n",
"session",
".",
"dropPackets",
"(",
"numReadBytes",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// add a TCP packet to the session and try to generate a HTTP packet
|
[
"add",
"a",
"TCP",
"packet",
"to",
"the",
"session",
"and",
"try",
"to",
"generate",
"a",
"HTTP",
"packet"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L267-L315
|
142,654 |
trivago/gollum
|
core/simpleconsumer.go
|
Configure
|
func (cons *SimpleConsumer) Configure(conf PluginConfigReader) {
cons.id = conf.GetID()
cons.Logger = conf.GetLogger()
cons.runState = NewPluginRunState()
cons.control = make(chan PluginControl, 1)
numRoutines := conf.GetInt("ModulatorRoutines", 0)
queueSize := conf.GetInt("ModulatorQueueSize", 1024)
if numRoutines > 0 {
cons.Logger.Debugf("Using %d modulator routines", numRoutines)
cons.modulatorQueue = NewMessageQueue(int(queueSize))
for i := 0; i < int(numRoutines); i++ {
go cons.processQueue()
}
cons.enqueueMessage = cons.parallelEnqueue
} else {
cons.enqueueMessage = cons.directEnqueue
}
// Simple health check for the plugin state
// Path: "/<plugin_id>/pluginState"
cons.AddHealthCheckAt("/pluginState", func() (code int, body string) {
if cons.IsActive() {
return thealthcheck.StatusOK, fmt.Sprintf("ACTIVE: %s", cons.runState.GetStateString())
}
return thealthcheck.StatusServiceUnavailable,
fmt.Sprintf("NOT_ACTIVE: %s", cons.runState.GetStateString())
})
}
|
go
|
func (cons *SimpleConsumer) Configure(conf PluginConfigReader) {
cons.id = conf.GetID()
cons.Logger = conf.GetLogger()
cons.runState = NewPluginRunState()
cons.control = make(chan PluginControl, 1)
numRoutines := conf.GetInt("ModulatorRoutines", 0)
queueSize := conf.GetInt("ModulatorQueueSize", 1024)
if numRoutines > 0 {
cons.Logger.Debugf("Using %d modulator routines", numRoutines)
cons.modulatorQueue = NewMessageQueue(int(queueSize))
for i := 0; i < int(numRoutines); i++ {
go cons.processQueue()
}
cons.enqueueMessage = cons.parallelEnqueue
} else {
cons.enqueueMessage = cons.directEnqueue
}
// Simple health check for the plugin state
// Path: "/<plugin_id>/pluginState"
cons.AddHealthCheckAt("/pluginState", func() (code int, body string) {
if cons.IsActive() {
return thealthcheck.StatusOK, fmt.Sprintf("ACTIVE: %s", cons.runState.GetStateString())
}
return thealthcheck.StatusServiceUnavailable,
fmt.Sprintf("NOT_ACTIVE: %s", cons.runState.GetStateString())
})
}
|
[
"func",
"(",
"cons",
"*",
"SimpleConsumer",
")",
"Configure",
"(",
"conf",
"PluginConfigReader",
")",
"{",
"cons",
".",
"id",
"=",
"conf",
".",
"GetID",
"(",
")",
"\n",
"cons",
".",
"Logger",
"=",
"conf",
".",
"GetLogger",
"(",
")",
"\n",
"cons",
".",
"runState",
"=",
"NewPluginRunState",
"(",
")",
"\n",
"cons",
".",
"control",
"=",
"make",
"(",
"chan",
"PluginControl",
",",
"1",
")",
"\n\n",
"numRoutines",
":=",
"conf",
".",
"GetInt",
"(",
"\"",
"\"",
",",
"0",
")",
"\n",
"queueSize",
":=",
"conf",
".",
"GetInt",
"(",
"\"",
"\"",
",",
"1024",
")",
"\n\n",
"if",
"numRoutines",
">",
"0",
"{",
"cons",
".",
"Logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"numRoutines",
")",
"\n",
"cons",
".",
"modulatorQueue",
"=",
"NewMessageQueue",
"(",
"int",
"(",
"queueSize",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"int",
"(",
"numRoutines",
")",
";",
"i",
"++",
"{",
"go",
"cons",
".",
"processQueue",
"(",
")",
"\n",
"}",
"\n",
"cons",
".",
"enqueueMessage",
"=",
"cons",
".",
"parallelEnqueue",
"\n",
"}",
"else",
"{",
"cons",
".",
"enqueueMessage",
"=",
"cons",
".",
"directEnqueue",
"\n",
"}",
"\n\n",
"// Simple health check for the plugin state",
"// Path: \"/<plugin_id>/pluginState\"",
"cons",
".",
"AddHealthCheckAt",
"(",
"\"",
"\"",
",",
"func",
"(",
")",
"(",
"code",
"int",
",",
"body",
"string",
")",
"{",
"if",
"cons",
".",
"IsActive",
"(",
")",
"{",
"return",
"thealthcheck",
".",
"StatusOK",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cons",
".",
"runState",
".",
"GetStateString",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"thealthcheck",
".",
"StatusServiceUnavailable",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cons",
".",
"runState",
".",
"GetStateString",
"(",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// Configure initializes standard consumer values from a plugin config.
|
[
"Configure",
"initializes",
"standard",
"consumer",
"values",
"from",
"a",
"plugin",
"config",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L77-L106
|
142,655 |
trivago/gollum
|
core/simpleconsumer.go
|
EnqueueWithMetadata
|
func (cons *SimpleConsumer) EnqueueWithMetadata(data []byte, metaData Metadata) {
msg := NewMessage(cons, data, metaData, InvalidStreamID)
cons.enqueueMessage(msg)
}
|
go
|
func (cons *SimpleConsumer) EnqueueWithMetadata(data []byte, metaData Metadata) {
msg := NewMessage(cons, data, metaData, InvalidStreamID)
cons.enqueueMessage(msg)
}
|
[
"func",
"(",
"cons",
"*",
"SimpleConsumer",
")",
"EnqueueWithMetadata",
"(",
"data",
"[",
"]",
"byte",
",",
"metaData",
"Metadata",
")",
"{",
"msg",
":=",
"NewMessage",
"(",
"cons",
",",
"data",
",",
"metaData",
",",
"InvalidStreamID",
")",
"\n",
"cons",
".",
"enqueueMessage",
"(",
"msg",
")",
"\n",
"}"
] |
// EnqueueWithMetadata works like EnqueueWithSequence and allows to set meta data directly
|
[
"EnqueueWithMetadata",
"works",
"like",
"EnqueueWithSequence",
"and",
"allows",
"to",
"set",
"meta",
"data",
"directly"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L207-L210
|
142,656 |
trivago/gollum
|
core/simpleconsumer.go
|
ControlLoop
|
func (cons *SimpleConsumer) ControlLoop() {
cons.setState(PluginStateActive)
defer cons.setState(PluginStateDead)
defer cons.Logger.Debug("Stopped")
for {
command := <-cons.control
switch command {
default:
cons.Logger.Debug("Received untracked command")
// Do nothing
case PluginControlStopConsumer:
cons.Logger.Debug("Preparing for stop")
cons.setState(PluginStatePrepareStop)
if cons.onPrepareStop != nil {
if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onPrepareStop) {
cons.Logger.Error("Timeout during onPrepareStop")
}
}
cons.Logger.Debug("Executing stop command")
cons.setState(PluginStateStopping)
if cons.onStop != nil {
if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onStop) {
cons.Logger.Errorf("Timeout during onStop")
}
}
if cons.modulatorQueue != nil {
close(cons.modulatorQueue)
}
return // ### return ###
case PluginControlRoll:
cons.Logger.Debug("Received roll command")
if cons.onRoll != nil {
cons.onRoll()
}
}
}
}
|
go
|
func (cons *SimpleConsumer) ControlLoop() {
cons.setState(PluginStateActive)
defer cons.setState(PluginStateDead)
defer cons.Logger.Debug("Stopped")
for {
command := <-cons.control
switch command {
default:
cons.Logger.Debug("Received untracked command")
// Do nothing
case PluginControlStopConsumer:
cons.Logger.Debug("Preparing for stop")
cons.setState(PluginStatePrepareStop)
if cons.onPrepareStop != nil {
if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onPrepareStop) {
cons.Logger.Error("Timeout during onPrepareStop")
}
}
cons.Logger.Debug("Executing stop command")
cons.setState(PluginStateStopping)
if cons.onStop != nil {
if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onStop) {
cons.Logger.Errorf("Timeout during onStop")
}
}
if cons.modulatorQueue != nil {
close(cons.modulatorQueue)
}
return // ### return ###
case PluginControlRoll:
cons.Logger.Debug("Received roll command")
if cons.onRoll != nil {
cons.onRoll()
}
}
}
}
|
[
"func",
"(",
"cons",
"*",
"SimpleConsumer",
")",
"ControlLoop",
"(",
")",
"{",
"cons",
".",
"setState",
"(",
"PluginStateActive",
")",
"\n",
"defer",
"cons",
".",
"setState",
"(",
"PluginStateDead",
")",
"\n",
"defer",
"cons",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"for",
"{",
"command",
":=",
"<-",
"cons",
".",
"control",
"\n",
"switch",
"command",
"{",
"default",
":",
"cons",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"// Do nothing",
"case",
"PluginControlStopConsumer",
":",
"cons",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"cons",
".",
"setState",
"(",
"PluginStatePrepareStop",
")",
"\n\n",
"if",
"cons",
".",
"onPrepareStop",
"!=",
"nil",
"{",
"if",
"!",
"tgo",
".",
"ReturnAfter",
"(",
"cons",
".",
"shutdownTimeout",
"*",
"5",
",",
"cons",
".",
"onPrepareStop",
")",
"{",
"cons",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"cons",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"cons",
".",
"setState",
"(",
"PluginStateStopping",
")",
"\n\n",
"if",
"cons",
".",
"onStop",
"!=",
"nil",
"{",
"if",
"!",
"tgo",
".",
"ReturnAfter",
"(",
"cons",
".",
"shutdownTimeout",
"*",
"5",
",",
"cons",
".",
"onStop",
")",
"{",
"cons",
".",
"Logger",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"cons",
".",
"modulatorQueue",
"!=",
"nil",
"{",
"close",
"(",
"cons",
".",
"modulatorQueue",
")",
"\n",
"}",
"\n",
"return",
"// ### return ###",
"\n\n",
"case",
"PluginControlRoll",
":",
"cons",
".",
"Logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"if",
"cons",
".",
"onRoll",
"!=",
"nil",
"{",
"cons",
".",
"onRoll",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// ControlLoop listens to the control channel and triggers callbacks for these
// messages. Upon stop control message doExit will be set to true.
|
[
"ControlLoop",
"listens",
"to",
"the",
"control",
"channel",
"and",
"triggers",
"callbacks",
"for",
"these",
"messages",
".",
"Upon",
"stop",
"control",
"message",
"doExit",
"will",
"be",
"set",
"to",
"true",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L266-L309
|
142,657 |
trivago/gollum
|
core/simpleconsumer.go
|
TickerControlLoop
|
func (cons *SimpleConsumer) TickerControlLoop(interval time.Duration, onTick func()) {
cons.setState(PluginStateActive)
go cons.tickerLoop(interval, onTick)
cons.ControlLoop()
}
|
go
|
func (cons *SimpleConsumer) TickerControlLoop(interval time.Duration, onTick func()) {
cons.setState(PluginStateActive)
go cons.tickerLoop(interval, onTick)
cons.ControlLoop()
}
|
[
"func",
"(",
"cons",
"*",
"SimpleConsumer",
")",
"TickerControlLoop",
"(",
"interval",
"time",
".",
"Duration",
",",
"onTick",
"func",
"(",
")",
")",
"{",
"cons",
".",
"setState",
"(",
"PluginStateActive",
")",
"\n",
"go",
"cons",
".",
"tickerLoop",
"(",
"interval",
",",
"onTick",
")",
"\n",
"cons",
".",
"ControlLoop",
"(",
")",
"\n",
"}"
] |
// TickerControlLoop is like MessageLoop but executes a given function at
// every given interval tick, too. Note that the interval is not exact. If the
// onTick function takes longer than interval, the next tick will be delayed
// until onTick finishes.
|
[
"TickerControlLoop",
"is",
"like",
"MessageLoop",
"but",
"executes",
"a",
"given",
"function",
"at",
"every",
"given",
"interval",
"tick",
"too",
".",
"Note",
"that",
"the",
"interval",
"is",
"not",
"exact",
".",
"If",
"the",
"onTick",
"function",
"takes",
"longer",
"than",
"interval",
"the",
"next",
"tick",
"will",
"be",
"delayed",
"until",
"onTick",
"finishes",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L315-L319
|
142,658 |
trivago/gollum
|
producer/awsCloudwatchlogs.go
|
numEvents
|
func (prod *AwsCloudwatchLogs) numEvents(messages []*core.Message, checkFn ...indexNumFn) int {
index := maxBatchEvents
for _, fn := range checkFn {
result := fn(messages)
if result < index {
index = result
}
}
return index
}
|
go
|
func (prod *AwsCloudwatchLogs) numEvents(messages []*core.Message, checkFn ...indexNumFn) int {
index := maxBatchEvents
for _, fn := range checkFn {
result := fn(messages)
if result < index {
index = result
}
}
return index
}
|
[
"func",
"(",
"prod",
"*",
"AwsCloudwatchLogs",
")",
"numEvents",
"(",
"messages",
"[",
"]",
"*",
"core",
".",
"Message",
",",
"checkFn",
"...",
"indexNumFn",
")",
"int",
"{",
"index",
":=",
"maxBatchEvents",
"\n",
"for",
"_",
",",
"fn",
":=",
"range",
"checkFn",
"{",
"result",
":=",
"fn",
"(",
"messages",
")",
"\n",
"if",
"result",
"<",
"index",
"{",
"index",
"=",
"result",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"index",
"\n",
"}"
] |
// Return lowest index based on all check functions
// This function assumes that messages are sorted by timestamp in ascending order
|
[
"Return",
"lowest",
"index",
"based",
"on",
"all",
"check",
"functions",
"This",
"function",
"assumes",
"that",
"messages",
"are",
"sorted",
"by",
"timestamp",
"in",
"ascending",
"order"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L112-L121
|
142,659 |
trivago/gollum
|
producer/awsCloudwatchlogs.go
|
sizeIndex
|
func (prod *AwsCloudwatchLogs) sizeIndex(messages []*core.Message) int {
size, index := 0, 0
for i, message := range messages {
size += len(message.String()) + eventSizeOverhead
if size > maxBatchSize {
break
}
index = i + 1
}
return index
}
|
go
|
func (prod *AwsCloudwatchLogs) sizeIndex(messages []*core.Message) int {
size, index := 0, 0
for i, message := range messages {
size += len(message.String()) + eventSizeOverhead
if size > maxBatchSize {
break
}
index = i + 1
}
return index
}
|
[
"func",
"(",
"prod",
"*",
"AwsCloudwatchLogs",
")",
"sizeIndex",
"(",
"messages",
"[",
"]",
"*",
"core",
".",
"Message",
")",
"int",
"{",
"size",
",",
"index",
":=",
"0",
",",
"0",
"\n",
"for",
"i",
",",
"message",
":=",
"range",
"messages",
"{",
"size",
"+=",
"len",
"(",
"message",
".",
"String",
"(",
")",
")",
"+",
"eventSizeOverhead",
"\n",
"if",
"size",
">",
"maxBatchSize",
"{",
"break",
"\n",
"}",
"\n",
"index",
"=",
"i",
"+",
"1",
"\n",
"}",
"\n",
"return",
"index",
"\n",
"}"
] |
// Return lowest index based on message size
|
[
"Return",
"lowest",
"index",
"based",
"on",
"message",
"size"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L126-L136
|
142,660 |
trivago/gollum
|
producer/awsCloudwatchlogs.go
|
timeIndex
|
func (prod *AwsCloudwatchLogs) timeIndex(messages []*core.Message) (index int) {
if len(messages) == 0 {
return 0
}
firstTimestamp := messages[0].GetCreationTime().Unix()
for i, message := range messages {
if (message.GetCreationTime().Unix() - firstTimestamp) > int64(maxBatchTimeSpan) {
break
}
index = i + 1
}
return index
}
|
go
|
func (prod *AwsCloudwatchLogs) timeIndex(messages []*core.Message) (index int) {
if len(messages) == 0 {
return 0
}
firstTimestamp := messages[0].GetCreationTime().Unix()
for i, message := range messages {
if (message.GetCreationTime().Unix() - firstTimestamp) > int64(maxBatchTimeSpan) {
break
}
index = i + 1
}
return index
}
|
[
"func",
"(",
"prod",
"*",
"AwsCloudwatchLogs",
")",
"timeIndex",
"(",
"messages",
"[",
"]",
"*",
"core",
".",
"Message",
")",
"(",
"index",
"int",
")",
"{",
"if",
"len",
"(",
"messages",
")",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"firstTimestamp",
":=",
"messages",
"[",
"0",
"]",
".",
"GetCreationTime",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"for",
"i",
",",
"message",
":=",
"range",
"messages",
"{",
"if",
"(",
"message",
".",
"GetCreationTime",
"(",
")",
".",
"Unix",
"(",
")",
"-",
"firstTimestamp",
")",
">",
"int64",
"(",
"maxBatchTimeSpan",
")",
"{",
"break",
"\n",
"}",
"\n",
"index",
"=",
"i",
"+",
"1",
"\n",
"}",
"\n",
"return",
"index",
"\n",
"}"
] |
// Return lowest index based on timespan
// This function assumes that messages are sorted by timestamp in ascending order
|
[
"Return",
"lowest",
"index",
"based",
"on",
"timespan",
"This",
"function",
"assumes",
"that",
"messages",
"are",
"sorted",
"by",
"timestamp",
"in",
"ascending",
"order"
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L140-L152
|
142,661 |
trivago/gollum
|
producer/awsCloudwatchlogs.go
|
handleResult
|
func (prod *AwsCloudwatchLogs) handleResult(resp *cloudwatchlogs.PutLogEventsOutput, result error) {
switch err := result.(type) {
case awserr.Error:
switch err.Code() {
case "InvalidSequenceTokenException":
prod.Logger.Debugf("invalid sequence token, updating")
prod.setToken()
case "ResourceNotFoundException":
prod.Logger.Debugf("missing group/stream, creating")
prod.create()
prod.token = nil
default:
prod.Logger.Errorf("error while sending batch. code: %s message: %q", err.Code(), err.Message())
}
case nil:
prod.token = resp.NextSequenceToken
default:
prod.Logger.Errorf("error while sending batch: %q", err)
}
}
|
go
|
func (prod *AwsCloudwatchLogs) handleResult(resp *cloudwatchlogs.PutLogEventsOutput, result error) {
switch err := result.(type) {
case awserr.Error:
switch err.Code() {
case "InvalidSequenceTokenException":
prod.Logger.Debugf("invalid sequence token, updating")
prod.setToken()
case "ResourceNotFoundException":
prod.Logger.Debugf("missing group/stream, creating")
prod.create()
prod.token = nil
default:
prod.Logger.Errorf("error while sending batch. code: %s message: %q", err.Code(), err.Message())
}
case nil:
prod.token = resp.NextSequenceToken
default:
prod.Logger.Errorf("error while sending batch: %q", err)
}
}
|
[
"func",
"(",
"prod",
"*",
"AwsCloudwatchLogs",
")",
"handleResult",
"(",
"resp",
"*",
"cloudwatchlogs",
".",
"PutLogEventsOutput",
",",
"result",
"error",
")",
"{",
"switch",
"err",
":=",
"result",
".",
"(",
"type",
")",
"{",
"case",
"awserr",
".",
"Error",
":",
"switch",
"err",
".",
"Code",
"(",
")",
"{",
"case",
"\"",
"\"",
":",
"prod",
".",
"Logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"prod",
".",
"setToken",
"(",
")",
"\n",
"case",
"\"",
"\"",
":",
"prod",
".",
"Logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"prod",
".",
"create",
"(",
")",
"\n",
"prod",
".",
"token",
"=",
"nil",
"\n",
"default",
":",
"prod",
".",
"Logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Code",
"(",
")",
",",
"err",
".",
"Message",
"(",
")",
")",
"\n",
"}",
"\n",
"case",
"nil",
":",
"prod",
".",
"token",
"=",
"resp",
".",
"NextSequenceToken",
"\n",
"default",
":",
"prod",
".",
"Logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// When rejectedLogEventsInfo is not empty, app can not
// do anything reasonable with rejected logs. Ignore it.
|
[
"When",
"rejectedLogEventsInfo",
"is",
"not",
"empty",
"app",
"can",
"not",
"do",
"anything",
"reasonable",
"with",
"rejected",
"logs",
".",
"Ignore",
"it",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L184-L203
|
142,662 |
trivago/gollum
|
producer/awsCloudwatchlogs.go
|
setToken
|
func (prod *AwsCloudwatchLogs) setToken() error {
params := &cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: &prod.group,
LogStreamNamePrefix: &prod.stream,
}
return prod.service.DescribeLogStreamsPages(params,
func(page *cloudwatchlogs.DescribeLogStreamsOutput, lastPage bool) bool {
return !findToken(prod, page)
})
}
|
go
|
func (prod *AwsCloudwatchLogs) setToken() error {
params := &cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: &prod.group,
LogStreamNamePrefix: &prod.stream,
}
return prod.service.DescribeLogStreamsPages(params,
func(page *cloudwatchlogs.DescribeLogStreamsOutput, lastPage bool) bool {
return !findToken(prod, page)
})
}
|
[
"func",
"(",
"prod",
"*",
"AwsCloudwatchLogs",
")",
"setToken",
"(",
")",
"error",
"{",
"params",
":=",
"&",
"cloudwatchlogs",
".",
"DescribeLogStreamsInput",
"{",
"LogGroupName",
":",
"&",
"prod",
".",
"group",
",",
"LogStreamNamePrefix",
":",
"&",
"prod",
".",
"stream",
",",
"}",
"\n\n",
"return",
"prod",
".",
"service",
".",
"DescribeLogStreamsPages",
"(",
"params",
",",
"func",
"(",
"page",
"*",
"cloudwatchlogs",
".",
"DescribeLogStreamsOutput",
",",
"lastPage",
"bool",
")",
"bool",
"{",
"return",
"!",
"findToken",
"(",
"prod",
",",
"page",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// For newly created log streams, token is an empty string.
|
[
"For",
"newly",
"created",
"log",
"streams",
"token",
"is",
"an",
"empty",
"string",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L240-L250
|
142,663 |
trivago/gollum
|
producer/awsCloudwatchlogs.go
|
create
|
func (prod *AwsCloudwatchLogs) create() error {
if err := prod.createGroup(); err != nil {
return err
}
return prod.createStream()
}
|
go
|
func (prod *AwsCloudwatchLogs) create() error {
if err := prod.createGroup(); err != nil {
return err
}
return prod.createStream()
}
|
[
"func",
"(",
"prod",
"*",
"AwsCloudwatchLogs",
")",
"create",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"prod",
".",
"createGroup",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"prod",
".",
"createStream",
"(",
")",
"\n",
"}"
] |
// Create log group and stream. If an error is returned, PutLogEvents cannot succeed.
|
[
"Create",
"log",
"group",
"and",
"stream",
".",
"If",
"an",
"error",
"is",
"returned",
"PutLogEvents",
"cannot",
"succeed",
"."
] |
de2faa584cd526bb852e8a4b693982ba4216757f
|
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L263-L268
|
142,664 |
microcosm-cc/bluemonday
|
policies.go
|
UGCPolicy
|
func UGCPolicy() *Policy {
p := NewPolicy()
///////////////////////
// Global attributes //
///////////////////////
// "class" is not permitted as we are not allowing users to style their own
// content
p.AllowStandardAttributes()
//////////////////////////////
// Global URL format policy //
//////////////////////////////
p.AllowStandardURLs()
////////////////////////////////
// Declarations and structure //
////////////////////////////////
// "xml" "xslt" "DOCTYPE" "html" "head" are not permitted as we are
// expecting user generated content to be a fragment of HTML and not a full
// document.
//////////////////////////
// Sectioning root tags //
//////////////////////////
// "article" and "aside" are permitted and takes no attributes
p.AllowElements("article", "aside")
// "body" is not permitted as we are expecting user generated content to be a fragment
// of HTML and not a full document.
// "details" is permitted, including the "open" attribute which can either
// be blank or the value "open".
p.AllowAttrs(
"open",
).Matching(regexp.MustCompile(`(?i)^(|open)$`)).OnElements("details")
// "fieldset" is not permitted as we are not allowing forms to be created.
// "figure" is permitted and takes no attributes
p.AllowElements("figure")
// "nav" is not permitted as it is assumed that the site (and not the user)
// has defined navigation elements
// "section" is permitted and takes no attributes
p.AllowElements("section")
// "summary" is permitted and takes no attributes
p.AllowElements("summary")
//////////////////////////
// Headings and footers //
//////////////////////////
// "footer" is not permitted as we expect user content to be a fragment and
// not structural to this extent
// "h1" through "h6" are permitted and take no attributes
p.AllowElements("h1", "h2", "h3", "h4", "h5", "h6")
// "header" is not permitted as we expect user content to be a fragment and
// not structural to this extent
// "hgroup" is permitted and takes no attributes
p.AllowElements("hgroup")
/////////////////////////////////////
// Content grouping and separating //
/////////////////////////////////////
// "blockquote" is permitted, including the "cite" attribute which must be
// a standard URL.
p.AllowAttrs("cite").OnElements("blockquote")
// "br" "div" "hr" "p" "span" "wbr" are permitted and take no attributes
p.AllowElements("br", "div", "hr", "p", "span", "wbr")
///////////
// Links //
///////////
// "a" is permitted
p.AllowAttrs("href").OnElements("a")
// "area" is permitted along with the attributes that map image maps work
p.AllowAttrs("name").Matching(
regexp.MustCompile(`^([\p{L}\p{N}_-]+)$`),
).OnElements("map")
p.AllowAttrs("alt").Matching(Paragraph).OnElements("area")
p.AllowAttrs("coords").Matching(
regexp.MustCompile(`^([0-9]+,)+[0-9]+$`),
).OnElements("area")
p.AllowAttrs("href").OnElements("area")
p.AllowAttrs("rel").Matching(SpaceSeparatedTokens).OnElements("area")
p.AllowAttrs("shape").Matching(
regexp.MustCompile(`(?i)^(default|circle|rect|poly)$`),
).OnElements("area")
p.AllowAttrs("usemap").Matching(
regexp.MustCompile(`(?i)^#[\p{L}\p{N}_-]+$`),
).OnElements("img")
// "link" is not permitted
/////////////////////
// Phrase elements //
/////////////////////
// The following are all inline phrasing elements
p.AllowElements("abbr", "acronym", "cite", "code", "dfn", "em",
"figcaption", "mark", "s", "samp", "strong", "sub", "sup", "var")
// "q" is permitted and "cite" is a URL and handled by URL policies
p.AllowAttrs("cite").OnElements("q")
// "time" is permitted
p.AllowAttrs("datetime").Matching(ISO8601).OnElements("time")
////////////////////
// Style elements //
////////////////////
// block and inline elements that impart no semantic meaning but style the
// document
p.AllowElements("b", "i", "pre", "small", "strike", "tt", "u")
// "style" is not permitted as we are not yet sanitising CSS and it is an
// XSS attack vector
//////////////////////
// HTML5 Formatting //
//////////////////////
// "bdi" "bdo" are permitted
p.AllowAttrs("dir").Matching(Direction).OnElements("bdi", "bdo")
// "rp" "rt" "ruby" are permitted
p.AllowElements("rp", "rt", "ruby")
///////////////////////////
// HTML5 Change tracking //
///////////////////////////
// "del" "ins" are permitted
p.AllowAttrs("cite").Matching(Paragraph).OnElements("del", "ins")
p.AllowAttrs("datetime").Matching(ISO8601).OnElements("del", "ins")
///////////
// Lists //
///////////
p.AllowLists()
////////////
// Tables //
////////////
p.AllowTables()
///////////
// Forms //
///////////
// By and large, forms are not permitted. However there are some form
// elements that can be used to present data, and we do permit those
//
// "button" "fieldset" "input" "keygen" "label" "output" "select" "datalist"
// "textarea" "optgroup" "option" are all not permitted
// "meter" is permitted
p.AllowAttrs(
"value",
"min",
"max",
"low",
"high",
"optimum",
).Matching(Number).OnElements("meter")
// "progress" is permitted
p.AllowAttrs("value", "max").Matching(Number).OnElements("progress")
//////////////////////
// Embedded content //
//////////////////////
// Vast majority not permitted
// "audio" "canvas" "embed" "iframe" "object" "param" "source" "svg" "track"
// "video" are all not permitted
p.AllowImages()
return p
}
|
go
|
func UGCPolicy() *Policy {
p := NewPolicy()
///////////////////////
// Global attributes //
///////////////////////
// "class" is not permitted as we are not allowing users to style their own
// content
p.AllowStandardAttributes()
//////////////////////////////
// Global URL format policy //
//////////////////////////////
p.AllowStandardURLs()
////////////////////////////////
// Declarations and structure //
////////////////////////////////
// "xml" "xslt" "DOCTYPE" "html" "head" are not permitted as we are
// expecting user generated content to be a fragment of HTML and not a full
// document.
//////////////////////////
// Sectioning root tags //
//////////////////////////
// "article" and "aside" are permitted and takes no attributes
p.AllowElements("article", "aside")
// "body" is not permitted as we are expecting user generated content to be a fragment
// of HTML and not a full document.
// "details" is permitted, including the "open" attribute which can either
// be blank or the value "open".
p.AllowAttrs(
"open",
).Matching(regexp.MustCompile(`(?i)^(|open)$`)).OnElements("details")
// "fieldset" is not permitted as we are not allowing forms to be created.
// "figure" is permitted and takes no attributes
p.AllowElements("figure")
// "nav" is not permitted as it is assumed that the site (and not the user)
// has defined navigation elements
// "section" is permitted and takes no attributes
p.AllowElements("section")
// "summary" is permitted and takes no attributes
p.AllowElements("summary")
//////////////////////////
// Headings and footers //
//////////////////////////
// "footer" is not permitted as we expect user content to be a fragment and
// not structural to this extent
// "h1" through "h6" are permitted and take no attributes
p.AllowElements("h1", "h2", "h3", "h4", "h5", "h6")
// "header" is not permitted as we expect user content to be a fragment and
// not structural to this extent
// "hgroup" is permitted and takes no attributes
p.AllowElements("hgroup")
/////////////////////////////////////
// Content grouping and separating //
/////////////////////////////////////
// "blockquote" is permitted, including the "cite" attribute which must be
// a standard URL.
p.AllowAttrs("cite").OnElements("blockquote")
// "br" "div" "hr" "p" "span" "wbr" are permitted and take no attributes
p.AllowElements("br", "div", "hr", "p", "span", "wbr")
///////////
// Links //
///////////
// "a" is permitted
p.AllowAttrs("href").OnElements("a")
// "area" is permitted along with the attributes that map image maps work
p.AllowAttrs("name").Matching(
regexp.MustCompile(`^([\p{L}\p{N}_-]+)$`),
).OnElements("map")
p.AllowAttrs("alt").Matching(Paragraph).OnElements("area")
p.AllowAttrs("coords").Matching(
regexp.MustCompile(`^([0-9]+,)+[0-9]+$`),
).OnElements("area")
p.AllowAttrs("href").OnElements("area")
p.AllowAttrs("rel").Matching(SpaceSeparatedTokens).OnElements("area")
p.AllowAttrs("shape").Matching(
regexp.MustCompile(`(?i)^(default|circle|rect|poly)$`),
).OnElements("area")
p.AllowAttrs("usemap").Matching(
regexp.MustCompile(`(?i)^#[\p{L}\p{N}_-]+$`),
).OnElements("img")
// "link" is not permitted
/////////////////////
// Phrase elements //
/////////////////////
// The following are all inline phrasing elements
p.AllowElements("abbr", "acronym", "cite", "code", "dfn", "em",
"figcaption", "mark", "s", "samp", "strong", "sub", "sup", "var")
// "q" is permitted and "cite" is a URL and handled by URL policies
p.AllowAttrs("cite").OnElements("q")
// "time" is permitted
p.AllowAttrs("datetime").Matching(ISO8601).OnElements("time")
////////////////////
// Style elements //
////////////////////
// block and inline elements that impart no semantic meaning but style the
// document
p.AllowElements("b", "i", "pre", "small", "strike", "tt", "u")
// "style" is not permitted as we are not yet sanitising CSS and it is an
// XSS attack vector
//////////////////////
// HTML5 Formatting //
//////////////////////
// "bdi" "bdo" are permitted
p.AllowAttrs("dir").Matching(Direction).OnElements("bdi", "bdo")
// "rp" "rt" "ruby" are permitted
p.AllowElements("rp", "rt", "ruby")
///////////////////////////
// HTML5 Change tracking //
///////////////////////////
// "del" "ins" are permitted
p.AllowAttrs("cite").Matching(Paragraph).OnElements("del", "ins")
p.AllowAttrs("datetime").Matching(ISO8601).OnElements("del", "ins")
///////////
// Lists //
///////////
p.AllowLists()
////////////
// Tables //
////////////
p.AllowTables()
///////////
// Forms //
///////////
// By and large, forms are not permitted. However there are some form
// elements that can be used to present data, and we do permit those
//
// "button" "fieldset" "input" "keygen" "label" "output" "select" "datalist"
// "textarea" "optgroup" "option" are all not permitted
// "meter" is permitted
p.AllowAttrs(
"value",
"min",
"max",
"low",
"high",
"optimum",
).Matching(Number).OnElements("meter")
// "progress" is permitted
p.AllowAttrs("value", "max").Matching(Number).OnElements("progress")
//////////////////////
// Embedded content //
//////////////////////
// Vast majority not permitted
// "audio" "canvas" "embed" "iframe" "object" "param" "source" "svg" "track"
// "video" are all not permitted
p.AllowImages()
return p
}
|
[
"func",
"UGCPolicy",
"(",
")",
"*",
"Policy",
"{",
"p",
":=",
"NewPolicy",
"(",
")",
"\n\n",
"///////////////////////",
"// Global attributes //",
"///////////////////////",
"// \"class\" is not permitted as we are not allowing users to style their own",
"// content",
"p",
".",
"AllowStandardAttributes",
"(",
")",
"\n\n",
"//////////////////////////////",
"// Global URL format policy //",
"//////////////////////////////",
"p",
".",
"AllowStandardURLs",
"(",
")",
"\n\n",
"////////////////////////////////",
"// Declarations and structure //",
"////////////////////////////////",
"// \"xml\" \"xslt\" \"DOCTYPE\" \"html\" \"head\" are not permitted as we are",
"// expecting user generated content to be a fragment of HTML and not a full",
"// document.",
"//////////////////////////",
"// Sectioning root tags //",
"//////////////////////////",
"// \"article\" and \"aside\" are permitted and takes no attributes",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"body\" is not permitted as we are expecting user generated content to be a fragment",
"// of HTML and not a full document.",
"// \"details\" is permitted, including the \"open\" attribute which can either",
"// be blank or the value \"open\".",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`(?i)^(|open)$`",
")",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"fieldset\" is not permitted as we are not allowing forms to be created.",
"// \"figure\" is permitted and takes no attributes",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"nav\" is not permitted as it is assumed that the site (and not the user)",
"// has defined navigation elements",
"// \"section\" is permitted and takes no attributes",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"summary\" is permitted and takes no attributes",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
")",
"\n\n",
"//////////////////////////",
"// Headings and footers //",
"//////////////////////////",
"// \"footer\" is not permitted as we expect user content to be a fragment and",
"// not structural to this extent",
"// \"h1\" through \"h6\" are permitted and take no attributes",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"header\" is not permitted as we expect user content to be a fragment and",
"// not structural to this extent",
"// \"hgroup\" is permitted and takes no attributes",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
")",
"\n\n",
"/////////////////////////////////////",
"// Content grouping and separating //",
"/////////////////////////////////////",
"// \"blockquote\" is permitted, including the \"cite\" attribute which must be",
"// a standard URL.",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"br\" \"div\" \"hr\" \"p\" \"span\" \"wbr\" are permitted and take no attributes",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"///////////",
"// Links //",
"///////////",
"// \"a\" is permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"area\" is permitted along with the attributes that map image maps work",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`^([\\p{L}\\p{N}_-]+)$`",
")",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Paragraph",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`^([0-9]+,)+[0-9]+$`",
")",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"SpaceSeparatedTokens",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`(?i)^(default|circle|rect|poly)$`",
")",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`(?i)^#[\\p{L}\\p{N}_-]+$`",
")",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"link\" is not permitted",
"/////////////////////",
"// Phrase elements //",
"/////////////////////",
"// The following are all inline phrasing elements",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"q\" is permitted and \"cite\" is a URL and handled by URL policies",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"time\" is permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"ISO8601",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"////////////////////",
"// Style elements //",
"////////////////////",
"// block and inline elements that impart no semantic meaning but style the",
"// document",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"style\" is not permitted as we are not yet sanitising CSS and it is an",
"// XSS attack vector",
"//////////////////////",
"// HTML5 Formatting //",
"//////////////////////",
"// \"bdi\" \"bdo\" are permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Direction",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"rp\" \"rt\" \"ruby\" are permitted",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"///////////////////////////",
"// HTML5 Change tracking //",
"///////////////////////////",
"// \"del\" \"ins\" are permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Paragraph",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"ISO8601",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"///////////",
"// Lists //",
"///////////",
"p",
".",
"AllowLists",
"(",
")",
"\n\n",
"////////////",
"// Tables //",
"////////////",
"p",
".",
"AllowTables",
"(",
")",
"\n\n",
"///////////",
"// Forms //",
"///////////",
"// By and large, forms are not permitted. However there are some form",
"// elements that can be used to present data, and we do permit those",
"//",
"// \"button\" \"fieldset\" \"input\" \"keygen\" \"label\" \"output\" \"select\" \"datalist\"",
"// \"textarea\" \"optgroup\" \"option\" are all not permitted",
"// \"meter\" is permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
")",
".",
"Matching",
"(",
"Number",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"progress\" is permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Number",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"//////////////////////",
"// Embedded content //",
"//////////////////////",
"// Vast majority not permitted",
"// \"audio\" \"canvas\" \"embed\" \"iframe\" \"object\" \"param\" \"source\" \"svg\" \"track\"",
"// \"video\" are all not permitted",
"p",
".",
"AllowImages",
"(",
")",
"\n\n",
"return",
"p",
"\n",
"}"
] |
// UGCPolicy returns a policy aimed at user generated content that is a result
// of HTML WYSIWYG tools and Markdown conversions.
//
// This is expected to be a fairly rich document where as much markup as
// possible should be retained. Markdown permits raw HTML so we are basically
// providing a policy to sanitise HTML5 documents safely but with the
// least intrusion on the formatting expectations of the user.
|
[
"UGCPolicy",
"returns",
"a",
"policy",
"aimed",
"at",
"user",
"generated",
"content",
"that",
"is",
"a",
"result",
"of",
"HTML",
"WYSIWYG",
"tools",
"and",
"Markdown",
"conversions",
".",
"This",
"is",
"expected",
"to",
"be",
"a",
"fairly",
"rich",
"document",
"where",
"as",
"much",
"markup",
"as",
"possible",
"should",
"be",
"retained",
".",
"Markdown",
"permits",
"raw",
"HTML",
"so",
"we",
"are",
"basically",
"providing",
"a",
"policy",
"to",
"sanitise",
"HTML5",
"documents",
"safely",
"but",
"with",
"the",
"least",
"intrusion",
"on",
"the",
"formatting",
"expectations",
"of",
"the",
"user",
"."
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policies.go#L54-L253
|
142,665 |
microcosm-cc/bluemonday
|
helpers.go
|
AllowStandardAttributes
|
func (p *Policy) AllowStandardAttributes() {
// "dir" "lang" are permitted as both language attributes affect charsets
// and direction of text.
p.AllowAttrs("dir").Matching(Direction).Globally()
p.AllowAttrs(
"lang",
).Matching(regexp.MustCompile(`[a-zA-Z]{2,20}`)).Globally()
// "id" is permitted. This is pretty much as some HTML elements require this
// to work well ("dfn" is an example of a "id" being value)
// This does create a risk that JavaScript and CSS within your web page
// might identify the wrong elements. Ensure that you select things
// accurately
p.AllowAttrs("id").Matching(
regexp.MustCompile(`[a-zA-Z0-9\:\-_\.]+`),
).Globally()
// "title" is permitted as it improves accessibility.
p.AllowAttrs("title").Matching(Paragraph).Globally()
}
|
go
|
func (p *Policy) AllowStandardAttributes() {
// "dir" "lang" are permitted as both language attributes affect charsets
// and direction of text.
p.AllowAttrs("dir").Matching(Direction).Globally()
p.AllowAttrs(
"lang",
).Matching(regexp.MustCompile(`[a-zA-Z]{2,20}`)).Globally()
// "id" is permitted. This is pretty much as some HTML elements require this
// to work well ("dfn" is an example of a "id" being value)
// This does create a risk that JavaScript and CSS within your web page
// might identify the wrong elements. Ensure that you select things
// accurately
p.AllowAttrs("id").Matching(
regexp.MustCompile(`[a-zA-Z0-9\:\-_\.]+`),
).Globally()
// "title" is permitted as it improves accessibility.
p.AllowAttrs("title").Matching(Paragraph).Globally()
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"AllowStandardAttributes",
"(",
")",
"{",
"// \"dir\" \"lang\" are permitted as both language attributes affect charsets",
"// and direction of text.",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Direction",
")",
".",
"Globally",
"(",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`[a-zA-Z]{2,20}`",
")",
")",
".",
"Globally",
"(",
")",
"\n\n",
"// \"id\" is permitted. This is pretty much as some HTML elements require this",
"// to work well (\"dfn\" is an example of a \"id\" being value)",
"// This does create a risk that JavaScript and CSS within your web page",
"// might identify the wrong elements. Ensure that you select things",
"// accurately",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`[a-zA-Z0-9\\:\\-_\\.]+`",
")",
",",
")",
".",
"Globally",
"(",
")",
"\n\n",
"// \"title\" is permitted as it improves accessibility.",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Paragraph",
")",
".",
"Globally",
"(",
")",
"\n",
"}"
] |
// AllowStandardAttributes will enable "id", "title" and the language specific
// attributes "dir" and "lang" on all elements that are whitelisted
|
[
"AllowStandardAttributes",
"will",
"enable",
"id",
"title",
"and",
"the",
"language",
"specific",
"attributes",
"dir",
"and",
"lang",
"on",
"all",
"elements",
"that",
"are",
"whitelisted"
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/helpers.go#L145-L164
|
142,666 |
microcosm-cc/bluemonday
|
helpers.go
|
AllowLists
|
func (p *Policy) AllowLists() {
// "ol" "ul" are permitted
p.AllowAttrs("type").Matching(ListType).OnElements("ol", "ul")
// "li" is permitted
p.AllowAttrs("type").Matching(ListType).OnElements("li")
p.AllowAttrs("value").Matching(Integer).OnElements("li")
// "dl" "dt" "dd" are permitted
p.AllowElements("dl", "dt", "dd")
}
|
go
|
func (p *Policy) AllowLists() {
// "ol" "ul" are permitted
p.AllowAttrs("type").Matching(ListType).OnElements("ol", "ul")
// "li" is permitted
p.AllowAttrs("type").Matching(ListType).OnElements("li")
p.AllowAttrs("value").Matching(Integer).OnElements("li")
// "dl" "dt" "dd" are permitted
p.AllowElements("dl", "dt", "dd")
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"AllowLists",
"(",
")",
"{",
"// \"ol\" \"ul\" are permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"ListType",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"li\" is permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"ListType",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Integer",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"dl\" \"dt\" \"dd\" are permitted",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// AllowLists will enabled ordered and unordered lists, as well as definition
// lists
|
[
"AllowLists",
"will",
"enabled",
"ordered",
"and",
"unordered",
"lists",
"as",
"well",
"as",
"definition",
"lists"
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/helpers.go#L235-L245
|
142,667 |
microcosm-cc/bluemonday
|
helpers.go
|
AllowTables
|
func (p *Policy) AllowTables() {
// "table" is permitted
p.AllowAttrs("height", "width").Matching(NumberOrPercent).OnElements("table")
p.AllowAttrs("summary").Matching(Paragraph).OnElements("table")
// "caption" is permitted
p.AllowElements("caption")
// "col" "colgroup" are permitted
p.AllowAttrs("align").Matching(CellAlign).OnElements("col", "colgroup")
p.AllowAttrs("height", "width").Matching(
NumberOrPercent,
).OnElements("col", "colgroup")
p.AllowAttrs("span").Matching(Integer).OnElements("colgroup", "col")
p.AllowAttrs("valign").Matching(
CellVerticalAlign,
).OnElements("col", "colgroup")
// "thead" "tr" are permitted
p.AllowAttrs("align").Matching(CellAlign).OnElements("thead", "tr")
p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("thead", "tr")
// "td" "th" are permitted
p.AllowAttrs("abbr").Matching(Paragraph).OnElements("td", "th")
p.AllowAttrs("align").Matching(CellAlign).OnElements("td", "th")
p.AllowAttrs("colspan", "rowspan").Matching(Integer).OnElements("td", "th")
p.AllowAttrs("headers").Matching(
SpaceSeparatedTokens,
).OnElements("td", "th")
p.AllowAttrs("height", "width").Matching(
NumberOrPercent,
).OnElements("td", "th")
p.AllowAttrs(
"scope",
).Matching(
regexp.MustCompile(`(?i)(?:row|col)(?:group)?`),
).OnElements("td", "th")
p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("td", "th")
p.AllowAttrs("nowrap").Matching(
regexp.MustCompile(`(?i)|nowrap`),
).OnElements("td", "th")
// "tbody" "tfoot"
p.AllowAttrs("align").Matching(CellAlign).OnElements("tbody", "tfoot")
p.AllowAttrs("valign").Matching(
CellVerticalAlign,
).OnElements("tbody", "tfoot")
}
|
go
|
func (p *Policy) AllowTables() {
// "table" is permitted
p.AllowAttrs("height", "width").Matching(NumberOrPercent).OnElements("table")
p.AllowAttrs("summary").Matching(Paragraph).OnElements("table")
// "caption" is permitted
p.AllowElements("caption")
// "col" "colgroup" are permitted
p.AllowAttrs("align").Matching(CellAlign).OnElements("col", "colgroup")
p.AllowAttrs("height", "width").Matching(
NumberOrPercent,
).OnElements("col", "colgroup")
p.AllowAttrs("span").Matching(Integer).OnElements("colgroup", "col")
p.AllowAttrs("valign").Matching(
CellVerticalAlign,
).OnElements("col", "colgroup")
// "thead" "tr" are permitted
p.AllowAttrs("align").Matching(CellAlign).OnElements("thead", "tr")
p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("thead", "tr")
// "td" "th" are permitted
p.AllowAttrs("abbr").Matching(Paragraph).OnElements("td", "th")
p.AllowAttrs("align").Matching(CellAlign).OnElements("td", "th")
p.AllowAttrs("colspan", "rowspan").Matching(Integer).OnElements("td", "th")
p.AllowAttrs("headers").Matching(
SpaceSeparatedTokens,
).OnElements("td", "th")
p.AllowAttrs("height", "width").Matching(
NumberOrPercent,
).OnElements("td", "th")
p.AllowAttrs(
"scope",
).Matching(
regexp.MustCompile(`(?i)(?:row|col)(?:group)?`),
).OnElements("td", "th")
p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("td", "th")
p.AllowAttrs("nowrap").Matching(
regexp.MustCompile(`(?i)|nowrap`),
).OnElements("td", "th")
// "tbody" "tfoot"
p.AllowAttrs("align").Matching(CellAlign).OnElements("tbody", "tfoot")
p.AllowAttrs("valign").Matching(
CellVerticalAlign,
).OnElements("tbody", "tfoot")
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"AllowTables",
"(",
")",
"{",
"// \"table\" is permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Matching",
"(",
"NumberOrPercent",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Paragraph",
")",
".",
"OnElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"caption\" is permitted",
"p",
".",
"AllowElements",
"(",
"\"",
"\"",
")",
"\n\n",
"// \"col\" \"colgroup\" are permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellAlign",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Matching",
"(",
"NumberOrPercent",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Integer",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellVerticalAlign",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"thead\" \"tr\" are permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellAlign",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellVerticalAlign",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"td\" \"th\" are permitted",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Paragraph",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellAlign",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Matching",
"(",
"Integer",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"SpaceSeparatedTokens",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Matching",
"(",
"NumberOrPercent",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
",",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`(?i)(?:row|col)(?:group)?`",
")",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellVerticalAlign",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"regexp",
".",
"MustCompile",
"(",
"`(?i)|nowrap`",
")",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// \"tbody\" \"tfoot\"",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellAlign",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"AllowAttrs",
"(",
"\"",
"\"",
")",
".",
"Matching",
"(",
"CellVerticalAlign",
",",
")",
".",
"OnElements",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// AllowTables will enable a rich set of elements and attributes to describe
// HTML tables
|
[
"AllowTables",
"will",
"enable",
"a",
"rich",
"set",
"of",
"elements",
"and",
"attributes",
"to",
"describe",
"HTML",
"tables"
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/helpers.go#L249-L297
|
142,668 |
microcosm-cc/bluemonday
|
sanitize.go
|
SanitizeReader
|
func (p *Policy) SanitizeReader(r io.Reader) *bytes.Buffer {
return p.sanitize(r)
}
|
go
|
func (p *Policy) SanitizeReader(r io.Reader) *bytes.Buffer {
return p.sanitize(r)
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"SanitizeReader",
"(",
"r",
"io",
".",
"Reader",
")",
"*",
"bytes",
".",
"Buffer",
"{",
"return",
"p",
".",
"sanitize",
"(",
"r",
")",
"\n",
"}"
] |
// SanitizeReader takes an io.Reader that contains a HTML fragment or document
// and applies the given policy whitelist.
//
// It returns a bytes.Buffer containing the HTML that has been sanitized by the
// policy. Errors during sanitization will merely return an empty result.
|
[
"SanitizeReader",
"takes",
"an",
"io",
".",
"Reader",
"that",
"contains",
"a",
"HTML",
"fragment",
"or",
"document",
"and",
"applies",
"the",
"given",
"policy",
"whitelist",
".",
"It",
"returns",
"a",
"bytes",
".",
"Buffer",
"containing",
"the",
"HTML",
"that",
"has",
"been",
"sanitized",
"by",
"the",
"policy",
".",
"Errors",
"during",
"sanitization",
"will",
"merely",
"return",
"an",
"empty",
"result",
"."
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/sanitize.go#L81-L83
|
142,669 |
microcosm-cc/bluemonday
|
policy.go
|
init
|
func (p *Policy) init() {
if !p.initialized {
p.elsAndAttrs = make(map[string]map[string]attrPolicy)
p.globalAttrs = make(map[string]attrPolicy)
p.allowURLSchemes = make(map[string]urlPolicy)
p.setOfElementsAllowedWithoutAttrs = make(map[string]struct{})
p.setOfElementsToSkipContent = make(map[string]struct{})
p.initialized = true
}
}
|
go
|
func (p *Policy) init() {
if !p.initialized {
p.elsAndAttrs = make(map[string]map[string]attrPolicy)
p.globalAttrs = make(map[string]attrPolicy)
p.allowURLSchemes = make(map[string]urlPolicy)
p.setOfElementsAllowedWithoutAttrs = make(map[string]struct{})
p.setOfElementsToSkipContent = make(map[string]struct{})
p.initialized = true
}
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"init",
"(",
")",
"{",
"if",
"!",
"p",
".",
"initialized",
"{",
"p",
".",
"elsAndAttrs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"attrPolicy",
")",
"\n",
"p",
".",
"globalAttrs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"attrPolicy",
")",
"\n",
"p",
".",
"allowURLSchemes",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"urlPolicy",
")",
"\n",
"p",
".",
"setOfElementsAllowedWithoutAttrs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"p",
".",
"setOfElementsToSkipContent",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"p",
".",
"initialized",
"=",
"true",
"\n",
"}",
"\n",
"}"
] |
// init initializes the maps if this has not been done already
|
[
"init",
"initializes",
"the",
"maps",
"if",
"this",
"has",
"not",
"been",
"done",
"already"
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L117-L126
|
142,670 |
microcosm-cc/bluemonday
|
policy.go
|
Matching
|
func (abp *attrPolicyBuilder) Matching(regex *regexp.Regexp) *attrPolicyBuilder {
abp.regexp = regex
return abp
}
|
go
|
func (abp *attrPolicyBuilder) Matching(regex *regexp.Regexp) *attrPolicyBuilder {
abp.regexp = regex
return abp
}
|
[
"func",
"(",
"abp",
"*",
"attrPolicyBuilder",
")",
"Matching",
"(",
"regex",
"*",
"regexp",
".",
"Regexp",
")",
"*",
"attrPolicyBuilder",
"{",
"abp",
".",
"regexp",
"=",
"regex",
"\n\n",
"return",
"abp",
"\n",
"}"
] |
// Matching allows a regular expression to be applied to a nascent attribute
// policy, and returns the attribute policy. Calling this more than once will
// replace the existing regexp.
|
[
"Matching",
"allows",
"a",
"regular",
"expression",
"to",
"be",
"applied",
"to",
"a",
"nascent",
"attribute",
"policy",
"and",
"returns",
"the",
"attribute",
"policy",
".",
"Calling",
"this",
"more",
"than",
"once",
"will",
"replace",
"the",
"existing",
"regexp",
"."
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L208-L213
|
142,671 |
microcosm-cc/bluemonday
|
policy.go
|
OnElements
|
func (abp *attrPolicyBuilder) OnElements(elements ...string) *Policy {
for _, element := range elements {
element = strings.ToLower(element)
for _, attr := range abp.attrNames {
if _, ok := abp.p.elsAndAttrs[element]; !ok {
abp.p.elsAndAttrs[element] = make(map[string]attrPolicy)
}
ap := attrPolicy{}
if abp.regexp != nil {
ap.regexp = abp.regexp
}
abp.p.elsAndAttrs[element][attr] = ap
}
if abp.allowEmpty {
abp.p.setOfElementsAllowedWithoutAttrs[element] = struct{}{}
if _, ok := abp.p.elsAndAttrs[element]; !ok {
abp.p.elsAndAttrs[element] = make(map[string]attrPolicy)
}
}
}
return abp.p
}
|
go
|
func (abp *attrPolicyBuilder) OnElements(elements ...string) *Policy {
for _, element := range elements {
element = strings.ToLower(element)
for _, attr := range abp.attrNames {
if _, ok := abp.p.elsAndAttrs[element]; !ok {
abp.p.elsAndAttrs[element] = make(map[string]attrPolicy)
}
ap := attrPolicy{}
if abp.regexp != nil {
ap.regexp = abp.regexp
}
abp.p.elsAndAttrs[element][attr] = ap
}
if abp.allowEmpty {
abp.p.setOfElementsAllowedWithoutAttrs[element] = struct{}{}
if _, ok := abp.p.elsAndAttrs[element]; !ok {
abp.p.elsAndAttrs[element] = make(map[string]attrPolicy)
}
}
}
return abp.p
}
|
[
"func",
"(",
"abp",
"*",
"attrPolicyBuilder",
")",
"OnElements",
"(",
"elements",
"...",
"string",
")",
"*",
"Policy",
"{",
"for",
"_",
",",
"element",
":=",
"range",
"elements",
"{",
"element",
"=",
"strings",
".",
"ToLower",
"(",
"element",
")",
"\n\n",
"for",
"_",
",",
"attr",
":=",
"range",
"abp",
".",
"attrNames",
"{",
"if",
"_",
",",
"ok",
":=",
"abp",
".",
"p",
".",
"elsAndAttrs",
"[",
"element",
"]",
";",
"!",
"ok",
"{",
"abp",
".",
"p",
".",
"elsAndAttrs",
"[",
"element",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"attrPolicy",
")",
"\n",
"}",
"\n\n",
"ap",
":=",
"attrPolicy",
"{",
"}",
"\n",
"if",
"abp",
".",
"regexp",
"!=",
"nil",
"{",
"ap",
".",
"regexp",
"=",
"abp",
".",
"regexp",
"\n",
"}",
"\n\n",
"abp",
".",
"p",
".",
"elsAndAttrs",
"[",
"element",
"]",
"[",
"attr",
"]",
"=",
"ap",
"\n",
"}",
"\n\n",
"if",
"abp",
".",
"allowEmpty",
"{",
"abp",
".",
"p",
".",
"setOfElementsAllowedWithoutAttrs",
"[",
"element",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"abp",
".",
"p",
".",
"elsAndAttrs",
"[",
"element",
"]",
";",
"!",
"ok",
"{",
"abp",
".",
"p",
".",
"elsAndAttrs",
"[",
"element",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"attrPolicy",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"abp",
".",
"p",
"\n",
"}"
] |
// OnElements will bind an attribute policy to a given range of HTML elements
// and return the updated policy
|
[
"OnElements",
"will",
"bind",
"an",
"attribute",
"policy",
"to",
"a",
"given",
"range",
"of",
"HTML",
"elements",
"and",
"return",
"the",
"updated",
"policy"
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L217-L246
|
142,672 |
microcosm-cc/bluemonday
|
policy.go
|
Globally
|
func (abp *attrPolicyBuilder) Globally() *Policy {
for _, attr := range abp.attrNames {
if _, ok := abp.p.globalAttrs[attr]; !ok {
abp.p.globalAttrs[attr] = attrPolicy{}
}
ap := attrPolicy{}
if abp.regexp != nil {
ap.regexp = abp.regexp
}
abp.p.globalAttrs[attr] = ap
}
return abp.p
}
|
go
|
func (abp *attrPolicyBuilder) Globally() *Policy {
for _, attr := range abp.attrNames {
if _, ok := abp.p.globalAttrs[attr]; !ok {
abp.p.globalAttrs[attr] = attrPolicy{}
}
ap := attrPolicy{}
if abp.regexp != nil {
ap.regexp = abp.regexp
}
abp.p.globalAttrs[attr] = ap
}
return abp.p
}
|
[
"func",
"(",
"abp",
"*",
"attrPolicyBuilder",
")",
"Globally",
"(",
")",
"*",
"Policy",
"{",
"for",
"_",
",",
"attr",
":=",
"range",
"abp",
".",
"attrNames",
"{",
"if",
"_",
",",
"ok",
":=",
"abp",
".",
"p",
".",
"globalAttrs",
"[",
"attr",
"]",
";",
"!",
"ok",
"{",
"abp",
".",
"p",
".",
"globalAttrs",
"[",
"attr",
"]",
"=",
"attrPolicy",
"{",
"}",
"\n",
"}",
"\n\n",
"ap",
":=",
"attrPolicy",
"{",
"}",
"\n",
"if",
"abp",
".",
"regexp",
"!=",
"nil",
"{",
"ap",
".",
"regexp",
"=",
"abp",
".",
"regexp",
"\n",
"}",
"\n\n",
"abp",
".",
"p",
".",
"globalAttrs",
"[",
"attr",
"]",
"=",
"ap",
"\n",
"}",
"\n\n",
"return",
"abp",
".",
"p",
"\n",
"}"
] |
// Globally will bind an attribute policy to all HTML elements and return the
// updated policy
|
[
"Globally",
"will",
"bind",
"an",
"attribute",
"policy",
"to",
"all",
"HTML",
"elements",
"and",
"return",
"the",
"updated",
"policy"
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L250-L266
|
142,673 |
microcosm-cc/bluemonday
|
policy.go
|
SkipElementsContent
|
func (p *Policy) SkipElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
element = strings.ToLower(element)
if _, ok := p.setOfElementsToSkipContent[element]; !ok {
p.setOfElementsToSkipContent[element] = struct{}{}
}
}
return p
}
|
go
|
func (p *Policy) SkipElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
element = strings.ToLower(element)
if _, ok := p.setOfElementsToSkipContent[element]; !ok {
p.setOfElementsToSkipContent[element] = struct{}{}
}
}
return p
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"SkipElementsContent",
"(",
"names",
"...",
"string",
")",
"*",
"Policy",
"{",
"p",
".",
"init",
"(",
")",
"\n\n",
"for",
"_",
",",
"element",
":=",
"range",
"names",
"{",
"element",
"=",
"strings",
".",
"ToLower",
"(",
"element",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"setOfElementsToSkipContent",
"[",
"element",
"]",
";",
"!",
"ok",
"{",
"p",
".",
"setOfElementsToSkipContent",
"[",
"element",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"p",
"\n",
"}"
] |
// SkipElementsContent adds the HTML elements whose tags is needed to be removed
// with its content.
|
[
"SkipElementsContent",
"adds",
"the",
"HTML",
"elements",
"whose",
"tags",
"is",
"needed",
"to",
"be",
"removed",
"with",
"its",
"content",
"."
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L406-L419
|
142,674 |
microcosm-cc/bluemonday
|
policy.go
|
AllowElementsContent
|
func (p *Policy) AllowElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
delete(p.setOfElementsToSkipContent, strings.ToLower(element))
}
return p
}
|
go
|
func (p *Policy) AllowElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
delete(p.setOfElementsToSkipContent, strings.ToLower(element))
}
return p
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"AllowElementsContent",
"(",
"names",
"...",
"string",
")",
"*",
"Policy",
"{",
"p",
".",
"init",
"(",
")",
"\n\n",
"for",
"_",
",",
"element",
":=",
"range",
"names",
"{",
"delete",
"(",
"p",
".",
"setOfElementsToSkipContent",
",",
"strings",
".",
"ToLower",
"(",
"element",
")",
")",
"\n",
"}",
"\n\n",
"return",
"p",
"\n",
"}"
] |
// AllowElementsContent marks the HTML elements whose content should be
// retained after removing the tag.
|
[
"AllowElementsContent",
"marks",
"the",
"HTML",
"elements",
"whose",
"content",
"should",
"be",
"retained",
"after",
"removing",
"the",
"tag",
"."
] |
89802068f71166e95c92040512bf2e11767721ed
|
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L423-L432
|
142,675 |
pierrre/imageserver
|
source/file/file.go
|
IdentifyMime
|
func IdentifyMime(pth string, data []byte) (format string, err error) {
ext := filepath.Ext(pth)
if ext == "" {
return "", fmt.Errorf("no file extension: %s", pth)
}
typ := mime.TypeByExtension(ext)
if typ == "" {
return "", fmt.Errorf("unkwnon file type for extension %s", ext)
}
const pref = "image/"
if !strings.HasPrefix(typ, pref) {
return "", fmt.Errorf("file type does not begin with \"%s\": %s", pref, typ)
}
return typ[len(pref):], nil
}
|
go
|
func IdentifyMime(pth string, data []byte) (format string, err error) {
ext := filepath.Ext(pth)
if ext == "" {
return "", fmt.Errorf("no file extension: %s", pth)
}
typ := mime.TypeByExtension(ext)
if typ == "" {
return "", fmt.Errorf("unkwnon file type for extension %s", ext)
}
const pref = "image/"
if !strings.HasPrefix(typ, pref) {
return "", fmt.Errorf("file type does not begin with \"%s\": %s", pref, typ)
}
return typ[len(pref):], nil
}
|
[
"func",
"IdentifyMime",
"(",
"pth",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"format",
"string",
",",
"err",
"error",
")",
"{",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"pth",
")",
"\n",
"if",
"ext",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pth",
")",
"\n",
"}",
"\n",
"typ",
":=",
"mime",
".",
"TypeByExtension",
"(",
"ext",
")",
"\n",
"if",
"typ",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ext",
")",
"\n",
"}",
"\n",
"const",
"pref",
"=",
"\"",
"\"",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"typ",
",",
"pref",
")",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"pref",
",",
"typ",
")",
"\n",
"}",
"\n",
"return",
"typ",
"[",
"len",
"(",
"pref",
")",
":",
"]",
",",
"nil",
"\n",
"}"
] |
// IdentifyMime identifies the Image format with the "mime" package.
|
[
"IdentifyMime",
"identifies",
"the",
"Image",
"format",
"with",
"the",
"mime",
"package",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/source/file/file.go#L87-L101
|
142,676 |
pierrre/imageserver
|
http/parser.go
|
Parse
|
func (lp ListParser) Parse(req *http.Request, params imageserver.Params) error {
for _, subParser := range lp {
err := subParser.Parse(req, params)
if err != nil {
return err
}
}
return nil
}
|
go
|
func (lp ListParser) Parse(req *http.Request, params imageserver.Params) error {
for _, subParser := range lp {
err := subParser.Parse(req, params)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"lp",
"ListParser",
")",
"Parse",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"for",
"_",
",",
"subParser",
":=",
"range",
"lp",
"{",
"err",
":=",
"subParser",
".",
"Parse",
"(",
"req",
",",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Parse implements Parser.
//
// It iterates through all sub parsers.
// An error interrupts the iteration.
|
[
"Parse",
"implements",
"Parser",
".",
"It",
"iterates",
"through",
"all",
"sub",
"parsers",
".",
"An",
"error",
"interrupts",
"the",
"iteration",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L30-L38
|
142,677 |
pierrre/imageserver
|
http/parser.go
|
Resolve
|
func (lp ListParser) Resolve(param string) string {
for _, subParser := range lp {
httpParam := subParser.Resolve(param)
if httpParam != "" {
return httpParam
}
}
return ""
}
|
go
|
func (lp ListParser) Resolve(param string) string {
for _, subParser := range lp {
httpParam := subParser.Resolve(param)
if httpParam != "" {
return httpParam
}
}
return ""
}
|
[
"func",
"(",
"lp",
"ListParser",
")",
"Resolve",
"(",
"param",
"string",
")",
"string",
"{",
"for",
"_",
",",
"subParser",
":=",
"range",
"lp",
"{",
"httpParam",
":=",
"subParser",
".",
"Resolve",
"(",
"param",
")",
"\n",
"if",
"httpParam",
"!=",
"\"",
"\"",
"{",
"return",
"httpParam",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// Resolve implements Parser.
//
// It iterates through sub parsers, and return the first non-empty string.
|
[
"Resolve",
"implements",
"Parser",
".",
"It",
"iterates",
"through",
"sub",
"parsers",
"and",
"return",
"the",
"first",
"non",
"-",
"empty",
"string",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L43-L51
|
142,678 |
pierrre/imageserver
|
http/parser.go
|
Resolve
|
func (parser *SourceParser) Resolve(param string) string {
if param == imageserver_source.Param {
return imageserver_source.Param
}
return ""
}
|
go
|
func (parser *SourceParser) Resolve(param string) string {
if param == imageserver_source.Param {
return imageserver_source.Param
}
return ""
}
|
[
"func",
"(",
"parser",
"*",
"SourceParser",
")",
"Resolve",
"(",
"param",
"string",
")",
"string",
"{",
"if",
"param",
"==",
"imageserver_source",
".",
"Param",
"{",
"return",
"imageserver_source",
".",
"Param",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// Resolve implements Parser.
|
[
"Resolve",
"implements",
"Parser",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L63-L68
|
142,679 |
pierrre/imageserver
|
http/parser.go
|
ParseQueryString
|
func ParseQueryString(param string, req *http.Request, params imageserver.Params) {
s := req.URL.Query().Get(param)
if s != "" {
params.Set(param, s)
}
}
|
go
|
func ParseQueryString(param string, req *http.Request, params imageserver.Params) {
s := req.URL.Query().Get(param)
if s != "" {
params.Set(param, s)
}
}
|
[
"func",
"ParseQueryString",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"!=",
"\"",
"\"",
"{",
"params",
".",
"Set",
"(",
"param",
",",
"s",
")",
"\n",
"}",
"\n",
"}"
] |
// ParseQueryString takes the param from the HTTP URL query and add it to the Params.
|
[
"ParseQueryString",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L131-L136
|
142,680 |
pierrre/imageserver
|
http/parser.go
|
ParseQueryInt
|
func ParseQueryInt(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
i, err := strconv.Atoi(s)
if err != nil {
return newParseTypeParamError(param, "int", err)
}
params.Set(param, i)
return nil
}
|
go
|
func ParseQueryInt(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
i, err := strconv.Atoi(s)
if err != nil {
return newParseTypeParamError(param, "int", err)
}
params.Set(param, i)
return nil
}
|
[
"func",
"ParseQueryInt",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"newParseTypeParamError",
"(",
"param",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"params",
".",
"Set",
"(",
"param",
",",
"i",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ParseQueryInt takes the param from the HTTP URL query, parse it as an int and add it to the Params.
|
[
"ParseQueryInt",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"parse",
"it",
"as",
"an",
"int",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L139-L150
|
142,681 |
pierrre/imageserver
|
http/parser.go
|
ParseQueryFloat
|
func ParseQueryFloat(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return newParseTypeParamError(param, "float", err)
}
params.Set(param, f)
return nil
}
|
go
|
func ParseQueryFloat(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return newParseTypeParamError(param, "float", err)
}
params.Set(param, f)
return nil
}
|
[
"func",
"ParseQueryFloat",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"s",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"newParseTypeParamError",
"(",
"param",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"params",
".",
"Set",
"(",
"param",
",",
"f",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ParseQueryFloat takes the param from the HTTP URL query, parse it as a float64 and add it to the Params.
|
[
"ParseQueryFloat",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"parse",
"it",
"as",
"a",
"float64",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L167-L178
|
142,682 |
pierrre/imageserver
|
http/parser.go
|
ParseQueryBool
|
func ParseQueryBool(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
b, err := strconv.ParseBool(s)
if err != nil {
return newParseTypeParamError(param, "bool", err)
}
params.Set(param, b)
return nil
}
|
go
|
func ParseQueryBool(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
b, err := strconv.ParseBool(s)
if err != nil {
return newParseTypeParamError(param, "bool", err)
}
params.Set(param, b)
return nil
}
|
[
"func",
"ParseQueryBool",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"newParseTypeParamError",
"(",
"param",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"params",
".",
"Set",
"(",
"param",
",",
"b",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ParseQueryBool takes the param from the HTTP URL query, parse it as an bool and add it to the Params.
|
[
"ParseQueryBool",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"parse",
"it",
"as",
"an",
"bool",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L181-L192
|
142,683 |
pierrre/imageserver
|
cache/groupcache/http.go
|
HTTPPoolContext
|
func HTTPPoolContext(req *http.Request) groupcache.Context {
ctx, err := getContext(req)
if err != nil {
return nil
}
return ctx
}
|
go
|
func HTTPPoolContext(req *http.Request) groupcache.Context {
ctx, err := getContext(req)
if err != nil {
return nil
}
return ctx
}
|
[
"func",
"HTTPPoolContext",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"groupcache",
".",
"Context",
"{",
"ctx",
",",
"err",
":=",
"getContext",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"ctx",
"\n",
"}"
] |
// HTTPPoolContext must be used in groupcache.HTTPPool.Context.
|
[
"HTTPPoolContext",
"must",
"be",
"used",
"in",
"groupcache",
".",
"HTTPPool",
".",
"Context",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/groupcache/http.go#L18-L24
|
142,684 |
pierrre/imageserver
|
cache/groupcache/http.go
|
NewHTTPPoolTransport
|
func NewHTTPPoolTransport(rt http.RoundTripper) func(groupcache.Context) http.RoundTripper {
if rt == nil {
rt = http.DefaultTransport
}
return func(ctx groupcache.Context) http.RoundTripper {
return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if ctx, ok := ctx.(*Context); ok && ctx != nil {
err := setContext(req, ctx)
if err != nil {
return nil, err
}
}
return rt.RoundTrip(req)
})
}
}
|
go
|
func NewHTTPPoolTransport(rt http.RoundTripper) func(groupcache.Context) http.RoundTripper {
if rt == nil {
rt = http.DefaultTransport
}
return func(ctx groupcache.Context) http.RoundTripper {
return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if ctx, ok := ctx.(*Context); ok && ctx != nil {
err := setContext(req, ctx)
if err != nil {
return nil, err
}
}
return rt.RoundTrip(req)
})
}
}
|
[
"func",
"NewHTTPPoolTransport",
"(",
"rt",
"http",
".",
"RoundTripper",
")",
"func",
"(",
"groupcache",
".",
"Context",
")",
"http",
".",
"RoundTripper",
"{",
"if",
"rt",
"==",
"nil",
"{",
"rt",
"=",
"http",
".",
"DefaultTransport",
"\n",
"}",
"\n",
"return",
"func",
"(",
"ctx",
"groupcache",
".",
"Context",
")",
"http",
".",
"RoundTripper",
"{",
"return",
"roundTripperFunc",
"(",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"ctx",
",",
"ok",
":=",
"ctx",
".",
"(",
"*",
"Context",
")",
";",
"ok",
"&&",
"ctx",
"!=",
"nil",
"{",
"err",
":=",
"setContext",
"(",
"req",
",",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"rt",
".",
"RoundTrip",
"(",
"req",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] |
// NewHTTPPoolTransport returns a function that must be used in groupcache.HTTPPool.Transport.
//
// rt is optional, http.DefaultTransport is used by default.
|
[
"NewHTTPPoolTransport",
"returns",
"a",
"function",
"that",
"must",
"be",
"used",
"in",
"groupcache",
".",
"HTTPPool",
".",
"Transport",
".",
"rt",
"is",
"optional",
"http",
".",
"DefaultTransport",
"is",
"used",
"by",
"default",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/groupcache/http.go#L50-L65
|
142,685 |
pierrre/imageserver
|
params.go
|
Get
|
func (params Params) Get(key string) (interface{}, error) {
v, ok := params[key]
if !ok {
return nil, &ParamError{Param: key, Message: "not set"}
}
return v, nil
}
|
go
|
func (params Params) Get(key string) (interface{}, error) {
v, ok := params[key]
if !ok {
return nil, &ParamError{Param: key, Message: "not set"}
}
return v, nil
}
|
[
"func",
"(",
"params",
"Params",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"v",
",",
"ok",
":=",
"params",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"&",
"ParamError",
"{",
"Param",
":",
"key",
",",
"Message",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"return",
"v",
",",
"nil",
"\n",
"}"
] |
// Get returns the value for the key.
|
[
"Get",
"returns",
"the",
"value",
"for",
"the",
"key",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L24-L30
|
142,686 |
pierrre/imageserver
|
params.go
|
GetString
|
func (params Params) GetString(key string) (string, error) {
v, err := params.Get(key)
if err != nil {
return "", err
}
vt, ok := v.(string)
if !ok {
return vt, newErrorType(key, v, "string")
}
return vt, nil
}
|
go
|
func (params Params) GetString(key string) (string, error) {
v, err := params.Get(key)
if err != nil {
return "", err
}
vt, ok := v.(string)
if !ok {
return vt, newErrorType(key, v, "string")
}
return vt, nil
}
|
[
"func",
"(",
"params",
"Params",
")",
"GetString",
"(",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"v",
",",
"err",
":=",
"params",
".",
"Get",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"vt",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"vt",
",",
"newErrorType",
"(",
"key",
",",
"v",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"vt",
",",
"nil",
"\n",
"}"
] |
// GetString returns the string value for the key.
|
[
"GetString",
"returns",
"the",
"string",
"value",
"for",
"the",
"key",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L33-L43
|
142,687 |
pierrre/imageserver
|
params.go
|
GetBool
|
func (params Params) GetBool(key string) (bool, error) {
v, err := params.Get(key)
if err != nil {
return false, err
}
vt, ok := v.(bool)
if !ok {
return false, newErrorType(key, v, "bool")
}
return vt, nil
}
|
go
|
func (params Params) GetBool(key string) (bool, error) {
v, err := params.Get(key)
if err != nil {
return false, err
}
vt, ok := v.(bool)
if !ok {
return false, newErrorType(key, v, "bool")
}
return vt, nil
}
|
[
"func",
"(",
"params",
"Params",
")",
"GetBool",
"(",
"key",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"v",
",",
"err",
":=",
"params",
".",
"Get",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"vt",
",",
"ok",
":=",
"v",
".",
"(",
"bool",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
",",
"newErrorType",
"(",
"key",
",",
"v",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"vt",
",",
"nil",
"\n",
"}"
] |
// GetBool returns the bool value for the key.
|
[
"GetBool",
"returns",
"the",
"bool",
"value",
"for",
"the",
"key",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L85-L95
|
142,688 |
pierrre/imageserver
|
params.go
|
Has
|
func (params Params) Has(key string) bool {
_, ok := params[key]
return ok
}
|
go
|
func (params Params) Has(key string) bool {
_, ok := params[key]
return ok
}
|
[
"func",
"(",
"params",
"Params",
")",
"Has",
"(",
"key",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"params",
"[",
"key",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] |
// Has returns true if the key exists and false otherwise.
|
[
"Has",
"returns",
"true",
"if",
"the",
"key",
"exists",
"and",
"false",
"otherwise",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L115-L118
|
142,689 |
pierrre/imageserver
|
params.go
|
Keys
|
func (params Params) Keys() []string {
length := params.Len()
keys := make([]string, length)
i := 0
for key := range params {
keys[i] = key
i++
}
return keys
}
|
go
|
func (params Params) Keys() []string {
length := params.Len()
keys := make([]string, length)
i := 0
for key := range params {
keys[i] = key
i++
}
return keys
}
|
[
"func",
"(",
"params",
"Params",
")",
"Keys",
"(",
")",
"[",
"]",
"string",
"{",
"length",
":=",
"params",
".",
"Len",
"(",
")",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"length",
")",
"\n",
"i",
":=",
"0",
"\n",
"for",
"key",
":=",
"range",
"params",
"{",
"keys",
"[",
"i",
"]",
"=",
"key",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"return",
"keys",
"\n",
"}"
] |
// Keys returns the keys.
|
[
"Keys",
"returns",
"the",
"keys",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L131-L140
|
142,690 |
pierrre/imageserver
|
params.go
|
String
|
func (params Params) String() string {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufferPool.Put(buf)
params.toBuffer(buf)
return buf.String()
}
|
go
|
func (params Params) String() string {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufferPool.Put(buf)
params.toBuffer(buf)
return buf.String()
}
|
[
"func",
"(",
"params",
"Params",
")",
"String",
"(",
")",
"string",
"{",
"buf",
":=",
"bufferPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"bytes",
".",
"Buffer",
")",
"\n",
"buf",
".",
"Reset",
"(",
")",
"\n",
"defer",
"bufferPool",
".",
"Put",
"(",
"buf",
")",
"\n",
"params",
".",
"toBuffer",
"(",
"buf",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// String returns the string representation.
//
// Keys are sorted alphabetically.
|
[
"String",
"returns",
"the",
"string",
"representation",
".",
"Keys",
"are",
"sorted",
"alphabetically",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L151-L157
|
142,691 |
pierrre/imageserver
|
params.go
|
Copy
|
func (params Params) Copy() Params {
p := Params{}
for k, v := range params {
if q, ok := v.(Params); ok {
v = q.Copy()
}
p[k] = v
}
return p
}
|
go
|
func (params Params) Copy() Params {
p := Params{}
for k, v := range params {
if q, ok := v.(Params); ok {
v = q.Copy()
}
p[k] = v
}
return p
}
|
[
"func",
"(",
"params",
"Params",
")",
"Copy",
"(",
")",
"Params",
"{",
"p",
":=",
"Params",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"params",
"{",
"if",
"q",
",",
"ok",
":=",
"v",
".",
"(",
"Params",
")",
";",
"ok",
"{",
"v",
"=",
"q",
".",
"Copy",
"(",
")",
"\n",
"}",
"\n",
"p",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] |
// Copy returns a deep copy of the Params.
|
[
"Copy",
"returns",
"a",
"deep",
"copy",
"of",
"the",
"Params",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L181-L190
|
142,692 |
pierrre/imageserver
|
image.go
|
UnmarshalBinaryNoCopy
|
func (im *Image) UnmarshalBinaryNoCopy(data []byte) error {
readData := func(length int) ([]byte, error) {
if length > len(data) {
return nil, &ImageError{Message: "unmarshal: unexpected end of data"}
}
res := data[:length]
data = data[length:]
return res, nil
}
var buf []byte
var err error
buf, err = readData(4)
if err != nil {
return err
}
formatLen := imageByteOrder.Uint32(buf)
if formatLen > ImageFormatMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: format length %d is greater than the maximum value %d", formatLen, ImageFormatMaxLen)}
}
buf, err = readData(int(formatLen))
if err != nil {
return err
}
im.Format = string(buf)
buf, err = readData(4)
if err != nil {
return err
}
dataLen := imageByteOrder.Uint32(buf)
if dataLen > ImageDataMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: data length %d is greater than the maximum value %d", dataLen, ImageDataMaxLen)}
}
buf, err = readData(int(dataLen))
if err != nil {
return err
}
im.Data = buf
return nil
}
|
go
|
func (im *Image) UnmarshalBinaryNoCopy(data []byte) error {
readData := func(length int) ([]byte, error) {
if length > len(data) {
return nil, &ImageError{Message: "unmarshal: unexpected end of data"}
}
res := data[:length]
data = data[length:]
return res, nil
}
var buf []byte
var err error
buf, err = readData(4)
if err != nil {
return err
}
formatLen := imageByteOrder.Uint32(buf)
if formatLen > ImageFormatMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: format length %d is greater than the maximum value %d", formatLen, ImageFormatMaxLen)}
}
buf, err = readData(int(formatLen))
if err != nil {
return err
}
im.Format = string(buf)
buf, err = readData(4)
if err != nil {
return err
}
dataLen := imageByteOrder.Uint32(buf)
if dataLen > ImageDataMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: data length %d is greater than the maximum value %d", dataLen, ImageDataMaxLen)}
}
buf, err = readData(int(dataLen))
if err != nil {
return err
}
im.Data = buf
return nil
}
|
[
"func",
"(",
"im",
"*",
"Image",
")",
"UnmarshalBinaryNoCopy",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"readData",
":=",
"func",
"(",
"length",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"length",
">",
"len",
"(",
"data",
")",
"{",
"return",
"nil",
",",
"&",
"ImageError",
"{",
"Message",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"res",
":=",
"data",
"[",
":",
"length",
"]",
"\n",
"data",
"=",
"data",
"[",
"length",
":",
"]",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}",
"\n\n",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"formatLen",
":=",
"imageByteOrder",
".",
"Uint32",
"(",
"buf",
")",
"\n",
"if",
"formatLen",
">",
"ImageFormatMaxLen",
"{",
"return",
"&",
"ImageError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"formatLen",
",",
"ImageFormatMaxLen",
")",
"}",
"\n",
"}",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"int",
"(",
"formatLen",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"im",
".",
"Format",
"=",
"string",
"(",
"buf",
")",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"dataLen",
":=",
"imageByteOrder",
".",
"Uint32",
"(",
"buf",
")",
"\n",
"if",
"dataLen",
">",
"ImageDataMaxLen",
"{",
"return",
"&",
"ImageError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"dataLen",
",",
"ImageDataMaxLen",
")",
"}",
"\n",
"}",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"int",
"(",
"dataLen",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"im",
".",
"Data",
"=",
"buf",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalBinaryNoCopy is like encoding.BinaryUnmarshaler but does no copy.
//
// The caller must not reuse data after that.
|
[
"UnmarshalBinaryNoCopy",
"is",
"like",
"encoding",
".",
"BinaryUnmarshaler",
"but",
"does",
"no",
"copy",
".",
"The",
"caller",
"must",
"not",
"reuse",
"data",
"after",
"that",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image.go#L72-L116
|
142,693 |
pierrre/imageserver
|
server.go
|
NewLimitServer
|
func NewLimitServer(s Server, limit int) Server {
return &limitServer{
Server: s,
limitCh: make(chan struct{}, limit),
}
}
|
go
|
func NewLimitServer(s Server, limit int) Server {
return &limitServer{
Server: s,
limitCh: make(chan struct{}, limit),
}
}
|
[
"func",
"NewLimitServer",
"(",
"s",
"Server",
",",
"limit",
"int",
")",
"Server",
"{",
"return",
"&",
"limitServer",
"{",
"Server",
":",
"s",
",",
"limitCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"limit",
")",
",",
"}",
"\n",
"}"
] |
// NewLimitServer creates a new Server that limits the number of concurrent executions.
//
// It uses a buffered channel to limit the number of concurrent executions.
|
[
"NewLimitServer",
"creates",
"a",
"new",
"Server",
"that",
"limits",
"the",
"number",
"of",
"concurrent",
"executions",
".",
"It",
"uses",
"a",
"buffered",
"channel",
"to",
"limit",
"the",
"number",
"of",
"concurrent",
"executions",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/server.go#L20-L25
|
142,694 |
pierrre/imageserver
|
source/http/http.go
|
IdentifyHeader
|
func IdentifyHeader(resp *http.Response, data []byte) (format string, err error) {
ct := resp.Header.Get("Content-Type")
if ct == "" {
return "", fmt.Errorf("no HTTP \"Content-Type\" header")
}
const pref = "image/"
if !strings.HasPrefix(ct, pref) {
return "", fmt.Errorf("HTTP \"Content-Type\" header does not begin with \"%s\": %s", pref, ct)
}
return ct[len(pref):], nil
}
|
go
|
func IdentifyHeader(resp *http.Response, data []byte) (format string, err error) {
ct := resp.Header.Get("Content-Type")
if ct == "" {
return "", fmt.Errorf("no HTTP \"Content-Type\" header")
}
const pref = "image/"
if !strings.HasPrefix(ct, pref) {
return "", fmt.Errorf("HTTP \"Content-Type\" header does not begin with \"%s\": %s", pref, ct)
}
return ct[len(pref):], nil
}
|
[
"func",
"IdentifyHeader",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"format",
"string",
",",
"err",
"error",
")",
"{",
"ct",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"ct",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n",
"const",
"pref",
"=",
"\"",
"\"",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"ct",
",",
"pref",
")",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"pref",
",",
"ct",
")",
"\n",
"}",
"\n",
"return",
"ct",
"[",
"len",
"(",
"pref",
")",
":",
"]",
",",
"nil",
"\n",
"}"
] |
// IdentifyHeader identifies the Image format with the "Content-Type" header.
|
[
"IdentifyHeader",
"identifies",
"the",
"Image",
"format",
"with",
"the",
"Content",
"-",
"Type",
"header",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/source/http/http.go#L102-L112
|
142,695 |
pierrre/imageserver
|
image/processor.go
|
Change
|
func (prc ListProcessor) Change(params imageserver.Params) bool {
for _, p := range prc {
if p.Change(params) {
return true
}
}
return false
}
|
go
|
func (prc ListProcessor) Change(params imageserver.Params) bool {
for _, p := range prc {
if p.Change(params) {
return true
}
}
return false
}
|
[
"func",
"(",
"prc",
"ListProcessor",
")",
"Change",
"(",
"params",
"imageserver",
".",
"Params",
")",
"bool",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"prc",
"{",
"if",
"p",
".",
"Change",
"(",
"params",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Change implements Processor.
|
[
"Change",
"implements",
"Processor",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/processor.go#L46-L53
|
142,696 |
pierrre/imageserver
|
image/gamma/gamma.go
|
NewProcessor
|
func NewProcessor(gamma float64, highQuality bool) *Processor {
prc := new(Processor)
gammaInv := 1 / gamma
for i := range prc.vals {
prc.vals[i] = uint16(math.Pow(float64(i)/65535, gammaInv)*65535 + 0.5)
}
if highQuality {
prc.newDrawable = func(p image.Image) draw.Image {
return image.NewNRGBA64(p.Bounds())
}
} else {
prc.newDrawable = imageserver_image_internal.NewDrawable
}
return prc
}
|
go
|
func NewProcessor(gamma float64, highQuality bool) *Processor {
prc := new(Processor)
gammaInv := 1 / gamma
for i := range prc.vals {
prc.vals[i] = uint16(math.Pow(float64(i)/65535, gammaInv)*65535 + 0.5)
}
if highQuality {
prc.newDrawable = func(p image.Image) draw.Image {
return image.NewNRGBA64(p.Bounds())
}
} else {
prc.newDrawable = imageserver_image_internal.NewDrawable
}
return prc
}
|
[
"func",
"NewProcessor",
"(",
"gamma",
"float64",
",",
"highQuality",
"bool",
")",
"*",
"Processor",
"{",
"prc",
":=",
"new",
"(",
"Processor",
")",
"\n",
"gammaInv",
":=",
"1",
"/",
"gamma",
"\n",
"for",
"i",
":=",
"range",
"prc",
".",
"vals",
"{",
"prc",
".",
"vals",
"[",
"i",
"]",
"=",
"uint16",
"(",
"math",
".",
"Pow",
"(",
"float64",
"(",
"i",
")",
"/",
"65535",
",",
"gammaInv",
")",
"*",
"65535",
"+",
"0.5",
")",
"\n",
"}",
"\n",
"if",
"highQuality",
"{",
"prc",
".",
"newDrawable",
"=",
"func",
"(",
"p",
"image",
".",
"Image",
")",
"draw",
".",
"Image",
"{",
"return",
"image",
".",
"NewNRGBA64",
"(",
"p",
".",
"Bounds",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"prc",
".",
"newDrawable",
"=",
"imageserver_image_internal",
".",
"NewDrawable",
"\n",
"}",
"\n",
"return",
"prc",
"\n",
"}"
] |
// NewProcessor creates a Processor.
//
// "highQuality" indicates if the Processor return a NRGBA64 Image or an Image with the same quality as the given Image.
|
[
"NewProcessor",
"creates",
"a",
"Processor",
".",
"highQuality",
"indicates",
"if",
"the",
"Processor",
"return",
"a",
"NRGBA64",
"Image",
"or",
"an",
"Image",
"with",
"the",
"same",
"quality",
"as",
"the",
"given",
"Image",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/gamma/gamma.go#L24-L38
|
142,697 |
pierrre/imageserver
|
image/gamma/gamma.go
|
NewCorrectionProcessor
|
func NewCorrectionProcessor(prc imageserver_image.Processor, enabled bool) *CorrectionProcessor {
return &CorrectionProcessor{
Processor: prc,
enabled: enabled,
before: NewProcessor(1/correct, true),
after: NewProcessor(correct, true),
}
}
|
go
|
func NewCorrectionProcessor(prc imageserver_image.Processor, enabled bool) *CorrectionProcessor {
return &CorrectionProcessor{
Processor: prc,
enabled: enabled,
before: NewProcessor(1/correct, true),
after: NewProcessor(correct, true),
}
}
|
[
"func",
"NewCorrectionProcessor",
"(",
"prc",
"imageserver_image",
".",
"Processor",
",",
"enabled",
"bool",
")",
"*",
"CorrectionProcessor",
"{",
"return",
"&",
"CorrectionProcessor",
"{",
"Processor",
":",
"prc",
",",
"enabled",
":",
"enabled",
",",
"before",
":",
"NewProcessor",
"(",
"1",
"/",
"correct",
",",
"true",
")",
",",
"after",
":",
"NewProcessor",
"(",
"correct",
",",
"true",
")",
",",
"}",
"\n",
"}"
] |
// NewCorrectionProcessor creates a CorrectionProcessor.
//
// "enabled" indicated if the CorrectionProcessor is enabled by default.
|
[
"NewCorrectionProcessor",
"creates",
"a",
"CorrectionProcessor",
".",
"enabled",
"indicated",
"if",
"the",
"CorrectionProcessor",
"is",
"enabled",
"by",
"default",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/gamma/gamma.go#L91-L98
|
142,698 |
pierrre/imageserver
|
handler.go
|
Handle
|
func (f HandlerFunc) Handle(im *Image, params Params) (*Image, error) {
return f(im, params)
}
|
go
|
func (f HandlerFunc) Handle(im *Image, params Params) (*Image, error) {
return f(im, params)
}
|
[
"func",
"(",
"f",
"HandlerFunc",
")",
"Handle",
"(",
"im",
"*",
"Image",
",",
"params",
"Params",
")",
"(",
"*",
"Image",
",",
"error",
")",
"{",
"return",
"f",
"(",
"im",
",",
"params",
")",
"\n",
"}"
] |
// Handle implements Handler.
|
[
"Handle",
"implements",
"Handler",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/handler.go#L12-L14
|
142,699 |
pierrre/imageserver
|
handler.go
|
Get
|
func (srv *HandlerServer) Get(params Params) (*Image, error) {
im, err := srv.Server.Get(params)
if err != nil {
return nil, err
}
im, err = srv.Handler.Handle(im, params)
if err != nil {
return nil, err
}
return im, nil
}
|
go
|
func (srv *HandlerServer) Get(params Params) (*Image, error) {
im, err := srv.Server.Get(params)
if err != nil {
return nil, err
}
im, err = srv.Handler.Handle(im, params)
if err != nil {
return nil, err
}
return im, nil
}
|
[
"func",
"(",
"srv",
"*",
"HandlerServer",
")",
"Get",
"(",
"params",
"Params",
")",
"(",
"*",
"Image",
",",
"error",
")",
"{",
"im",
",",
"err",
":=",
"srv",
".",
"Server",
".",
"Get",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"im",
",",
"err",
"=",
"srv",
".",
"Handler",
".",
"Handle",
"(",
"im",
",",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"im",
",",
"nil",
"\n",
"}"
] |
// Get implements Server.
|
[
"Get",
"implements",
"Server",
"."
] |
05bccbfbe5b29f4842ff43827f6768b04b1d3a55
|
https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/handler.go#L23-L33
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.