repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
goadesign/goa
design/definitions.go
SetReadOnly
func (a *AttributeDefinition) SetReadOnly() { if a.Metadata == nil { a.Metadata = map[string][]string{} } a.Metadata["swagger:read-only"] = nil }
go
func (a *AttributeDefinition) SetReadOnly() { if a.Metadata == nil { a.Metadata = map[string][]string{} } a.Metadata["swagger:read-only"] = nil }
[ "func", "(", "a", "*", "AttributeDefinition", ")", "SetReadOnly", "(", ")", "{", "if", "a", ".", "Metadata", "==", "nil", "{", "a", ".", "Metadata", "=", "map", "[", "string", "]", "[", "]", "string", "{", "}", "\n", "}", "\n", "a", ".", "Metadata", "[", "\"swagger:read-only\"", "]", "=", "nil", "\n", "}" ]
// SetReadOnly sets the attribute's ReadOnly field as true.
[ "SetReadOnly", "sets", "the", "attribute", "s", "ReadOnly", "field", "as", "true", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1152-L1157
train
goadesign/goa
design/definitions.go
Merge
func (a *AttributeDefinition) Merge(other *AttributeDefinition) *AttributeDefinition { if other == nil { return a } if a == nil { return other } left := a.Type.(Object) right := other.Type.(Object) if left == nil || right == nil { panic("cannot merge non object attributes") // bug } for n, v := range right { left[n] = v } if other.Validation != nil && len(other.Validation.Required) > 0 { if a.Validation == nil { a.Validation = &dslengine.ValidationDefinition{} } for _, r := range other.Validation.Required { a.Validation.Required = append(a.Validation.Required, r) } } return a }
go
func (a *AttributeDefinition) Merge(other *AttributeDefinition) *AttributeDefinition { if other == nil { return a } if a == nil { return other } left := a.Type.(Object) right := other.Type.(Object) if left == nil || right == nil { panic("cannot merge non object attributes") // bug } for n, v := range right { left[n] = v } if other.Validation != nil && len(other.Validation.Required) > 0 { if a.Validation == nil { a.Validation = &dslengine.ValidationDefinition{} } for _, r := range other.Validation.Required { a.Validation.Required = append(a.Validation.Required, r) } } return a }
[ "func", "(", "a", "*", "AttributeDefinition", ")", "Merge", "(", "other", "*", "AttributeDefinition", ")", "*", "AttributeDefinition", "{", "if", "other", "==", "nil", "{", "return", "a", "\n", "}", "\n", "if", "a", "==", "nil", "{", "return", "other", "\n", "}", "\n", "left", ":=", "a", ".", "Type", ".", "(", "Object", ")", "\n", "right", ":=", "other", ".", "Type", ".", "(", "Object", ")", "\n", "if", "left", "==", "nil", "||", "right", "==", "nil", "{", "panic", "(", "\"cannot merge non object attributes\"", ")", "\n", "}", "\n", "for", "n", ",", "v", ":=", "range", "right", "{", "left", "[", "n", "]", "=", "v", "\n", "}", "\n", "if", "other", ".", "Validation", "!=", "nil", "&&", "len", "(", "other", ".", "Validation", ".", "Required", ")", ">", "0", "{", "if", "a", ".", "Validation", "==", "nil", "{", "a", ".", "Validation", "=", "&", "dslengine", ".", "ValidationDefinition", "{", "}", "\n", "}", "\n", "for", "_", ",", "r", ":=", "range", "other", ".", "Validation", ".", "Required", "{", "a", ".", "Validation", ".", "Required", "=", "append", "(", "a", ".", "Validation", ".", "Required", ",", "r", ")", "\n", "}", "\n", "}", "\n", "return", "a", "\n", "}" ]
// Merge merges the argument attributes into the target and returns the target overriding existing // attributes with identical names. // This only applies to attributes of type Object and Merge panics if the // argument or the target is not of type Object.
[ "Merge", "merges", "the", "argument", "attributes", "into", "the", "target", "and", "returns", "the", "target", "overriding", "existing", "attributes", "with", "identical", "names", ".", "This", "only", "applies", "to", "attributes", "of", "type", "Object", "and", "Merge", "panics", "if", "the", "argument", "or", "the", "target", "is", "not", "of", "type", "Object", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1243-L1267
train
goadesign/goa
design/definitions.go
Inherit
func (a *AttributeDefinition) Inherit(parent *AttributeDefinition, seen ...map[*AttributeDefinition]struct{}) { if !a.shouldInherit(parent) { return } a.inheritValidations(parent) a.inheritRecursive(parent, seen...) }
go
func (a *AttributeDefinition) Inherit(parent *AttributeDefinition, seen ...map[*AttributeDefinition]struct{}) { if !a.shouldInherit(parent) { return } a.inheritValidations(parent) a.inheritRecursive(parent, seen...) }
[ "func", "(", "a", "*", "AttributeDefinition", ")", "Inherit", "(", "parent", "*", "AttributeDefinition", ",", "seen", "...", "map", "[", "*", "AttributeDefinition", "]", "struct", "{", "}", ")", "{", "if", "!", "a", ".", "shouldInherit", "(", "parent", ")", "{", "return", "\n", "}", "\n", "a", ".", "inheritValidations", "(", "parent", ")", "\n", "a", ".", "inheritRecursive", "(", "parent", ",", "seen", "...", ")", "\n", "}" ]
// Inherit merges the properties of existing target type attributes with the argument's. // The algorithm is recursive so that child attributes are also merged.
[ "Inherit", "merges", "the", "properties", "of", "existing", "target", "type", "attributes", "with", "the", "argument", "s", ".", "The", "algorithm", "is", "recursive", "so", "that", "child", "attributes", "are", "also", "merged", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1271-L1278
train
goadesign/goa
design/definitions.go
Finalize
func (r *ResponseDefinition) Finalize() { if r.Type == nil { return } if r.MediaType != "" && r.MediaType != "text/plain" { return } mt, ok := r.Type.(*MediaTypeDefinition) if !ok { return } r.MediaType = mt.Identifier }
go
func (r *ResponseDefinition) Finalize() { if r.Type == nil { return } if r.MediaType != "" && r.MediaType != "text/plain" { return } mt, ok := r.Type.(*MediaTypeDefinition) if !ok { return } r.MediaType = mt.Identifier }
[ "func", "(", "r", "*", "ResponseDefinition", ")", "Finalize", "(", ")", "{", "if", "r", ".", "Type", "==", "nil", "{", "return", "\n", "}", "\n", "if", "r", ".", "MediaType", "!=", "\"\"", "&&", "r", ".", "MediaType", "!=", "\"text/plain\"", "{", "return", "\n", "}", "\n", "mt", ",", "ok", ":=", "r", ".", "Type", ".", "(", "*", "MediaTypeDefinition", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "r", ".", "MediaType", "=", "mt", ".", "Identifier", "\n", "}" ]
// Finalize sets the response media type from its type if the type is a media type and no media // type is already specified.
[ "Finalize", "sets", "the", "response", "media", "type", "from", "its", "type", "if", "the", "type", "is", "a", "media", "type", "and", "no", "media", "type", "is", "already", "specified", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1405-L1417
train
goadesign/goa
design/definitions.go
Dup
func (r *ResponseDefinition) Dup() *ResponseDefinition { res := ResponseDefinition{ Name: r.Name, Status: r.Status, Description: r.Description, MediaType: r.MediaType, ViewName: r.ViewName, } if r.Headers != nil { res.Headers = DupAtt(r.Headers) } return &res }
go
func (r *ResponseDefinition) Dup() *ResponseDefinition { res := ResponseDefinition{ Name: r.Name, Status: r.Status, Description: r.Description, MediaType: r.MediaType, ViewName: r.ViewName, } if r.Headers != nil { res.Headers = DupAtt(r.Headers) } return &res }
[ "func", "(", "r", "*", "ResponseDefinition", ")", "Dup", "(", ")", "*", "ResponseDefinition", "{", "res", ":=", "ResponseDefinition", "{", "Name", ":", "r", ".", "Name", ",", "Status", ":", "r", ".", "Status", ",", "Description", ":", "r", ".", "Description", ",", "MediaType", ":", "r", ".", "MediaType", ",", "ViewName", ":", "r", ".", "ViewName", ",", "}", "\n", "if", "r", ".", "Headers", "!=", "nil", "{", "res", ".", "Headers", "=", "DupAtt", "(", "r", ".", "Headers", ")", "\n", "}", "\n", "return", "&", "res", "\n", "}" ]
// Dup returns a copy of the response definition.
[ "Dup", "returns", "a", "copy", "of", "the", "response", "definition", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1420-L1432
train
goadesign/goa
design/definitions.go
Merge
func (r *ResponseDefinition) Merge(other *ResponseDefinition) { if other == nil { return } if r.Name == "" { r.Name = other.Name } if r.Status == 0 { r.Status = other.Status } if r.Description == "" { r.Description = other.Description } if r.MediaType == "" { r.MediaType = other.MediaType r.ViewName = other.ViewName } if other.Headers != nil { otherHeaders := other.Headers.Type.ToObject() if len(otherHeaders) > 0 { if r.Headers == nil { r.Headers = &AttributeDefinition{Type: Object{}} } headers := r.Headers.Type.ToObject() for n, h := range otherHeaders { if _, ok := headers[n]; !ok { headers[n] = h } } } } }
go
func (r *ResponseDefinition) Merge(other *ResponseDefinition) { if other == nil { return } if r.Name == "" { r.Name = other.Name } if r.Status == 0 { r.Status = other.Status } if r.Description == "" { r.Description = other.Description } if r.MediaType == "" { r.MediaType = other.MediaType r.ViewName = other.ViewName } if other.Headers != nil { otherHeaders := other.Headers.Type.ToObject() if len(otherHeaders) > 0 { if r.Headers == nil { r.Headers = &AttributeDefinition{Type: Object{}} } headers := r.Headers.Type.ToObject() for n, h := range otherHeaders { if _, ok := headers[n]; !ok { headers[n] = h } } } } }
[ "func", "(", "r", "*", "ResponseDefinition", ")", "Merge", "(", "other", "*", "ResponseDefinition", ")", "{", "if", "other", "==", "nil", "{", "return", "\n", "}", "\n", "if", "r", ".", "Name", "==", "\"\"", "{", "r", ".", "Name", "=", "other", ".", "Name", "\n", "}", "\n", "if", "r", ".", "Status", "==", "0", "{", "r", ".", "Status", "=", "other", ".", "Status", "\n", "}", "\n", "if", "r", ".", "Description", "==", "\"\"", "{", "r", ".", "Description", "=", "other", ".", "Description", "\n", "}", "\n", "if", "r", ".", "MediaType", "==", "\"\"", "{", "r", ".", "MediaType", "=", "other", ".", "MediaType", "\n", "r", ".", "ViewName", "=", "other", ".", "ViewName", "\n", "}", "\n", "if", "other", ".", "Headers", "!=", "nil", "{", "otherHeaders", ":=", "other", ".", "Headers", ".", "Type", ".", "ToObject", "(", ")", "\n", "if", "len", "(", "otherHeaders", ")", ">", "0", "{", "if", "r", ".", "Headers", "==", "nil", "{", "r", ".", "Headers", "=", "&", "AttributeDefinition", "{", "Type", ":", "Object", "{", "}", "}", "\n", "}", "\n", "headers", ":=", "r", ".", "Headers", ".", "Type", ".", "ToObject", "(", ")", "\n", "for", "n", ",", "h", ":=", "range", "otherHeaders", "{", "if", "_", ",", "ok", ":=", "headers", "[", "n", "]", ";", "!", "ok", "{", "headers", "[", "n", "]", "=", "h", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Merge merges other into target. Only the fields of target that are not already set are merged.
[ "Merge", "merges", "other", "into", "target", ".", "Only", "the", "fields", "of", "target", "that", "are", "not", "already", "set", "are", "merged", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1435-L1466
train
goadesign/goa
design/definitions.go
PathParams
func (a *ActionDefinition) PathParams() *AttributeDefinition { obj := make(Object) allParams := a.AllParams().Type.ToObject() for _, r := range a.Routes { for _, p := range r.Params() { if _, ok := obj[p]; !ok { obj[p] = allParams[p] } } } return &AttributeDefinition{Type: obj} }
go
func (a *ActionDefinition) PathParams() *AttributeDefinition { obj := make(Object) allParams := a.AllParams().Type.ToObject() for _, r := range a.Routes { for _, p := range r.Params() { if _, ok := obj[p]; !ok { obj[p] = allParams[p] } } } return &AttributeDefinition{Type: obj} }
[ "func", "(", "a", "*", "ActionDefinition", ")", "PathParams", "(", ")", "*", "AttributeDefinition", "{", "obj", ":=", "make", "(", "Object", ")", "\n", "allParams", ":=", "a", ".", "AllParams", "(", ")", ".", "Type", ".", "ToObject", "(", ")", "\n", "for", "_", ",", "r", ":=", "range", "a", ".", "Routes", "{", "for", "_", ",", "p", ":=", "range", "r", ".", "Params", "(", ")", "{", "if", "_", ",", "ok", ":=", "obj", "[", "p", "]", ";", "!", "ok", "{", "obj", "[", "p", "]", "=", "allParams", "[", "p", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "&", "AttributeDefinition", "{", "Type", ":", "obj", "}", "\n", "}" ]
// PathParams returns the path parameters of the action across all its routes.
[ "PathParams", "returns", "the", "path", "parameters", "of", "the", "action", "across", "all", "its", "routes", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1491-L1502
train
goadesign/goa
design/definitions.go
AllParams
func (a *ActionDefinition) AllParams() *AttributeDefinition { var res *AttributeDefinition if a.Params != nil { res = DupAtt(a.Params) } else { res = &AttributeDefinition{Type: Object{}} } if a.HasAbsoluteRoutes() { return res } res = res.Merge(a.Parent.Params) if p := a.Parent.Parent(); p != nil { res = res.Merge(p.CanonicalAction().PathParams()) } else { res = res.Merge(a.Parent.PathParams()) } return res.Merge(Design.Params) }
go
func (a *ActionDefinition) AllParams() *AttributeDefinition { var res *AttributeDefinition if a.Params != nil { res = DupAtt(a.Params) } else { res = &AttributeDefinition{Type: Object{}} } if a.HasAbsoluteRoutes() { return res } res = res.Merge(a.Parent.Params) if p := a.Parent.Parent(); p != nil { res = res.Merge(p.CanonicalAction().PathParams()) } else { res = res.Merge(a.Parent.PathParams()) } return res.Merge(Design.Params) }
[ "func", "(", "a", "*", "ActionDefinition", ")", "AllParams", "(", ")", "*", "AttributeDefinition", "{", "var", "res", "*", "AttributeDefinition", "\n", "if", "a", ".", "Params", "!=", "nil", "{", "res", "=", "DupAtt", "(", "a", ".", "Params", ")", "\n", "}", "else", "{", "res", "=", "&", "AttributeDefinition", "{", "Type", ":", "Object", "{", "}", "}", "\n", "}", "\n", "if", "a", ".", "HasAbsoluteRoutes", "(", ")", "{", "return", "res", "\n", "}", "\n", "res", "=", "res", ".", "Merge", "(", "a", ".", "Parent", ".", "Params", ")", "\n", "if", "p", ":=", "a", ".", "Parent", ".", "Parent", "(", ")", ";", "p", "!=", "nil", "{", "res", "=", "res", ".", "Merge", "(", "p", ".", "CanonicalAction", "(", ")", ".", "PathParams", "(", ")", ")", "\n", "}", "else", "{", "res", "=", "res", ".", "Merge", "(", "a", ".", "Parent", ".", "PathParams", "(", ")", ")", "\n", "}", "\n", "return", "res", ".", "Merge", "(", "Design", ".", "Params", ")", "\n", "}" ]
// AllParams returns the path and query string parameters of the action across all its routes.
[ "AllParams", "returns", "the", "path", "and", "query", "string", "parameters", "of", "the", "action", "across", "all", "its", "routes", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1505-L1522
train
goadesign/goa
design/definitions.go
HasAbsoluteRoutes
func (a *ActionDefinition) HasAbsoluteRoutes() bool { for _, r := range a.Routes { if !r.IsAbsolute() { return false } } return true }
go
func (a *ActionDefinition) HasAbsoluteRoutes() bool { for _, r := range a.Routes { if !r.IsAbsolute() { return false } } return true }
[ "func", "(", "a", "*", "ActionDefinition", ")", "HasAbsoluteRoutes", "(", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "a", ".", "Routes", "{", "if", "!", "r", ".", "IsAbsolute", "(", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// HasAbsoluteRoutes returns true if all the action routes are absolute.
[ "HasAbsoluteRoutes", "returns", "true", "if", "all", "the", "action", "routes", "are", "absolute", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1525-L1532
train
goadesign/goa
design/definitions.go
CanonicalScheme
func (a *ActionDefinition) CanonicalScheme() string { if a.WebSocket() { for _, s := range a.EffectiveSchemes() { if s == "wss" { return s } } return "ws" } for _, s := range a.EffectiveSchemes() { if s == "https" { return s } } return "http" }
go
func (a *ActionDefinition) CanonicalScheme() string { if a.WebSocket() { for _, s := range a.EffectiveSchemes() { if s == "wss" { return s } } return "ws" } for _, s := range a.EffectiveSchemes() { if s == "https" { return s } } return "http" }
[ "func", "(", "a", "*", "ActionDefinition", ")", "CanonicalScheme", "(", ")", "string", "{", "if", "a", ".", "WebSocket", "(", ")", "{", "for", "_", ",", "s", ":=", "range", "a", ".", "EffectiveSchemes", "(", ")", "{", "if", "s", "==", "\"wss\"", "{", "return", "s", "\n", "}", "\n", "}", "\n", "return", "\"ws\"", "\n", "}", "\n", "for", "_", ",", "s", ":=", "range", "a", ".", "EffectiveSchemes", "(", ")", "{", "if", "s", "==", "\"https\"", "{", "return", "s", "\n", "}", "\n", "}", "\n", "return", "\"http\"", "\n", "}" ]
// CanonicalScheme returns the preferred scheme for making requests. Favor secure schemes.
[ "CanonicalScheme", "returns", "the", "preferred", "scheme", "for", "making", "requests", ".", "Favor", "secure", "schemes", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1535-L1550
train
goadesign/goa
design/definitions.go
EffectiveSchemes
func (a *ActionDefinition) EffectiveSchemes() []string { // Compute the schemes schemes := a.Schemes if len(schemes) == 0 { res := a.Parent schemes = res.Schemes parent := res.Parent() for len(schemes) == 0 && parent != nil { schemes = parent.Schemes parent = parent.Parent() } if len(schemes) == 0 { schemes = Design.Schemes } } return schemes }
go
func (a *ActionDefinition) EffectiveSchemes() []string { // Compute the schemes schemes := a.Schemes if len(schemes) == 0 { res := a.Parent schemes = res.Schemes parent := res.Parent() for len(schemes) == 0 && parent != nil { schemes = parent.Schemes parent = parent.Parent() } if len(schemes) == 0 { schemes = Design.Schemes } } return schemes }
[ "func", "(", "a", "*", "ActionDefinition", ")", "EffectiveSchemes", "(", ")", "[", "]", "string", "{", "schemes", ":=", "a", ".", "Schemes", "\n", "if", "len", "(", "schemes", ")", "==", "0", "{", "res", ":=", "a", ".", "Parent", "\n", "schemes", "=", "res", ".", "Schemes", "\n", "parent", ":=", "res", ".", "Parent", "(", ")", "\n", "for", "len", "(", "schemes", ")", "==", "0", "&&", "parent", "!=", "nil", "{", "schemes", "=", "parent", ".", "Schemes", "\n", "parent", "=", "parent", ".", "Parent", "(", ")", "\n", "}", "\n", "if", "len", "(", "schemes", ")", "==", "0", "{", "schemes", "=", "Design", ".", "Schemes", "\n", "}", "\n", "}", "\n", "return", "schemes", "\n", "}" ]
// EffectiveSchemes return the URL schemes that apply to the action. Looks recursively into action // resource, parent resources and API.
[ "EffectiveSchemes", "return", "the", "URL", "schemes", "that", "apply", "to", "the", "action", ".", "Looks", "recursively", "into", "action", "resource", "parent", "resources", "and", "API", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1554-L1570
train
goadesign/goa
design/definitions.go
Finalize
func (a *ActionDefinition) Finalize() { // Inherit security scheme if a.Security == nil { a.Security = a.Parent.Security // ResourceDefinition if a.Security == nil { a.Security = Design.Security } } if a.Security != nil && a.Security.Scheme.Kind == NoSecurityKind { a.Security = nil } if a.Payload != nil { a.Payload.Finalize() } a.mergeResponses() a.initImplicitParams() a.initQueryParams() }
go
func (a *ActionDefinition) Finalize() { // Inherit security scheme if a.Security == nil { a.Security = a.Parent.Security // ResourceDefinition if a.Security == nil { a.Security = Design.Security } } if a.Security != nil && a.Security.Scheme.Kind == NoSecurityKind { a.Security = nil } if a.Payload != nil { a.Payload.Finalize() } a.mergeResponses() a.initImplicitParams() a.initQueryParams() }
[ "func", "(", "a", "*", "ActionDefinition", ")", "Finalize", "(", ")", "{", "if", "a", ".", "Security", "==", "nil", "{", "a", ".", "Security", "=", "a", ".", "Parent", ".", "Security", "\n", "if", "a", ".", "Security", "==", "nil", "{", "a", ".", "Security", "=", "Design", ".", "Security", "\n", "}", "\n", "}", "\n", "if", "a", ".", "Security", "!=", "nil", "&&", "a", ".", "Security", ".", "Scheme", ".", "Kind", "==", "NoSecurityKind", "{", "a", ".", "Security", "=", "nil", "\n", "}", "\n", "if", "a", ".", "Payload", "!=", "nil", "{", "a", ".", "Payload", ".", "Finalize", "(", ")", "\n", "}", "\n", "a", ".", "mergeResponses", "(", ")", "\n", "a", ".", "initImplicitParams", "(", ")", "\n", "a", ".", "initQueryParams", "(", ")", "\n", "}" ]
// Finalize inherits security scheme and action responses from parent and top level design.
[ "Finalize", "inherits", "security", "scheme", "and", "action", "responses", "from", "parent", "and", "top", "level", "design", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1588-L1608
train
goadesign/goa
design/definitions.go
UserTypes
func (a *ActionDefinition) UserTypes() map[string]*UserTypeDefinition { types := make(map[string]*UserTypeDefinition) allp := a.AllParams().Type.ToObject() if a.Payload != nil { allp["__payload__"] = &AttributeDefinition{Type: a.Payload} } for n, ut := range UserTypes(allp) { types[n] = ut } for _, r := range a.Responses { if mt := Design.MediaTypeWithIdentifier(r.MediaType); mt != nil { types[mt.TypeName] = mt.UserTypeDefinition for n, ut := range UserTypes(mt.UserTypeDefinition) { types[n] = ut } } } if len(types) == 0 { return nil } return types }
go
func (a *ActionDefinition) UserTypes() map[string]*UserTypeDefinition { types := make(map[string]*UserTypeDefinition) allp := a.AllParams().Type.ToObject() if a.Payload != nil { allp["__payload__"] = &AttributeDefinition{Type: a.Payload} } for n, ut := range UserTypes(allp) { types[n] = ut } for _, r := range a.Responses { if mt := Design.MediaTypeWithIdentifier(r.MediaType); mt != nil { types[mt.TypeName] = mt.UserTypeDefinition for n, ut := range UserTypes(mt.UserTypeDefinition) { types[n] = ut } } } if len(types) == 0 { return nil } return types }
[ "func", "(", "a", "*", "ActionDefinition", ")", "UserTypes", "(", ")", "map", "[", "string", "]", "*", "UserTypeDefinition", "{", "types", ":=", "make", "(", "map", "[", "string", "]", "*", "UserTypeDefinition", ")", "\n", "allp", ":=", "a", ".", "AllParams", "(", ")", ".", "Type", ".", "ToObject", "(", ")", "\n", "if", "a", ".", "Payload", "!=", "nil", "{", "allp", "[", "\"__payload__\"", "]", "=", "&", "AttributeDefinition", "{", "Type", ":", "a", ".", "Payload", "}", "\n", "}", "\n", "for", "n", ",", "ut", ":=", "range", "UserTypes", "(", "allp", ")", "{", "types", "[", "n", "]", "=", "ut", "\n", "}", "\n", "for", "_", ",", "r", ":=", "range", "a", ".", "Responses", "{", "if", "mt", ":=", "Design", ".", "MediaTypeWithIdentifier", "(", "r", ".", "MediaType", ")", ";", "mt", "!=", "nil", "{", "types", "[", "mt", ".", "TypeName", "]", "=", "mt", ".", "UserTypeDefinition", "\n", "for", "n", ",", "ut", ":=", "range", "UserTypes", "(", "mt", ".", "UserTypeDefinition", ")", "{", "types", "[", "n", "]", "=", "ut", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "types", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "types", "\n", "}" ]
// UserTypes returns all the user types used by the action payload and parameters.
[ "UserTypes", "returns", "all", "the", "user", "types", "used", "by", "the", "action", "payload", "and", "parameters", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1611-L1632
train
goadesign/goa
design/definitions.go
IterateHeaders
func (a *ActionDefinition) IterateHeaders(it HeaderIterator) error { mergedHeaders := a.Parent.Headers.Merge(a.Headers) isRequired := func(name string) bool { // header required in either the Resource or Action scope? return a.Parent.Headers.IsRequired(name) || a.Headers.IsRequired(name) } return iterateHeaders(mergedHeaders, isRequired, it) }
go
func (a *ActionDefinition) IterateHeaders(it HeaderIterator) error { mergedHeaders := a.Parent.Headers.Merge(a.Headers) isRequired := func(name string) bool { // header required in either the Resource or Action scope? return a.Parent.Headers.IsRequired(name) || a.Headers.IsRequired(name) } return iterateHeaders(mergedHeaders, isRequired, it) }
[ "func", "(", "a", "*", "ActionDefinition", ")", "IterateHeaders", "(", "it", "HeaderIterator", ")", "error", "{", "mergedHeaders", ":=", "a", ".", "Parent", ".", "Headers", ".", "Merge", "(", "a", ".", "Headers", ")", "\n", "isRequired", ":=", "func", "(", "name", "string", ")", "bool", "{", "return", "a", ".", "Parent", ".", "Headers", ".", "IsRequired", "(", "name", ")", "||", "a", ".", "Headers", ".", "IsRequired", "(", "name", ")", "\n", "}", "\n", "return", "iterateHeaders", "(", "mergedHeaders", ",", "isRequired", ",", "it", ")", "\n", "}" ]
// IterateHeaders iterates over the resource-level and action-level headers, // calling the given iterator passing in each response sorted in alphabetical order. // Iteration stops if an iterator returns an error and in this case IterateHeaders returns that // error.
[ "IterateHeaders", "iterates", "over", "the", "resource", "-", "level", "and", "action", "-", "level", "headers", "calling", "the", "given", "iterator", "passing", "in", "each", "response", "sorted", "in", "alphabetical", "order", ".", "Iteration", "stops", "if", "an", "iterator", "returns", "an", "error", "and", "in", "this", "case", "IterateHeaders", "returns", "that", "error", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1638-L1647
train
goadesign/goa
design/definitions.go
mergeResponses
func (a *ActionDefinition) mergeResponses() { for name, resp := range a.Parent.Responses { if _, ok := a.Responses[name]; !ok { if a.Responses == nil { a.Responses = make(map[string]*ResponseDefinition) } a.Responses[name] = resp.Dup() } } for name, resp := range a.Responses { resp.Finalize() if pr, ok := a.Parent.Responses[name]; ok { resp.Merge(pr) } if ar, ok := Design.Responses[name]; ok { resp.Merge(ar) } if dr, ok := Design.DefaultResponses[name]; ok { resp.Merge(dr) } } }
go
func (a *ActionDefinition) mergeResponses() { for name, resp := range a.Parent.Responses { if _, ok := a.Responses[name]; !ok { if a.Responses == nil { a.Responses = make(map[string]*ResponseDefinition) } a.Responses[name] = resp.Dup() } } for name, resp := range a.Responses { resp.Finalize() if pr, ok := a.Parent.Responses[name]; ok { resp.Merge(pr) } if ar, ok := Design.Responses[name]; ok { resp.Merge(ar) } if dr, ok := Design.DefaultResponses[name]; ok { resp.Merge(dr) } } }
[ "func", "(", "a", "*", "ActionDefinition", ")", "mergeResponses", "(", ")", "{", "for", "name", ",", "resp", ":=", "range", "a", ".", "Parent", ".", "Responses", "{", "if", "_", ",", "ok", ":=", "a", ".", "Responses", "[", "name", "]", ";", "!", "ok", "{", "if", "a", ".", "Responses", "==", "nil", "{", "a", ".", "Responses", "=", "make", "(", "map", "[", "string", "]", "*", "ResponseDefinition", ")", "\n", "}", "\n", "a", ".", "Responses", "[", "name", "]", "=", "resp", ".", "Dup", "(", ")", "\n", "}", "\n", "}", "\n", "for", "name", ",", "resp", ":=", "range", "a", ".", "Responses", "{", "resp", ".", "Finalize", "(", ")", "\n", "if", "pr", ",", "ok", ":=", "a", ".", "Parent", ".", "Responses", "[", "name", "]", ";", "ok", "{", "resp", ".", "Merge", "(", "pr", ")", "\n", "}", "\n", "if", "ar", ",", "ok", ":=", "Design", ".", "Responses", "[", "name", "]", ";", "ok", "{", "resp", ".", "Merge", "(", "ar", ")", "\n", "}", "\n", "if", "dr", ",", "ok", ":=", "Design", ".", "DefaultResponses", "[", "name", "]", ";", "ok", "{", "resp", ".", "Merge", "(", "dr", ")", "\n", "}", "\n", "}", "\n", "}" ]
// mergeResponses merges the parent resource and design responses.
[ "mergeResponses", "merges", "the", "parent", "resource", "and", "design", "responses", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1669-L1690
train
goadesign/goa
design/definitions.go
initImplicitParams
func (a *ActionDefinition) initImplicitParams() { for _, ro := range a.Routes { for _, wc := range ro.Params() { found := false search := func(params *AttributeDefinition) { if params == nil { return } att, ok := params.Type.ToObject()[wc] if ok { if a.Params == nil { a.Params = &AttributeDefinition{Type: Object{}} } a.Params.Type.ToObject()[wc] = att found = true } } search(a.Params) parent := a.Parent for !found && parent != nil { bp := parent.Params parent = parent.Parent() search(bp) } if found { continue } search(Design.Params) if found { continue } if a.Params == nil { a.Params = &AttributeDefinition{Type: Object{}} } a.Params.Type.ToObject()[wc] = &AttributeDefinition{Type: String} } } }
go
func (a *ActionDefinition) initImplicitParams() { for _, ro := range a.Routes { for _, wc := range ro.Params() { found := false search := func(params *AttributeDefinition) { if params == nil { return } att, ok := params.Type.ToObject()[wc] if ok { if a.Params == nil { a.Params = &AttributeDefinition{Type: Object{}} } a.Params.Type.ToObject()[wc] = att found = true } } search(a.Params) parent := a.Parent for !found && parent != nil { bp := parent.Params parent = parent.Parent() search(bp) } if found { continue } search(Design.Params) if found { continue } if a.Params == nil { a.Params = &AttributeDefinition{Type: Object{}} } a.Params.Type.ToObject()[wc] = &AttributeDefinition{Type: String} } } }
[ "func", "(", "a", "*", "ActionDefinition", ")", "initImplicitParams", "(", ")", "{", "for", "_", ",", "ro", ":=", "range", "a", ".", "Routes", "{", "for", "_", ",", "wc", ":=", "range", "ro", ".", "Params", "(", ")", "{", "found", ":=", "false", "\n", "search", ":=", "func", "(", "params", "*", "AttributeDefinition", ")", "{", "if", "params", "==", "nil", "{", "return", "\n", "}", "\n", "att", ",", "ok", ":=", "params", ".", "Type", ".", "ToObject", "(", ")", "[", "wc", "]", "\n", "if", "ok", "{", "if", "a", ".", "Params", "==", "nil", "{", "a", ".", "Params", "=", "&", "AttributeDefinition", "{", "Type", ":", "Object", "{", "}", "}", "\n", "}", "\n", "a", ".", "Params", ".", "Type", ".", "ToObject", "(", ")", "[", "wc", "]", "=", "att", "\n", "found", "=", "true", "\n", "}", "\n", "}", "\n", "search", "(", "a", ".", "Params", ")", "\n", "parent", ":=", "a", ".", "Parent", "\n", "for", "!", "found", "&&", "parent", "!=", "nil", "{", "bp", ":=", "parent", ".", "Params", "\n", "parent", "=", "parent", ".", "Parent", "(", ")", "\n", "search", "(", "bp", ")", "\n", "}", "\n", "if", "found", "{", "continue", "\n", "}", "\n", "search", "(", "Design", ".", "Params", ")", "\n", "if", "found", "{", "continue", "\n", "}", "\n", "if", "a", ".", "Params", "==", "nil", "{", "a", ".", "Params", "=", "&", "AttributeDefinition", "{", "Type", ":", "Object", "{", "}", "}", "\n", "}", "\n", "a", ".", "Params", ".", "Type", ".", "ToObject", "(", ")", "[", "wc", "]", "=", "&", "AttributeDefinition", "{", "Type", ":", "String", "}", "\n", "}", "\n", "}", "\n", "}" ]
// initImplicitParams creates params for path segments that don't have one.
[ "initImplicitParams", "creates", "params", "for", "path", "segments", "that", "don", "t", "have", "one", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1693-L1730
train
goadesign/goa
design/definitions.go
initQueryParams
func (a *ActionDefinition) initQueryParams() { // 3. Compute QueryParams from Params and set all path params as non zero attributes if params := a.AllParams(); params != nil { queryParams := DupAtt(params) queryParams.Type = Dup(queryParams.Type) if a.Params == nil { a.Params = &AttributeDefinition{Type: Object{}} } a.Params.NonZeroAttributes = make(map[string]bool) for _, route := range a.Routes { pnames := route.Params() for _, pname := range pnames { a.Params.NonZeroAttributes[pname] = true delete(queryParams.Type.ToObject(), pname) if queryParams.Validation != nil { req := queryParams.Validation.Required for i, n := range req { if n == pname { queryParams.Validation.Required = append(req[:i], req[i+1:]...) break } } } } } a.QueryParams = queryParams } }
go
func (a *ActionDefinition) initQueryParams() { // 3. Compute QueryParams from Params and set all path params as non zero attributes if params := a.AllParams(); params != nil { queryParams := DupAtt(params) queryParams.Type = Dup(queryParams.Type) if a.Params == nil { a.Params = &AttributeDefinition{Type: Object{}} } a.Params.NonZeroAttributes = make(map[string]bool) for _, route := range a.Routes { pnames := route.Params() for _, pname := range pnames { a.Params.NonZeroAttributes[pname] = true delete(queryParams.Type.ToObject(), pname) if queryParams.Validation != nil { req := queryParams.Validation.Required for i, n := range req { if n == pname { queryParams.Validation.Required = append(req[:i], req[i+1:]...) break } } } } } a.QueryParams = queryParams } }
[ "func", "(", "a", "*", "ActionDefinition", ")", "initQueryParams", "(", ")", "{", "if", "params", ":=", "a", ".", "AllParams", "(", ")", ";", "params", "!=", "nil", "{", "queryParams", ":=", "DupAtt", "(", "params", ")", "\n", "queryParams", ".", "Type", "=", "Dup", "(", "queryParams", ".", "Type", ")", "\n", "if", "a", ".", "Params", "==", "nil", "{", "a", ".", "Params", "=", "&", "AttributeDefinition", "{", "Type", ":", "Object", "{", "}", "}", "\n", "}", "\n", "a", ".", "Params", ".", "NonZeroAttributes", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "route", ":=", "range", "a", ".", "Routes", "{", "pnames", ":=", "route", ".", "Params", "(", ")", "\n", "for", "_", ",", "pname", ":=", "range", "pnames", "{", "a", ".", "Params", ".", "NonZeroAttributes", "[", "pname", "]", "=", "true", "\n", "delete", "(", "queryParams", ".", "Type", ".", "ToObject", "(", ")", ",", "pname", ")", "\n", "if", "queryParams", ".", "Validation", "!=", "nil", "{", "req", ":=", "queryParams", ".", "Validation", ".", "Required", "\n", "for", "i", ",", "n", ":=", "range", "req", "{", "if", "n", "==", "pname", "{", "queryParams", ".", "Validation", ".", "Required", "=", "append", "(", "req", "[", ":", "i", "]", ",", "req", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "a", ".", "QueryParams", "=", "queryParams", "\n", "}", "\n", "}" ]
// initQueryParams extract the query parameters from the action params.
[ "initQueryParams", "extract", "the", "query", "parameters", "from", "the", "action", "params", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1733-L1760
train
goadesign/goa
design/definitions.go
Finalize
func (f *FileServerDefinition) Finalize() { // Make sure request path starts with a "/" so codegen can rely on it. if !strings.HasPrefix(f.RequestPath, "/") { f.RequestPath = "/" + f.RequestPath } // Inherit security if f.Security == nil { f.Security = f.Parent.Security // ResourceDefinition if f.Security == nil { f.Security = Design.Security } } if f.Security != nil && f.Security.Scheme.Kind == NoSecurityKind { f.Security = nil } }
go
func (f *FileServerDefinition) Finalize() { // Make sure request path starts with a "/" so codegen can rely on it. if !strings.HasPrefix(f.RequestPath, "/") { f.RequestPath = "/" + f.RequestPath } // Inherit security if f.Security == nil { f.Security = f.Parent.Security // ResourceDefinition if f.Security == nil { f.Security = Design.Security } } if f.Security != nil && f.Security.Scheme.Kind == NoSecurityKind { f.Security = nil } }
[ "func", "(", "f", "*", "FileServerDefinition", ")", "Finalize", "(", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "f", ".", "RequestPath", ",", "\"/\"", ")", "{", "f", ".", "RequestPath", "=", "\"/\"", "+", "f", ".", "RequestPath", "\n", "}", "\n", "if", "f", ".", "Security", "==", "nil", "{", "f", ".", "Security", "=", "f", ".", "Parent", ".", "Security", "\n", "if", "f", ".", "Security", "==", "nil", "{", "f", ".", "Security", "=", "Design", ".", "Security", "\n", "}", "\n", "}", "\n", "if", "f", ".", "Security", "!=", "nil", "&&", "f", ".", "Security", ".", "Scheme", ".", "Kind", "==", "NoSecurityKind", "{", "f", ".", "Security", "=", "nil", "\n", "}", "\n", "}" ]
// Finalize inherits security scheme from parent and top level design.
[ "Finalize", "inherits", "security", "scheme", "from", "parent", "and", "top", "level", "design", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1773-L1788
train
goadesign/goa
design/definitions.go
Attribute
func (l *LinkDefinition) Attribute() *AttributeDefinition { p := l.Parent.ToObject() if p == nil { return nil } att, _ := p[l.Name] return att }
go
func (l *LinkDefinition) Attribute() *AttributeDefinition { p := l.Parent.ToObject() if p == nil { return nil } att, _ := p[l.Name] return att }
[ "func", "(", "l", "*", "LinkDefinition", ")", "Attribute", "(", ")", "*", "AttributeDefinition", "{", "p", ":=", "l", ".", "Parent", ".", "ToObject", "(", ")", "\n", "if", "p", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "att", ",", "_", ":=", "p", "[", "l", ".", "Name", "]", "\n", "return", "att", "\n", "}" ]
// Attribute returns the linked attribute.
[ "Attribute", "returns", "the", "linked", "attribute", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1817-L1825
train
goadesign/goa
design/definitions.go
MediaType
func (l *LinkDefinition) MediaType() *MediaTypeDefinition { att := l.Attribute() mt, _ := att.Type.(*MediaTypeDefinition) return mt }
go
func (l *LinkDefinition) MediaType() *MediaTypeDefinition { att := l.Attribute() mt, _ := att.Type.(*MediaTypeDefinition) return mt }
[ "func", "(", "l", "*", "LinkDefinition", ")", "MediaType", "(", ")", "*", "MediaTypeDefinition", "{", "att", ":=", "l", ".", "Attribute", "(", ")", "\n", "mt", ",", "_", ":=", "att", ".", "Type", ".", "(", "*", "MediaTypeDefinition", ")", "\n", "return", "mt", "\n", "}" ]
// MediaType returns the media type of the linked attribute.
[ "MediaType", "returns", "the", "media", "type", "of", "the", "linked", "attribute", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1828-L1832
train
goadesign/goa
design/definitions.go
FullPath
func (r *RouteDefinition) FullPath() string { if r.IsAbsolute() { return httppath.Clean(r.Path[1:]) } var base string if r.Parent != nil && r.Parent.Parent != nil { base = r.Parent.Parent.FullPath() } joinedPath := path.Join(base, r.Path) if strings.HasSuffix(r.Path, "/") { //add slash removed by Join back again (it may be important for routing) joinedPath += "/" } return httppath.Clean(joinedPath) }
go
func (r *RouteDefinition) FullPath() string { if r.IsAbsolute() { return httppath.Clean(r.Path[1:]) } var base string if r.Parent != nil && r.Parent.Parent != nil { base = r.Parent.Parent.FullPath() } joinedPath := path.Join(base, r.Path) if strings.HasSuffix(r.Path, "/") { //add slash removed by Join back again (it may be important for routing) joinedPath += "/" } return httppath.Clean(joinedPath) }
[ "func", "(", "r", "*", "RouteDefinition", ")", "FullPath", "(", ")", "string", "{", "if", "r", ".", "IsAbsolute", "(", ")", "{", "return", "httppath", ".", "Clean", "(", "r", ".", "Path", "[", "1", ":", "]", ")", "\n", "}", "\n", "var", "base", "string", "\n", "if", "r", ".", "Parent", "!=", "nil", "&&", "r", ".", "Parent", ".", "Parent", "!=", "nil", "{", "base", "=", "r", ".", "Parent", ".", "Parent", ".", "FullPath", "(", ")", "\n", "}", "\n", "joinedPath", ":=", "path", ".", "Join", "(", "base", ",", "r", ".", "Path", ")", "\n", "if", "strings", ".", "HasSuffix", "(", "r", ".", "Path", ",", "\"/\"", ")", "{", "joinedPath", "+=", "\"/\"", "\n", "}", "\n", "return", "httppath", ".", "Clean", "(", "joinedPath", ")", "\n", "}" ]
// FullPath returns the action full path computed by concatenating the API and resource base paths // with the action specific path.
[ "FullPath", "returns", "the", "action", "full", "path", "computed", "by", "concatenating", "the", "API", "and", "resource", "base", "paths", "with", "the", "action", "specific", "path", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/definitions.go#L1861-L1877
train
goadesign/goa
middleware/log_request.go
from
func from(req *http.Request) string { if f := req.Header.Get("X-Forwarded-For"); f != "" { return f } f := req.RemoteAddr ip, _, err := net.SplitHostPort(f) if err != nil { return f } return ip }
go
func from(req *http.Request) string { if f := req.Header.Get("X-Forwarded-For"); f != "" { return f } f := req.RemoteAddr ip, _, err := net.SplitHostPort(f) if err != nil { return f } return ip }
[ "func", "from", "(", "req", "*", "http", ".", "Request", ")", "string", "{", "if", "f", ":=", "req", ".", "Header", ".", "Get", "(", "\"X-Forwarded-For\"", ")", ";", "f", "!=", "\"\"", "{", "return", "f", "\n", "}", "\n", "f", ":=", "req", ".", "RemoteAddr", "\n", "ip", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "f", "\n", "}", "\n", "return", "ip", "\n", "}" ]
// from makes a best effort to compute the request client IP.
[ "from", "makes", "a", "best", "effort", "to", "compute", "the", "request", "client", "IP", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/log_request.go#L121-L131
train
goadesign/goa
service.go
Use
func (service *Service) Use(m Middleware) { service.middleware = append(service.middleware, m) }
go
func (service *Service) Use(m Middleware) { service.middleware = append(service.middleware, m) }
[ "func", "(", "service", "*", "Service", ")", "Use", "(", "m", "Middleware", ")", "{", "service", ".", "middleware", "=", "append", "(", "service", ".", "middleware", ",", "m", ")", "\n", "}" ]
// Use adds a middleware to the service wide middleware chain. // goa comes with a set of commonly used middleware, see the middleware package. // Controller specific middleware should be mounted using the Controller struct Use method instead.
[ "Use", "adds", "a", "middleware", "to", "the", "service", "wide", "middleware", "chain", ".", "goa", "comes", "with", "a", "set", "of", "commonly", "used", "middleware", "see", "the", "middleware", "package", ".", "Controller", "specific", "middleware", "should", "be", "mounted", "using", "the", "Controller", "struct", "Use", "method", "instead", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L181-L183
train
goadesign/goa
service.go
WithLogger
func (service *Service) WithLogger(logger LogAdapter) { service.Context = WithLogger(service.Context, logger) }
go
func (service *Service) WithLogger(logger LogAdapter) { service.Context = WithLogger(service.Context, logger) }
[ "func", "(", "service", "*", "Service", ")", "WithLogger", "(", "logger", "LogAdapter", ")", "{", "service", ".", "Context", "=", "WithLogger", "(", "service", ".", "Context", ",", "logger", ")", "\n", "}" ]
// WithLogger sets the logger used internally by the service and by Log.
[ "WithLogger", "sets", "the", "logger", "used", "internally", "by", "the", "service", "and", "by", "Log", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L186-L188
train
goadesign/goa
service.go
LogInfo
func (service *Service) LogInfo(msg string, keyvals ...interface{}) { LogInfo(service.Context, msg, keyvals...) }
go
func (service *Service) LogInfo(msg string, keyvals ...interface{}) { LogInfo(service.Context, msg, keyvals...) }
[ "func", "(", "service", "*", "Service", ")", "LogInfo", "(", "msg", "string", ",", "keyvals", "...", "interface", "{", "}", ")", "{", "LogInfo", "(", "service", ".", "Context", ",", "msg", ",", "keyvals", "...", ")", "\n", "}" ]
// LogInfo logs the message and values at odd indeces using the keys at even indeces of the keyvals slice.
[ "LogInfo", "logs", "the", "message", "and", "values", "at", "odd", "indeces", "using", "the", "keys", "at", "even", "indeces", "of", "the", "keyvals", "slice", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L191-L193
train
goadesign/goa
service.go
LogError
func (service *Service) LogError(msg string, keyvals ...interface{}) { LogError(service.Context, msg, keyvals...) }
go
func (service *Service) LogError(msg string, keyvals ...interface{}) { LogError(service.Context, msg, keyvals...) }
[ "func", "(", "service", "*", "Service", ")", "LogError", "(", "msg", "string", ",", "keyvals", "...", "interface", "{", "}", ")", "{", "LogError", "(", "service", ".", "Context", ",", "msg", ",", "keyvals", "...", ")", "\n", "}" ]
// LogError logs the error and values at odd indeces using the keys at even indeces of the keyvals slice.
[ "LogError", "logs", "the", "error", "and", "values", "at", "odd", "indeces", "using", "the", "keys", "at", "even", "indeces", "of", "the", "keyvals", "slice", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L196-L198
train
goadesign/goa
service.go
Serve
func (service *Service) Serve(l net.Listener) error { return service.Server.Serve(l) }
go
func (service *Service) Serve(l net.Listener) error { return service.Server.Serve(l) }
[ "func", "(", "service", "*", "Service", ")", "Serve", "(", "l", "net", ".", "Listener", ")", "error", "{", "return", "service", ".", "Server", ".", "Serve", "(", "l", ")", "\n", "}" ]
// Serve accepts incoming HTTP connections on the listener l, invoking the service mux handler for each.
[ "Serve", "accepts", "incoming", "HTTP", "connections", "on", "the", "listener", "l", "invoking", "the", "service", "mux", "handler", "for", "each", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L215-L217
train
goadesign/goa
service.go
NewController
func (service *Service) NewController(name string) *Controller { return &Controller{ Name: name, Service: service, Context: context.WithValue(service.Context, ctrlKey, name), MaxRequestBodyLength: 1073741824, // 1 GB FileSystem: func(dir string) http.FileSystem { return http.Dir(dir) }, } }
go
func (service *Service) NewController(name string) *Controller { return &Controller{ Name: name, Service: service, Context: context.WithValue(service.Context, ctrlKey, name), MaxRequestBodyLength: 1073741824, // 1 GB FileSystem: func(dir string) http.FileSystem { return http.Dir(dir) }, } }
[ "func", "(", "service", "*", "Service", ")", "NewController", "(", "name", "string", ")", "*", "Controller", "{", "return", "&", "Controller", "{", "Name", ":", "name", ",", "Service", ":", "service", ",", "Context", ":", "context", ".", "WithValue", "(", "service", ".", "Context", ",", "ctrlKey", ",", "name", ")", ",", "MaxRequestBodyLength", ":", "1073741824", ",", "FileSystem", ":", "func", "(", "dir", "string", ")", "http", ".", "FileSystem", "{", "return", "http", ".", "Dir", "(", "dir", ")", "\n", "}", ",", "}", "\n", "}" ]
// NewController returns a controller for the given resource. This method is mainly intended for // use by the generated code. User code shouldn't have to call it directly.
[ "NewController", "returns", "a", "controller", "for", "the", "given", "resource", ".", "This", "method", "is", "mainly", "intended", "for", "use", "by", "the", "generated", "code", ".", "User", "code", "shouldn", "t", "have", "to", "call", "it", "directly", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L221-L231
train
goadesign/goa
service.go
Send
func (service *Service) Send(ctx context.Context, code int, body interface{}) error { r := ContextResponse(ctx) if r == nil { return fmt.Errorf("no response data in context") } r.WriteHeader(code) return service.EncodeResponse(ctx, body) }
go
func (service *Service) Send(ctx context.Context, code int, body interface{}) error { r := ContextResponse(ctx) if r == nil { return fmt.Errorf("no response data in context") } r.WriteHeader(code) return service.EncodeResponse(ctx, body) }
[ "func", "(", "service", "*", "Service", ")", "Send", "(", "ctx", "context", ".", "Context", ",", "code", "int", ",", "body", "interface", "{", "}", ")", "error", "{", "r", ":=", "ContextResponse", "(", "ctx", ")", "\n", "if", "r", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"no response data in context\"", ")", "\n", "}", "\n", "r", ".", "WriteHeader", "(", "code", ")", "\n", "return", "service", ".", "EncodeResponse", "(", "ctx", ",", "body", ")", "\n", "}" ]
// Send serializes the given body matching the request Accept header against the service // encoders. It uses the default service encoder if no match is found.
[ "Send", "serializes", "the", "given", "body", "matching", "the", "request", "Accept", "header", "against", "the", "service", "encoders", ".", "It", "uses", "the", "default", "service", "encoder", "if", "no", "match", "is", "found", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L235-L242
train
goadesign/goa
service.go
ServeFiles
func (service *Service) ServeFiles(path, filename string) error { ctrl := service.NewController("FileServer") return ctrl.ServeFiles(path, filename) }
go
func (service *Service) ServeFiles(path, filename string) error { ctrl := service.NewController("FileServer") return ctrl.ServeFiles(path, filename) }
[ "func", "(", "service", "*", "Service", ")", "ServeFiles", "(", "path", ",", "filename", "string", ")", "error", "{", "ctrl", ":=", "service", ".", "NewController", "(", "\"FileServer\"", ")", "\n", "return", "ctrl", ".", "ServeFiles", "(", "path", ",", "filename", ")", "\n", "}" ]
// ServeFiles create a "FileServer" controller and calls ServerFiles on it.
[ "ServeFiles", "create", "a", "FileServer", "controller", "and", "calls", "ServerFiles", "on", "it", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L245-L248
train
goadesign/goa
service.go
DecodeRequest
func (service *Service) DecodeRequest(req *http.Request, v interface{}) error { body, contentType := req.Body, req.Header.Get("Content-Type") defer body.Close() if err := service.Decoder.Decode(v, body, contentType); err != nil { return fmt.Errorf("failed to decode request body with content type %#v: %s", contentType, err) } return nil }
go
func (service *Service) DecodeRequest(req *http.Request, v interface{}) error { body, contentType := req.Body, req.Header.Get("Content-Type") defer body.Close() if err := service.Decoder.Decode(v, body, contentType); err != nil { return fmt.Errorf("failed to decode request body with content type %#v: %s", contentType, err) } return nil }
[ "func", "(", "service", "*", "Service", ")", "DecodeRequest", "(", "req", "*", "http", ".", "Request", ",", "v", "interface", "{", "}", ")", "error", "{", "body", ",", "contentType", ":=", "req", ".", "Body", ",", "req", ".", "Header", ".", "Get", "(", "\"Content-Type\"", ")", "\n", "defer", "body", ".", "Close", "(", ")", "\n", "if", "err", ":=", "service", ".", "Decoder", ".", "Decode", "(", "v", ",", "body", ",", "contentType", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to decode request body with content type %#v: %s\"", ",", "contentType", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DecodeRequest uses the HTTP decoder to unmarshal the request body into the provided value based // on the request Content-Type header.
[ "DecodeRequest", "uses", "the", "HTTP", "decoder", "to", "unmarshal", "the", "request", "body", "into", "the", "provided", "value", "based", "on", "the", "request", "Content", "-", "Type", "header", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L252-L261
train
goadesign/goa
service.go
EncodeResponse
func (service *Service) EncodeResponse(ctx context.Context, v interface{}) error { accept := ContextRequest(ctx).Header.Get("Accept") return service.Encoder.Encode(v, ContextResponse(ctx), accept) }
go
func (service *Service) EncodeResponse(ctx context.Context, v interface{}) error { accept := ContextRequest(ctx).Header.Get("Accept") return service.Encoder.Encode(v, ContextResponse(ctx), accept) }
[ "func", "(", "service", "*", "Service", ")", "EncodeResponse", "(", "ctx", "context", ".", "Context", ",", "v", "interface", "{", "}", ")", "error", "{", "accept", ":=", "ContextRequest", "(", "ctx", ")", ".", "Header", ".", "Get", "(", "\"Accept\"", ")", "\n", "return", "service", ".", "Encoder", ".", "Encode", "(", "v", ",", "ContextResponse", "(", "ctx", ")", ",", "accept", ")", "\n", "}" ]
// EncodeResponse uses the HTTP encoder to marshal and write the response body based on the request // Accept header.
[ "EncodeResponse", "uses", "the", "HTTP", "encoder", "to", "marshal", "and", "write", "the", "response", "body", "based", "on", "the", "request", "Accept", "header", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L265-L268
train
goadesign/goa
service.go
ServeFiles
func (ctrl *Controller) ServeFiles(path, filename string) error { if strings.Contains(path, ":") { return fmt.Errorf("path may only include wildcards that match the entire end of the URL (e.g. *filepath)") } LogInfo(ctrl.Context, "mount file", "name", filename, "route", fmt.Sprintf("GET %s", path)) handler := func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if !ContextResponse(ctx).Written() { return ctrl.FileHandler(path, filename)(ctx, rw, req) } return nil } ctrl.Service.Mux.Handle("GET", path, ctrl.MuxHandler("serve", handler, nil)) return nil }
go
func (ctrl *Controller) ServeFiles(path, filename string) error { if strings.Contains(path, ":") { return fmt.Errorf("path may only include wildcards that match the entire end of the URL (e.g. *filepath)") } LogInfo(ctrl.Context, "mount file", "name", filename, "route", fmt.Sprintf("GET %s", path)) handler := func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if !ContextResponse(ctx).Written() { return ctrl.FileHandler(path, filename)(ctx, rw, req) } return nil } ctrl.Service.Mux.Handle("GET", path, ctrl.MuxHandler("serve", handler, nil)) return nil }
[ "func", "(", "ctrl", "*", "Controller", ")", "ServeFiles", "(", "path", ",", "filename", "string", ")", "error", "{", "if", "strings", ".", "Contains", "(", "path", ",", "\":\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"path may only include wildcards that match the entire end of the URL (e.g. *filepath)\"", ")", "\n", "}", "\n", "LogInfo", "(", "ctrl", ".", "Context", ",", "\"mount file\"", ",", "\"name\"", ",", "filename", ",", "\"route\"", ",", "fmt", ".", "Sprintf", "(", "\"GET %s\"", ",", "path", ")", ")", "\n", "handler", ":=", "func", "(", "ctx", "context", ".", "Context", ",", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "error", "{", "if", "!", "ContextResponse", "(", "ctx", ")", ".", "Written", "(", ")", "{", "return", "ctrl", ".", "FileHandler", "(", "path", ",", "filename", ")", "(", "ctx", ",", "rw", ",", "req", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "ctrl", ".", "Service", ".", "Mux", ".", "Handle", "(", "\"GET\"", ",", "path", ",", "ctrl", ".", "MuxHandler", "(", "\"serve\"", ",", "handler", ",", "nil", ")", ")", "\n", "return", "nil", "\n", "}" ]
// ServeFiles replies to the request with the contents of the named file or directory. See // FileHandler for details.
[ "ServeFiles", "replies", "to", "the", "request", "with", "the", "contents", "of", "the", "named", "file", "or", "directory", ".", "See", "FileHandler", "for", "details", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L272-L285
train
goadesign/goa
service.go
Use
func (ctrl *Controller) Use(m Middleware) { ctrl.middleware = append(ctrl.middleware, m) }
go
func (ctrl *Controller) Use(m Middleware) { ctrl.middleware = append(ctrl.middleware, m) }
[ "func", "(", "ctrl", "*", "Controller", ")", "Use", "(", "m", "Middleware", ")", "{", "ctrl", ".", "middleware", "=", "append", "(", "ctrl", ".", "middleware", ",", "m", ")", "\n", "}" ]
// Use adds a middleware to the controller. // Service-wide middleware should be added via the Service Use method instead.
[ "Use", "adds", "a", "middleware", "to", "the", "controller", ".", "Service", "-", "wide", "middleware", "should", "be", "added", "via", "the", "Service", "Use", "method", "instead", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/service.go#L289-L291
train
goadesign/goa
goagen/gen_controller/generator.go
NewGenerator
func NewGenerator(options ...Option) *Generator { g := &Generator{} for _, option := range options { option(g) } return g }
go
func NewGenerator(options ...Option) *Generator { g := &Generator{} for _, option := range options { option(g) } return g }
[ "func", "NewGenerator", "(", "options", "...", "Option", ")", "*", "Generator", "{", "g", ":=", "&", "Generator", "{", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "g", ")", "\n", "}", "\n", "return", "g", "\n", "}" ]
//NewGenerator returns an initialized instance of a JavaScript Client Generator
[ "NewGenerator", "returns", "an", "initialized", "instance", "of", "a", "JavaScript", "Client", "Generator" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_controller/generator.go#L18-L26
train
goadesign/goa
goagen/gen_controller/generator.go
Generate
func (g *Generator) Generate() (_ []string, err error) { if g.API == nil { return nil, fmt.Errorf("missing API definition, make sure design is properly initialized") } go utils.Catch(nil, func() { g.Cleanup() }) defer func() { if err != nil { g.Cleanup() } }() if g.AppPkg == "" { g.AppPkg = "app" } g.smartenPkg() elems := strings.Split(g.AppPkg, "/") pkgName := elems[len(elems)-1] codegen.Reserved[pkgName] = true err = g.API.IterateResources(func(r *design.ResourceDefinition) error { var ( filename string err error ) if g.Resource == "" || g.Resource == r.Name { filename, err = genmain.GenerateController(g.Force, g.Regen, g.AppPkg, g.OutDir, g.Pkg, r.Name, r) } if err != nil { return err } g.genfiles = append(g.genfiles, filename) return nil }) if err != nil { return nil, err } return g.genfiles, err }
go
func (g *Generator) Generate() (_ []string, err error) { if g.API == nil { return nil, fmt.Errorf("missing API definition, make sure design is properly initialized") } go utils.Catch(nil, func() { g.Cleanup() }) defer func() { if err != nil { g.Cleanup() } }() if g.AppPkg == "" { g.AppPkg = "app" } g.smartenPkg() elems := strings.Split(g.AppPkg, "/") pkgName := elems[len(elems)-1] codegen.Reserved[pkgName] = true err = g.API.IterateResources(func(r *design.ResourceDefinition) error { var ( filename string err error ) if g.Resource == "" || g.Resource == r.Name { filename, err = genmain.GenerateController(g.Force, g.Regen, g.AppPkg, g.OutDir, g.Pkg, r.Name, r) } if err != nil { return err } g.genfiles = append(g.genfiles, filename) return nil }) if err != nil { return nil, err } return g.genfiles, err }
[ "func", "(", "g", "*", "Generator", ")", "Generate", "(", ")", "(", "_", "[", "]", "string", ",", "err", "error", ")", "{", "if", "g", ".", "API", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"missing API definition, make sure design is properly initialized\"", ")", "\n", "}", "\n", "go", "utils", ".", "Catch", "(", "nil", ",", "func", "(", ")", "{", "g", ".", "Cleanup", "(", ")", "}", ")", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "g", ".", "Cleanup", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "g", ".", "AppPkg", "==", "\"\"", "{", "g", ".", "AppPkg", "=", "\"app\"", "\n", "}", "\n", "g", ".", "smartenPkg", "(", ")", "\n", "elems", ":=", "strings", ".", "Split", "(", "g", ".", "AppPkg", ",", "\"/\"", ")", "\n", "pkgName", ":=", "elems", "[", "len", "(", "elems", ")", "-", "1", "]", "\n", "codegen", ".", "Reserved", "[", "pkgName", "]", "=", "true", "\n", "err", "=", "g", ".", "API", ".", "IterateResources", "(", "func", "(", "r", "*", "design", ".", "ResourceDefinition", ")", "error", "{", "var", "(", "filename", "string", "\n", "err", "error", "\n", ")", "\n", "if", "g", ".", "Resource", "==", "\"\"", "||", "g", ".", "Resource", "==", "r", ".", "Name", "{", "filename", ",", "err", "=", "genmain", ".", "GenerateController", "(", "g", ".", "Force", ",", "g", ".", "Regen", ",", "g", ".", "AppPkg", ",", "g", ".", "OutDir", ",", "g", ".", "Pkg", ",", "r", ".", "Name", ",", "r", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "g", ".", "genfiles", "=", "append", "(", "g", ".", "genfiles", ",", "filename", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "g", ".", "genfiles", ",", "err", "\n", "}" ]
// Generate produces the skeleton controller service factory.
[ "Generate", "produces", "the", "skeleton", "controller", "service", "factory", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_controller/generator.go#L70-L112
train
goadesign/goa
goagen/gen_controller/generator.go
Cleanup
func (g *Generator) Cleanup() { for _, f := range g.genfiles { os.Remove(f) } g.genfiles = nil }
go
func (g *Generator) Cleanup() { for _, f := range g.genfiles { os.Remove(f) } g.genfiles = nil }
[ "func", "(", "g", "*", "Generator", ")", "Cleanup", "(", ")", "{", "for", "_", ",", "f", ":=", "range", "g", ".", "genfiles", "{", "os", ".", "Remove", "(", "f", ")", "\n", "}", "\n", "g", ".", "genfiles", "=", "nil", "\n", "}" ]
// Cleanup removes all the files generated by this generator during the last invokation of Generate.
[ "Cleanup", "removes", "all", "the", "files", "generated", "by", "this", "generator", "during", "the", "last", "invokation", "of", "Generate", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_controller/generator.go#L139-L144
train
goadesign/goa
context.go
WithAction
func WithAction(ctx context.Context, action string) context.Context { return context.WithValue(ctx, actionKey, action) }
go
func WithAction(ctx context.Context, action string) context.Context { return context.WithValue(ctx, actionKey, action) }
[ "func", "WithAction", "(", "ctx", "context", ".", "Context", ",", "action", "string", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "actionKey", ",", "action", ")", "\n", "}" ]
// WithAction creates a context with the given action name.
[ "WithAction", "creates", "a", "context", "with", "the", "given", "action", "name", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L70-L72
train
goadesign/goa
context.go
WithLogger
func WithLogger(ctx context.Context, logger LogAdapter) context.Context { return context.WithValue(ctx, logKey, logger) }
go
func WithLogger(ctx context.Context, logger LogAdapter) context.Context { return context.WithValue(ctx, logKey, logger) }
[ "func", "WithLogger", "(", "ctx", "context", ".", "Context", ",", "logger", "LogAdapter", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "logKey", ",", "logger", ")", "\n", "}" ]
// WithLogger sets the request context logger and returns the resulting new context.
[ "WithLogger", "sets", "the", "request", "context", "logger", "and", "returns", "the", "resulting", "new", "context", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L75-L77
train
goadesign/goa
context.go
WithError
func WithError(ctx context.Context, err error) context.Context { return context.WithValue(ctx, errKey, err) }
go
func WithError(ctx context.Context, err error) context.Context { return context.WithValue(ctx, errKey, err) }
[ "func", "WithError", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "errKey", ",", "err", ")", "\n", "}" ]
// WithError creates a context with the given error.
[ "WithError", "creates", "a", "context", "with", "the", "given", "error", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L91-L93
train
goadesign/goa
context.go
ContextController
func ContextController(ctx context.Context) string { if c := ctx.Value(ctrlKey); c != nil { return c.(string) } return "<unknown>" }
go
func ContextController(ctx context.Context) string { if c := ctx.Value(ctrlKey); c != nil { return c.(string) } return "<unknown>" }
[ "func", "ContextController", "(", "ctx", "context", ".", "Context", ")", "string", "{", "if", "c", ":=", "ctx", ".", "Value", "(", "ctrlKey", ")", ";", "c", "!=", "nil", "{", "return", "c", ".", "(", "string", ")", "\n", "}", "\n", "return", "\"<unknown>\"", "\n", "}" ]
// ContextController extracts the controller name from the given context.
[ "ContextController", "extracts", "the", "controller", "name", "from", "the", "given", "context", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L96-L101
train
goadesign/goa
context.go
ContextAction
func ContextAction(ctx context.Context) string { if a := ctx.Value(actionKey); a != nil { return a.(string) } return "<unknown>" }
go
func ContextAction(ctx context.Context) string { if a := ctx.Value(actionKey); a != nil { return a.(string) } return "<unknown>" }
[ "func", "ContextAction", "(", "ctx", "context", ".", "Context", ")", "string", "{", "if", "a", ":=", "ctx", ".", "Value", "(", "actionKey", ")", ";", "a", "!=", "nil", "{", "return", "a", ".", "(", "string", ")", "\n", "}", "\n", "return", "\"<unknown>\"", "\n", "}" ]
// ContextAction extracts the action name from the given context.
[ "ContextAction", "extracts", "the", "action", "name", "from", "the", "given", "context", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L104-L109
train
goadesign/goa
context.go
ContextRequest
func ContextRequest(ctx context.Context) *RequestData { if r := ctx.Value(reqKey); r != nil { return r.(*RequestData) } return nil }
go
func ContextRequest(ctx context.Context) *RequestData { if r := ctx.Value(reqKey); r != nil { return r.(*RequestData) } return nil }
[ "func", "ContextRequest", "(", "ctx", "context", ".", "Context", ")", "*", "RequestData", "{", "if", "r", ":=", "ctx", ".", "Value", "(", "reqKey", ")", ";", "r", "!=", "nil", "{", "return", "r", ".", "(", "*", "RequestData", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ContextRequest extracts the request data from the given context.
[ "ContextRequest", "extracts", "the", "request", "data", "from", "the", "given", "context", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L112-L117
train
goadesign/goa
context.go
ContextResponse
func ContextResponse(ctx context.Context) *ResponseData { if r := ctx.Value(respKey); r != nil { return r.(*ResponseData) } return nil }
go
func ContextResponse(ctx context.Context) *ResponseData { if r := ctx.Value(respKey); r != nil { return r.(*ResponseData) } return nil }
[ "func", "ContextResponse", "(", "ctx", "context", ".", "Context", ")", "*", "ResponseData", "{", "if", "r", ":=", "ctx", ".", "Value", "(", "respKey", ")", ";", "r", "!=", "nil", "{", "return", "r", ".", "(", "*", "ResponseData", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ContextResponse extracts the response data from the given context.
[ "ContextResponse", "extracts", "the", "response", "data", "from", "the", "given", "context", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L120-L125
train
goadesign/goa
context.go
ContextLogger
func ContextLogger(ctx context.Context) LogAdapter { if v := ctx.Value(logKey); v != nil { return v.(LogAdapter) } return nil }
go
func ContextLogger(ctx context.Context) LogAdapter { if v := ctx.Value(logKey); v != nil { return v.(LogAdapter) } return nil }
[ "func", "ContextLogger", "(", "ctx", "context", ".", "Context", ")", "LogAdapter", "{", "if", "v", ":=", "ctx", ".", "Value", "(", "logKey", ")", ";", "v", "!=", "nil", "{", "return", "v", ".", "(", "LogAdapter", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ContextLogger extracts the logger from the given context.
[ "ContextLogger", "extracts", "the", "logger", "from", "the", "given", "context", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L128-L133
train
goadesign/goa
context.go
ContextError
func ContextError(ctx context.Context) error { if err := ctx.Value(errKey); err != nil { return err.(error) } return nil }
go
func ContextError(ctx context.Context) error { if err := ctx.Value(errKey); err != nil { return err.(error) } return nil }
[ "func", "ContextError", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "err", ":=", "ctx", ".", "Value", "(", "errKey", ")", ";", "err", "!=", "nil", "{", "return", "err", ".", "(", "error", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ContextError extracts the error from the given context.
[ "ContextError", "extracts", "the", "error", "from", "the", "given", "context", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L136-L141
train
goadesign/goa
context.go
SwitchWriter
func (r *ResponseData) SwitchWriter(rw http.ResponseWriter) http.ResponseWriter { rwo := r.ResponseWriter r.ResponseWriter = rw return rwo }
go
func (r *ResponseData) SwitchWriter(rw http.ResponseWriter) http.ResponseWriter { rwo := r.ResponseWriter r.ResponseWriter = rw return rwo }
[ "func", "(", "r", "*", "ResponseData", ")", "SwitchWriter", "(", "rw", "http", ".", "ResponseWriter", ")", "http", ".", "ResponseWriter", "{", "rwo", ":=", "r", ".", "ResponseWriter", "\n", "r", ".", "ResponseWriter", "=", "rw", "\n", "return", "rwo", "\n", "}" ]
// SwitchWriter overrides the underlying response writer. It returns the response // writer that was previously set.
[ "SwitchWriter", "overrides", "the", "underlying", "response", "writer", ".", "It", "returns", "the", "response", "writer", "that", "was", "previously", "set", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L145-L149
train
goadesign/goa
context.go
WriteHeader
func (r *ResponseData) WriteHeader(status int) { go IncrCounter([]string{"goa", "response", strconv.Itoa(status)}, 1.0) r.Status = status r.ResponseWriter.WriteHeader(status) }
go
func (r *ResponseData) WriteHeader(status int) { go IncrCounter([]string{"goa", "response", strconv.Itoa(status)}, 1.0) r.Status = status r.ResponseWriter.WriteHeader(status) }
[ "func", "(", "r", "*", "ResponseData", ")", "WriteHeader", "(", "status", "int", ")", "{", "go", "IncrCounter", "(", "[", "]", "string", "{", "\"goa\"", ",", "\"response\"", ",", "strconv", ".", "Itoa", "(", "status", ")", "}", ",", "1.0", ")", "\n", "r", ".", "Status", "=", "status", "\n", "r", ".", "ResponseWriter", ".", "WriteHeader", "(", "status", ")", "\n", "}" ]
// WriteHeader records the response status code and calls the underlying writer.
[ "WriteHeader", "records", "the", "response", "status", "code", "and", "calls", "the", "underlying", "writer", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L157-L161
train
goadesign/goa
context.go
Write
func (r *ResponseData) Write(b []byte) (int, error) { if !r.Written() { r.WriteHeader(http.StatusOK) } r.Length += len(b) return r.ResponseWriter.Write(b) }
go
func (r *ResponseData) Write(b []byte) (int, error) { if !r.Written() { r.WriteHeader(http.StatusOK) } r.Length += len(b) return r.ResponseWriter.Write(b) }
[ "func", "(", "r", "*", "ResponseData", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "!", "r", ".", "Written", "(", ")", "{", "r", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}", "\n", "r", ".", "Length", "+=", "len", "(", "b", ")", "\n", "return", "r", ".", "ResponseWriter", ".", "Write", "(", "b", ")", "\n", "}" ]
// Write records the amount of data written and calls the underlying writer.
[ "Write", "records", "the", "amount", "of", "data", "written", "and", "calls", "the", "underlying", "writer", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/context.go#L164-L170
train
goadesign/goa
goagen/gen_main/generator.go
funcMap
func funcMap(appPkg string, actionImpls map[string]string) template.FuncMap { return template.FuncMap{ "tempvar": tempvar, "okResp": okResp, "targetPkg": func() string { return appPkg }, "actionBody": func(name string) string { body, ok := actionImpls[name] if !ok { return defaultActionBody } return body }, "printResp": func(name string) bool { _, ok := actionImpls[name] return !ok }, } }
go
func funcMap(appPkg string, actionImpls map[string]string) template.FuncMap { return template.FuncMap{ "tempvar": tempvar, "okResp": okResp, "targetPkg": func() string { return appPkg }, "actionBody": func(name string) string { body, ok := actionImpls[name] if !ok { return defaultActionBody } return body }, "printResp": func(name string) bool { _, ok := actionImpls[name] return !ok }, } }
[ "func", "funcMap", "(", "appPkg", "string", ",", "actionImpls", "map", "[", "string", "]", "string", ")", "template", ".", "FuncMap", "{", "return", "template", ".", "FuncMap", "{", "\"tempvar\"", ":", "tempvar", ",", "\"okResp\"", ":", "okResp", ",", "\"targetPkg\"", ":", "func", "(", ")", "string", "{", "return", "appPkg", "}", ",", "\"actionBody\"", ":", "func", "(", "name", "string", ")", "string", "{", "body", ",", "ok", ":=", "actionImpls", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "defaultActionBody", "\n", "}", "\n", "return", "body", "\n", "}", ",", "\"printResp\"", ":", "func", "(", "name", "string", ")", "bool", "{", "_", ",", "ok", ":=", "actionImpls", "[", "name", "]", "\n", "return", "!", "ok", "\n", "}", ",", "}", "\n", "}" ]
// funcMap creates the funcMap used to render the controller code.
[ "funcMap", "creates", "the", "funcMap", "used", "to", "render", "the", "controller", "code", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_main/generator.go#L380-L397
train
goadesign/goa
middleware/gzip/middleware.go
AddContentTypes
func AddContentTypes(types ...string) Option { return func(c *options) error { dst := make([]string, len(c.contentTypes)+len(types)) copy(dst, c.contentTypes) copy(dst[len(c.contentTypes):], types) c.contentTypes = dst return nil } }
go
func AddContentTypes(types ...string) Option { return func(c *options) error { dst := make([]string, len(c.contentTypes)+len(types)) copy(dst, c.contentTypes) copy(dst[len(c.contentTypes):], types) c.contentTypes = dst return nil } }
[ "func", "AddContentTypes", "(", "types", "...", "string", ")", "Option", "{", "return", "func", "(", "c", "*", "options", ")", "error", "{", "dst", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "c", ".", "contentTypes", ")", "+", "len", "(", "types", ")", ")", "\n", "copy", "(", "dst", ",", "c", ".", "contentTypes", ")", "\n", "copy", "(", "dst", "[", "len", "(", "c", ".", "contentTypes", ")", ":", "]", ",", "types", ")", "\n", "c", ".", "contentTypes", "=", "dst", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// AddContentTypes allows to specify specific content types to encode. // Adds to previous content types.
[ "AddContentTypes", "allows", "to", "specify", "specific", "content", "types", "to", "encode", ".", "Adds", "to", "previous", "content", "types", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/gzip/middleware.go#L168-L176
train
goadesign/goa
middleware/gzip/middleware.go
AddStatusCodes
func AddStatusCodes(codes ...int) Option { return func(c *options) error { dst := make(map[int]struct{}, len(c.statusCodes)+len(codes)) for code := range c.statusCodes { dst[code] = struct{}{} } for _, code := range codes { c.statusCodes[code] = struct{}{} } return nil } }
go
func AddStatusCodes(codes ...int) Option { return func(c *options) error { dst := make(map[int]struct{}, len(c.statusCodes)+len(codes)) for code := range c.statusCodes { dst[code] = struct{}{} } for _, code := range codes { c.statusCodes[code] = struct{}{} } return nil } }
[ "func", "AddStatusCodes", "(", "codes", "...", "int", ")", "Option", "{", "return", "func", "(", "c", "*", "options", ")", "error", "{", "dst", ":=", "make", "(", "map", "[", "int", "]", "struct", "{", "}", ",", "len", "(", "c", ".", "statusCodes", ")", "+", "len", "(", "codes", ")", ")", "\n", "for", "code", ":=", "range", "c", ".", "statusCodes", "{", "dst", "[", "code", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "for", "_", ",", "code", ":=", "range", "codes", "{", "c", ".", "statusCodes", "[", "code", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// AddStatusCodes allows to specify specific content types to encode. // All content types that has the supplied prefixes are compressed.
[ "AddStatusCodes", "allows", "to", "specify", "specific", "content", "types", "to", "encode", ".", "All", "content", "types", "that", "has", "the", "supplied", "prefixes", "are", "compressed", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/gzip/middleware.go#L194-L205
train
goadesign/goa
middleware/gzip/middleware.go
MinSize
func MinSize(n int) Option { return func(c *options) error { if n <= 0 { c.minSize = 0 return nil } c.minSize = n return nil } }
go
func MinSize(n int) Option { return func(c *options) error { if n <= 0 { c.minSize = 0 return nil } c.minSize = n return nil } }
[ "func", "MinSize", "(", "n", "int", ")", "Option", "{", "return", "func", "(", "c", "*", "options", ")", "error", "{", "if", "n", "<=", "0", "{", "c", ".", "minSize", "=", "0", "\n", "return", "nil", "\n", "}", "\n", "c", ".", "minSize", "=", "n", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MinSize will set a minimum size for compression.
[ "MinSize", "will", "set", "a", "minimum", "size", "for", "compression", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/gzip/middleware.go#L225-L234
train
goadesign/goa
middleware/gzip/middleware.go
IgnoreRange
func IgnoreRange(b bool) Option { return func(c *options) error { c.ignoreRange = b return nil } }
go
func IgnoreRange(b bool) Option { return func(c *options) error { c.ignoreRange = b return nil } }
[ "func", "IgnoreRange", "(", "b", "bool", ")", "Option", "{", "return", "func", "(", "c", "*", "options", ")", "error", "{", "c", ".", "ignoreRange", "=", "b", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// IgnoreRange will set make the compressor ignore Range requests. // Range requests are incompatible with compressed content, // so if this is set to true "Range" headers will be ignored. // If set to false, compression is disabled for all requests with Range header.
[ "IgnoreRange", "will", "set", "make", "the", "compressor", "ignore", "Range", "requests", ".", "Range", "requests", "are", "incompatible", "with", "compressed", "content", "so", "if", "this", "is", "set", "to", "true", "Range", "headers", "will", "be", "ignored", ".", "If", "set", "to", "false", "compression", "is", "disabled", "for", "all", "requests", "with", "Range", "header", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/gzip/middleware.go#L240-L245
train
goadesign/goa
middleware/gzip/middleware.go
Middleware
func Middleware(level int, o ...Option) goa.Middleware { opts := options{ ignoreRange: true, minSize: 256, contentTypes: defaultContentTypes, } opts.statusCodes = make(map[int]struct{}, len(defaultStatusCodes)) for _, v := range defaultStatusCodes { opts.statusCodes[v] = struct{}{} } for _, opt := range o { err := opt(&opts) if err != nil { panic(err) } } gzipPool := sync.Pool{ New: func() interface{} { gz, err := gzip.NewWriterLevel(ioutil.Discard, level) if err != nil { panic(err) } return gz }, } return func(h goa.Handler) goa.Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) (err error) { // Skip compression if the client doesn't accept gzip encoding, is // requesting a WebSocket or the data is already compressed. if !strings.Contains(req.Header.Get(headerAcceptEncoding), encodingGzip) || len(req.Header.Get(headerSecWebSocketKey)) > 0 || rw.Header().Get(headerContentEncoding) == encodingGzip || (!opts.ignoreRange && req.Header.Get(headerRange) != "") { return h(ctx, rw, req) } // Set the appropriate gzip headers. resp := goa.ContextResponse(ctx) // Get the original http.ResponseWriter w := resp.SwitchWriter(nil) // Wrap the original http.ResponseWriter with our gzipResponseWriter grw := &gzipResponseWriter{ ResponseWriter: w, pool: &gzipPool, statusCode: http.StatusOK, o: opts, } // Set the new http.ResponseWriter resp.SwitchWriter(grw) // We cannot do ranges, if possibly gzipped responses. req.Header.Del("Range") // Call the next handler supplying the gzipResponseWriter instead of // the original. err = h(ctx, rw, req) if err != nil { return } // Check for uncompressed data if grw.buf.Len() > 0 { w.Header().Set(headerContentLength, strconv.Itoa(grw.buf.Len())) w.WriteHeader(grw.statusCode) _, err = w.Write(grw.buf.Bytes()) return } // Flush compressor. if grw.gzw != nil { if err = grw.gzw.Close(); err != nil { return } gzipPool.Put(grw.gzw) return } // No writes, set status code. if grw.shouldCompress == nil { w.WriteHeader(grw.statusCode) } return } } }
go
func Middleware(level int, o ...Option) goa.Middleware { opts := options{ ignoreRange: true, minSize: 256, contentTypes: defaultContentTypes, } opts.statusCodes = make(map[int]struct{}, len(defaultStatusCodes)) for _, v := range defaultStatusCodes { opts.statusCodes[v] = struct{}{} } for _, opt := range o { err := opt(&opts) if err != nil { panic(err) } } gzipPool := sync.Pool{ New: func() interface{} { gz, err := gzip.NewWriterLevel(ioutil.Discard, level) if err != nil { panic(err) } return gz }, } return func(h goa.Handler) goa.Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) (err error) { // Skip compression if the client doesn't accept gzip encoding, is // requesting a WebSocket or the data is already compressed. if !strings.Contains(req.Header.Get(headerAcceptEncoding), encodingGzip) || len(req.Header.Get(headerSecWebSocketKey)) > 0 || rw.Header().Get(headerContentEncoding) == encodingGzip || (!opts.ignoreRange && req.Header.Get(headerRange) != "") { return h(ctx, rw, req) } // Set the appropriate gzip headers. resp := goa.ContextResponse(ctx) // Get the original http.ResponseWriter w := resp.SwitchWriter(nil) // Wrap the original http.ResponseWriter with our gzipResponseWriter grw := &gzipResponseWriter{ ResponseWriter: w, pool: &gzipPool, statusCode: http.StatusOK, o: opts, } // Set the new http.ResponseWriter resp.SwitchWriter(grw) // We cannot do ranges, if possibly gzipped responses. req.Header.Del("Range") // Call the next handler supplying the gzipResponseWriter instead of // the original. err = h(ctx, rw, req) if err != nil { return } // Check for uncompressed data if grw.buf.Len() > 0 { w.Header().Set(headerContentLength, strconv.Itoa(grw.buf.Len())) w.WriteHeader(grw.statusCode) _, err = w.Write(grw.buf.Bytes()) return } // Flush compressor. if grw.gzw != nil { if err = grw.gzw.Close(); err != nil { return } gzipPool.Put(grw.gzw) return } // No writes, set status code. if grw.shouldCompress == nil { w.WriteHeader(grw.statusCode) } return } } }
[ "func", "Middleware", "(", "level", "int", ",", "o", "...", "Option", ")", "goa", ".", "Middleware", "{", "opts", ":=", "options", "{", "ignoreRange", ":", "true", ",", "minSize", ":", "256", ",", "contentTypes", ":", "defaultContentTypes", ",", "}", "\n", "opts", ".", "statusCodes", "=", "make", "(", "map", "[", "int", "]", "struct", "{", "}", ",", "len", "(", "defaultStatusCodes", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "defaultStatusCodes", "{", "opts", ".", "statusCodes", "[", "v", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "for", "_", ",", "opt", ":=", "range", "o", "{", "err", ":=", "opt", "(", "&", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "gzipPool", ":=", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "gz", ",", "err", ":=", "gzip", ".", "NewWriterLevel", "(", "ioutil", ".", "Discard", ",", "level", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "gz", "\n", "}", ",", "}", "\n", "return", "func", "(", "h", "goa", ".", "Handler", ")", "goa", ".", "Handler", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "(", "err", "error", ")", "{", "if", "!", "strings", ".", "Contains", "(", "req", ".", "Header", ".", "Get", "(", "headerAcceptEncoding", ")", ",", "encodingGzip", ")", "||", "len", "(", "req", ".", "Header", ".", "Get", "(", "headerSecWebSocketKey", ")", ")", ">", "0", "||", "rw", ".", "Header", "(", ")", ".", "Get", "(", "headerContentEncoding", ")", "==", "encodingGzip", "||", "(", "!", "opts", ".", "ignoreRange", "&&", "req", ".", "Header", ".", "Get", "(", "headerRange", ")", "!=", "\"\"", ")", "{", "return", "h", "(", "ctx", ",", "rw", ",", "req", ")", "\n", "}", "\n", "resp", ":=", "goa", ".", "ContextResponse", "(", "ctx", ")", "\n", "w", ":=", "resp", ".", "SwitchWriter", "(", "nil", ")", "\n", "grw", ":=", "&", "gzipResponseWriter", "{", "ResponseWriter", ":", "w", ",", "pool", ":", "&", "gzipPool", ",", "statusCode", ":", "http", ".", "StatusOK", ",", "o", ":", "opts", ",", "}", "\n", "resp", ".", "SwitchWriter", "(", "grw", ")", "\n", "req", ".", "Header", ".", "Del", "(", "\"Range\"", ")", "\n", "err", "=", "h", "(", "ctx", ",", "rw", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "grw", ".", "buf", ".", "Len", "(", ")", ">", "0", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "headerContentLength", ",", "strconv", ".", "Itoa", "(", "grw", ".", "buf", ".", "Len", "(", ")", ")", ")", "\n", "w", ".", "WriteHeader", "(", "grw", ".", "statusCode", ")", "\n", "_", ",", "err", "=", "w", ".", "Write", "(", "grw", ".", "buf", ".", "Bytes", "(", ")", ")", "\n", "return", "\n", "}", "\n", "if", "grw", ".", "gzw", "!=", "nil", "{", "if", "err", "=", "grw", ".", "gzw", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "gzipPool", ".", "Put", "(", "grw", ".", "gzw", ")", "\n", "return", "\n", "}", "\n", "if", "grw", ".", "shouldCompress", "==", "nil", "{", "w", ".", "WriteHeader", "(", "grw", ".", "statusCode", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Middleware encodes the response using Gzip encoding and sets all the // appropriate headers. If the Content-Type is not set, it will be set by // calling http.DetectContentType on the data being written.
[ "Middleware", "encodes", "the", "response", "using", "Gzip", "encoding", "and", "sets", "all", "the", "appropriate", "headers", ".", "If", "the", "Content", "-", "Type", "is", "not", "set", "it", "will", "be", "set", "by", "calling", "http", ".", "DetectContentType", "on", "the", "data", "being", "written", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/gzip/middleware.go#L250-L336
train
goadesign/goa
middleware/gzip/middleware.go
shouldCompress
func (o options) shouldCompress(contentType string, statusCode int) bool { // If contentTypes is nil we handle all content types. if len(o.contentTypes) > 0 { ct := strings.ToLower(contentType) ct = strings.Split(ct, ";")[0] found := false for _, v := range o.contentTypes { if strings.HasPrefix(ct, v) { found = true break } } if !found { return false } } if len(o.statusCodes) > 0 { _, ok := o.statusCodes[statusCode] if !ok { return false } } return true }
go
func (o options) shouldCompress(contentType string, statusCode int) bool { // If contentTypes is nil we handle all content types. if len(o.contentTypes) > 0 { ct := strings.ToLower(contentType) ct = strings.Split(ct, ";")[0] found := false for _, v := range o.contentTypes { if strings.HasPrefix(ct, v) { found = true break } } if !found { return false } } if len(o.statusCodes) > 0 { _, ok := o.statusCodes[statusCode] if !ok { return false } } return true }
[ "func", "(", "o", "options", ")", "shouldCompress", "(", "contentType", "string", ",", "statusCode", "int", ")", "bool", "{", "if", "len", "(", "o", ".", "contentTypes", ")", ">", "0", "{", "ct", ":=", "strings", ".", "ToLower", "(", "contentType", ")", "\n", "ct", "=", "strings", ".", "Split", "(", "ct", ",", "\";\"", ")", "[", "0", "]", "\n", "found", ":=", "false", "\n", "for", "_", ",", "v", ":=", "range", "o", ".", "contentTypes", "{", "if", "strings", ".", "HasPrefix", "(", "ct", ",", "v", ")", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "o", ".", "statusCodes", ")", ">", "0", "{", "_", ",", "ok", ":=", "o", ".", "statusCodes", "[", "statusCode", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// returns true if we've been configured to compress the specific content type.
[ "returns", "true", "if", "we", "ve", "been", "configured", "to", "compress", "the", "specific", "content", "type", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/gzip/middleware.go#L339-L363
train
goadesign/goa
middleware/xray/transport.go
RoundTrip
func (t *xrayTransport) RoundTrip(req *http.Request) (*http.Response, error) { s := ContextSegment(req.Context()) if s == nil { return t.wrapped.RoundTrip(req) } sub := s.NewSubsegment(req.URL.Host) defer sub.Close() sub.RecordRequest(req, "remote") resp, err := t.wrapped.RoundTrip(req) if err != nil { sub.RecordError(err) } else { sub.RecordResponse(resp) } return resp, err }
go
func (t *xrayTransport) RoundTrip(req *http.Request) (*http.Response, error) { s := ContextSegment(req.Context()) if s == nil { return t.wrapped.RoundTrip(req) } sub := s.NewSubsegment(req.URL.Host) defer sub.Close() sub.RecordRequest(req, "remote") resp, err := t.wrapped.RoundTrip(req) if err != nil { sub.RecordError(err) } else { sub.RecordResponse(resp) } return resp, err }
[ "func", "(", "t", "*", "xrayTransport", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "s", ":=", "ContextSegment", "(", "req", ".", "Context", "(", ")", ")", "\n", "if", "s", "==", "nil", "{", "return", "t", ".", "wrapped", ".", "RoundTrip", "(", "req", ")", "\n", "}", "\n", "sub", ":=", "s", ".", "NewSubsegment", "(", "req", ".", "URL", ".", "Host", ")", "\n", "defer", "sub", ".", "Close", "(", ")", "\n", "sub", ".", "RecordRequest", "(", "req", ",", "\"remote\"", ")", "\n", "resp", ",", "err", ":=", "t", ".", "wrapped", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "sub", ".", "RecordError", "(", "err", ")", "\n", "}", "else", "{", "sub", ".", "RecordResponse", "(", "resp", ")", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}" ]
// RoundTrip wraps the original RoundTripper.RoundTrip to create xray tracing segments
[ "RoundTrip", "wraps", "the", "original", "RoundTripper", ".", "RoundTrip", "to", "create", "xray", "tracing", "segments" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/xray/transport.go#L26-L46
train
goadesign/goa
middleware.go
handlerToMiddleware
func handlerToMiddleware(m Handler) Middleware { return func(h Handler) Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := m(ctx, rw, req); err != nil { return err } return h(ctx, rw, req) } } }
go
func handlerToMiddleware(m Handler) Middleware { return func(h Handler) Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { if err := m(ctx, rw, req); err != nil { return err } return h(ctx, rw, req) } } }
[ "func", "handlerToMiddleware", "(", "m", "Handler", ")", "Middleware", "{", "return", "func", "(", "h", "Handler", ")", "Handler", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "error", "{", "if", "err", ":=", "m", "(", "ctx", ",", "rw", ",", "req", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "h", "(", "ctx", ",", "rw", ",", "req", ")", "\n", "}", "\n", "}", "\n", "}" ]
// handlerToMiddleware creates a middleware from a raw handler. // The middleware calls the handler and either breaks the middleware chain if the handler returns // an error by also returning the error or calls the next handler in the chain otherwise.
[ "handlerToMiddleware", "creates", "a", "middleware", "from", "a", "raw", "handler", ".", "The", "middleware", "calls", "the", "handler", "and", "either", "breaks", "the", "middleware", "chain", "if", "the", "handler", "returns", "an", "error", "by", "also", "returning", "the", "error", "or", "calls", "the", "next", "handler", "in", "the", "chain", "otherwise", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware.go#L59-L68
train
goadesign/goa
middleware.go
httpHandlerToMiddleware
func httpHandlerToMiddleware(m http.HandlerFunc) Middleware { return func(h Handler) Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { m.ServeHTTP(rw, req) return h(ctx, rw, req) } } }
go
func httpHandlerToMiddleware(m http.HandlerFunc) Middleware { return func(h Handler) Handler { return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { m.ServeHTTP(rw, req) return h(ctx, rw, req) } } }
[ "func", "httpHandlerToMiddleware", "(", "m", "http", ".", "HandlerFunc", ")", "Middleware", "{", "return", "func", "(", "h", "Handler", ")", "Handler", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "error", "{", "m", ".", "ServeHTTP", "(", "rw", ",", "req", ")", "\n", "return", "h", "(", "ctx", ",", "rw", ",", "req", ")", "\n", "}", "\n", "}", "\n", "}" ]
// httpHandlerToMiddleware creates a middleware from a http.HandlerFunc. // The middleware calls the ServerHTTP method exposed by the http handler and then calls the next // middleware in the chain.
[ "httpHandlerToMiddleware", "creates", "a", "middleware", "from", "a", "http", ".", "HandlerFunc", ".", "The", "middleware", "calls", "the", "ServerHTTP", "method", "exposed", "by", "the", "http", "handler", "and", "then", "calls", "the", "next", "middleware", "in", "the", "chain", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware.go#L73-L80
train
goadesign/goa
goagen/codegen/workspace.go
NewWorkspace
func NewWorkspace(prefix string) (*Workspace, error) { dir, err := ioutil.TempDir("", prefix) if err != nil { return nil, err } // create workspace layout os.MkdirAll(filepath.Join(dir, "src"), 0755) os.MkdirAll(filepath.Join(dir, "pkg"), 0755) os.MkdirAll(filepath.Join(dir, "bin"), 0755) // setup GOPATH gopath := envOr("GOPATH", build.Default.GOPATH) os.Setenv("GOPATH", fmt.Sprintf("%s%c%s", dir, os.PathListSeparator, gopath)) // we're done return &Workspace{Path: dir, gopath: gopath}, nil }
go
func NewWorkspace(prefix string) (*Workspace, error) { dir, err := ioutil.TempDir("", prefix) if err != nil { return nil, err } // create workspace layout os.MkdirAll(filepath.Join(dir, "src"), 0755) os.MkdirAll(filepath.Join(dir, "pkg"), 0755) os.MkdirAll(filepath.Join(dir, "bin"), 0755) // setup GOPATH gopath := envOr("GOPATH", build.Default.GOPATH) os.Setenv("GOPATH", fmt.Sprintf("%s%c%s", dir, os.PathListSeparator, gopath)) // we're done return &Workspace{Path: dir, gopath: gopath}, nil }
[ "func", "NewWorkspace", "(", "prefix", "string", ")", "(", "*", "Workspace", ",", "error", ")", "{", "dir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"\"", ",", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "os", ".", "MkdirAll", "(", "filepath", ".", "Join", "(", "dir", ",", "\"src\"", ")", ",", "0755", ")", "\n", "os", ".", "MkdirAll", "(", "filepath", ".", "Join", "(", "dir", ",", "\"pkg\"", ")", ",", "0755", ")", "\n", "os", ".", "MkdirAll", "(", "filepath", ".", "Join", "(", "dir", ",", "\"bin\"", ")", ",", "0755", ")", "\n", "gopath", ":=", "envOr", "(", "\"GOPATH\"", ",", "build", ".", "Default", ".", "GOPATH", ")", "\n", "os", ".", "Setenv", "(", "\"GOPATH\"", ",", "fmt", ".", "Sprintf", "(", "\"%s%c%s\"", ",", "dir", ",", "os", ".", "PathListSeparator", ",", "gopath", ")", ")", "\n", "return", "&", "Workspace", "{", "Path", ":", "dir", ",", "gopath", ":", "gopath", "}", ",", "nil", "\n", "}" ]
// NewWorkspace returns a newly created temporary Go workspace. // Use Delete to delete the corresponding temporary directory when done.
[ "NewWorkspace", "returns", "a", "newly", "created", "temporary", "Go", "workspace", ".", "Use", "Delete", "to", "delete", "the", "corresponding", "temporary", "directory", "when", "done", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L84-L100
train
goadesign/goa
goagen/codegen/workspace.go
WorkspaceFor
func WorkspaceFor(source string) (*Workspace, error) { gopaths := envOr("GOPATH", build.Default.GOPATH) // We use absolute paths so that in particular on Windows the case gets normalized sourcePath, err := filepath.Abs(source) if err != nil { sourcePath = source } if os.Getenv("GO111MODULE") != "on" { // GOPATH mode for _, gp := range filepath.SplitList(gopaths) { gopath, err := filepath.Abs(gp) if err != nil { gopath = gp } if filepath.HasPrefix(sourcePath, gopath) { return &Workspace{ gopath: gopaths, isModuleMode: false, Path: gopath, }, nil } } } if os.Getenv("GO111MODULE") != "off" { // Module mode root, _ := findModuleRoot(sourcePath, "", false) if root != "" { return &Workspace{ gopath: gopaths, isModuleMode: true, Path: root, }, nil } } return nil, fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, source, gopaths) }
go
func WorkspaceFor(source string) (*Workspace, error) { gopaths := envOr("GOPATH", build.Default.GOPATH) // We use absolute paths so that in particular on Windows the case gets normalized sourcePath, err := filepath.Abs(source) if err != nil { sourcePath = source } if os.Getenv("GO111MODULE") != "on" { // GOPATH mode for _, gp := range filepath.SplitList(gopaths) { gopath, err := filepath.Abs(gp) if err != nil { gopath = gp } if filepath.HasPrefix(sourcePath, gopath) { return &Workspace{ gopath: gopaths, isModuleMode: false, Path: gopath, }, nil } } } if os.Getenv("GO111MODULE") != "off" { // Module mode root, _ := findModuleRoot(sourcePath, "", false) if root != "" { return &Workspace{ gopath: gopaths, isModuleMode: true, Path: root, }, nil } } return nil, fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, source, gopaths) }
[ "func", "WorkspaceFor", "(", "source", "string", ")", "(", "*", "Workspace", ",", "error", ")", "{", "gopaths", ":=", "envOr", "(", "\"GOPATH\"", ",", "build", ".", "Default", ".", "GOPATH", ")", "\n", "sourcePath", ",", "err", ":=", "filepath", ".", "Abs", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "sourcePath", "=", "source", "\n", "}", "\n", "if", "os", ".", "Getenv", "(", "\"GO111MODULE\"", ")", "!=", "\"on\"", "{", "for", "_", ",", "gp", ":=", "range", "filepath", ".", "SplitList", "(", "gopaths", ")", "{", "gopath", ",", "err", ":=", "filepath", ".", "Abs", "(", "gp", ")", "\n", "if", "err", "!=", "nil", "{", "gopath", "=", "gp", "\n", "}", "\n", "if", "filepath", ".", "HasPrefix", "(", "sourcePath", ",", "gopath", ")", "{", "return", "&", "Workspace", "{", "gopath", ":", "gopaths", ",", "isModuleMode", ":", "false", ",", "Path", ":", "gopath", ",", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "os", ".", "Getenv", "(", "\"GO111MODULE\"", ")", "!=", "\"off\"", "{", "root", ",", "_", ":=", "findModuleRoot", "(", "sourcePath", ",", "\"\"", ",", "false", ")", "\n", "if", "root", "!=", "\"\"", "{", "return", "&", "Workspace", "{", "gopath", ":", "gopaths", ",", "isModuleMode", ":", "true", ",", "Path", ":", "root", ",", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "`Go source file \"%s\" not in Go workspace, adjust GOPATH %s or use modules`", ",", "source", ",", "gopaths", ")", "\n", "}" ]
// WorkspaceFor returns the Go workspace for the given Go source file.
[ "WorkspaceFor", "returns", "the", "Go", "workspace", "for", "the", "given", "Go", "source", "file", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L103-L136
train
goadesign/goa
goagen/codegen/workspace.go
Delete
func (w *Workspace) Delete() { if w.gopath != "" { os.Setenv("GOPATH", w.gopath) } os.RemoveAll(w.Path) }
go
func (w *Workspace) Delete() { if w.gopath != "" { os.Setenv("GOPATH", w.gopath) } os.RemoveAll(w.Path) }
[ "func", "(", "w", "*", "Workspace", ")", "Delete", "(", ")", "{", "if", "w", ".", "gopath", "!=", "\"\"", "{", "os", ".", "Setenv", "(", "\"GOPATH\"", ",", "w", ".", "gopath", ")", "\n", "}", "\n", "os", ".", "RemoveAll", "(", "w", ".", "Path", ")", "\n", "}" ]
// Delete deletes the workspace temporary directory.
[ "Delete", "deletes", "the", "workspace", "temporary", "directory", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L139-L144
train
goadesign/goa
goagen/codegen/workspace.go
Reset
func (w *Workspace) Reset() error { d, err := os.Open(w.Path) if err != nil { return err } defer d.Close() names, err := d.Readdirnames(-1) if err != nil { return err } for _, name := range names { err = os.RemoveAll(filepath.Join(w.Path, name)) if err != nil { return err } } return nil }
go
func (w *Workspace) Reset() error { d, err := os.Open(w.Path) if err != nil { return err } defer d.Close() names, err := d.Readdirnames(-1) if err != nil { return err } for _, name := range names { err = os.RemoveAll(filepath.Join(w.Path, name)) if err != nil { return err } } return nil }
[ "func", "(", "w", "*", "Workspace", ")", "Reset", "(", ")", "error", "{", "d", ",", "err", ":=", "os", ".", "Open", "(", "w", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "d", ".", "Close", "(", ")", "\n", "names", ",", "err", ":=", "d", ".", "Readdirnames", "(", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "err", "=", "os", ".", "RemoveAll", "(", "filepath", ".", "Join", "(", "w", ".", "Path", ",", "name", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Reset removes all content from the workspace.
[ "Reset", "removes", "all", "content", "from", "the", "workspace", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L147-L164
train
goadesign/goa
goagen/codegen/workspace.go
PackageFor
func PackageFor(source string) (*Package, error) { w, err := WorkspaceFor(source) if err != nil { return nil, err } basepath := filepath.Join(w.Path, "src") // GOPATH mode. if w.isModuleMode { basepath = w.Path // Module mode. } path, err := filepath.Rel(basepath, filepath.Dir(source)) if err != nil { return nil, err } return &Package{Workspace: w, Path: filepath.ToSlash(path)}, nil }
go
func PackageFor(source string) (*Package, error) { w, err := WorkspaceFor(source) if err != nil { return nil, err } basepath := filepath.Join(w.Path, "src") // GOPATH mode. if w.isModuleMode { basepath = w.Path // Module mode. } path, err := filepath.Rel(basepath, filepath.Dir(source)) if err != nil { return nil, err } return &Package{Workspace: w, Path: filepath.ToSlash(path)}, nil }
[ "func", "PackageFor", "(", "source", "string", ")", "(", "*", "Package", ",", "error", ")", "{", "w", ",", "err", ":=", "WorkspaceFor", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "basepath", ":=", "filepath", ".", "Join", "(", "w", ".", "Path", ",", "\"src\"", ")", "\n", "if", "w", ".", "isModuleMode", "{", "basepath", "=", "w", ".", "Path", "\n", "}", "\n", "path", ",", "err", ":=", "filepath", ".", "Rel", "(", "basepath", ",", "filepath", ".", "Dir", "(", "source", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Package", "{", "Workspace", ":", "w", ",", "Path", ":", "filepath", ".", "ToSlash", "(", "path", ")", "}", ",", "nil", "\n", "}" ]
// PackageFor returns the package for the given source file.
[ "PackageFor", "returns", "the", "package", "for", "the", "given", "source", "file", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L178-L192
train
goadesign/goa
goagen/codegen/workspace.go
Abs
func (p *Package) Abs() string { elem := "src" // GOPATH mode. if p.Workspace.isModuleMode { elem = "" // Module mode. } return filepath.Join(p.Workspace.Path, elem, p.Path) }
go
func (p *Package) Abs() string { elem := "src" // GOPATH mode. if p.Workspace.isModuleMode { elem = "" // Module mode. } return filepath.Join(p.Workspace.Path, elem, p.Path) }
[ "func", "(", "p", "*", "Package", ")", "Abs", "(", ")", "string", "{", "elem", ":=", "\"src\"", "\n", "if", "p", ".", "Workspace", ".", "isModuleMode", "{", "elem", "=", "\"\"", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "p", ".", "Workspace", ".", "Path", ",", "elem", ",", "p", ".", "Path", ")", "\n", "}" ]
// Abs returns the absolute path to the package source directory
[ "Abs", "returns", "the", "absolute", "path", "to", "the", "package", "source", "directory" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L195-L201
train
goadesign/goa
goagen/codegen/workspace.go
CreateSourceFile
func (p *Package) CreateSourceFile(name string) (*SourceFile, error) { os.RemoveAll(filepath.Join(p.Abs(), name)) return p.OpenSourceFile(name) }
go
func (p *Package) CreateSourceFile(name string) (*SourceFile, error) { os.RemoveAll(filepath.Join(p.Abs(), name)) return p.OpenSourceFile(name) }
[ "func", "(", "p", "*", "Package", ")", "CreateSourceFile", "(", "name", "string", ")", "(", "*", "SourceFile", ",", "error", ")", "{", "os", ".", "RemoveAll", "(", "filepath", ".", "Join", "(", "p", ".", "Abs", "(", ")", ",", "name", ")", ")", "\n", "return", "p", ".", "OpenSourceFile", "(", "name", ")", "\n", "}" ]
// CreateSourceFile creates a Go source file in the given package. If the file // already exists it is overwritten.
[ "CreateSourceFile", "creates", "a", "Go", "source", "file", "in", "the", "given", "package", ".", "If", "the", "file", "already", "exists", "it", "is", "overwritten", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L205-L208
train
goadesign/goa
goagen/codegen/workspace.go
OpenSourceFile
func (p *Package) OpenSourceFile(name string) (*SourceFile, error) { f := &SourceFile{Name: name, Package: p} file, err := os.OpenFile(f.Abs(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return nil, err } f.osFile = file return f, nil }
go
func (p *Package) OpenSourceFile(name string) (*SourceFile, error) { f := &SourceFile{Name: name, Package: p} file, err := os.OpenFile(f.Abs(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return nil, err } f.osFile = file return f, nil }
[ "func", "(", "p", "*", "Package", ")", "OpenSourceFile", "(", "name", "string", ")", "(", "*", "SourceFile", ",", "error", ")", "{", "f", ":=", "&", "SourceFile", "{", "Name", ":", "name", ",", "Package", ":", "p", "}", "\n", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "f", ".", "Abs", "(", ")", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_APPEND", "|", "os", ".", "O_WRONLY", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "f", ".", "osFile", "=", "file", "\n", "return", "f", ",", "nil", "\n", "}" ]
// OpenSourceFile opens an existing file to append to it. If the file does not // exist OpenSourceFile creates it.
[ "OpenSourceFile", "opens", "an", "existing", "file", "to", "append", "to", "it", ".", "If", "the", "file", "does", "not", "exist", "OpenSourceFile", "creates", "it", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L212-L220
train
goadesign/goa
goagen/codegen/workspace.go
Compile
func (p *Package) Compile(bin string) (string, error) { gobin, err := exec.LookPath("go") if err != nil { return "", fmt.Errorf(`failed to find a go compiler, looked in "%s"`, os.Getenv("PATH")) } if runtime.GOOS == "windows" { bin += ".exe" } c := exec.Cmd{ Path: gobin, Args: []string{gobin, "build", "-o", bin}, Dir: p.Abs(), } out, err := c.CombinedOutput() if err != nil { if len(out) > 0 { return "", fmt.Errorf(string(out)) } return "", fmt.Errorf("failed to compile %s: %s", bin, err) } return filepath.Join(p.Abs(), bin), nil }
go
func (p *Package) Compile(bin string) (string, error) { gobin, err := exec.LookPath("go") if err != nil { return "", fmt.Errorf(`failed to find a go compiler, looked in "%s"`, os.Getenv("PATH")) } if runtime.GOOS == "windows" { bin += ".exe" } c := exec.Cmd{ Path: gobin, Args: []string{gobin, "build", "-o", bin}, Dir: p.Abs(), } out, err := c.CombinedOutput() if err != nil { if len(out) > 0 { return "", fmt.Errorf(string(out)) } return "", fmt.Errorf("failed to compile %s: %s", bin, err) } return filepath.Join(p.Abs(), bin), nil }
[ "func", "(", "p", "*", "Package", ")", "Compile", "(", "bin", "string", ")", "(", "string", ",", "error", ")", "{", "gobin", ",", "err", ":=", "exec", ".", "LookPath", "(", "\"go\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "`failed to find a go compiler, looked in \"%s\"`", ",", "os", ".", "Getenv", "(", "\"PATH\"", ")", ")", "\n", "}", "\n", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "bin", "+=", "\".exe\"", "\n", "}", "\n", "c", ":=", "exec", ".", "Cmd", "{", "Path", ":", "gobin", ",", "Args", ":", "[", "]", "string", "{", "gobin", ",", "\"build\"", ",", "\"-o\"", ",", "bin", "}", ",", "Dir", ":", "p", ".", "Abs", "(", ")", ",", "}", "\n", "out", ",", "err", ":=", "c", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "len", "(", "out", ")", ">", "0", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "string", "(", "out", ")", ")", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"failed to compile %s: %s\"", ",", "bin", ",", "err", ")", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "p", ".", "Abs", "(", ")", ",", "bin", ")", ",", "nil", "\n", "}" ]
// Compile compiles a package and returns the path to the compiled binary.
[ "Compile", "compiles", "a", "package", "and", "returns", "the", "path", "to", "the", "compiled", "binary", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L223-L244
train
goadesign/goa
goagen/codegen/workspace.go
SourceFileFor
func SourceFileFor(path string) (*SourceFile, error) { absPath, err := filepath.Abs(path) if err != nil { absPath = path } p, err := PackageFor(absPath) if err != nil { return nil, err } return p.OpenSourceFile(filepath.Base(absPath)) }
go
func SourceFileFor(path string) (*SourceFile, error) { absPath, err := filepath.Abs(path) if err != nil { absPath = path } p, err := PackageFor(absPath) if err != nil { return nil, err } return p.OpenSourceFile(filepath.Base(absPath)) }
[ "func", "SourceFileFor", "(", "path", "string", ")", "(", "*", "SourceFile", ",", "error", ")", "{", "absPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "absPath", "=", "path", "\n", "}", "\n", "p", ",", "err", ":=", "PackageFor", "(", "absPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ".", "OpenSourceFile", "(", "filepath", ".", "Base", "(", "absPath", ")", ")", "\n", "}" ]
// SourceFileFor returns a SourceFile for the file at the given path.
[ "SourceFileFor", "returns", "a", "SourceFile", "for", "the", "file", "at", "the", "given", "path", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L247-L257
train
goadesign/goa
goagen/codegen/workspace.go
WriteHeader
func (f *SourceFile) WriteHeader(title, pack string, imports []*ImportSpec) error { ctx := map[string]interface{}{ "Title": title, "ToolVersion": version.String(), "Pkg": pack, "Imports": imports, } if err := headerTmpl.Execute(f, ctx); err != nil { return fmt.Errorf("failed to generate contexts: %s", err) } return nil }
go
func (f *SourceFile) WriteHeader(title, pack string, imports []*ImportSpec) error { ctx := map[string]interface{}{ "Title": title, "ToolVersion": version.String(), "Pkg": pack, "Imports": imports, } if err := headerTmpl.Execute(f, ctx); err != nil { return fmt.Errorf("failed to generate contexts: %s", err) } return nil }
[ "func", "(", "f", "*", "SourceFile", ")", "WriteHeader", "(", "title", ",", "pack", "string", ",", "imports", "[", "]", "*", "ImportSpec", ")", "error", "{", "ctx", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"Title\"", ":", "title", ",", "\"ToolVersion\"", ":", "version", ".", "String", "(", ")", ",", "\"Pkg\"", ":", "pack", ",", "\"Imports\"", ":", "imports", ",", "}", "\n", "if", "err", ":=", "headerTmpl", ".", "Execute", "(", "f", ",", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to generate contexts: %s\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// WriteHeader writes the generic generated code header.
[ "WriteHeader", "writes", "the", "generic", "generated", "code", "header", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L260-L271
train
goadesign/goa
goagen/codegen/workspace.go
Close
func (f *SourceFile) Close() { if err := f.osFile.Close(); err != nil { panic(err) // bug } }
go
func (f *SourceFile) Close() { if err := f.osFile.Close(); err != nil { panic(err) // bug } }
[ "func", "(", "f", "*", "SourceFile", ")", "Close", "(", ")", "{", "if", "err", ":=", "f", ".", "osFile", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// Close closes the underlying OS file.
[ "Close", "closes", "the", "underlying", "OS", "file", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L280-L284
train
goadesign/goa
goagen/codegen/workspace.go
FormatCode
func (f *SourceFile) FormatCode() error { // Parse file into AST fset := token.NewFileSet() file, err := parser.ParseFile(fset, f.Abs(), nil, parser.ParseComments) if err != nil { content, _ := ioutil.ReadFile(f.Abs()) var buf bytes.Buffer scanner.PrintError(&buf, err) return fmt.Errorf("%s\n========\nContent:\n%s", buf.String(), content) } // Clean unused imports imports := astutil.Imports(fset, file) for _, group := range imports { for _, imp := range group { path := strings.Trim(imp.Path.Value, `"`) if !astutil.UsesImport(file, path) { if imp.Name != nil { astutil.DeleteNamedImport(fset, file, imp.Name.Name, path) } else { astutil.DeleteImport(fset, file, path) } } } } ast.SortImports(fset, file) // Open file to be written w, err := os.OpenFile(f.Abs(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm) if err != nil { return err } defer w.Close() // Write formatted code without unused imports return format.Node(w, fset, file) }
go
func (f *SourceFile) FormatCode() error { // Parse file into AST fset := token.NewFileSet() file, err := parser.ParseFile(fset, f.Abs(), nil, parser.ParseComments) if err != nil { content, _ := ioutil.ReadFile(f.Abs()) var buf bytes.Buffer scanner.PrintError(&buf, err) return fmt.Errorf("%s\n========\nContent:\n%s", buf.String(), content) } // Clean unused imports imports := astutil.Imports(fset, file) for _, group := range imports { for _, imp := range group { path := strings.Trim(imp.Path.Value, `"`) if !astutil.UsesImport(file, path) { if imp.Name != nil { astutil.DeleteNamedImport(fset, file, imp.Name.Name, path) } else { astutil.DeleteImport(fset, file, path) } } } } ast.SortImports(fset, file) // Open file to be written w, err := os.OpenFile(f.Abs(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm) if err != nil { return err } defer w.Close() // Write formatted code without unused imports return format.Node(w, fset, file) }
[ "func", "(", "f", "*", "SourceFile", ")", "FormatCode", "(", ")", "error", "{", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "file", ",", "err", ":=", "parser", ".", "ParseFile", "(", "fset", ",", "f", ".", "Abs", "(", ")", ",", "nil", ",", "parser", ".", "ParseComments", ")", "\n", "if", "err", "!=", "nil", "{", "content", ",", "_", ":=", "ioutil", ".", "ReadFile", "(", "f", ".", "Abs", "(", ")", ")", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "scanner", ".", "PrintError", "(", "&", "buf", ",", "err", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"%s\\n========\\nContent:\\n%s\"", ",", "\\n", ",", "\\n", ")", "\n", "}", "\n", "\\n", "\n", "buf", ".", "String", "(", ")", "\n", "content", "\n", "imports", ":=", "astutil", ".", "Imports", "(", "fset", ",", "file", ")", "\n", "for", "_", ",", "group", ":=", "range", "imports", "{", "for", "_", ",", "imp", ":=", "range", "group", "{", "path", ":=", "strings", ".", "Trim", "(", "imp", ".", "Path", ".", "Value", ",", "`\"`", ")", "\n", "if", "!", "astutil", ".", "UsesImport", "(", "file", ",", "path", ")", "{", "if", "imp", ".", "Name", "!=", "nil", "{", "astutil", ".", "DeleteNamedImport", "(", "fset", ",", "file", ",", "imp", ".", "Name", ".", "Name", ",", "path", ")", "\n", "}", "else", "{", "astutil", ".", "DeleteImport", "(", "fset", ",", "file", ",", "path", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "ast", ".", "SortImports", "(", "fset", ",", "file", ")", "\n", "w", ",", "err", ":=", "os", ".", "OpenFile", "(", "f", ".", "Abs", "(", ")", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "os", ".", "ModePerm", ")", "\n", "}" ]
// FormatCode performs the equivalent of "goimports -w" on the source file.
[ "FormatCode", "performs", "the", "equivalent", "of", "goimports", "-", "w", "on", "the", "source", "file", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L287-L320
train
goadesign/goa
goagen/codegen/workspace.go
Abs
func (f *SourceFile) Abs() string { return filepath.Join(f.Package.Abs(), f.Name) }
go
func (f *SourceFile) Abs() string { return filepath.Join(f.Package.Abs(), f.Name) }
[ "func", "(", "f", "*", "SourceFile", ")", "Abs", "(", ")", "string", "{", "return", "filepath", ".", "Join", "(", "f", ".", "Package", ".", "Abs", "(", ")", ",", "f", ".", "Name", ")", "\n", "}" ]
// Abs returne the source file absolute filename
[ "Abs", "returne", "the", "source", "file", "absolute", "filename" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L323-L325
train
goadesign/goa
goagen/codegen/workspace.go
ExecuteTemplate
func (f *SourceFile) ExecuteTemplate(name, source string, funcMap template.FuncMap, data interface{}) error { tmpl, err := template.New(name).Funcs(DefaultFuncMap).Funcs(funcMap).Parse(source) if err != nil { panic(err) // bug } return tmpl.Execute(f, data) }
go
func (f *SourceFile) ExecuteTemplate(name, source string, funcMap template.FuncMap, data interface{}) error { tmpl, err := template.New(name).Funcs(DefaultFuncMap).Funcs(funcMap).Parse(source) if err != nil { panic(err) // bug } return tmpl.Execute(f, data) }
[ "func", "(", "f", "*", "SourceFile", ")", "ExecuteTemplate", "(", "name", ",", "source", "string", ",", "funcMap", "template", ".", "FuncMap", ",", "data", "interface", "{", "}", ")", "error", "{", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "name", ")", ".", "Funcs", "(", "DefaultFuncMap", ")", ".", "Funcs", "(", "funcMap", ")", ".", "Parse", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "tmpl", ".", "Execute", "(", "f", ",", "data", ")", "\n", "}" ]
// ExecuteTemplate executes the template and writes the output to the file.
[ "ExecuteTemplate", "executes", "the", "template", "and", "writes", "the", "output", "to", "the", "file", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L328-L334
train
goadesign/goa
goagen/codegen/workspace.go
PackagePath
func PackagePath(path string) (string, error) { absPath, err := filepath.Abs(path) if err != nil { absPath = path } gopaths := filepath.SplitList(envOr("GOPATH", build.Default.GOPATH)) if os.Getenv("GO111MODULE") != "on" { // GOPATH mode for _, gopath := range gopaths { if gp, err := filepath.Abs(gopath); err == nil { gopath = gp } if filepath.HasPrefix(absPath, gopath) { base := filepath.FromSlash(gopath + "/src") rel, err := filepath.Rel(base, absPath) return filepath.ToSlash(rel), err } } } if os.Getenv("GO111MODULE") != "off" { // Module mode root, file := findModuleRoot(absPath, "", false) if root != "" { content, err := ioutil.ReadFile(filepath.Join(root, file)) if err == nil { p := modulePath(content) base := filepath.FromSlash(root) rel, err := filepath.Rel(base, absPath) return filepath.ToSlash(filepath.Join(p, rel)), err } } } return "", fmt.Errorf("%s does not contain a Go package", absPath) }
go
func PackagePath(path string) (string, error) { absPath, err := filepath.Abs(path) if err != nil { absPath = path } gopaths := filepath.SplitList(envOr("GOPATH", build.Default.GOPATH)) if os.Getenv("GO111MODULE") != "on" { // GOPATH mode for _, gopath := range gopaths { if gp, err := filepath.Abs(gopath); err == nil { gopath = gp } if filepath.HasPrefix(absPath, gopath) { base := filepath.FromSlash(gopath + "/src") rel, err := filepath.Rel(base, absPath) return filepath.ToSlash(rel), err } } } if os.Getenv("GO111MODULE") != "off" { // Module mode root, file := findModuleRoot(absPath, "", false) if root != "" { content, err := ioutil.ReadFile(filepath.Join(root, file)) if err == nil { p := modulePath(content) base := filepath.FromSlash(root) rel, err := filepath.Rel(base, absPath) return filepath.ToSlash(filepath.Join(p, rel)), err } } } return "", fmt.Errorf("%s does not contain a Go package", absPath) }
[ "func", "PackagePath", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "absPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "absPath", "=", "path", "\n", "}", "\n", "gopaths", ":=", "filepath", ".", "SplitList", "(", "envOr", "(", "\"GOPATH\"", ",", "build", ".", "Default", ".", "GOPATH", ")", ")", "\n", "if", "os", ".", "Getenv", "(", "\"GO111MODULE\"", ")", "!=", "\"on\"", "{", "for", "_", ",", "gopath", ":=", "range", "gopaths", "{", "if", "gp", ",", "err", ":=", "filepath", ".", "Abs", "(", "gopath", ")", ";", "err", "==", "nil", "{", "gopath", "=", "gp", "\n", "}", "\n", "if", "filepath", ".", "HasPrefix", "(", "absPath", ",", "gopath", ")", "{", "base", ":=", "filepath", ".", "FromSlash", "(", "gopath", "+", "\"/src\"", ")", "\n", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "base", ",", "absPath", ")", "\n", "return", "filepath", ".", "ToSlash", "(", "rel", ")", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "os", ".", "Getenv", "(", "\"GO111MODULE\"", ")", "!=", "\"off\"", "{", "root", ",", "file", ":=", "findModuleRoot", "(", "absPath", ",", "\"\"", ",", "false", ")", "\n", "if", "root", "!=", "\"\"", "{", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "root", ",", "file", ")", ")", "\n", "if", "err", "==", "nil", "{", "p", ":=", "modulePath", "(", "content", ")", "\n", "base", ":=", "filepath", ".", "FromSlash", "(", "root", ")", "\n", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "base", ",", "absPath", ")", "\n", "return", "filepath", ".", "ToSlash", "(", "filepath", ".", "Join", "(", "p", ",", "rel", ")", ")", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"%s does not contain a Go package\"", ",", "absPath", ")", "\n", "}" ]
// PackagePath returns the Go package path for the directory that lives under the given absolute // file path.
[ "PackagePath", "returns", "the", "Go", "package", "path", "for", "the", "directory", "that", "lives", "under", "the", "given", "absolute", "file", "path", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L338-L369
train
goadesign/goa
goagen/codegen/workspace.go
PackageSourcePath
func PackageSourcePath(pkg string) (string, error) { buildCtx := build.Default buildCtx.GOPATH = envOr("GOPATH", build.Default.GOPATH) // Reevaluate each time to be nice to tests wd, err := os.Getwd() if err != nil { wd = "." } p, err := buildCtx.Import(pkg, wd, 0) if err != nil { return "", err } return p.Dir, nil }
go
func PackageSourcePath(pkg string) (string, error) { buildCtx := build.Default buildCtx.GOPATH = envOr("GOPATH", build.Default.GOPATH) // Reevaluate each time to be nice to tests wd, err := os.Getwd() if err != nil { wd = "." } p, err := buildCtx.Import(pkg, wd, 0) if err != nil { return "", err } return p.Dir, nil }
[ "func", "PackageSourcePath", "(", "pkg", "string", ")", "(", "string", ",", "error", ")", "{", "buildCtx", ":=", "build", ".", "Default", "\n", "buildCtx", ".", "GOPATH", "=", "envOr", "(", "\"GOPATH\"", ",", "build", ".", "Default", ".", "GOPATH", ")", "\n", "wd", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "wd", "=", "\".\"", "\n", "}", "\n", "p", ",", "err", ":=", "buildCtx", ".", "Import", "(", "pkg", ",", "wd", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "p", ".", "Dir", ",", "nil", "\n", "}" ]
// PackageSourcePath returns the absolute path to the given package source.
[ "PackageSourcePath", "returns", "the", "absolute", "path", "to", "the", "given", "package", "source", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L372-L384
train
goadesign/goa
goagen/codegen/workspace.go
PackageName
func PackageName(path string) (string, error) { fset := token.NewFileSet() pkgs, err := parser.ParseDir(fset, path, nil, parser.PackageClauseOnly) if err != nil { return "", err } var pkgNames []string for n := range pkgs { if !strings.HasSuffix(n, "_test") { pkgNames = append(pkgNames, n) } } if len(pkgNames) > 1 { return "", fmt.Errorf("more than one Go package found in %s (%s)", path, strings.Join(pkgNames, ",")) } if len(pkgNames) == 0 { return "", fmt.Errorf("no Go package found in %s", path) } return pkgNames[0], nil }
go
func PackageName(path string) (string, error) { fset := token.NewFileSet() pkgs, err := parser.ParseDir(fset, path, nil, parser.PackageClauseOnly) if err != nil { return "", err } var pkgNames []string for n := range pkgs { if !strings.HasSuffix(n, "_test") { pkgNames = append(pkgNames, n) } } if len(pkgNames) > 1 { return "", fmt.Errorf("more than one Go package found in %s (%s)", path, strings.Join(pkgNames, ",")) } if len(pkgNames) == 0 { return "", fmt.Errorf("no Go package found in %s", path) } return pkgNames[0], nil }
[ "func", "PackageName", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "pkgs", ",", "err", ":=", "parser", ".", "ParseDir", "(", "fset", ",", "path", ",", "nil", ",", "parser", ".", "PackageClauseOnly", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "var", "pkgNames", "[", "]", "string", "\n", "for", "n", ":=", "range", "pkgs", "{", "if", "!", "strings", ".", "HasSuffix", "(", "n", ",", "\"_test\"", ")", "{", "pkgNames", "=", "append", "(", "pkgNames", ",", "n", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "pkgNames", ")", ">", "1", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"more than one Go package found in %s (%s)\"", ",", "path", ",", "strings", ".", "Join", "(", "pkgNames", ",", "\",\"", ")", ")", "\n", "}", "\n", "if", "len", "(", "pkgNames", ")", "==", "0", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"no Go package found in %s\"", ",", "path", ")", "\n", "}", "\n", "return", "pkgNames", "[", "0", "]", ",", "nil", "\n", "}" ]
// PackageName returns the name of a package at the given path
[ "PackageName", "returns", "the", "name", "of", "a", "package", "at", "the", "given", "path" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/workspace.go#L387-L407
train
goadesign/goa
goagen/codegen/helpers.go
CheckVersion
func CheckVersion(ver string) error { compat, err := version.Compatible(ver) if err != nil { return err } if !compat { return fmt.Errorf("version mismatch: using goagen %s to generate code that compiles with goa %s", ver, version.String()) } return nil }
go
func CheckVersion(ver string) error { compat, err := version.Compatible(ver) if err != nil { return err } if !compat { return fmt.Errorf("version mismatch: using goagen %s to generate code that compiles with goa %s", ver, version.String()) } return nil }
[ "func", "CheckVersion", "(", "ver", "string", ")", "error", "{", "compat", ",", "err", ":=", "version", ".", "Compatible", "(", "ver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "compat", "{", "return", "fmt", ".", "Errorf", "(", "\"version mismatch: using goagen %s to generate code that compiles with goa %s\"", ",", "ver", ",", "version", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckVersion returns an error if the ver is empty, contains an incorrect value or // a version number that is not compatible with the version of this repo.
[ "CheckVersion", "returns", "an", "error", "if", "the", "ver", "is", "empty", "contains", "an", "incorrect", "value", "or", "a", "version", "number", "that", "is", "not", "compatible", "with", "the", "version", "of", "this", "repo", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L18-L28
train
goadesign/goa
goagen/codegen/helpers.go
CommandLine
func CommandLine() string { // We don't use the full path to the tool so that running goagen multiple times doesn't // end up creating different command line comments (because of the temporary directory it // runs in). var param string if len(os.Args) > 1 { args := make([]string, len(os.Args)-1) gopaths := filepath.SplitList(envOr("GOPATH", build.Default.GOPATH)) for i, a := range os.Args[1:] { for _, p := range gopaths { p = "=" + p if strings.Contains(a, p) { args[i] = strings.Replace(a, p, "=$(GOPATH)", 1) break } } if args[i] == "" { args[i] = a } } param = strings.Join(args, " ") } rawcmd := filepath.Base(os.Args[0]) // Remove possible .exe suffix to not create different ouptut just because // you ran goagen on Windows. rawcmd = strings.TrimSuffix(rawcmd, ".exe") cmd := fmt.Sprintf("$ %s %s", rawcmd, param) return strings.Replace(cmd, " --", "\n\t--", -1) }
go
func CommandLine() string { // We don't use the full path to the tool so that running goagen multiple times doesn't // end up creating different command line comments (because of the temporary directory it // runs in). var param string if len(os.Args) > 1 { args := make([]string, len(os.Args)-1) gopaths := filepath.SplitList(envOr("GOPATH", build.Default.GOPATH)) for i, a := range os.Args[1:] { for _, p := range gopaths { p = "=" + p if strings.Contains(a, p) { args[i] = strings.Replace(a, p, "=$(GOPATH)", 1) break } } if args[i] == "" { args[i] = a } } param = strings.Join(args, " ") } rawcmd := filepath.Base(os.Args[0]) // Remove possible .exe suffix to not create different ouptut just because // you ran goagen on Windows. rawcmd = strings.TrimSuffix(rawcmd, ".exe") cmd := fmt.Sprintf("$ %s %s", rawcmd, param) return strings.Replace(cmd, " --", "\n\t--", -1) }
[ "func", "CommandLine", "(", ")", "string", "{", "var", "param", "string", "\n", "if", "len", "(", "os", ".", "Args", ")", ">", "1", "{", "args", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "os", ".", "Args", ")", "-", "1", ")", "\n", "gopaths", ":=", "filepath", ".", "SplitList", "(", "envOr", "(", "\"GOPATH\"", ",", "build", ".", "Default", ".", "GOPATH", ")", ")", "\n", "for", "i", ",", "a", ":=", "range", "os", ".", "Args", "[", "1", ":", "]", "{", "for", "_", ",", "p", ":=", "range", "gopaths", "{", "p", "=", "\"=\"", "+", "p", "\n", "if", "strings", ".", "Contains", "(", "a", ",", "p", ")", "{", "args", "[", "i", "]", "=", "strings", ".", "Replace", "(", "a", ",", "p", ",", "\"=$(GOPATH)\"", ",", "1", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "args", "[", "i", "]", "==", "\"\"", "{", "args", "[", "i", "]", "=", "a", "\n", "}", "\n", "}", "\n", "param", "=", "strings", ".", "Join", "(", "args", ",", "\" \"", ")", "\n", "}", "\n", "rawcmd", ":=", "filepath", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", "\n", "rawcmd", "=", "strings", ".", "TrimSuffix", "(", "rawcmd", ",", "\".exe\"", ")", "\n", "cmd", ":=", "fmt", ".", "Sprintf", "(", "\"$ %s %s\"", ",", "rawcmd", ",", "param", ")", "\n", "return", "strings", ".", "Replace", "(", "cmd", ",", "\" --\"", ",", "\"\\n\\t--\"", ",", "\\n", ")", "\n", "}" ]
// CommandLine return the command used to run this process.
[ "CommandLine", "return", "the", "command", "used", "to", "run", "this", "process", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L31-L61
train
goadesign/goa
goagen/codegen/helpers.go
Indent
func Indent(s, prefix string) string { return string(IndentBytes([]byte(s), []byte(prefix))) }
go
func Indent(s, prefix string) string { return string(IndentBytes([]byte(s), []byte(prefix))) }
[ "func", "Indent", "(", "s", ",", "prefix", "string", ")", "string", "{", "return", "string", "(", "IndentBytes", "(", "[", "]", "byte", "(", "s", ")", ",", "[", "]", "byte", "(", "prefix", ")", ")", ")", "\n", "}" ]
// Indent inserts prefix at the beginning of each non-empty line of s. The // end-of-line marker is NL.
[ "Indent", "inserts", "prefix", "at", "the", "beginning", "of", "each", "non", "-", "empty", "line", "of", "s", ".", "The", "end", "-", "of", "-", "line", "marker", "is", "NL", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L90-L92
train
goadesign/goa
goagen/codegen/helpers.go
IndentBytes
func IndentBytes(b, prefix []byte) []byte { var res []byte bol := true for _, c := range b { if bol && c != '\n' { res = append(res, prefix...) } res = append(res, c) bol = c == '\n' } return res }
go
func IndentBytes(b, prefix []byte) []byte { var res []byte bol := true for _, c := range b { if bol && c != '\n' { res = append(res, prefix...) } res = append(res, c) bol = c == '\n' } return res }
[ "func", "IndentBytes", "(", "b", ",", "prefix", "[", "]", "byte", ")", "[", "]", "byte", "{", "var", "res", "[", "]", "byte", "\n", "bol", ":=", "true", "\n", "for", "_", ",", "c", ":=", "range", "b", "{", "if", "bol", "&&", "c", "!=", "'\\n'", "{", "res", "=", "append", "(", "res", ",", "prefix", "...", ")", "\n", "}", "\n", "res", "=", "append", "(", "res", ",", "c", ")", "\n", "bol", "=", "c", "==", "'\\n'", "\n", "}", "\n", "return", "res", "\n", "}" ]
// IndentBytes inserts prefix at the beginning of each non-empty line of b. // The end-of-line marker is NL.
[ "IndentBytes", "inserts", "prefix", "at", "the", "beginning", "of", "each", "non", "-", "empty", "line", "of", "b", ".", "The", "end", "-", "of", "-", "line", "marker", "is", "NL", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L96-L107
train
goadesign/goa
goagen/codegen/helpers.go
Tabs
func Tabs(depth int) string { var tabs string for i := 0; i < depth; i++ { tabs += "\t" } // return fmt.Sprintf("%d%s", depth, tabs) return tabs }
go
func Tabs(depth int) string { var tabs string for i := 0; i < depth; i++ { tabs += "\t" } // return fmt.Sprintf("%d%s", depth, tabs) return tabs }
[ "func", "Tabs", "(", "depth", "int", ")", "string", "{", "var", "tabs", "string", "\n", "for", "i", ":=", "0", ";", "i", "<", "depth", ";", "i", "++", "{", "tabs", "+=", "\"\\t\"", "\n", "}", "\n", "\\t", "\n", "}" ]
// Tabs returns a string made of depth tab characters.
[ "Tabs", "returns", "a", "string", "made", "of", "depth", "tab", "characters", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L110-L117
train
goadesign/goa
goagen/codegen/helpers.go
CanonicalTemplate
func CanonicalTemplate(r *design.ResourceDefinition) string { return design.WildcardRegex.ReplaceAllLiteralString(r.URITemplate(), "/%v") }
go
func CanonicalTemplate(r *design.ResourceDefinition) string { return design.WildcardRegex.ReplaceAllLiteralString(r.URITemplate(), "/%v") }
[ "func", "CanonicalTemplate", "(", "r", "*", "design", ".", "ResourceDefinition", ")", "string", "{", "return", "design", ".", "WildcardRegex", ".", "ReplaceAllLiteralString", "(", "r", ".", "URITemplate", "(", ")", ",", "\"/%v\"", ")", "\n", "}" ]
// CanonicalTemplate returns the resource URI template as a format string suitable for use in the // fmt.Printf function family.
[ "CanonicalTemplate", "returns", "the", "resource", "URI", "template", "as", "a", "format", "string", "suitable", "for", "use", "in", "the", "fmt", ".", "Printf", "function", "family", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L124-L126
train
goadesign/goa
goagen/codegen/helpers.go
CanonicalParams
func CanonicalParams(r *design.ResourceDefinition) []string { var params []string if ca := r.CanonicalAction(); ca != nil { if len(ca.Routes) > 0 { params = ca.Routes[0].Params() } for i, p := range params { params[i] = Goify(p, false) } } return params }
go
func CanonicalParams(r *design.ResourceDefinition) []string { var params []string if ca := r.CanonicalAction(); ca != nil { if len(ca.Routes) > 0 { params = ca.Routes[0].Params() } for i, p := range params { params[i] = Goify(p, false) } } return params }
[ "func", "CanonicalParams", "(", "r", "*", "design", ".", "ResourceDefinition", ")", "[", "]", "string", "{", "var", "params", "[", "]", "string", "\n", "if", "ca", ":=", "r", ".", "CanonicalAction", "(", ")", ";", "ca", "!=", "nil", "{", "if", "len", "(", "ca", ".", "Routes", ")", ">", "0", "{", "params", "=", "ca", ".", "Routes", "[", "0", "]", ".", "Params", "(", ")", "\n", "}", "\n", "for", "i", ",", "p", ":=", "range", "params", "{", "params", "[", "i", "]", "=", "Goify", "(", "p", ",", "false", ")", "\n", "}", "\n", "}", "\n", "return", "params", "\n", "}" ]
// CanonicalParams returns the list of parameter names needed to build the canonical href to the // resource. It returns nil if the resource does not have a canonical action.
[ "CanonicalParams", "returns", "the", "list", "of", "parameter", "names", "needed", "to", "build", "the", "canonical", "href", "to", "the", "resource", ".", "It", "returns", "nil", "if", "the", "resource", "does", "not", "have", "a", "canonical", "action", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L130-L141
train
goadesign/goa
goagen/codegen/helpers.go
SnakeCase
func SnakeCase(name string) string { for u, l := range toLower { name = strings.Replace(name, u, l, -1) } var b bytes.Buffer var lastUnderscore bool ln := len(name) if ln == 0 { return "" } b.WriteRune(unicode.ToLower(rune(name[0]))) for i := 1; i < ln; i++ { r := rune(name[i]) nextIsLower := false if i < ln-1 { n := rune(name[i+1]) nextIsLower = unicode.IsLower(n) && unicode.IsLetter(n) } if unicode.IsUpper(r) { if !lastUnderscore && nextIsLower { b.WriteRune('_') lastUnderscore = true } b.WriteRune(unicode.ToLower(r)) } else { b.WriteRune(r) lastUnderscore = false } } return b.String() }
go
func SnakeCase(name string) string { for u, l := range toLower { name = strings.Replace(name, u, l, -1) } var b bytes.Buffer var lastUnderscore bool ln := len(name) if ln == 0 { return "" } b.WriteRune(unicode.ToLower(rune(name[0]))) for i := 1; i < ln; i++ { r := rune(name[i]) nextIsLower := false if i < ln-1 { n := rune(name[i+1]) nextIsLower = unicode.IsLower(n) && unicode.IsLetter(n) } if unicode.IsUpper(r) { if !lastUnderscore && nextIsLower { b.WriteRune('_') lastUnderscore = true } b.WriteRune(unicode.ToLower(r)) } else { b.WriteRune(r) lastUnderscore = false } } return b.String() }
[ "func", "SnakeCase", "(", "name", "string", ")", "string", "{", "for", "u", ",", "l", ":=", "range", "toLower", "{", "name", "=", "strings", ".", "Replace", "(", "name", ",", "u", ",", "l", ",", "-", "1", ")", "\n", "}", "\n", "var", "b", "bytes", ".", "Buffer", "\n", "var", "lastUnderscore", "bool", "\n", "ln", ":=", "len", "(", "name", ")", "\n", "if", "ln", "==", "0", "{", "return", "\"\"", "\n", "}", "\n", "b", ".", "WriteRune", "(", "unicode", ".", "ToLower", "(", "rune", "(", "name", "[", "0", "]", ")", ")", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "ln", ";", "i", "++", "{", "r", ":=", "rune", "(", "name", "[", "i", "]", ")", "\n", "nextIsLower", ":=", "false", "\n", "if", "i", "<", "ln", "-", "1", "{", "n", ":=", "rune", "(", "name", "[", "i", "+", "1", "]", ")", "\n", "nextIsLower", "=", "unicode", ".", "IsLower", "(", "n", ")", "&&", "unicode", ".", "IsLetter", "(", "n", ")", "\n", "}", "\n", "if", "unicode", ".", "IsUpper", "(", "r", ")", "{", "if", "!", "lastUnderscore", "&&", "nextIsLower", "{", "b", ".", "WriteRune", "(", "'_'", ")", "\n", "lastUnderscore", "=", "true", "\n", "}", "\n", "b", ".", "WriteRune", "(", "unicode", ".", "ToLower", "(", "r", ")", ")", "\n", "}", "else", "{", "b", ".", "WriteRune", "(", "r", ")", "\n", "lastUnderscore", "=", "false", "\n", "}", "\n", "}", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// SnakeCase produces the snake_case version of the given CamelCase string.
[ "SnakeCase", "produces", "the", "snake_case", "version", "of", "the", "given", "CamelCase", "string", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L147-L177
train
goadesign/goa
goagen/codegen/helpers.go
KebabCase
func KebabCase(name string) string { name = SnakeCase(name) return strings.Replace(name, "_", "-", -1) }
go
func KebabCase(name string) string { name = SnakeCase(name) return strings.Replace(name, "_", "-", -1) }
[ "func", "KebabCase", "(", "name", "string", ")", "string", "{", "name", "=", "SnakeCase", "(", "name", ")", "\n", "return", "strings", ".", "Replace", "(", "name", ",", "\"_\"", ",", "\"-\"", ",", "-", "1", ")", "\n", "}" ]
// KebabCase produces the kebab-case version of the given CamelCase string.
[ "KebabCase", "produces", "the", "kebab", "-", "case", "version", "of", "the", "given", "CamelCase", "string", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/helpers.go#L180-L183
train
goadesign/goa
design/random.go
NewRandomGenerator
func NewRandomGenerator(seed string) *RandomGenerator { hasher := md5.New() hasher.Write([]byte(seed)) sint := int64(binary.BigEndian.Uint64(hasher.Sum(nil))) source := rand.NewSource(sint) ran := rand.New(source) faker := &faker.Faker{ Language: "end", Dict: faker.Dict["en"], Rand: ran, } return &RandomGenerator{ Seed: seed, faker: faker, rand: ran, } }
go
func NewRandomGenerator(seed string) *RandomGenerator { hasher := md5.New() hasher.Write([]byte(seed)) sint := int64(binary.BigEndian.Uint64(hasher.Sum(nil))) source := rand.NewSource(sint) ran := rand.New(source) faker := &faker.Faker{ Language: "end", Dict: faker.Dict["en"], Rand: ran, } return &RandomGenerator{ Seed: seed, faker: faker, rand: ran, } }
[ "func", "NewRandomGenerator", "(", "seed", "string", ")", "*", "RandomGenerator", "{", "hasher", ":=", "md5", ".", "New", "(", ")", "\n", "hasher", ".", "Write", "(", "[", "]", "byte", "(", "seed", ")", ")", "\n", "sint", ":=", "int64", "(", "binary", ".", "BigEndian", ".", "Uint64", "(", "hasher", ".", "Sum", "(", "nil", ")", ")", ")", "\n", "source", ":=", "rand", ".", "NewSource", "(", "sint", ")", "\n", "ran", ":=", "rand", ".", "New", "(", "source", ")", "\n", "faker", ":=", "&", "faker", ".", "Faker", "{", "Language", ":", "\"end\"", ",", "Dict", ":", "faker", ".", "Dict", "[", "\"en\"", "]", ",", "Rand", ":", "ran", ",", "}", "\n", "return", "&", "RandomGenerator", "{", "Seed", ":", "seed", ",", "faker", ":", "faker", ",", "rand", ":", "ran", ",", "}", "\n", "}" ]
// NewRandomGenerator returns a random value generator seeded from the given string value.
[ "NewRandomGenerator", "returns", "a", "random", "value", "generator", "seeded", "from", "the", "given", "string", "value", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/random.go#L24-L40
train
goadesign/goa
design/random.go
DateTime
func (r *RandomGenerator) DateTime() time.Time { // Use a constant max value to make sure the same pseudo random // values get generated for a given API. max := time.Date(2016, time.July, 11, 23, 0, 0, 0, time.UTC).Unix() unix := r.rand.Int63n(max) return time.Unix(unix, 0).UTC() }
go
func (r *RandomGenerator) DateTime() time.Time { // Use a constant max value to make sure the same pseudo random // values get generated for a given API. max := time.Date(2016, time.July, 11, 23, 0, 0, 0, time.UTC).Unix() unix := r.rand.Int63n(max) return time.Unix(unix, 0).UTC() }
[ "func", "(", "r", "*", "RandomGenerator", ")", "DateTime", "(", ")", "time", ".", "Time", "{", "max", ":=", "time", ".", "Date", "(", "2016", ",", "time", ".", "July", ",", "11", ",", "23", ",", "0", ",", "0", ",", "0", ",", "time", ".", "UTC", ")", ".", "Unix", "(", ")", "\n", "unix", ":=", "r", ".", "rand", ".", "Int63n", "(", "max", ")", "\n", "return", "time", ".", "Unix", "(", "unix", ",", "0", ")", ".", "UTC", "(", ")", "\n", "}" ]
// DateTime produces a random date.
[ "DateTime", "produces", "a", "random", "date", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/random.go#L54-L60
train
goadesign/goa
design/random.go
File
func (r *RandomGenerator) File() string { return fmt.Sprintf("%sjpg", r.faker.Sentence(1, false)) }
go
func (r *RandomGenerator) File() string { return fmt.Sprintf("%sjpg", r.faker.Sentence(1, false)) }
[ "func", "(", "r", "*", "RandomGenerator", ")", "File", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"%sjpg\"", ",", "r", ".", "faker", ".", "Sentence", "(", "1", ",", "false", ")", ")", "\n", "}" ]
// File produces a random file.
[ "File", "produces", "a", "random", "file", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/random.go#L78-L80
train
goadesign/goa
version/version.go
String
func String() string { return "v" + strconv.Itoa(Major) + "." + strconv.Itoa(Minor) + "." + strconv.Itoa(Build) }
go
func String() string { return "v" + strconv.Itoa(Major) + "." + strconv.Itoa(Minor) + "." + strconv.Itoa(Build) }
[ "func", "String", "(", ")", "string", "{", "return", "\"v\"", "+", "strconv", ".", "Itoa", "(", "Major", ")", "+", "\".\"", "+", "strconv", ".", "Itoa", "(", "Minor", ")", "+", "\".\"", "+", "strconv", ".", "Itoa", "(", "Build", ")", "\n", "}" ]
// String returns the complete version number.
[ "String", "returns", "the", "complete", "version", "number", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/version/version.go#L19-L21
train
goadesign/goa
version/version.go
Compatible
func Compatible(v string) (bool, error) { if len(v) < 5 { return false, fmt.Errorf("invalid version string format %#v", v) } v = v[1:] elems := strings.Split(v, ".") if len(elems) != 3 { return false, fmt.Errorf("version not of the form Major.Minor.Build %#v", v) } mj, err := strconv.Atoi(elems[0]) if err != nil { return false, fmt.Errorf("invalid major version number %#v, must be number", elems[0]) } return mj == Major, nil }
go
func Compatible(v string) (bool, error) { if len(v) < 5 { return false, fmt.Errorf("invalid version string format %#v", v) } v = v[1:] elems := strings.Split(v, ".") if len(elems) != 3 { return false, fmt.Errorf("version not of the form Major.Minor.Build %#v", v) } mj, err := strconv.Atoi(elems[0]) if err != nil { return false, fmt.Errorf("invalid major version number %#v, must be number", elems[0]) } return mj == Major, nil }
[ "func", "Compatible", "(", "v", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "len", "(", "v", ")", "<", "5", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"invalid version string format %#v\"", ",", "v", ")", "\n", "}", "\n", "v", "=", "v", "[", "1", ":", "]", "\n", "elems", ":=", "strings", ".", "Split", "(", "v", ",", "\".\"", ")", "\n", "if", "len", "(", "elems", ")", "!=", "3", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"version not of the form Major.Minor.Build %#v\"", ",", "v", ")", "\n", "}", "\n", "mj", ",", "err", ":=", "strconv", ".", "Atoi", "(", "elems", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"invalid major version number %#v, must be number\"", ",", "elems", "[", "0", "]", ")", "\n", "}", "\n", "return", "mj", "==", "Major", ",", "nil", "\n", "}" ]
// Compatible returns true if Major matches the major version of the given version string. // It returns an error if the given string is not a valid version string.
[ "Compatible", "returns", "true", "if", "Major", "matches", "the", "major", "version", "of", "the", "given", "version", "string", ".", "It", "returns", "an", "error", "if", "the", "given", "string", "is", "not", "a", "valid", "version", "string", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/version/version.go#L25-L39
train
goadesign/goa
uuid/uuid_js.go
FromString
func FromString(input string) (u UUID, err error) { err = u.UnmarshalText([]byte(input)) return }
go
func FromString(input string) (u UUID, err error) { err = u.UnmarshalText([]byte(input)) return }
[ "func", "FromString", "(", "input", "string", ")", "(", "u", "UUID", ",", "err", "error", ")", "{", "err", "=", "u", ".", "UnmarshalText", "(", "[", "]", "byte", "(", "input", ")", ")", "\n", "return", "\n", "}" ]
// FromString returns UUID parsed from string input. // Input is expected in a form accepted by UnmarshalText.
[ "FromString", "returns", "UUID", "parsed", "from", "string", "input", ".", "Input", "is", "expected", "in", "a", "form", "accepted", "by", "UnmarshalText", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/uuid/uuid_js.go#L22-L25
train
goadesign/goa
goagen/codegen/publicizer.go
RecursivePublicizer
func RecursivePublicizer(att *design.AttributeDefinition, source, target string, depth int) string { var publications []string if o := att.Type.ToObject(); o != nil { if ds, ok := att.Type.(design.DataStructure); ok { att = ds.Definition() } o.IterateAttributes(func(n string, catt *design.AttributeDefinition) error { publication := Publicizer( catt, fmt.Sprintf("%s.%s", source, Goify(n, true)), fmt.Sprintf("%s.%s", target, Goify(n, true)), catt.Type.IsPrimitive() && !att.IsPrimitivePointer(n) && !att.IsInterface(n), depth+1, false, ) publication = fmt.Sprintf("%sif %s.%s != nil {\n%s\n%s}", Tabs(depth), source, Goify(n, true), publication, Tabs(depth)) publications = append(publications, publication) return nil }) } return strings.Join(publications, "\n") }
go
func RecursivePublicizer(att *design.AttributeDefinition, source, target string, depth int) string { var publications []string if o := att.Type.ToObject(); o != nil { if ds, ok := att.Type.(design.DataStructure); ok { att = ds.Definition() } o.IterateAttributes(func(n string, catt *design.AttributeDefinition) error { publication := Publicizer( catt, fmt.Sprintf("%s.%s", source, Goify(n, true)), fmt.Sprintf("%s.%s", target, Goify(n, true)), catt.Type.IsPrimitive() && !att.IsPrimitivePointer(n) && !att.IsInterface(n), depth+1, false, ) publication = fmt.Sprintf("%sif %s.%s != nil {\n%s\n%s}", Tabs(depth), source, Goify(n, true), publication, Tabs(depth)) publications = append(publications, publication) return nil }) } return strings.Join(publications, "\n") }
[ "func", "RecursivePublicizer", "(", "att", "*", "design", ".", "AttributeDefinition", ",", "source", ",", "target", "string", ",", "depth", "int", ")", "string", "{", "var", "publications", "[", "]", "string", "\n", "if", "o", ":=", "att", ".", "Type", ".", "ToObject", "(", ")", ";", "o", "!=", "nil", "{", "if", "ds", ",", "ok", ":=", "att", ".", "Type", ".", "(", "design", ".", "DataStructure", ")", ";", "ok", "{", "att", "=", "ds", ".", "Definition", "(", ")", "\n", "}", "\n", "o", ".", "IterateAttributes", "(", "func", "(", "n", "string", ",", "catt", "*", "design", ".", "AttributeDefinition", ")", "error", "{", "publication", ":=", "Publicizer", "(", "catt", ",", "fmt", ".", "Sprintf", "(", "\"%s.%s\"", ",", "source", ",", "Goify", "(", "n", ",", "true", ")", ")", ",", "fmt", ".", "Sprintf", "(", "\"%s.%s\"", ",", "target", ",", "Goify", "(", "n", ",", "true", ")", ")", ",", "catt", ".", "Type", ".", "IsPrimitive", "(", ")", "&&", "!", "att", ".", "IsPrimitivePointer", "(", "n", ")", "&&", "!", "att", ".", "IsInterface", "(", "n", ")", ",", "depth", "+", "1", ",", "false", ",", ")", "\n", "publication", "=", "fmt", ".", "Sprintf", "(", "\"%sif %s.%s != nil {\\n%s\\n%s}\"", ",", "\\n", ",", "\\n", ",", "Tabs", "(", "depth", ")", ",", "source", ",", "Goify", "(", "n", ",", "true", ")", ")", "\n", "publication", "\n", "Tabs", "(", "depth", ")", "\n", "}", ")", "\n", "}", "\n", "publications", "=", "append", "(", "publications", ",", "publication", ")", "\n", "}" ]
// RecursivePublicizer produces code that copies fields from the private struct to the // public struct
[ "RecursivePublicizer", "produces", "code", "that", "copies", "fields", "from", "the", "private", "struct", "to", "the", "public", "struct" ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/publicizer.go#L49-L71
train
goadesign/goa
goagen/codegen/publicizer.go
Publicizer
func Publicizer(att *design.AttributeDefinition, sourceField, targetField string, dereference bool, depth int, init bool) string { var publication string data := map[string]interface{}{ "sourceField": sourceField, "targetField": targetField, "depth": depth, "att": att, "dereference": dereference, "init": init, } switch { case att.Type.IsPrimitive(): publication = RunTemplate(simplePublicizeT, data) case att.Type.IsObject(): if _, ok := att.Type.(*design.MediaTypeDefinition); ok { publication = RunTemplate(recursivePublicizeT, data) } else if _, ok := att.Type.(*design.UserTypeDefinition); ok { publication = RunTemplate(recursivePublicizeT, data) } else { publication = RunTemplate(objectPublicizeT, data) } case att.Type.IsArray(): // If the array element is primitive type, we can simply copy the elements over (i.e) []string if att.Type.HasAttributes() { data["elemType"] = att.Type.ToArray().ElemType publication = RunTemplate(arrayPublicizeT, data) } else { publication = RunTemplate(simplePublicizeT, data) } case att.Type.IsHash(): if att.Type.HasAttributes() { h := att.Type.ToHash() data["keyType"] = h.KeyType data["elemType"] = h.ElemType publication = RunTemplate(hashPublicizeT, data) } else { publication = RunTemplate(simplePublicizeT, data) } } return publication }
go
func Publicizer(att *design.AttributeDefinition, sourceField, targetField string, dereference bool, depth int, init bool) string { var publication string data := map[string]interface{}{ "sourceField": sourceField, "targetField": targetField, "depth": depth, "att": att, "dereference": dereference, "init": init, } switch { case att.Type.IsPrimitive(): publication = RunTemplate(simplePublicizeT, data) case att.Type.IsObject(): if _, ok := att.Type.(*design.MediaTypeDefinition); ok { publication = RunTemplate(recursivePublicizeT, data) } else if _, ok := att.Type.(*design.UserTypeDefinition); ok { publication = RunTemplate(recursivePublicizeT, data) } else { publication = RunTemplate(objectPublicizeT, data) } case att.Type.IsArray(): // If the array element is primitive type, we can simply copy the elements over (i.e) []string if att.Type.HasAttributes() { data["elemType"] = att.Type.ToArray().ElemType publication = RunTemplate(arrayPublicizeT, data) } else { publication = RunTemplate(simplePublicizeT, data) } case att.Type.IsHash(): if att.Type.HasAttributes() { h := att.Type.ToHash() data["keyType"] = h.KeyType data["elemType"] = h.ElemType publication = RunTemplate(hashPublicizeT, data) } else { publication = RunTemplate(simplePublicizeT, data) } } return publication }
[ "func", "Publicizer", "(", "att", "*", "design", ".", "AttributeDefinition", ",", "sourceField", ",", "targetField", "string", ",", "dereference", "bool", ",", "depth", "int", ",", "init", "bool", ")", "string", "{", "var", "publication", "string", "\n", "data", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"sourceField\"", ":", "sourceField", ",", "\"targetField\"", ":", "targetField", ",", "\"depth\"", ":", "depth", ",", "\"att\"", ":", "att", ",", "\"dereference\"", ":", "dereference", ",", "\"init\"", ":", "init", ",", "}", "\n", "switch", "{", "case", "att", ".", "Type", ".", "IsPrimitive", "(", ")", ":", "publication", "=", "RunTemplate", "(", "simplePublicizeT", ",", "data", ")", "\n", "case", "att", ".", "Type", ".", "IsObject", "(", ")", ":", "if", "_", ",", "ok", ":=", "att", ".", "Type", ".", "(", "*", "design", ".", "MediaTypeDefinition", ")", ";", "ok", "{", "publication", "=", "RunTemplate", "(", "recursivePublicizeT", ",", "data", ")", "\n", "}", "else", "if", "_", ",", "ok", ":=", "att", ".", "Type", ".", "(", "*", "design", ".", "UserTypeDefinition", ")", ";", "ok", "{", "publication", "=", "RunTemplate", "(", "recursivePublicizeT", ",", "data", ")", "\n", "}", "else", "{", "publication", "=", "RunTemplate", "(", "objectPublicizeT", ",", "data", ")", "\n", "}", "\n", "case", "att", ".", "Type", ".", "IsArray", "(", ")", ":", "if", "att", ".", "Type", ".", "HasAttributes", "(", ")", "{", "data", "[", "\"elemType\"", "]", "=", "att", ".", "Type", ".", "ToArray", "(", ")", ".", "ElemType", "\n", "publication", "=", "RunTemplate", "(", "arrayPublicizeT", ",", "data", ")", "\n", "}", "else", "{", "publication", "=", "RunTemplate", "(", "simplePublicizeT", ",", "data", ")", "\n", "}", "\n", "case", "att", ".", "Type", ".", "IsHash", "(", ")", ":", "if", "att", ".", "Type", ".", "HasAttributes", "(", ")", "{", "h", ":=", "att", ".", "Type", ".", "ToHash", "(", ")", "\n", "data", "[", "\"keyType\"", "]", "=", "h", ".", "KeyType", "\n", "data", "[", "\"elemType\"", "]", "=", "h", ".", "ElemType", "\n", "publication", "=", "RunTemplate", "(", "hashPublicizeT", ",", "data", ")", "\n", "}", "else", "{", "publication", "=", "RunTemplate", "(", "simplePublicizeT", ",", "data", ")", "\n", "}", "\n", "}", "\n", "return", "publication", "\n", "}" ]
// Publicizer publicizes a single attribute based on the type.
[ "Publicizer", "publicizes", "a", "single", "attribute", "based", "on", "the", "type", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/publicizer.go#L74-L114
train
goadesign/goa
middleware/security/jwt/resolver.go
NewResolver
func NewResolver(keys map[string][]Key, header string) (*GroupResolver, error) { if header == "" { return nil, ErrEmptyHeaderName } keyMap := make(map[string][]Key) for name := range keys { for _, keys := range keys[name] { switch keys := keys.(type) { case *rsa.PublicKey, *ecdsa.PublicKey, string, []byte: keyMap[name] = append(keyMap[name], keys) case []*rsa.PublicKey: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } case []*ecdsa.PublicKey: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } case [][]byte: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } case []string: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } default: return nil, ErrInvalidKey } } } return &GroupResolver{ RWMutex: &sync.RWMutex{}, keyMap: keyMap, keyHeader: header, }, nil }
go
func NewResolver(keys map[string][]Key, header string) (*GroupResolver, error) { if header == "" { return nil, ErrEmptyHeaderName } keyMap := make(map[string][]Key) for name := range keys { for _, keys := range keys[name] { switch keys := keys.(type) { case *rsa.PublicKey, *ecdsa.PublicKey, string, []byte: keyMap[name] = append(keyMap[name], keys) case []*rsa.PublicKey: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } case []*ecdsa.PublicKey: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } case [][]byte: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } case []string: for _, key := range keys { keyMap[name] = append(keyMap[name], key) } default: return nil, ErrInvalidKey } } } return &GroupResolver{ RWMutex: &sync.RWMutex{}, keyMap: keyMap, keyHeader: header, }, nil }
[ "func", "NewResolver", "(", "keys", "map", "[", "string", "]", "[", "]", "Key", ",", "header", "string", ")", "(", "*", "GroupResolver", ",", "error", ")", "{", "if", "header", "==", "\"\"", "{", "return", "nil", ",", "ErrEmptyHeaderName", "\n", "}", "\n", "keyMap", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "Key", ")", "\n", "for", "name", ":=", "range", "keys", "{", "for", "_", ",", "keys", ":=", "range", "keys", "[", "name", "]", "{", "switch", "keys", ":=", "keys", ".", "(", "type", ")", "{", "case", "*", "rsa", ".", "PublicKey", ",", "*", "ecdsa", ".", "PublicKey", ",", "string", ",", "[", "]", "byte", ":", "keyMap", "[", "name", "]", "=", "append", "(", "keyMap", "[", "name", "]", ",", "keys", ")", "\n", "case", "[", "]", "*", "rsa", ".", "PublicKey", ":", "for", "_", ",", "key", ":=", "range", "keys", "{", "keyMap", "[", "name", "]", "=", "append", "(", "keyMap", "[", "name", "]", ",", "key", ")", "\n", "}", "\n", "case", "[", "]", "*", "ecdsa", ".", "PublicKey", ":", "for", "_", ",", "key", ":=", "range", "keys", "{", "keyMap", "[", "name", "]", "=", "append", "(", "keyMap", "[", "name", "]", ",", "key", ")", "\n", "}", "\n", "case", "[", "]", "[", "]", "byte", ":", "for", "_", ",", "key", ":=", "range", "keys", "{", "keyMap", "[", "name", "]", "=", "append", "(", "keyMap", "[", "name", "]", ",", "key", ")", "\n", "}", "\n", "case", "[", "]", "string", ":", "for", "_", ",", "key", ":=", "range", "keys", "{", "keyMap", "[", "name", "]", "=", "append", "(", "keyMap", "[", "name", "]", ",", "key", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "ErrInvalidKey", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "&", "GroupResolver", "{", "RWMutex", ":", "&", "sync", ".", "RWMutex", "{", "}", ",", "keyMap", ":", "keyMap", ",", "keyHeader", ":", "header", ",", "}", ",", "nil", "\n", "}" ]
// NewResolver returns a GroupResolver that uses the value of the request header with the given name // to select the key group used for authorization. keys contains the initial set of key groups // indexed by name.
[ "NewResolver", "returns", "a", "GroupResolver", "that", "uses", "the", "value", "of", "the", "request", "header", "with", "the", "given", "name", "to", "select", "the", "key", "group", "used", "for", "authorization", ".", "keys", "contains", "the", "initial", "set", "of", "key", "groups", "indexed", "by", "name", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/security/jwt/resolver.go#L41-L77
train
goadesign/goa
middleware/security/jwt/resolver.go
RemoveAllKeys
func (kr *GroupResolver) RemoveAllKeys() { kr.Lock() defer kr.Unlock() kr.keyMap = make(map[string][]Key) return }
go
func (kr *GroupResolver) RemoveAllKeys() { kr.Lock() defer kr.Unlock() kr.keyMap = make(map[string][]Key) return }
[ "func", "(", "kr", "*", "GroupResolver", ")", "RemoveAllKeys", "(", ")", "{", "kr", ".", "Lock", "(", ")", "\n", "defer", "kr", ".", "Unlock", "(", ")", "\n", "kr", ".", "keyMap", "=", "make", "(", "map", "[", "string", "]", "[", "]", "Key", ")", "\n", "return", "\n", "}" ]
// RemoveAllKeys removes all keys from the resolver.
[ "RemoveAllKeys", "removes", "all", "keys", "from", "the", "resolver", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/security/jwt/resolver.go#L117-L122
train
goadesign/goa
middleware/security/jwt/resolver.go
RemoveKeys
func (kr *GroupResolver) RemoveKeys(name string) { kr.Lock() defer kr.Unlock() delete(kr.keyMap, name) return }
go
func (kr *GroupResolver) RemoveKeys(name string) { kr.Lock() defer kr.Unlock() delete(kr.keyMap, name) return }
[ "func", "(", "kr", "*", "GroupResolver", ")", "RemoveKeys", "(", "name", "string", ")", "{", "kr", ".", "Lock", "(", ")", "\n", "defer", "kr", ".", "Unlock", "(", ")", "\n", "delete", "(", "kr", ".", "keyMap", ",", "name", ")", "\n", "return", "\n", "}" ]
// RemoveKeys removes all keys from the resolver stored under the provided name.
[ "RemoveKeys", "removes", "all", "keys", "from", "the", "resolver", "stored", "under", "the", "provided", "name", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/security/jwt/resolver.go#L125-L130
train
goadesign/goa
middleware/security/jwt/resolver.go
RemoveKey
func (kr *GroupResolver) RemoveKey(name string, key Key) { kr.Lock() defer kr.Unlock() if keys, ok := kr.keyMap[name]; ok { for i, keyItem := range keys { if keyItem == key { kr.keyMap[name] = append(keys[:i], keys[i+1:]...) } } } return }
go
func (kr *GroupResolver) RemoveKey(name string, key Key) { kr.Lock() defer kr.Unlock() if keys, ok := kr.keyMap[name]; ok { for i, keyItem := range keys { if keyItem == key { kr.keyMap[name] = append(keys[:i], keys[i+1:]...) } } } return }
[ "func", "(", "kr", "*", "GroupResolver", ")", "RemoveKey", "(", "name", "string", ",", "key", "Key", ")", "{", "kr", ".", "Lock", "(", ")", "\n", "defer", "kr", ".", "Unlock", "(", ")", "\n", "if", "keys", ",", "ok", ":=", "kr", ".", "keyMap", "[", "name", "]", ";", "ok", "{", "for", "i", ",", "keyItem", ":=", "range", "keys", "{", "if", "keyItem", "==", "key", "{", "kr", ".", "keyMap", "[", "name", "]", "=", "append", "(", "keys", "[", ":", "i", "]", ",", "keys", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// RemoveKey removes only the provided key stored under the provided name from // the resolver.
[ "RemoveKey", "removes", "only", "the", "provided", "key", "stored", "under", "the", "provided", "name", "from", "the", "resolver", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/security/jwt/resolver.go#L134-L145
train
goadesign/goa
middleware/security/jwt/resolver.go
GetAllKeys
func (kr *GroupResolver) GetAllKeys() []Key { kr.RLock() defer kr.RUnlock() var keys []Key for name := range kr.keyMap { for _, key := range kr.keyMap[name] { keys = append(keys, key) } } return keys }
go
func (kr *GroupResolver) GetAllKeys() []Key { kr.RLock() defer kr.RUnlock() var keys []Key for name := range kr.keyMap { for _, key := range kr.keyMap[name] { keys = append(keys, key) } } return keys }
[ "func", "(", "kr", "*", "GroupResolver", ")", "GetAllKeys", "(", ")", "[", "]", "Key", "{", "kr", ".", "RLock", "(", ")", "\n", "defer", "kr", ".", "RUnlock", "(", ")", "\n", "var", "keys", "[", "]", "Key", "\n", "for", "name", ":=", "range", "kr", ".", "keyMap", "{", "for", "_", ",", "key", ":=", "range", "kr", ".", "keyMap", "[", "name", "]", "{", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "}", "\n", "}", "\n", "return", "keys", "\n", "}" ]
// GetAllKeys returns a list of all the keys stored in the resolver.
[ "GetAllKeys", "returns", "a", "list", "of", "all", "the", "keys", "stored", "in", "the", "resolver", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/security/jwt/resolver.go#L148-L158
train
goadesign/goa
middleware/security/jwt/resolver.go
GetKeys
func (kr *GroupResolver) GetKeys(name string) ([]Key, error) { kr.RLock() defer kr.RUnlock() if keys, ok := kr.keyMap[name]; ok { return keys, nil } return nil, ErrKeyDoesNotExist }
go
func (kr *GroupResolver) GetKeys(name string) ([]Key, error) { kr.RLock() defer kr.RUnlock() if keys, ok := kr.keyMap[name]; ok { return keys, nil } return nil, ErrKeyDoesNotExist }
[ "func", "(", "kr", "*", "GroupResolver", ")", "GetKeys", "(", "name", "string", ")", "(", "[", "]", "Key", ",", "error", ")", "{", "kr", ".", "RLock", "(", ")", "\n", "defer", "kr", ".", "RUnlock", "(", ")", "\n", "if", "keys", ",", "ok", ":=", "kr", ".", "keyMap", "[", "name", "]", ";", "ok", "{", "return", "keys", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "ErrKeyDoesNotExist", "\n", "}" ]
// GetKeys returns a list of all the keys stored in the resolver under the // provided name.
[ "GetKeys", "returns", "a", "list", "of", "all", "the", "keys", "stored", "in", "the", "resolver", "under", "the", "provided", "name", "." ]
90bd33edff1a4f17fab06d1f9e14e659075d1328
https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/security/jwt/resolver.go#L162-L169
train