id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
166,900 | goadesign/goa | client/client.go | SetContextRequestID | func SetContextRequestID(ctx context.Context, reqID string) context.Context {
return context.WithValue(ctx, reqIDKey, reqID)
} | go | func SetContextRequestID(ctx context.Context, reqID string) context.Context {
return context.WithValue(ctx, reqIDKey, reqID)
} | [
"func",
"SetContextRequestID",
"(",
"ctx",
"context",
".",
"Context",
",",
"reqID",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"reqIDKey",
",",
"reqID",
")",
"\n",
"}"
] | // SetContextRequestID sets a request ID in the given context and returns a new context. | [
"SetContextRequestID",
"sets",
"a",
"request",
"ID",
"in",
"the",
"given",
"context",
"and",
"returns",
"a",
"new",
"context",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/client.go#L249-L251 |
166,901 | goadesign/goa | middleware/sampler.go | NewAdaptiveSampler | func NewAdaptiveSampler(maxSamplingRate, sampleSize int) Sampler {
if maxSamplingRate <= 0 {
panic("maxSamplingRate must be greater than 0")
}
if sampleSize <= 0 {
panic("sample size must be greater than 0")
}
return &adaptiveSampler{
lastRate: adaptiveUpperBoundInt, // samples all until initial count reaches sample size
maxSamplingRate: maxSamplingRate,
sampleSize: uint32(sampleSize),
start: time.Now(),
}
} | go | func NewAdaptiveSampler(maxSamplingRate, sampleSize int) Sampler {
if maxSamplingRate <= 0 {
panic("maxSamplingRate must be greater than 0")
}
if sampleSize <= 0 {
panic("sample size must be greater than 0")
}
return &adaptiveSampler{
lastRate: adaptiveUpperBoundInt, // samples all until initial count reaches sample size
maxSamplingRate: maxSamplingRate,
sampleSize: uint32(sampleSize),
start: time.Now(),
}
} | [
"func",
"NewAdaptiveSampler",
"(",
"maxSamplingRate",
",",
"sampleSize",
"int",
")",
"Sampler",
"{",
"if",
"maxSamplingRate",
"<=",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"sampleSize",
"<=",
"0",
"{",
"panic",
"(",
"\"",
"\"",
... | // NewAdaptiveSampler computes the interval for sampling for tracing middleware.
// it can also be used by non-web go routines to trace internal API calls.
//
// maxSamplingRate is the desired maximum sampling rate in requests per second.
//
// sampleSize sets the number of requests between two adjustments of the
// sampling rate when MaxSamplingRate is set. the sample rate cannot be adjusted
// until the sample size is reached at least once. | [
"NewAdaptiveSampler",
"computes",
"the",
"interval",
"for",
"sampling",
"for",
"tracing",
"middleware",
".",
"it",
"can",
"also",
"be",
"used",
"by",
"non",
"-",
"web",
"go",
"routines",
"to",
"trace",
"internal",
"API",
"calls",
".",
"maxSamplingRate",
"is",
... | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/sampler.go#L43-L56 |
166,902 | goadesign/goa | middleware/sampler.go | Sample | func (s *adaptiveSampler) Sample() bool {
// adjust sampling rate whenever sample size is reached.
var currentRate int
if atomic.AddUint32(&s.counter, 1) == s.sampleSize { // exact match prevents
atomic.StoreUint32(&s.counter, 0) // race is ok
s.Lock()
{
d := time.Since(s.start).Seconds()
r := float64(s.sampleSize) / d
currentRate = int((float64(s.maxSamplingRate) * adaptiveUpperBoundFloat) / r)
if currentRate > adaptiveUpperBoundInt {
currentRate = adaptiveUpperBoundInt
} else if currentRate < 1 {
currentRate = 1
}
s.start = time.Now()
}
s.Unlock()
atomic.StoreInt64(&s.lastRate, int64(currentRate))
} else {
currentRate = int(atomic.LoadInt64(&s.lastRate))
}
// currentRate is never zero.
return currentRate == adaptiveUpperBoundInt || rand.Intn(adaptiveUpperBoundInt) < currentRate
} | go | func (s *adaptiveSampler) Sample() bool {
// adjust sampling rate whenever sample size is reached.
var currentRate int
if atomic.AddUint32(&s.counter, 1) == s.sampleSize { // exact match prevents
atomic.StoreUint32(&s.counter, 0) // race is ok
s.Lock()
{
d := time.Since(s.start).Seconds()
r := float64(s.sampleSize) / d
currentRate = int((float64(s.maxSamplingRate) * adaptiveUpperBoundFloat) / r)
if currentRate > adaptiveUpperBoundInt {
currentRate = adaptiveUpperBoundInt
} else if currentRate < 1 {
currentRate = 1
}
s.start = time.Now()
}
s.Unlock()
atomic.StoreInt64(&s.lastRate, int64(currentRate))
} else {
currentRate = int(atomic.LoadInt64(&s.lastRate))
}
// currentRate is never zero.
return currentRate == adaptiveUpperBoundInt || rand.Intn(adaptiveUpperBoundInt) < currentRate
} | [
"func",
"(",
"s",
"*",
"adaptiveSampler",
")",
"Sample",
"(",
")",
"bool",
"{",
"// adjust sampling rate whenever sample size is reached.",
"var",
"currentRate",
"int",
"\n",
"if",
"atomic",
".",
"AddUint32",
"(",
"&",
"s",
".",
"counter",
",",
"1",
")",
"==",... | // Sample implementation for adaptive rate | [
"Sample",
"implementation",
"for",
"adaptive",
"rate"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/sampler.go#L67-L92 |
166,903 | goadesign/goa | middleware/sampler.go | Sample | func (s fixedSampler) Sample() bool {
samplingPercent := int(s)
return samplingPercent > 0 && (samplingPercent == 100 || rand.Intn(100) < samplingPercent)
} | go | func (s fixedSampler) Sample() bool {
samplingPercent := int(s)
return samplingPercent > 0 && (samplingPercent == 100 || rand.Intn(100) < samplingPercent)
} | [
"func",
"(",
"s",
"fixedSampler",
")",
"Sample",
"(",
")",
"bool",
"{",
"samplingPercent",
":=",
"int",
"(",
"s",
")",
"\n",
"return",
"samplingPercent",
">",
"0",
"&&",
"(",
"samplingPercent",
"==",
"100",
"||",
"rand",
".",
"Intn",
"(",
"100",
")",
... | // Sample implementation for fixed percentage | [
"Sample",
"implementation",
"for",
"fixed",
"percentage"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/sampler.go#L95-L98 |
166,904 | goadesign/goa | goagen/codegen/import_spec.go | NewImport | func NewImport(name, path string) *ImportSpec {
return &ImportSpec{Name: name, Path: path}
} | go | func NewImport(name, path string) *ImportSpec {
return &ImportSpec{Name: name, Path: path}
} | [
"func",
"NewImport",
"(",
"name",
",",
"path",
"string",
")",
"*",
"ImportSpec",
"{",
"return",
"&",
"ImportSpec",
"{",
"Name",
":",
"name",
",",
"Path",
":",
"path",
"}",
"\n",
"}"
] | // NewImport creates an import spec. | [
"NewImport",
"creates",
"an",
"import",
"spec",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/import_spec.go#L16-L18 |
166,905 | goadesign/goa | goagen/codegen/import_spec.go | Code | func (s *ImportSpec) Code() string {
if len(s.Name) > 0 {
return fmt.Sprintf(`%s "%s"`, s.Name, s.Path)
}
return fmt.Sprintf(`"%s"`, s.Path)
} | go | func (s *ImportSpec) Code() string {
if len(s.Name) > 0 {
return fmt.Sprintf(`%s "%s"`, s.Name, s.Path)
}
return fmt.Sprintf(`"%s"`, s.Path)
} | [
"func",
"(",
"s",
"*",
"ImportSpec",
")",
"Code",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"s",
".",
"Name",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"`%s \"%s\"`",
",",
"s",
".",
"Name",
",",
"s",
".",
"Path",
")",
"\n",
"... | // Code returns the Go import statement for the ImportSpec. | [
"Code",
"returns",
"the",
"Go",
"import",
"statement",
"for",
"the",
"ImportSpec",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/import_spec.go#L26-L31 |
166,906 | goadesign/goa | goagen/codegen/import_spec.go | appendImports | func appendImports(i, a []*ImportSpec) []*ImportSpec {
for _, v := range a {
contains := false
for _, att := range i {
if att.Path == v.Path {
contains = true
break
}
}
if contains != true {
i = append(i, v)
}
}
return i
} | go | func appendImports(i, a []*ImportSpec) []*ImportSpec {
for _, v := range a {
contains := false
for _, att := range i {
if att.Path == v.Path {
contains = true
break
}
}
if contains != true {
i = append(i, v)
}
}
return i
} | [
"func",
"appendImports",
"(",
"i",
",",
"a",
"[",
"]",
"*",
"ImportSpec",
")",
"[",
"]",
"*",
"ImportSpec",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"a",
"{",
"contains",
":=",
"false",
"\n",
"for",
"_",
",",
"att",
":=",
"range",
"i",
"{",
"i... | // appendImports appends two ImportSpec slices and preserves uniqueness | [
"appendImports",
"appends",
"two",
"ImportSpec",
"slices",
"and",
"preserves",
"uniqueness"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/import_spec.go#L74-L88 |
166,907 | goadesign/goa | goagen/gen_schema/json_schema.go | NewJSONSchema | func NewJSONSchema() *JSONSchema {
js := JSONSchema{
Properties: make(map[string]*JSONSchema),
Definitions: make(map[string]*JSONSchema),
}
return &js
} | go | func NewJSONSchema() *JSONSchema {
js := JSONSchema{
Properties: make(map[string]*JSONSchema),
Definitions: make(map[string]*JSONSchema),
}
return &js
} | [
"func",
"NewJSONSchema",
"(",
")",
"*",
"JSONSchema",
"{",
"js",
":=",
"JSONSchema",
"{",
"Properties",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"JSONSchema",
")",
",",
"Definitions",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"JSONSche... | // NewJSONSchema instantiates a new JSON schema. | [
"NewJSONSchema",
"instantiates",
"a",
"new",
"JSON",
"schema",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L110-L116 |
166,908 | goadesign/goa | goagen/gen_schema/json_schema.go | APISchema | func APISchema(api *design.APIDefinition) *JSONSchema {
api.IterateResources(func(r *design.ResourceDefinition) error {
GenerateResourceDefinition(api, r)
return nil
})
scheme := "http"
if len(api.Schemes) > 0 {
scheme = api.Schemes[0]
}
u := url.URL{Scheme: scheme, Host: api.Host}
href := u.String()
links := []*JSONLink{
{
Href: href,
Rel: "self",
},
{
Href: "/schema",
Method: "GET",
Rel: "self",
TargetSchema: &JSONSchema{
Schema: SchemaRef,
AdditionalProperties: true,
},
},
}
s := JSONSchema{
ID: fmt.Sprintf("%s/schema", href),
Title: api.Title,
Description: api.Description,
Type: JSONObject,
Definitions: Definitions,
Properties: propertiesFromDefs(Definitions, "#/definitions/"),
Links: links,
}
return &s
} | go | func APISchema(api *design.APIDefinition) *JSONSchema {
api.IterateResources(func(r *design.ResourceDefinition) error {
GenerateResourceDefinition(api, r)
return nil
})
scheme := "http"
if len(api.Schemes) > 0 {
scheme = api.Schemes[0]
}
u := url.URL{Scheme: scheme, Host: api.Host}
href := u.String()
links := []*JSONLink{
{
Href: href,
Rel: "self",
},
{
Href: "/schema",
Method: "GET",
Rel: "self",
TargetSchema: &JSONSchema{
Schema: SchemaRef,
AdditionalProperties: true,
},
},
}
s := JSONSchema{
ID: fmt.Sprintf("%s/schema", href),
Title: api.Title,
Description: api.Description,
Type: JSONObject,
Definitions: Definitions,
Properties: propertiesFromDefs(Definitions, "#/definitions/"),
Links: links,
}
return &s
} | [
"func",
"APISchema",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
")",
"*",
"JSONSchema",
"{",
"api",
".",
"IterateResources",
"(",
"func",
"(",
"r",
"*",
"design",
".",
"ResourceDefinition",
")",
"error",
"{",
"GenerateResourceDefinition",
"(",
"api",
"... | // APISchema produces the API JSON hyper schema. | [
"APISchema",
"produces",
"the",
"API",
"JSON",
"hyper",
"schema",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L129-L165 |
166,909 | goadesign/goa | goagen/gen_schema/json_schema.go | GenerateResourceDefinition | func GenerateResourceDefinition(api *design.APIDefinition, r *design.ResourceDefinition) {
s := NewJSONSchema()
s.Description = r.Description
s.Type = JSONObject
s.Title = r.Name
Definitions[r.Name] = s
if mt, ok := api.MediaTypes[r.MediaType]; ok {
for _, v := range mt.Views {
buildMediaTypeSchema(api, mt, v.Name, s)
}
}
r.IterateActions(func(a *design.ActionDefinition) error {
var requestSchema *JSONSchema
if a.Payload != nil {
requestSchema = TypeSchema(api, a.Payload)
requestSchema.Description = a.Name + " payload"
}
if a.Params != nil {
params := design.DupAtt(a.Params)
// We don't want to keep the path params, these are defined inline in the href
for _, r := range a.Routes {
for _, p := range r.Params() {
delete(params.Type.ToObject(), p)
}
}
}
var targetSchema *JSONSchema
var identifier string
for _, resp := range a.Responses {
if mt, ok := api.MediaTypes[resp.MediaType]; ok {
if identifier == "" {
identifier = mt.Identifier
} else {
identifier = ""
}
if targetSchema == nil {
targetSchema = TypeSchema(api, mt)
} else if targetSchema.AnyOf == nil {
firstSchema := targetSchema
targetSchema = NewJSONSchema()
targetSchema.AnyOf = []*JSONSchema{firstSchema, TypeSchema(api, mt)}
} else {
targetSchema.AnyOf = append(targetSchema.AnyOf, TypeSchema(api, mt))
}
}
}
for i, r := range a.Routes {
link := JSONLink{
Title: a.Name,
Rel: a.Name,
Href: toSchemaHref(api, r),
Method: r.Verb,
Schema: requestSchema,
TargetSchema: targetSchema,
MediaType: identifier,
}
if i == 0 {
if ca := a.Parent.CanonicalAction(); ca != nil {
if ca.Name == a.Name {
link.Rel = "self"
}
}
}
s.Links = append(s.Links, &link)
}
return nil
})
} | go | func GenerateResourceDefinition(api *design.APIDefinition, r *design.ResourceDefinition) {
s := NewJSONSchema()
s.Description = r.Description
s.Type = JSONObject
s.Title = r.Name
Definitions[r.Name] = s
if mt, ok := api.MediaTypes[r.MediaType]; ok {
for _, v := range mt.Views {
buildMediaTypeSchema(api, mt, v.Name, s)
}
}
r.IterateActions(func(a *design.ActionDefinition) error {
var requestSchema *JSONSchema
if a.Payload != nil {
requestSchema = TypeSchema(api, a.Payload)
requestSchema.Description = a.Name + " payload"
}
if a.Params != nil {
params := design.DupAtt(a.Params)
// We don't want to keep the path params, these are defined inline in the href
for _, r := range a.Routes {
for _, p := range r.Params() {
delete(params.Type.ToObject(), p)
}
}
}
var targetSchema *JSONSchema
var identifier string
for _, resp := range a.Responses {
if mt, ok := api.MediaTypes[resp.MediaType]; ok {
if identifier == "" {
identifier = mt.Identifier
} else {
identifier = ""
}
if targetSchema == nil {
targetSchema = TypeSchema(api, mt)
} else if targetSchema.AnyOf == nil {
firstSchema := targetSchema
targetSchema = NewJSONSchema()
targetSchema.AnyOf = []*JSONSchema{firstSchema, TypeSchema(api, mt)}
} else {
targetSchema.AnyOf = append(targetSchema.AnyOf, TypeSchema(api, mt))
}
}
}
for i, r := range a.Routes {
link := JSONLink{
Title: a.Name,
Rel: a.Name,
Href: toSchemaHref(api, r),
Method: r.Verb,
Schema: requestSchema,
TargetSchema: targetSchema,
MediaType: identifier,
}
if i == 0 {
if ca := a.Parent.CanonicalAction(); ca != nil {
if ca.Name == a.Name {
link.Rel = "self"
}
}
}
s.Links = append(s.Links, &link)
}
return nil
})
} | [
"func",
"GenerateResourceDefinition",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"r",
"*",
"design",
".",
"ResourceDefinition",
")",
"{",
"s",
":=",
"NewJSONSchema",
"(",
")",
"\n",
"s",
".",
"Description",
"=",
"r",
".",
"Description",
"\n",
"s... | // GenerateResourceDefinition produces the JSON schema corresponding to the given API resource.
// It stores the results in cachedSchema. | [
"GenerateResourceDefinition",
"produces",
"the",
"JSON",
"schema",
"corresponding",
"to",
"the",
"given",
"API",
"resource",
".",
"It",
"stores",
"the",
"results",
"in",
"cachedSchema",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L169-L236 |
166,910 | goadesign/goa | goagen/gen_schema/json_schema.go | MediaTypeRef | func MediaTypeRef(api *design.APIDefinition, mt *design.MediaTypeDefinition, view string) string {
projected, _, err := mt.Project(view)
if err != nil {
panic(fmt.Sprintf("failed to project media type %#v: %s", mt.Identifier, err)) // bug
}
if _, ok := Definitions[projected.TypeName]; !ok {
GenerateMediaTypeDefinition(api, projected, "default")
}
ref := fmt.Sprintf("#/definitions/%s", projected.TypeName)
return ref
} | go | func MediaTypeRef(api *design.APIDefinition, mt *design.MediaTypeDefinition, view string) string {
projected, _, err := mt.Project(view)
if err != nil {
panic(fmt.Sprintf("failed to project media type %#v: %s", mt.Identifier, err)) // bug
}
if _, ok := Definitions[projected.TypeName]; !ok {
GenerateMediaTypeDefinition(api, projected, "default")
}
ref := fmt.Sprintf("#/definitions/%s", projected.TypeName)
return ref
} | [
"func",
"MediaTypeRef",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"mt",
"*",
"design",
".",
"MediaTypeDefinition",
",",
"view",
"string",
")",
"string",
"{",
"projected",
",",
"_",
",",
"err",
":=",
"mt",
".",
"Project",
"(",
"view",
")",
"... | // MediaTypeRef produces the JSON reference to the media type definition with the given view. | [
"MediaTypeRef",
"produces",
"the",
"JSON",
"reference",
"to",
"the",
"media",
"type",
"definition",
"with",
"the",
"given",
"view",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L239-L249 |
166,911 | goadesign/goa | goagen/gen_schema/json_schema.go | TypeRef | func TypeRef(api *design.APIDefinition, ut *design.UserTypeDefinition) string {
if _, ok := Definitions[ut.TypeName]; !ok {
GenerateTypeDefinition(api, ut)
}
return fmt.Sprintf("#/definitions/%s", ut.TypeName)
} | go | func TypeRef(api *design.APIDefinition, ut *design.UserTypeDefinition) string {
if _, ok := Definitions[ut.TypeName]; !ok {
GenerateTypeDefinition(api, ut)
}
return fmt.Sprintf("#/definitions/%s", ut.TypeName)
} | [
"func",
"TypeRef",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"ut",
"*",
"design",
".",
"UserTypeDefinition",
")",
"string",
"{",
"if",
"_",
",",
"ok",
":=",
"Definitions",
"[",
"ut",
".",
"TypeName",
"]",
";",
"!",
"ok",
"{",
"GenerateTypeD... | // TypeRef produces the JSON reference to the type definition. | [
"TypeRef",
"produces",
"the",
"JSON",
"reference",
"to",
"the",
"type",
"definition",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L252-L257 |
166,912 | goadesign/goa | goagen/gen_schema/json_schema.go | GenerateMediaTypeDefinition | func GenerateMediaTypeDefinition(api *design.APIDefinition, mt *design.MediaTypeDefinition, view string) {
if _, ok := Definitions[mt.TypeName]; ok {
return
}
s := NewJSONSchema()
s.Title = fmt.Sprintf("Mediatype identifier: %s", mt.Identifier)
Definitions[mt.TypeName] = s
buildMediaTypeSchema(api, mt, view, s)
} | go | func GenerateMediaTypeDefinition(api *design.APIDefinition, mt *design.MediaTypeDefinition, view string) {
if _, ok := Definitions[mt.TypeName]; ok {
return
}
s := NewJSONSchema()
s.Title = fmt.Sprintf("Mediatype identifier: %s", mt.Identifier)
Definitions[mt.TypeName] = s
buildMediaTypeSchema(api, mt, view, s)
} | [
"func",
"GenerateMediaTypeDefinition",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"mt",
"*",
"design",
".",
"MediaTypeDefinition",
",",
"view",
"string",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"Definitions",
"[",
"mt",
".",
"TypeName",
"]",
";",
... | // GenerateMediaTypeDefinition produces the JSON schema corresponding to the given media type and
// given view. | [
"GenerateMediaTypeDefinition",
"produces",
"the",
"JSON",
"schema",
"corresponding",
"to",
"the",
"given",
"media",
"type",
"and",
"given",
"view",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L261-L269 |
166,913 | goadesign/goa | goagen/gen_schema/json_schema.go | GenerateTypeDefinition | func GenerateTypeDefinition(api *design.APIDefinition, ut *design.UserTypeDefinition) {
if _, ok := Definitions[ut.TypeName]; ok {
return
}
s := NewJSONSchema()
s.Title = ut.TypeName
Definitions[ut.TypeName] = s
buildAttributeSchema(api, s, ut.AttributeDefinition)
} | go | func GenerateTypeDefinition(api *design.APIDefinition, ut *design.UserTypeDefinition) {
if _, ok := Definitions[ut.TypeName]; ok {
return
}
s := NewJSONSchema()
s.Title = ut.TypeName
Definitions[ut.TypeName] = s
buildAttributeSchema(api, s, ut.AttributeDefinition)
} | [
"func",
"GenerateTypeDefinition",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"ut",
"*",
"design",
".",
"UserTypeDefinition",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"Definitions",
"[",
"ut",
".",
"TypeName",
"]",
";",
"ok",
"{",
"return",
"\n",
... | // GenerateTypeDefinition produces the JSON schema corresponding to the given type. | [
"GenerateTypeDefinition",
"produces",
"the",
"JSON",
"schema",
"corresponding",
"to",
"the",
"given",
"type",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L272-L280 |
166,914 | goadesign/goa | goagen/gen_schema/json_schema.go | TypeSchema | func TypeSchema(api *design.APIDefinition, t design.DataType) *JSONSchema {
s := NewJSONSchema()
switch actual := t.(type) {
case design.Primitive:
if name := actual.Name(); name != "any" {
s.Type = JSONType(actual.Name())
}
switch actual.Kind() {
case design.UUIDKind:
s.Format = "uuid"
case design.DateTimeKind:
s.Format = "date-time"
case design.NumberKind:
s.Format = "double"
case design.IntegerKind:
s.Format = "int64"
}
case *design.Array:
s.Type = JSONArray
s.Items = NewJSONSchema()
buildAttributeSchema(api, s.Items, actual.ElemType)
case design.Object:
s.Type = JSONObject
for n, at := range actual {
prop := NewJSONSchema()
buildAttributeSchema(api, prop, at)
s.Properties[n] = prop
}
case *design.Hash:
s.Type = JSONObject
s.AdditionalProperties = true
case *design.UserTypeDefinition:
s.Ref = TypeRef(api, actual)
case *design.MediaTypeDefinition:
// Use "default" view by default
s.Ref = MediaTypeRef(api, actual, design.DefaultView)
}
return s
} | go | func TypeSchema(api *design.APIDefinition, t design.DataType) *JSONSchema {
s := NewJSONSchema()
switch actual := t.(type) {
case design.Primitive:
if name := actual.Name(); name != "any" {
s.Type = JSONType(actual.Name())
}
switch actual.Kind() {
case design.UUIDKind:
s.Format = "uuid"
case design.DateTimeKind:
s.Format = "date-time"
case design.NumberKind:
s.Format = "double"
case design.IntegerKind:
s.Format = "int64"
}
case *design.Array:
s.Type = JSONArray
s.Items = NewJSONSchema()
buildAttributeSchema(api, s.Items, actual.ElemType)
case design.Object:
s.Type = JSONObject
for n, at := range actual {
prop := NewJSONSchema()
buildAttributeSchema(api, prop, at)
s.Properties[n] = prop
}
case *design.Hash:
s.Type = JSONObject
s.AdditionalProperties = true
case *design.UserTypeDefinition:
s.Ref = TypeRef(api, actual)
case *design.MediaTypeDefinition:
// Use "default" view by default
s.Ref = MediaTypeRef(api, actual, design.DefaultView)
}
return s
} | [
"func",
"TypeSchema",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"t",
"design",
".",
"DataType",
")",
"*",
"JSONSchema",
"{",
"s",
":=",
"NewJSONSchema",
"(",
")",
"\n",
"switch",
"actual",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
"d... | // TypeSchema produces the JSON schema corresponding to the given data type. | [
"TypeSchema",
"produces",
"the",
"JSON",
"schema",
"corresponding",
"to",
"the",
"given",
"data",
"type",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L283-L321 |
166,915 | goadesign/goa | goagen/gen_schema/json_schema.go | Merge | func (s *JSONSchema) Merge(other *JSONSchema) {
items := s.createMergeItems(other)
for _, v := range items {
if v.needed && v.b != nil {
reflect.Indirect(reflect.ValueOf(v.a)).Set(reflect.ValueOf(v.b))
}
}
for n, p := range other.Properties {
if _, ok := s.Properties[n]; !ok {
if s.Properties == nil {
s.Properties = make(map[string]*JSONSchema)
}
s.Properties[n] = p
}
}
for n, d := range other.Definitions {
if _, ok := s.Definitions[n]; !ok {
s.Definitions[n] = d
}
}
for _, l := range other.Links {
s.Links = append(s.Links, l)
}
for _, r := range other.Required {
s.Required = append(s.Required, r)
}
} | go | func (s *JSONSchema) Merge(other *JSONSchema) {
items := s.createMergeItems(other)
for _, v := range items {
if v.needed && v.b != nil {
reflect.Indirect(reflect.ValueOf(v.a)).Set(reflect.ValueOf(v.b))
}
}
for n, p := range other.Properties {
if _, ok := s.Properties[n]; !ok {
if s.Properties == nil {
s.Properties = make(map[string]*JSONSchema)
}
s.Properties[n] = p
}
}
for n, d := range other.Definitions {
if _, ok := s.Definitions[n]; !ok {
s.Definitions[n] = d
}
}
for _, l := range other.Links {
s.Links = append(s.Links, l)
}
for _, r := range other.Required {
s.Required = append(s.Required, r)
}
} | [
"func",
"(",
"s",
"*",
"JSONSchema",
")",
"Merge",
"(",
"other",
"*",
"JSONSchema",
")",
"{",
"items",
":=",
"s",
".",
"createMergeItems",
"(",
"other",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"items",
"{",
"if",
"v",
".",
"needed",
"&&",
... | // Merge does a two level deep merge of other into s. | [
"Merge",
"does",
"a",
"two",
"level",
"deep",
"merge",
"of",
"other",
"into",
"s",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L375-L405 |
166,916 | goadesign/goa | goagen/gen_schema/json_schema.go | Dup | func (s *JSONSchema) Dup() *JSONSchema {
js := JSONSchema{
ID: s.ID,
Description: s.Description,
Schema: s.Schema,
Type: s.Type,
DefaultValue: s.DefaultValue,
Title: s.Title,
Media: s.Media,
ReadOnly: s.ReadOnly,
PathStart: s.PathStart,
Links: s.Links,
Ref: s.Ref,
Enum: s.Enum,
Format: s.Format,
Pattern: s.Pattern,
Minimum: s.Minimum,
Maximum: s.Maximum,
MinLength: s.MinLength,
MaxLength: s.MaxLength,
MinItems: s.MinItems,
MaxItems: s.MaxItems,
Required: s.Required,
AdditionalProperties: s.AdditionalProperties,
}
for n, p := range s.Properties {
js.Properties[n] = p.Dup()
}
if s.Items != nil {
js.Items = s.Items.Dup()
}
for n, d := range s.Definitions {
js.Definitions[n] = d.Dup()
}
return &js
} | go | func (s *JSONSchema) Dup() *JSONSchema {
js := JSONSchema{
ID: s.ID,
Description: s.Description,
Schema: s.Schema,
Type: s.Type,
DefaultValue: s.DefaultValue,
Title: s.Title,
Media: s.Media,
ReadOnly: s.ReadOnly,
PathStart: s.PathStart,
Links: s.Links,
Ref: s.Ref,
Enum: s.Enum,
Format: s.Format,
Pattern: s.Pattern,
Minimum: s.Minimum,
Maximum: s.Maximum,
MinLength: s.MinLength,
MaxLength: s.MaxLength,
MinItems: s.MinItems,
MaxItems: s.MaxItems,
Required: s.Required,
AdditionalProperties: s.AdditionalProperties,
}
for n, p := range s.Properties {
js.Properties[n] = p.Dup()
}
if s.Items != nil {
js.Items = s.Items.Dup()
}
for n, d := range s.Definitions {
js.Definitions[n] = d.Dup()
}
return &js
} | [
"func",
"(",
"s",
"*",
"JSONSchema",
")",
"Dup",
"(",
")",
"*",
"JSONSchema",
"{",
"js",
":=",
"JSONSchema",
"{",
"ID",
":",
"s",
".",
"ID",
",",
"Description",
":",
"s",
".",
"Description",
",",
"Schema",
":",
"s",
".",
"Schema",
",",
"Type",
":... | // Dup creates a shallow clone of the given schema. | [
"Dup",
"creates",
"a",
"shallow",
"clone",
"of",
"the",
"given",
"schema",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L408-L443 |
166,917 | goadesign/goa | goagen/gen_schema/json_schema.go | buildAttributeSchema | func buildAttributeSchema(api *design.APIDefinition, s *JSONSchema, at *design.AttributeDefinition) *JSONSchema {
if at.View != "" {
inner := NewJSONSchema()
inner.Ref = MediaTypeRef(api, at.Type.(*design.MediaTypeDefinition), at.View)
s.Merge(inner)
return s
}
s.Merge(TypeSchema(api, at.Type))
if s.Ref != "" {
// Ref is exclusive with other fields
return s
}
s.DefaultValue = toStringMap(at.DefaultValue)
s.Description = at.Description
s.Example = at.GenerateExample(api.RandomGenerator(), nil)
s.ReadOnly = at.IsReadOnly()
val := at.Validation
if val == nil {
return s
}
s.Enum = val.Values
s.Format = val.Format
s.Pattern = val.Pattern
if val.Minimum != nil {
s.Minimum = val.Minimum
}
if val.Maximum != nil {
s.Maximum = val.Maximum
}
if val.MinLength != nil {
switch {
case at.Type.IsArray():
s.MinItems = val.MinLength
default:
s.MinLength = val.MinLength
}
}
if val.MaxLength != nil {
switch {
case at.Type.IsArray():
s.MaxItems = val.MaxLength
default:
s.MaxLength = val.MaxLength
}
}
s.Required = val.Required
return s
} | go | func buildAttributeSchema(api *design.APIDefinition, s *JSONSchema, at *design.AttributeDefinition) *JSONSchema {
if at.View != "" {
inner := NewJSONSchema()
inner.Ref = MediaTypeRef(api, at.Type.(*design.MediaTypeDefinition), at.View)
s.Merge(inner)
return s
}
s.Merge(TypeSchema(api, at.Type))
if s.Ref != "" {
// Ref is exclusive with other fields
return s
}
s.DefaultValue = toStringMap(at.DefaultValue)
s.Description = at.Description
s.Example = at.GenerateExample(api.RandomGenerator(), nil)
s.ReadOnly = at.IsReadOnly()
val := at.Validation
if val == nil {
return s
}
s.Enum = val.Values
s.Format = val.Format
s.Pattern = val.Pattern
if val.Minimum != nil {
s.Minimum = val.Minimum
}
if val.Maximum != nil {
s.Maximum = val.Maximum
}
if val.MinLength != nil {
switch {
case at.Type.IsArray():
s.MinItems = val.MinLength
default:
s.MinLength = val.MinLength
}
}
if val.MaxLength != nil {
switch {
case at.Type.IsArray():
s.MaxItems = val.MaxLength
default:
s.MaxLength = val.MaxLength
}
}
s.Required = val.Required
return s
} | [
"func",
"buildAttributeSchema",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"s",
"*",
"JSONSchema",
",",
"at",
"*",
"design",
".",
"AttributeDefinition",
")",
"*",
"JSONSchema",
"{",
"if",
"at",
".",
"View",
"!=",
"\"",
"\"",
"{",
"inner",
":="... | // buildAttributeSchema initializes the given JSON schema that corresponds to the given attribute. | [
"buildAttributeSchema",
"initializes",
"the",
"given",
"JSON",
"schema",
"that",
"corresponds",
"to",
"the",
"given",
"attribute",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L446-L493 |
166,918 | goadesign/goa | goagen/gen_schema/json_schema.go | toSchemaHref | func toSchemaHref(api *design.APIDefinition, r *design.RouteDefinition) string {
params := r.Params()
args := make([]interface{}, len(params))
for i, p := range params {
args[i] = fmt.Sprintf("/{%s}", p)
}
tmpl := design.WildcardRegex.ReplaceAllLiteralString(r.FullPath(), "%s")
return fmt.Sprintf(tmpl, args...)
} | go | func toSchemaHref(api *design.APIDefinition, r *design.RouteDefinition) string {
params := r.Params()
args := make([]interface{}, len(params))
for i, p := range params {
args[i] = fmt.Sprintf("/{%s}", p)
}
tmpl := design.WildcardRegex.ReplaceAllLiteralString(r.FullPath(), "%s")
return fmt.Sprintf(tmpl, args...)
} | [
"func",
"toSchemaHref",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"r",
"*",
"design",
".",
"RouteDefinition",
")",
"string",
"{",
"params",
":=",
"r",
".",
"Params",
"(",
")",
"\n",
"args",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"... | // toSchemaHref produces a href that replaces the path wildcards with JSON schema references when
// appropriate. | [
"toSchemaHref",
"produces",
"a",
"href",
"that",
"replaces",
"the",
"path",
"wildcards",
"with",
"JSON",
"schema",
"references",
"when",
"appropriate",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L533-L541 |
166,919 | goadesign/goa | goagen/gen_schema/json_schema.go | propertiesFromDefs | func propertiesFromDefs(definitions map[string]*JSONSchema, path string) map[string]*JSONSchema {
res := make(map[string]*JSONSchema, len(definitions))
for n := range definitions {
if n == "identity" {
continue
}
s := NewJSONSchema()
s.Ref = path + n
res[n] = s
}
return res
} | go | func propertiesFromDefs(definitions map[string]*JSONSchema, path string) map[string]*JSONSchema {
res := make(map[string]*JSONSchema, len(definitions))
for n := range definitions {
if n == "identity" {
continue
}
s := NewJSONSchema()
s.Ref = path + n
res[n] = s
}
return res
} | [
"func",
"propertiesFromDefs",
"(",
"definitions",
"map",
"[",
"string",
"]",
"*",
"JSONSchema",
",",
"path",
"string",
")",
"map",
"[",
"string",
"]",
"*",
"JSONSchema",
"{",
"res",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"JSONSchema",
",",
... | // propertiesFromDefs creates a Properties map referencing the given definitions under the given
// path. | [
"propertiesFromDefs",
"creates",
"a",
"Properties",
"map",
"referencing",
"the",
"given",
"definitions",
"under",
"the",
"given",
"path",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L545-L556 |
166,920 | goadesign/goa | goagen/gen_schema/json_schema.go | buildMediaTypeSchema | func buildMediaTypeSchema(api *design.APIDefinition, mt *design.MediaTypeDefinition, view string, s *JSONSchema) {
s.Media = &JSONMedia{Type: mt.Identifier}
projected, linksUT, err := mt.Project(view)
if err != nil {
panic(fmt.Sprintf("failed to project media type %#v: %s", mt.Identifier, err)) // bug
}
if linksUT != nil {
links := linksUT.Type.ToObject()
lnames := make([]string, len(links))
i := 0
for n := range links {
lnames[i] = n
i++
}
sort.Strings(lnames)
for _, ln := range lnames {
var (
att = links[ln]
lmt = att.Type.(*design.MediaTypeDefinition)
r = lmt.Resource
href string
)
if r != nil {
href = toSchemaHref(api, r.CanonicalAction().Routes[0])
}
sm := NewJSONSchema()
sm.Ref = MediaTypeRef(api, lmt, "default")
s.Links = append(s.Links, &JSONLink{
Title: ln,
Rel: ln,
Description: att.Description,
Href: href,
Method: "GET",
TargetSchema: sm,
MediaType: lmt.Identifier,
})
}
}
buildAttributeSchema(api, s, projected.AttributeDefinition)
} | go | func buildMediaTypeSchema(api *design.APIDefinition, mt *design.MediaTypeDefinition, view string, s *JSONSchema) {
s.Media = &JSONMedia{Type: mt.Identifier}
projected, linksUT, err := mt.Project(view)
if err != nil {
panic(fmt.Sprintf("failed to project media type %#v: %s", mt.Identifier, err)) // bug
}
if linksUT != nil {
links := linksUT.Type.ToObject()
lnames := make([]string, len(links))
i := 0
for n := range links {
lnames[i] = n
i++
}
sort.Strings(lnames)
for _, ln := range lnames {
var (
att = links[ln]
lmt = att.Type.(*design.MediaTypeDefinition)
r = lmt.Resource
href string
)
if r != nil {
href = toSchemaHref(api, r.CanonicalAction().Routes[0])
}
sm := NewJSONSchema()
sm.Ref = MediaTypeRef(api, lmt, "default")
s.Links = append(s.Links, &JSONLink{
Title: ln,
Rel: ln,
Description: att.Description,
Href: href,
Method: "GET",
TargetSchema: sm,
MediaType: lmt.Identifier,
})
}
}
buildAttributeSchema(api, s, projected.AttributeDefinition)
} | [
"func",
"buildMediaTypeSchema",
"(",
"api",
"*",
"design",
".",
"APIDefinition",
",",
"mt",
"*",
"design",
".",
"MediaTypeDefinition",
",",
"view",
"string",
",",
"s",
"*",
"JSONSchema",
")",
"{",
"s",
".",
"Media",
"=",
"&",
"JSONMedia",
"{",
"Type",
":... | // buildMediaTypeSchema initializes s as the JSON schema representing mt for the given view. | [
"buildMediaTypeSchema",
"initializes",
"s",
"as",
"the",
"JSON",
"schema",
"representing",
"mt",
"for",
"the",
"given",
"view",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/gen_schema/json_schema.go#L559-L598 |
166,921 | goadesign/goa | encoding.go | Decode | func (decoder *HTTPDecoder) Decode(v interface{}, body io.Reader, contentType string) error {
now := time.Now()
defer MeasureSince([]string{"goa", "decode", contentType}, now)
var p *decoderPool
if contentType == "" {
// Default to JSON
contentType = "application/json"
} else {
if mediaType, _, err := mime.ParseMediaType(contentType); err == nil {
contentType = mediaType
}
}
p = decoder.pools[contentType]
if p == nil {
p = decoder.pools["*/*"]
}
if p == nil {
return nil
}
// the decoderPool will handle whether or not a pool is actually in use
d := p.Get(body)
defer p.Put(d)
return d.Decode(v)
} | go | func (decoder *HTTPDecoder) Decode(v interface{}, body io.Reader, contentType string) error {
now := time.Now()
defer MeasureSince([]string{"goa", "decode", contentType}, now)
var p *decoderPool
if contentType == "" {
// Default to JSON
contentType = "application/json"
} else {
if mediaType, _, err := mime.ParseMediaType(contentType); err == nil {
contentType = mediaType
}
}
p = decoder.pools[contentType]
if p == nil {
p = decoder.pools["*/*"]
}
if p == nil {
return nil
}
// the decoderPool will handle whether or not a pool is actually in use
d := p.Get(body)
defer p.Put(d)
return d.Decode(v)
} | [
"func",
"(",
"decoder",
"*",
"HTTPDecoder",
")",
"Decode",
"(",
"v",
"interface",
"{",
"}",
",",
"body",
"io",
".",
"Reader",
",",
"contentType",
"string",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"defer",
"MeasureSince",
"... | // Decode uses registered Decoders to unmarshal a body based on the contentType. | [
"Decode",
"uses",
"registered",
"Decoders",
"to",
"unmarshal",
"a",
"body",
"based",
"on",
"the",
"contentType",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L106-L130 |
166,922 | goadesign/goa | encoding.go | Register | func (decoder *HTTPDecoder) Register(f DecoderFunc, contentTypes ...string) {
p := newDecodePool(f)
for _, contentType := range contentTypes {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
mediaType = contentType
}
decoder.pools[mediaType] = p
}
} | go | func (decoder *HTTPDecoder) Register(f DecoderFunc, contentTypes ...string) {
p := newDecodePool(f)
for _, contentType := range contentTypes {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
mediaType = contentType
}
decoder.pools[mediaType] = p
}
} | [
"func",
"(",
"decoder",
"*",
"HTTPDecoder",
")",
"Register",
"(",
"f",
"DecoderFunc",
",",
"contentTypes",
"...",
"string",
")",
"{",
"p",
":=",
"newDecodePool",
"(",
"f",
")",
"\n\n",
"for",
"_",
",",
"contentType",
":=",
"range",
"contentTypes",
"{",
"... | // Register sets a specific decoder to be used for the specified content types. If a decoder is
// already registered, it is overwritten. | [
"Register",
"sets",
"a",
"specific",
"decoder",
"to",
"be",
"used",
"for",
"the",
"specified",
"content",
"types",
".",
"If",
"a",
"decoder",
"is",
"already",
"registered",
"it",
"is",
"overwritten",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L134-L144 |
166,923 | goadesign/goa | encoding.go | newDecodePool | func newDecodePool(f DecoderFunc) *decoderPool {
// get a new decoder and type assert to see if it can be reset
d := f(nil)
rd, ok := d.(ResettableDecoder)
p := &decoderPool{fn: f}
// if the decoder can be reset, create a pool and put the typed decoder in
if ok {
p.pool = &sync.Pool{
New: func() interface{} { return f(nil) },
}
p.pool.Put(rd)
}
return p
} | go | func newDecodePool(f DecoderFunc) *decoderPool {
// get a new decoder and type assert to see if it can be reset
d := f(nil)
rd, ok := d.(ResettableDecoder)
p := &decoderPool{fn: f}
// if the decoder can be reset, create a pool and put the typed decoder in
if ok {
p.pool = &sync.Pool{
New: func() interface{} { return f(nil) },
}
p.pool.Put(rd)
}
return p
} | [
"func",
"newDecodePool",
"(",
"f",
"DecoderFunc",
")",
"*",
"decoderPool",
"{",
"// get a new decoder and type assert to see if it can be reset",
"d",
":=",
"f",
"(",
"nil",
")",
"\n",
"rd",
",",
"ok",
":=",
"d",
".",
"(",
"ResettableDecoder",
")",
"\n\n",
"p",
... | // newDecodePool checks to see if the DecoderFunc returns reusable decoders and if so, creates a
// pool. | [
"newDecodePool",
"checks",
"to",
"see",
"if",
"the",
"DecoderFunc",
"returns",
"reusable",
"decoders",
"and",
"if",
"so",
"creates",
"a",
"pool",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L148-L164 |
166,924 | goadesign/goa | encoding.go | Get | func (p *decoderPool) Get(r io.Reader) Decoder {
if p.pool == nil {
return p.fn(r)
}
d := p.pool.Get().(ResettableDecoder)
d.Reset(r)
return d
} | go | func (p *decoderPool) Get(r io.Reader) Decoder {
if p.pool == nil {
return p.fn(r)
}
d := p.pool.Get().(ResettableDecoder)
d.Reset(r)
return d
} | [
"func",
"(",
"p",
"*",
"decoderPool",
")",
"Get",
"(",
"r",
"io",
".",
"Reader",
")",
"Decoder",
"{",
"if",
"p",
".",
"pool",
"==",
"nil",
"{",
"return",
"p",
".",
"fn",
"(",
"r",
")",
"\n",
"}",
"\n\n",
"d",
":=",
"p",
".",
"pool",
".",
"G... | // Get returns an already reset Decoder from the pool or creates a new one if necessary. | [
"Get",
"returns",
"an",
"already",
"reset",
"Decoder",
"from",
"the",
"pool",
"or",
"creates",
"a",
"new",
"one",
"if",
"necessary",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L167-L175 |
166,925 | goadesign/goa | encoding.go | Encode | func (encoder *HTTPEncoder) Encode(v interface{}, resp io.Writer, accept string) error {
now := time.Now()
if accept == "" {
accept = "*/*"
}
var contentType string
for _, t := range encoder.contentTypes {
if accept == "*/*" || accept == t {
contentType = accept
break
}
}
defer MeasureSince([]string{"goa", "encode", contentType}, now)
p := encoder.pools[contentType]
if p == nil && contentType != "*/*" {
p = encoder.pools["*/*"]
}
if p == nil {
return fmt.Errorf("No encoder registered for %s and no default encoder", contentType)
}
// the encoderPool will handle whether or not a pool is actually in use
e := p.Get(resp)
if err := e.Encode(v); err != nil {
return err
}
p.Put(e)
return nil
} | go | func (encoder *HTTPEncoder) Encode(v interface{}, resp io.Writer, accept string) error {
now := time.Now()
if accept == "" {
accept = "*/*"
}
var contentType string
for _, t := range encoder.contentTypes {
if accept == "*/*" || accept == t {
contentType = accept
break
}
}
defer MeasureSince([]string{"goa", "encode", contentType}, now)
p := encoder.pools[contentType]
if p == nil && contentType != "*/*" {
p = encoder.pools["*/*"]
}
if p == nil {
return fmt.Errorf("No encoder registered for %s and no default encoder", contentType)
}
// the encoderPool will handle whether or not a pool is actually in use
e := p.Get(resp)
if err := e.Encode(v); err != nil {
return err
}
p.Put(e)
return nil
} | [
"func",
"(",
"encoder",
"*",
"HTTPEncoder",
")",
"Encode",
"(",
"v",
"interface",
"{",
"}",
",",
"resp",
"io",
".",
"Writer",
",",
"accept",
"string",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"if",
"accept",
"==",
"\"",
... | // Encode uses the registered encoders and given content type to marshal and write the given value
// using the given writer. | [
"Encode",
"uses",
"the",
"registered",
"encoders",
"and",
"given",
"content",
"type",
"to",
"marshal",
"and",
"write",
"the",
"given",
"value",
"using",
"the",
"given",
"writer",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L187-L216 |
166,926 | goadesign/goa | encoding.go | Register | func (encoder *HTTPEncoder) Register(f EncoderFunc, contentTypes ...string) {
p := newEncodePool(f)
for _, contentType := range contentTypes {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
mediaType = contentType
}
encoder.pools[mediaType] = p
}
// Rebuild a unique index of registered content encoders to be used in EncodeResponse
encoder.contentTypes = make([]string, 0, len(encoder.pools))
for contentType := range encoder.pools {
encoder.contentTypes = append(encoder.contentTypes, contentType)
}
} | go | func (encoder *HTTPEncoder) Register(f EncoderFunc, contentTypes ...string) {
p := newEncodePool(f)
for _, contentType := range contentTypes {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
mediaType = contentType
}
encoder.pools[mediaType] = p
}
// Rebuild a unique index of registered content encoders to be used in EncodeResponse
encoder.contentTypes = make([]string, 0, len(encoder.pools))
for contentType := range encoder.pools {
encoder.contentTypes = append(encoder.contentTypes, contentType)
}
} | [
"func",
"(",
"encoder",
"*",
"HTTPEncoder",
")",
"Register",
"(",
"f",
"EncoderFunc",
",",
"contentTypes",
"...",
"string",
")",
"{",
"p",
":=",
"newEncodePool",
"(",
"f",
")",
"\n",
"for",
"_",
",",
"contentType",
":=",
"range",
"contentTypes",
"{",
"me... | // Register sets a specific encoder to be used for the specified content types. If an encoder is
// already registered, it is overwritten. | [
"Register",
"sets",
"a",
"specific",
"encoder",
"to",
"be",
"used",
"for",
"the",
"specified",
"content",
"types",
".",
"If",
"an",
"encoder",
"is",
"already",
"registered",
"it",
"is",
"overwritten",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L220-L235 |
166,927 | goadesign/goa | encoding.go | newEncodePool | func newEncodePool(f EncoderFunc) *encoderPool {
// get a new encoder and type assert to see if it can be reset
e := f(nil)
re, ok := e.(ResettableEncoder)
p := &encoderPool{fn: f}
// if the encoder can be reset, create a pool and put the typed encoder in
if ok {
p.pool = &sync.Pool{
New: func() interface{} { return f(nil) },
}
p.pool.Put(re)
}
return p
} | go | func newEncodePool(f EncoderFunc) *encoderPool {
// get a new encoder and type assert to see if it can be reset
e := f(nil)
re, ok := e.(ResettableEncoder)
p := &encoderPool{fn: f}
// if the encoder can be reset, create a pool and put the typed encoder in
if ok {
p.pool = &sync.Pool{
New: func() interface{} { return f(nil) },
}
p.pool.Put(re)
}
return p
} | [
"func",
"newEncodePool",
"(",
"f",
"EncoderFunc",
")",
"*",
"encoderPool",
"{",
"// get a new encoder and type assert to see if it can be reset",
"e",
":=",
"f",
"(",
"nil",
")",
"\n",
"re",
",",
"ok",
":=",
"e",
".",
"(",
"ResettableEncoder",
")",
"\n\n",
"p",
... | // newEncodePool checks to see if the EncoderFactory returns reusable encoders and if so, creates
// a pool. | [
"newEncodePool",
"checks",
"to",
"see",
"if",
"the",
"EncoderFactory",
"returns",
"reusable",
"encoders",
"and",
"if",
"so",
"creates",
"a",
"pool",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L239-L255 |
166,928 | goadesign/goa | encoding.go | Get | func (p *encoderPool) Get(w io.Writer) Encoder {
if p.pool == nil {
return p.fn(w)
}
e := p.pool.Get().(ResettableEncoder)
e.Reset(w)
return e
} | go | func (p *encoderPool) Get(w io.Writer) Encoder {
if p.pool == nil {
return p.fn(w)
}
e := p.pool.Get().(ResettableEncoder)
e.Reset(w)
return e
} | [
"func",
"(",
"p",
"*",
"encoderPool",
")",
"Get",
"(",
"w",
"io",
".",
"Writer",
")",
"Encoder",
"{",
"if",
"p",
".",
"pool",
"==",
"nil",
"{",
"return",
"p",
".",
"fn",
"(",
"w",
")",
"\n",
"}",
"\n\n",
"e",
":=",
"p",
".",
"pool",
".",
"G... | // Get returns an already reset Encoder from the pool or creates a new one if necessary. | [
"Get",
"returns",
"an",
"already",
"reset",
"Encoder",
"from",
"the",
"pool",
"or",
"creates",
"a",
"new",
"one",
"if",
"necessary",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding.go#L258-L266 |
166,929 | goadesign/goa | design/security.go | Validate | func (s *SecuritySchemeDefinition) Validate() error {
_, err := url.Parse(s.TokenURL)
if err != nil {
return fmt.Errorf("invalid token URL %#v: %s", s.TokenURL, err)
}
_, err = url.Parse(s.AuthorizationURL)
if err != nil {
return fmt.Errorf("invalid authorization URL %#v: %s", s.AuthorizationURL, err)
}
return nil
} | go | func (s *SecuritySchemeDefinition) Validate() error {
_, err := url.Parse(s.TokenURL)
if err != nil {
return fmt.Errorf("invalid token URL %#v: %s", s.TokenURL, err)
}
_, err = url.Parse(s.AuthorizationURL)
if err != nil {
return fmt.Errorf("invalid authorization URL %#v: %s", s.AuthorizationURL, err)
}
return nil
} | [
"func",
"(",
"s",
"*",
"SecuritySchemeDefinition",
")",
"Validate",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"s",
".",
"TokenURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
... | // Validate ensures that TokenURL and AuthorizationURL are valid URLs. | [
"Validate",
"ensures",
"that",
"TokenURL",
"and",
"AuthorizationURL",
"are",
"valid",
"URLs",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/security.go#L98-L108 |
166,930 | goadesign/goa | design/security.go | Finalize | func (s *SecuritySchemeDefinition) Finalize() {
tu, _ := url.Parse(s.TokenURL) // validated in Validate
au, _ := url.Parse(s.AuthorizationURL) // validated in Validate
tokenOK := s.TokenURL == "" || tu.IsAbs()
authOK := s.AuthorizationURL == "" || au.IsAbs()
if tokenOK && authOK {
return
}
var scheme string
if len(Design.Schemes) > 0 {
scheme = Design.Schemes[0]
}
if !tokenOK {
tu.Scheme = scheme
tu.Host = Design.Host
s.TokenURL = tu.String()
}
if !authOK {
au.Scheme = scheme
au.Host = Design.Host
s.AuthorizationURL = au.String()
}
} | go | func (s *SecuritySchemeDefinition) Finalize() {
tu, _ := url.Parse(s.TokenURL) // validated in Validate
au, _ := url.Parse(s.AuthorizationURL) // validated in Validate
tokenOK := s.TokenURL == "" || tu.IsAbs()
authOK := s.AuthorizationURL == "" || au.IsAbs()
if tokenOK && authOK {
return
}
var scheme string
if len(Design.Schemes) > 0 {
scheme = Design.Schemes[0]
}
if !tokenOK {
tu.Scheme = scheme
tu.Host = Design.Host
s.TokenURL = tu.String()
}
if !authOK {
au.Scheme = scheme
au.Host = Design.Host
s.AuthorizationURL = au.String()
}
} | [
"func",
"(",
"s",
"*",
"SecuritySchemeDefinition",
")",
"Finalize",
"(",
")",
"{",
"tu",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"s",
".",
"TokenURL",
")",
"// validated in Validate",
"\n",
"au",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"s",
".",
... | // Finalize makes the TokenURL and AuthorizationURL complete if needed. | [
"Finalize",
"makes",
"the",
"TokenURL",
"and",
"AuthorizationURL",
"complete",
"if",
"needed",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/security.go#L111-L133 |
166,931 | goadesign/goa | encoding/cbor/encoding.go | NewDecoder | func NewDecoder(r io.Reader) goa.Decoder {
return codec.NewDecoder(r, &Handle)
} | go | func NewDecoder(r io.Reader) goa.Decoder {
return codec.NewDecoder(r, &Handle)
} | [
"func",
"NewDecoder",
"(",
"r",
"io",
".",
"Reader",
")",
"goa",
".",
"Decoder",
"{",
"return",
"codec",
".",
"NewDecoder",
"(",
"r",
",",
"&",
"Handle",
")",
"\n",
"}"
] | // NewDecoder returns a cbor decoder. | [
"NewDecoder",
"returns",
"a",
"cbor",
"decoder",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/cbor/encoding.go#L20-L22 |
166,932 | goadesign/goa | encoding/cbor/encoding.go | NewEncoder | func NewEncoder(w io.Writer) goa.Encoder {
return codec.NewEncoder(w, &Handle)
} | go | func NewEncoder(w io.Writer) goa.Encoder {
return codec.NewEncoder(w, &Handle)
} | [
"func",
"NewEncoder",
"(",
"w",
"io",
".",
"Writer",
")",
"goa",
".",
"Encoder",
"{",
"return",
"codec",
".",
"NewEncoder",
"(",
"w",
",",
"&",
"Handle",
")",
"\n",
"}"
] | // NewEncoder returns a cbor encoder. | [
"NewEncoder",
"returns",
"a",
"cbor",
"encoder",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/cbor/encoding.go#L25-L27 |
166,933 | goadesign/goa | client/signers.go | Sign | func (s *BasicSigner) Sign(req *http.Request) error {
if s.Username != "" && s.Password != "" {
req.SetBasicAuth(s.Username, s.Password)
}
return nil
} | go | func (s *BasicSigner) Sign(req *http.Request) error {
if s.Username != "" && s.Password != "" {
req.SetBasicAuth(s.Username, s.Password)
}
return nil
} | [
"func",
"(",
"s",
"*",
"BasicSigner",
")",
"Sign",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"if",
"s",
".",
"Username",
"!=",
"\"",
"\"",
"&&",
"s",
".",
"Password",
"!=",
"\"",
"\"",
"{",
"req",
".",
"SetBasicAuth",
"(",
"s",
... | // Sign adds the basic auth header to the request. | [
"Sign",
"adds",
"the",
"basic",
"auth",
"header",
"to",
"the",
"request",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/signers.go#L85-L90 |
166,934 | goadesign/goa | client/signers.go | Sign | func (s *APIKeySigner) Sign(req *http.Request) error {
if s.KeyName == "" {
s.KeyName = "Authorization"
}
if s.Format == "" {
s.Format = "Bearer %s"
}
name := s.KeyName
format := s.Format
val := fmt.Sprintf(format, s.KeyValue)
if s.SignQuery && val != "" {
query := req.URL.Query()
query.Set(name, val)
req.URL.RawQuery = query.Encode()
} else {
req.Header.Set(name, val)
}
return nil
} | go | func (s *APIKeySigner) Sign(req *http.Request) error {
if s.KeyName == "" {
s.KeyName = "Authorization"
}
if s.Format == "" {
s.Format = "Bearer %s"
}
name := s.KeyName
format := s.Format
val := fmt.Sprintf(format, s.KeyValue)
if s.SignQuery && val != "" {
query := req.URL.Query()
query.Set(name, val)
req.URL.RawQuery = query.Encode()
} else {
req.Header.Set(name, val)
}
return nil
} | [
"func",
"(",
"s",
"*",
"APIKeySigner",
")",
"Sign",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"if",
"s",
".",
"KeyName",
"==",
"\"",
"\"",
"{",
"s",
".",
"KeyName",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"s",
".",
"Format",
... | // Sign adds the API key header to the request. | [
"Sign",
"adds",
"the",
"API",
"key",
"header",
"to",
"the",
"request",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/signers.go#L93-L111 |
166,935 | goadesign/goa | client/signers.go | Sign | func (s *JWTSigner) Sign(req *http.Request) error {
return signFromSource(s.TokenSource, req)
} | go | func (s *JWTSigner) Sign(req *http.Request) error {
return signFromSource(s.TokenSource, req)
} | [
"func",
"(",
"s",
"*",
"JWTSigner",
")",
"Sign",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"return",
"signFromSource",
"(",
"s",
".",
"TokenSource",
",",
"req",
")",
"\n",
"}"
] | // Sign adds the JWT auth header. | [
"Sign",
"adds",
"the",
"JWT",
"auth",
"header",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/signers.go#L114-L116 |
166,936 | goadesign/goa | client/signers.go | signFromSource | func signFromSource(source TokenSource, req *http.Request) error {
token, err := source.Token()
if err != nil {
return err
}
if !token.Valid() {
return fmt.Errorf("token expired or invalid")
}
token.SetAuthHeader(req)
return nil
} | go | func signFromSource(source TokenSource, req *http.Request) error {
token, err := source.Token()
if err != nil {
return err
}
if !token.Valid() {
return fmt.Errorf("token expired or invalid")
}
token.SetAuthHeader(req)
return nil
} | [
"func",
"signFromSource",
"(",
"source",
"TokenSource",
",",
"req",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"token",
",",
"err",
":=",
"source",
".",
"Token",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
... | // signFromSource generates a token using the given source and uses it to sign the request. | [
"signFromSource",
"generates",
"a",
"token",
"using",
"the",
"given",
"source",
"and",
"uses",
"it",
"to",
"sign",
"the",
"request",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/signers.go#L124-L134 |
166,937 | goadesign/goa | client/signers.go | SetAuthHeader | func (t *StaticToken) SetAuthHeader(r *http.Request) {
typ := t.Type
if typ == "" {
typ = "Bearer"
}
r.Header.Set("Authorization", typ+" "+t.Value)
} | go | func (t *StaticToken) SetAuthHeader(r *http.Request) {
typ := t.Type
if typ == "" {
typ = "Bearer"
}
r.Header.Set("Authorization", typ+" "+t.Value)
} | [
"func",
"(",
"t",
"*",
"StaticToken",
")",
"SetAuthHeader",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"typ",
":=",
"t",
".",
"Type",
"\n",
"if",
"typ",
"==",
"\"",
"\"",
"{",
"typ",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"r",
".",
"Header",
... | // SetAuthHeader sets the Authorization header to r. | [
"SetAuthHeader",
"sets",
"the",
"Authorization",
"header",
"to",
"r",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/signers.go#L142-L148 |
166,938 | goadesign/goa | goagen/codegen/types.go | init | func init() {
var err error
fn := template.FuncMap{
"tabs": Tabs,
"add": func(a, b int) int { return a + b },
"goify": Goify,
"gotyperef": GoTypeRef,
"gotypename": GoTypeName,
"transformAttribute": transformAttribute,
"transformArray": transformArray,
"transformHash": transformHash,
"transformObject": transformObject,
"typeName": typeName,
}
if transformT, err = template.New("transform").Funcs(fn).Parse(transformTmpl); err != nil {
panic(err) // bug
}
if transformArrayT, err = template.New("transformArray").Funcs(fn).Parse(transformArrayTmpl); err != nil {
panic(err) // bug
}
if transformHashT, err = template.New("transformHash").Funcs(fn).Parse(transformHashTmpl); err != nil {
panic(err) // bug
}
if transformObjectT, err = template.New("transformObject").Funcs(fn).Parse(transformObjectTmpl); err != nil {
panic(err) // bug
}
} | go | func init() {
var err error
fn := template.FuncMap{
"tabs": Tabs,
"add": func(a, b int) int { return a + b },
"goify": Goify,
"gotyperef": GoTypeRef,
"gotypename": GoTypeName,
"transformAttribute": transformAttribute,
"transformArray": transformArray,
"transformHash": transformHash,
"transformObject": transformObject,
"typeName": typeName,
}
if transformT, err = template.New("transform").Funcs(fn).Parse(transformTmpl); err != nil {
panic(err) // bug
}
if transformArrayT, err = template.New("transformArray").Funcs(fn).Parse(transformArrayTmpl); err != nil {
panic(err) // bug
}
if transformHashT, err = template.New("transformHash").Funcs(fn).Parse(transformHashTmpl); err != nil {
panic(err) // bug
}
if transformObjectT, err = template.New("transformObject").Funcs(fn).Parse(transformObjectTmpl); err != nil {
panic(err) // bug
}
} | [
"func",
"init",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"fn",
":=",
"template",
".",
"FuncMap",
"{",
"\"",
"\"",
":",
"Tabs",
",",
"\"",
"\"",
":",
"func",
"(",
"a",
",",
"b",
"int",
")",
"int",
"{",
"return",
"a",
"+",
"b",
"}",
",",
"... | // Initialize all templates | [
"Initialize",
"all",
"templates"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L31-L57 |
166,939 | goadesign/goa | goagen/codegen/types.go | goTypeDefObject | func goTypeDefObject(obj design.Object, def *design.AttributeDefinition, tabs int, jsonTags, private bool) string {
var buffer bytes.Buffer
buffer.WriteString("struct {\n")
keys := make([]string, len(obj))
i := 0
for n := range obj {
keys[i] = n
i++
}
sort.Strings(keys)
for _, name := range keys {
WriteTabs(&buffer, tabs+1)
field := obj[name]
typedef := GoTypeDef(field, tabs+1, jsonTags, private)
if (private && field.Type.IsPrimitive() && !def.IsInterface(name)) || field.Type.IsObject() || def.IsPrimitivePointer(name) {
typedef = "*" + typedef
}
fname := GoifyAtt(field, name, true)
var tags string
if jsonTags {
tags = attributeTags(def, field, name, private)
}
desc := obj[name].Description
if desc != "" {
desc = strings.Replace(desc, "\n", "\n\t// ", -1)
desc = fmt.Sprintf("// %s\n\t", desc)
}
buffer.WriteString(fmt.Sprintf("%s%s %s%s\n", desc, fname, typedef, tags))
}
WriteTabs(&buffer, tabs)
buffer.WriteString("}")
return buffer.String()
} | go | func goTypeDefObject(obj design.Object, def *design.AttributeDefinition, tabs int, jsonTags, private bool) string {
var buffer bytes.Buffer
buffer.WriteString("struct {\n")
keys := make([]string, len(obj))
i := 0
for n := range obj {
keys[i] = n
i++
}
sort.Strings(keys)
for _, name := range keys {
WriteTabs(&buffer, tabs+1)
field := obj[name]
typedef := GoTypeDef(field, tabs+1, jsonTags, private)
if (private && field.Type.IsPrimitive() && !def.IsInterface(name)) || field.Type.IsObject() || def.IsPrimitivePointer(name) {
typedef = "*" + typedef
}
fname := GoifyAtt(field, name, true)
var tags string
if jsonTags {
tags = attributeTags(def, field, name, private)
}
desc := obj[name].Description
if desc != "" {
desc = strings.Replace(desc, "\n", "\n\t// ", -1)
desc = fmt.Sprintf("// %s\n\t", desc)
}
buffer.WriteString(fmt.Sprintf("%s%s %s%s\n", desc, fname, typedef, tags))
}
WriteTabs(&buffer, tabs)
buffer.WriteString("}")
return buffer.String()
} | [
"func",
"goTypeDefObject",
"(",
"obj",
"design",
".",
"Object",
",",
"def",
"*",
"design",
".",
"AttributeDefinition",
",",
"tabs",
"int",
",",
"jsonTags",
",",
"private",
"bool",
")",
"string",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"buffer",... | // goTypeDefObject returns the Go code that defines a Go struct. | [
"goTypeDefObject",
"returns",
"the",
"Go",
"code",
"that",
"defines",
"a",
"Go",
"struct",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L105-L137 |
166,940 | goadesign/goa | goagen/codegen/types.go | attributeTags | func attributeTags(parent, att *design.AttributeDefinition, name string, private bool) string {
var elems []string
keys := make([]string, len(att.Metadata))
i := 0
for k := range att.Metadata {
keys[i] = k
i++
}
sort.Strings(keys)
for _, key := range keys {
val := att.Metadata[key]
if strings.HasPrefix(key, "struct:tag:") {
name := key[11:]
value := strings.Join(val, ",")
elems = append(elems, fmt.Sprintf("%s:\"%s\"", name, value))
}
}
if len(elems) > 0 {
return " `" + strings.Join(elems, " ") + "`"
}
// Default algorithm
var omit string
if private || (!parent.IsRequired(name) && !parent.HasDefaultValue(name)) {
omit = ",omitempty"
}
return fmt.Sprintf(" `form:\"%s%s\" json:\"%s%s\" yaml:\"%s%s\" xml:\"%s%s\"`",
name, omit, name, omit, name, omit, name, omit)
} | go | func attributeTags(parent, att *design.AttributeDefinition, name string, private bool) string {
var elems []string
keys := make([]string, len(att.Metadata))
i := 0
for k := range att.Metadata {
keys[i] = k
i++
}
sort.Strings(keys)
for _, key := range keys {
val := att.Metadata[key]
if strings.HasPrefix(key, "struct:tag:") {
name := key[11:]
value := strings.Join(val, ",")
elems = append(elems, fmt.Sprintf("%s:\"%s\"", name, value))
}
}
if len(elems) > 0 {
return " `" + strings.Join(elems, " ") + "`"
}
// Default algorithm
var omit string
if private || (!parent.IsRequired(name) && !parent.HasDefaultValue(name)) {
omit = ",omitempty"
}
return fmt.Sprintf(" `form:\"%s%s\" json:\"%s%s\" yaml:\"%s%s\" xml:\"%s%s\"`",
name, omit, name, omit, name, omit, name, omit)
} | [
"func",
"attributeTags",
"(",
"parent",
",",
"att",
"*",
"design",
".",
"AttributeDefinition",
",",
"name",
"string",
",",
"private",
"bool",
")",
"string",
"{",
"var",
"elems",
"[",
"]",
"string",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
"... | // attributeTags computes the struct field tags. | [
"attributeTags",
"computes",
"the",
"struct",
"field",
"tags",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L140-L167 |
166,941 | goadesign/goa | goagen/codegen/types.go | GoNativeType | func GoNativeType(t design.DataType) string {
switch actual := t.(type) {
case design.Primitive:
switch actual.Kind() {
case design.BooleanKind:
return "bool"
case design.IntegerKind:
return "int"
case design.NumberKind:
return "float64"
case design.StringKind:
return "string"
case design.DateTimeKind:
return "time.Time"
case design.UUIDKind:
return "uuid.UUID"
case design.AnyKind:
return "interface{}"
case design.FileKind:
return "multipart.FileHeader"
default:
panic(fmt.Sprintf("goa bug: unknown primitive type %#v", actual))
}
case *design.Array:
return "[]" + GoNativeType(actual.ElemType.Type)
case design.Object:
return "map[string]interface{}"
case *design.Hash:
return fmt.Sprintf("map[%s]%s", GoNativeType(actual.KeyType.Type), GoNativeType(actual.ElemType.Type))
case *design.MediaTypeDefinition:
return GoNativeType(actual.Type)
case *design.UserTypeDefinition:
return GoNativeType(actual.Type)
default:
panic(fmt.Sprintf("goa bug: unknown type %#v", actual))
}
} | go | func GoNativeType(t design.DataType) string {
switch actual := t.(type) {
case design.Primitive:
switch actual.Kind() {
case design.BooleanKind:
return "bool"
case design.IntegerKind:
return "int"
case design.NumberKind:
return "float64"
case design.StringKind:
return "string"
case design.DateTimeKind:
return "time.Time"
case design.UUIDKind:
return "uuid.UUID"
case design.AnyKind:
return "interface{}"
case design.FileKind:
return "multipart.FileHeader"
default:
panic(fmt.Sprintf("goa bug: unknown primitive type %#v", actual))
}
case *design.Array:
return "[]" + GoNativeType(actual.ElemType.Type)
case design.Object:
return "map[string]interface{}"
case *design.Hash:
return fmt.Sprintf("map[%s]%s", GoNativeType(actual.KeyType.Type), GoNativeType(actual.ElemType.Type))
case *design.MediaTypeDefinition:
return GoNativeType(actual.Type)
case *design.UserTypeDefinition:
return GoNativeType(actual.Type)
default:
panic(fmt.Sprintf("goa bug: unknown type %#v", actual))
}
} | [
"func",
"GoNativeType",
"(",
"t",
"design",
".",
"DataType",
")",
"string",
"{",
"switch",
"actual",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
"design",
".",
"Primitive",
":",
"switch",
"actual",
".",
"Kind",
"(",
")",
"{",
"case",
"design",
"."... | // GoNativeType returns the Go built-in type from which instances of t can be initialized. | [
"GoNativeType",
"returns",
"the",
"Go",
"built",
"-",
"in",
"type",
"from",
"which",
"instances",
"of",
"t",
"can",
"be",
"initialized",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L227-L263 |
166,942 | goadesign/goa | goagen/codegen/types.go | GoTypeDesc | func GoTypeDesc(t design.DataType, upper bool) string {
switch actual := t.(type) {
case *design.UserTypeDefinition:
if actual.Description != "" {
return strings.Replace(actual.Description, "\n", "\n// ", -1)
}
return Goify(actual.TypeName, upper) + " user type."
case *design.MediaTypeDefinition:
if actual.Description != "" {
return strings.Replace(actual.Description, "\n", "\n// ", -1)
}
name := Goify(actual.TypeName, upper)
if actual.View != "default" {
name += Goify(actual.View, true)
}
switch elem := actual.UserTypeDefinition.AttributeDefinition.Type.(type) {
case *design.Array:
elemName := GoTypeName(elem.ElemType.Type, nil, 0, !upper)
if actual.View != "default" {
elemName += Goify(actual.View, true)
}
return fmt.Sprintf("%s media type is a collection of %s.", name, elemName)
default:
return name + " media type."
}
default:
return ""
}
} | go | func GoTypeDesc(t design.DataType, upper bool) string {
switch actual := t.(type) {
case *design.UserTypeDefinition:
if actual.Description != "" {
return strings.Replace(actual.Description, "\n", "\n// ", -1)
}
return Goify(actual.TypeName, upper) + " user type."
case *design.MediaTypeDefinition:
if actual.Description != "" {
return strings.Replace(actual.Description, "\n", "\n// ", -1)
}
name := Goify(actual.TypeName, upper)
if actual.View != "default" {
name += Goify(actual.View, true)
}
switch elem := actual.UserTypeDefinition.AttributeDefinition.Type.(type) {
case *design.Array:
elemName := GoTypeName(elem.ElemType.Type, nil, 0, !upper)
if actual.View != "default" {
elemName += Goify(actual.View, true)
}
return fmt.Sprintf("%s media type is a collection of %s.", name, elemName)
default:
return name + " media type."
}
default:
return ""
}
} | [
"func",
"GoTypeDesc",
"(",
"t",
"design",
".",
"DataType",
",",
"upper",
"bool",
")",
"string",
"{",
"switch",
"actual",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
"*",
"design",
".",
"UserTypeDefinition",
":",
"if",
"actual",
".",
"Description",
"... | // GoTypeDesc returns the description of a type. If no description is defined
// for the type, one will be generated. | [
"GoTypeDesc",
"returns",
"the",
"description",
"of",
"a",
"type",
".",
"If",
"no",
"description",
"is",
"defined",
"for",
"the",
"type",
"one",
"will",
"be",
"generated",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L267-L297 |
166,943 | goadesign/goa | goagen/codegen/types.go | removeTrailingInvalid | func removeTrailingInvalid(runes []rune) []rune {
valid := len(runes) - 1
for ; valid >= 0 && !validIdentifier(runes[valid]); valid-- {
}
return runes[0 : valid+1]
} | go | func removeTrailingInvalid(runes []rune) []rune {
valid := len(runes) - 1
for ; valid >= 0 && !validIdentifier(runes[valid]); valid-- {
}
return runes[0 : valid+1]
} | [
"func",
"removeTrailingInvalid",
"(",
"runes",
"[",
"]",
"rune",
")",
"[",
"]",
"rune",
"{",
"valid",
":=",
"len",
"(",
"runes",
")",
"-",
"1",
"\n",
"for",
";",
"valid",
">=",
"0",
"&&",
"!",
"validIdentifier",
"(",
"runes",
"[",
"valid",
"]",
")"... | // removeTrailingInvalid removes trailing invalid identifiers from runes. | [
"removeTrailingInvalid",
"removes",
"trailing",
"invalid",
"identifiers",
"from",
"runes",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L342-L348 |
166,944 | goadesign/goa | goagen/codegen/types.go | removeInvalidAtIndex | func removeInvalidAtIndex(i int, runes []rune) []rune {
valid := i
for ; valid < len(runes) && !validIdentifier(runes[valid]); valid++ {
}
return append(runes[:i], runes[valid:]...)
} | go | func removeInvalidAtIndex(i int, runes []rune) []rune {
valid := i
for ; valid < len(runes) && !validIdentifier(runes[valid]); valid++ {
}
return append(runes[:i], runes[valid:]...)
} | [
"func",
"removeInvalidAtIndex",
"(",
"i",
"int",
",",
"runes",
"[",
"]",
"rune",
")",
"[",
"]",
"rune",
"{",
"valid",
":=",
"i",
"\n",
"for",
";",
"valid",
"<",
"len",
"(",
"runes",
")",
"&&",
"!",
"validIdentifier",
"(",
"runes",
"[",
"valid",
"]"... | // removeInvalidAtIndex removes consecutive invalid identifiers from runes starting at index i. | [
"removeInvalidAtIndex",
"removes",
"consecutive",
"invalid",
"identifiers",
"from",
"runes",
"starting",
"at",
"index",
"i",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L351-L357 |
166,945 | goadesign/goa | goagen/codegen/types.go | Goify | func Goify(str string, firstUpper bool) string {
runes := []rune(str)
// remove trailing invalid identifiers (makes code below simpler)
runes = removeTrailingInvalid(runes)
w, i := 0, 0 // index of start of word, scan
for i+1 <= len(runes) {
eow := false // whether we hit the end of a word
// remove leading invalid identifiers
runes = removeInvalidAtIndex(i, runes)
if i+1 == len(runes) {
eow = true
} else if !validIdentifier(runes[i]) {
// get rid of it
runes = append(runes[:i], runes[i+1:]...)
} else if runes[i+1] == '_' {
// underscore; shift the remainder forward over any run of underscores
eow = true
n := 1
for i+n+1 < len(runes) && runes[i+n+1] == '_' {
n++
}
copy(runes[i+1:], runes[i+n+1:])
runes = runes[:len(runes)-n]
} else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
// lower->non-lower
eow = true
}
i++
if !eow {
continue
}
// [w,i] is a word.
word := string(runes[w:i])
// is it one of our initialisms?
if u := strings.ToUpper(word); commonInitialisms[u] {
if firstUpper {
u = strings.ToUpper(u)
} else if w == 0 {
u = strings.ToLower(u)
}
// All the common initialisms are ASCII,
// so we can replace the bytes exactly.
copy(runes[w:], []rune(u))
} else if w > 0 && strings.ToLower(word) == word {
// already all lowercase, and not the first word, so uppercase the first character.
runes[w] = unicode.ToUpper(runes[w])
} else if w == 0 && strings.ToLower(word) == word && firstUpper {
runes[w] = unicode.ToUpper(runes[w])
}
if w == 0 && !firstUpper {
runes[w] = unicode.ToLower(runes[w])
}
//advance to next word
w = i
}
return fixReserved(string(runes))
} | go | func Goify(str string, firstUpper bool) string {
runes := []rune(str)
// remove trailing invalid identifiers (makes code below simpler)
runes = removeTrailingInvalid(runes)
w, i := 0, 0 // index of start of word, scan
for i+1 <= len(runes) {
eow := false // whether we hit the end of a word
// remove leading invalid identifiers
runes = removeInvalidAtIndex(i, runes)
if i+1 == len(runes) {
eow = true
} else if !validIdentifier(runes[i]) {
// get rid of it
runes = append(runes[:i], runes[i+1:]...)
} else if runes[i+1] == '_' {
// underscore; shift the remainder forward over any run of underscores
eow = true
n := 1
for i+n+1 < len(runes) && runes[i+n+1] == '_' {
n++
}
copy(runes[i+1:], runes[i+n+1:])
runes = runes[:len(runes)-n]
} else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
// lower->non-lower
eow = true
}
i++
if !eow {
continue
}
// [w,i] is a word.
word := string(runes[w:i])
// is it one of our initialisms?
if u := strings.ToUpper(word); commonInitialisms[u] {
if firstUpper {
u = strings.ToUpper(u)
} else if w == 0 {
u = strings.ToLower(u)
}
// All the common initialisms are ASCII,
// so we can replace the bytes exactly.
copy(runes[w:], []rune(u))
} else if w > 0 && strings.ToLower(word) == word {
// already all lowercase, and not the first word, so uppercase the first character.
runes[w] = unicode.ToUpper(runes[w])
} else if w == 0 && strings.ToLower(word) == word && firstUpper {
runes[w] = unicode.ToUpper(runes[w])
}
if w == 0 && !firstUpper {
runes[w] = unicode.ToLower(runes[w])
}
//advance to next word
w = i
}
return fixReserved(string(runes))
} | [
"func",
"Goify",
"(",
"str",
"string",
",",
"firstUpper",
"bool",
")",
"string",
"{",
"runes",
":=",
"[",
"]",
"rune",
"(",
"str",
")",
"\n\n",
"// remove trailing invalid identifiers (makes code below simpler)",
"runes",
"=",
"removeTrailingInvalid",
"(",
"runes",
... | // Goify makes a valid Go identifier out of any string.
// It does that by removing any non letter and non digit character and by making sure the first
// character is a letter or "_".
// Goify produces a "CamelCase" version of the string, if firstUpper is true the first character
// of the identifier is uppercase otherwise it's lowercase. | [
"Goify",
"makes",
"a",
"valid",
"Go",
"identifier",
"out",
"of",
"any",
"string",
".",
"It",
"does",
"that",
"by",
"removing",
"any",
"non",
"letter",
"and",
"non",
"digit",
"character",
"and",
"by",
"making",
"sure",
"the",
"first",
"character",
"is",
"... | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L375-L438 |
166,946 | goadesign/goa | goagen/codegen/types.go | validIdentifier | func validIdentifier(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r)
} | go | func validIdentifier(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r)
} | [
"func",
"validIdentifier",
"(",
"r",
"rune",
")",
"bool",
"{",
"return",
"unicode",
".",
"IsLetter",
"(",
"r",
")",
"||",
"unicode",
".",
"IsDigit",
"(",
"r",
")",
"\n",
"}"
] | // validIdentifier returns true if the rune is a letter or number | [
"validIdentifier",
"returns",
"true",
"if",
"the",
"rune",
"is",
"a",
"letter",
"or",
"number"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L495-L497 |
166,947 | goadesign/goa | goagen/codegen/types.go | GoTypeTransformName | func GoTypeTransformName(source, target *design.UserTypeDefinition, suffix string) string {
return fmt.Sprintf("%sTo%s%s", Goify(source.TypeName, true), Goify(target.TypeName, true), Goify(suffix, true))
} | go | func GoTypeTransformName(source, target *design.UserTypeDefinition, suffix string) string {
return fmt.Sprintf("%sTo%s%s", Goify(source.TypeName, true), Goify(target.TypeName, true), Goify(suffix, true))
} | [
"func",
"GoTypeTransformName",
"(",
"source",
",",
"target",
"*",
"design",
".",
"UserTypeDefinition",
",",
"suffix",
"string",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"Goify",
"(",
"source",
".",
"TypeName",
",",
"true",... | // GoTypeTransformName generates a valid Go identifer that is adequate for naming the type
// transform function that creates an instance of the data structure described by target from an
// instance of the data strucuture described by source. | [
"GoTypeTransformName",
"generates",
"a",
"valid",
"Go",
"identifer",
"that",
"is",
"adequate",
"for",
"naming",
"the",
"type",
"transform",
"function",
"that",
"creates",
"an",
"instance",
"of",
"the",
"data",
"structure",
"described",
"by",
"target",
"from",
"a... | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L556-L558 |
166,948 | goadesign/goa | goagen/codegen/types.go | WriteTabs | func WriteTabs(buf *bytes.Buffer, count int) {
for i := 0; i < count; i++ {
buf.WriteByte('\t')
}
} | go | func WriteTabs(buf *bytes.Buffer, count int) {
for i := 0; i < count; i++ {
buf.WriteByte('\t')
}
} | [
"func",
"WriteTabs",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
",",
"count",
"int",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
"{",
"buf",
".",
"WriteByte",
"(",
"'\\t'",
")",
"\n",
"}",
"\n",
"}"
] | // WriteTabs is a helper function that writes count tabulation characters to buf. | [
"WriteTabs",
"is",
"a",
"helper",
"function",
"that",
"writes",
"count",
"tabulation",
"characters",
"to",
"buf",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L561-L565 |
166,949 | goadesign/goa | goagen/codegen/types.go | RunTemplate | func RunTemplate(tmpl *template.Template, data interface{}) string {
var b bytes.Buffer
err := tmpl.Execute(&b, data)
if err != nil {
panic(err) // should never happen, bug if it does.
}
return b.String()
} | go | func RunTemplate(tmpl *template.Template, data interface{}) string {
var b bytes.Buffer
err := tmpl.Execute(&b, data)
if err != nil {
panic(err) // should never happen, bug if it does.
}
return b.String()
} | [
"func",
"RunTemplate",
"(",
"tmpl",
"*",
"template",
".",
"Template",
",",
"data",
"interface",
"{",
"}",
")",
"string",
"{",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"err",
":=",
"tmpl",
".",
"Execute",
"(",
"&",
"b",
",",
"data",
")",
"\n",
"if"... | // RunTemplate executs the given template with the given input and returns
// the rendered string. | [
"RunTemplate",
"executs",
"the",
"given",
"template",
"with",
"the",
"given",
"input",
"and",
"returns",
"the",
"rendered",
"string",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L575-L582 |
166,950 | goadesign/goa | goagen/codegen/types.go | toSlice | func toSlice(val []interface{}) string {
elems := make([]string, len(val))
for i, v := range val {
elems[i] = fmt.Sprintf("%#v", v)
}
return fmt.Sprintf("[]interface{}{%s}", strings.Join(elems, ", "))
} | go | func toSlice(val []interface{}) string {
elems := make([]string, len(val))
for i, v := range val {
elems[i] = fmt.Sprintf("%#v", v)
}
return fmt.Sprintf("[]interface{}{%s}", strings.Join(elems, ", "))
} | [
"func",
"toSlice",
"(",
"val",
"[",
"]",
"interface",
"{",
"}",
")",
"string",
"{",
"elems",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"val",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"val",
"{",
"elems",
"[",
"i",
"]... | // toSlice returns Go code that represents the given slice. | [
"toSlice",
"returns",
"Go",
"code",
"that",
"represents",
"the",
"given",
"slice",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L706-L712 |
166,951 | goadesign/goa | goagen/codegen/types.go | typeName | func typeName(att *design.AttributeDefinition) (name string) {
if ut, ok := att.Type.(*design.UserTypeDefinition); ok {
name = Goify(ut.TypeName, true)
} else if mt, ok := att.Type.(*design.MediaTypeDefinition); ok {
name = Goify(mt.TypeName, true)
}
return
} | go | func typeName(att *design.AttributeDefinition) (name string) {
if ut, ok := att.Type.(*design.UserTypeDefinition); ok {
name = Goify(ut.TypeName, true)
} else if mt, ok := att.Type.(*design.MediaTypeDefinition); ok {
name = Goify(mt.TypeName, true)
}
return
} | [
"func",
"typeName",
"(",
"att",
"*",
"design",
".",
"AttributeDefinition",
")",
"(",
"name",
"string",
")",
"{",
"if",
"ut",
",",
"ok",
":=",
"att",
".",
"Type",
".",
"(",
"*",
"design",
".",
"UserTypeDefinition",
")",
";",
"ok",
"{",
"name",
"=",
... | // typeName returns the type name of the given attribute if it is a named type, empty string otherwise. | [
"typeName",
"returns",
"the",
"type",
"name",
"of",
"the",
"given",
"attribute",
"if",
"it",
"is",
"a",
"named",
"type",
"empty",
"string",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/types.go#L715-L722 |
166,952 | goadesign/goa | middleware/xray/middleware.go | NewID | func NewID() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
} | go | func NewID() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
} | [
"func",
"NewID",
"(",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"8",
")",
"\n",
"rand",
".",
"Read",
"(",
"b",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
")",
"\n",
"}"
] | // NewID is a span ID creation algorithm which produces values that are
// compatible with AWS X-Ray. | [
"NewID",
"is",
"a",
"span",
"ID",
"creation",
"algorithm",
"which",
"produces",
"values",
"that",
"are",
"compatible",
"with",
"AWS",
"X",
"-",
"Ray",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/xray/middleware.go#L90-L94 |
166,953 | goadesign/goa | middleware/xray/middleware.go | NewTraceID | func NewTraceID() string {
b := make([]byte, 12)
rand.Read(b)
return fmt.Sprintf("%d-%x-%s", 1, time.Now().Unix(), fmt.Sprintf("%x", b))
} | go | func NewTraceID() string {
b := make([]byte, 12)
rand.Read(b)
return fmt.Sprintf("%d-%x-%s", 1, time.Now().Unix(), fmt.Sprintf("%x", b))
} | [
"func",
"NewTraceID",
"(",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"12",
")",
"\n",
"rand",
".",
"Read",
"(",
"b",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"1",
",",
"time",
".",
"Now",
"(",... | // NewTraceID is a trace ID creation algorithm which produces values that are
// compatible with AWS X-Ray. | [
"NewTraceID",
"is",
"a",
"trace",
"ID",
"creation",
"algorithm",
"which",
"produces",
"values",
"that",
"are",
"compatible",
"with",
"AWS",
"X",
"-",
"Ray",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/xray/middleware.go#L98-L102 |
166,954 | goadesign/goa | middleware/xray/middleware.go | WithSegment | func WithSegment(ctx context.Context, s *Segment) context.Context {
return context.WithValue(ctx, segKey, s)
} | go | func WithSegment(ctx context.Context, s *Segment) context.Context {
return context.WithValue(ctx, segKey, s)
} | [
"func",
"WithSegment",
"(",
"ctx",
"context",
".",
"Context",
",",
"s",
"*",
"Segment",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"segKey",
",",
"s",
")",
"\n",
"}"
] | // WithSegment creates a context containing the given segment. Use ContextSegment
// to retrieve it. | [
"WithSegment",
"creates",
"a",
"context",
"containing",
"the",
"given",
"segment",
".",
"Use",
"ContextSegment",
"to",
"retrieve",
"it",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/xray/middleware.go#L106-L108 |
166,955 | goadesign/goa | middleware/xray/middleware.go | ContextSegment | func ContextSegment(ctx context.Context) *Segment {
if s := ctx.Value(segKey); s != nil {
return s.(*Segment)
}
return nil
} | go | func ContextSegment(ctx context.Context) *Segment {
if s := ctx.Value(segKey); s != nil {
return s.(*Segment)
}
return nil
} | [
"func",
"ContextSegment",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"Segment",
"{",
"if",
"s",
":=",
"ctx",
".",
"Value",
"(",
"segKey",
")",
";",
"s",
"!=",
"nil",
"{",
"return",
"s",
".",
"(",
"*",
"Segment",
")",
"\n",
"}",
"\n",
"retur... | // ContextSegment extracts the segment set in the context with WithSegment. | [
"ContextSegment",
"extracts",
"the",
"segment",
"set",
"in",
"the",
"context",
"with",
"WithSegment",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/xray/middleware.go#L111-L116 |
166,956 | goadesign/goa | middleware/xray/middleware.go | newSegment | func newSegment(ctx context.Context, traceID, name string, req *http.Request, c net.Conn) *Segment {
var (
spanID = middleware.ContextSpanID(ctx)
parentID = middleware.ContextParentSpanID(ctx)
)
s := NewSegment(name, traceID, spanID, c)
s.RecordRequest(req, "")
if parentID != "" {
s.ParentID = parentID
}
return s
} | go | func newSegment(ctx context.Context, traceID, name string, req *http.Request, c net.Conn) *Segment {
var (
spanID = middleware.ContextSpanID(ctx)
parentID = middleware.ContextParentSpanID(ctx)
)
s := NewSegment(name, traceID, spanID, c)
s.RecordRequest(req, "")
if parentID != "" {
s.ParentID = parentID
}
return s
} | [
"func",
"newSegment",
"(",
"ctx",
"context",
".",
"Context",
",",
"traceID",
",",
"name",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"c",
"net",
".",
"Conn",
")",
"*",
"Segment",
"{",
"var",
"(",
"spanID",
"=",
"middleware",
".",
"Contex... | // newSegment creates a new segment for the incoming request. | [
"newSegment",
"creates",
"a",
"new",
"segment",
"for",
"the",
"incoming",
"request",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/xray/middleware.go#L119-L133 |
166,957 | goadesign/goa | middleware/xray/middleware.go | periodicallyRedialingConn | func periodicallyRedialingConn(ctx context.Context, renewPeriod time.Duration, dial func() (net.Conn, error)) (func() net.Conn, error) {
var (
err error
// guard access to c
mu sync.RWMutex
c net.Conn
)
// get an initial connection
if c, err = dial(); err != nil {
return nil, err
}
// periodically re-dial
go func() {
ticker := time.NewTicker(renewPeriod)
for {
select {
case <-ticker.C:
newConn, err := dial()
if err != nil {
continue // we don't have anything better to replace `c` with
}
mu.Lock()
c = newConn
mu.Unlock()
case <-ctx.Done():
return
}
}
}()
return func() net.Conn {
mu.RLock()
defer mu.RUnlock()
return c
}, nil
} | go | func periodicallyRedialingConn(ctx context.Context, renewPeriod time.Duration, dial func() (net.Conn, error)) (func() net.Conn, error) {
var (
err error
// guard access to c
mu sync.RWMutex
c net.Conn
)
// get an initial connection
if c, err = dial(); err != nil {
return nil, err
}
// periodically re-dial
go func() {
ticker := time.NewTicker(renewPeriod)
for {
select {
case <-ticker.C:
newConn, err := dial()
if err != nil {
continue // we don't have anything better to replace `c` with
}
mu.Lock()
c = newConn
mu.Unlock()
case <-ctx.Done():
return
}
}
}()
return func() net.Conn {
mu.RLock()
defer mu.RUnlock()
return c
}, nil
} | [
"func",
"periodicallyRedialingConn",
"(",
"ctx",
"context",
".",
"Context",
",",
"renewPeriod",
"time",
".",
"Duration",
",",
"dial",
"func",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
")",
"(",
"func",
"(",
")",
"net",
".",
"Conn",
",",
"... | // periodicallyRedialingConn creates a goroutine to periodically re-dial a connection, so the hostname can be
// re-resolved if the IP changes.
// Returns a func that provides the latest Conn value. | [
"periodicallyRedialingConn",
"creates",
"a",
"goroutine",
"to",
"periodically",
"re",
"-",
"dial",
"a",
"connection",
"so",
"the",
"hostname",
"can",
"be",
"re",
"-",
"resolved",
"if",
"the",
"IP",
"changes",
".",
"Returns",
"a",
"func",
"that",
"provides",
... | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/xray/middleware.go#L143-L181 |
166,958 | goadesign/goa | design/apidsl/media_type.go | buildView | func buildView(name string, mt *design.MediaTypeDefinition, at *design.AttributeDefinition) (*design.ViewDefinition, error) {
if at.Type == nil || !at.Type.IsObject() {
return nil, fmt.Errorf("invalid view DSL")
}
o := at.Type.ToObject()
if o != nil {
mto := mt.Type.ToObject()
if mto == nil {
mto = mt.Type.ToArray().ElemType.Type.ToObject()
}
for n, cat := range o {
if existing, ok := mto[n]; ok {
dup := design.DupAtt(existing)
dup.View = cat.View
o[n] = dup
} else if n != "links" {
return nil, fmt.Errorf("unknown attribute %#v", n)
}
}
}
return &design.ViewDefinition{
AttributeDefinition: at,
Name: name,
Parent: mt,
}, nil
} | go | func buildView(name string, mt *design.MediaTypeDefinition, at *design.AttributeDefinition) (*design.ViewDefinition, error) {
if at.Type == nil || !at.Type.IsObject() {
return nil, fmt.Errorf("invalid view DSL")
}
o := at.Type.ToObject()
if o != nil {
mto := mt.Type.ToObject()
if mto == nil {
mto = mt.Type.ToArray().ElemType.Type.ToObject()
}
for n, cat := range o {
if existing, ok := mto[n]; ok {
dup := design.DupAtt(existing)
dup.View = cat.View
o[n] = dup
} else if n != "links" {
return nil, fmt.Errorf("unknown attribute %#v", n)
}
}
}
return &design.ViewDefinition{
AttributeDefinition: at,
Name: name,
Parent: mt,
}, nil
} | [
"func",
"buildView",
"(",
"name",
"string",
",",
"mt",
"*",
"design",
".",
"MediaTypeDefinition",
",",
"at",
"*",
"design",
".",
"AttributeDefinition",
")",
"(",
"*",
"design",
".",
"ViewDefinition",
",",
"error",
")",
"{",
"if",
"at",
".",
"Type",
"==",... | // buildView builds a view definition given an attribute and a corresponding media type. | [
"buildView",
"builds",
"a",
"view",
"definition",
"given",
"an",
"attribute",
"and",
"a",
"corresponding",
"media",
"type",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/media_type.go#L296-L321 |
166,959 | goadesign/goa | security.go | ContextRequiredScopes | func ContextRequiredScopes(ctx context.Context) []string {
if s := ctx.Value(securityScopesKey); s != nil {
return s.([]string)
}
return nil
} | go | func ContextRequiredScopes(ctx context.Context) []string {
if s := ctx.Value(securityScopesKey); s != nil {
return s.([]string)
}
return nil
} | [
"func",
"ContextRequiredScopes",
"(",
"ctx",
"context",
".",
"Context",
")",
"[",
"]",
"string",
"{",
"if",
"s",
":=",
"ctx",
".",
"Value",
"(",
"securityScopesKey",
")",
";",
"s",
"!=",
"nil",
"{",
"return",
"s",
".",
"(",
"[",
"]",
"string",
")",
... | // ContextRequiredScopes extracts the security scopes from the given context.
// This should be used in auth handlers to validate that the required scopes are present in the
// JWT or OAuth2 token. | [
"ContextRequiredScopes",
"extracts",
"the",
"security",
"scopes",
"from",
"the",
"given",
"context",
".",
"This",
"should",
"be",
"used",
"in",
"auth",
"handlers",
"to",
"validate",
"that",
"the",
"required",
"scopes",
"are",
"present",
"in",
"the",
"JWT",
"or... | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/security.go#L18-L23 |
166,960 | goadesign/goa | security.go | WithRequiredScopes | func WithRequiredScopes(ctx context.Context, scopes []string) context.Context {
return context.WithValue(ctx, securityScopesKey, scopes)
} | go | func WithRequiredScopes(ctx context.Context, scopes []string) context.Context {
return context.WithValue(ctx, securityScopesKey, scopes)
} | [
"func",
"WithRequiredScopes",
"(",
"ctx",
"context",
".",
"Context",
",",
"scopes",
"[",
"]",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"securityScopesKey",
",",
"scopes",
")",
"\n",
"}"
] | // WithRequiredScopes builds a context containing the given required scopes. | [
"WithRequiredScopes",
"builds",
"a",
"context",
"containing",
"the",
"given",
"required",
"scopes",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/security.go#L26-L28 |
166,961 | goadesign/goa | design/apidsl/action.go | GET | func GET(path string, dsl ...func()) *design.RouteDefinition {
route := &design.RouteDefinition{Verb: "GET", Path: path}
if len(dsl) != 0 {
if !dslengine.Execute(dsl[0], route) {
return nil
}
}
return route
} | go | func GET(path string, dsl ...func()) *design.RouteDefinition {
route := &design.RouteDefinition{Verb: "GET", Path: path}
if len(dsl) != 0 {
if !dslengine.Execute(dsl[0], route) {
return nil
}
}
return route
} | [
"func",
"GET",
"(",
"path",
"string",
",",
"dsl",
"...",
"func",
"(",
")",
")",
"*",
"design",
".",
"RouteDefinition",
"{",
"route",
":=",
"&",
"design",
".",
"RouteDefinition",
"{",
"Verb",
":",
"\"",
"\"",
",",
"Path",
":",
"path",
"}",
"\n",
"if... | // GET is used as an argument to Routing
//
// GET creates a route using the GET HTTP method. | [
"GET",
"is",
"used",
"as",
"an",
"argument",
"to",
"Routing",
"GET",
"creates",
"a",
"route",
"using",
"the",
"GET",
"HTTP",
"method",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/action.go#L138-L146 |
166,962 | goadesign/goa | design/apidsl/action.go | newAttribute | func newAttribute(baseMT string) *design.AttributeDefinition {
var base design.DataType
if mt := design.Design.MediaTypeWithIdentifier(baseMT); mt != nil {
base = mt.Type
}
return &design.AttributeDefinition{Reference: base}
} | go | func newAttribute(baseMT string) *design.AttributeDefinition {
var base design.DataType
if mt := design.Design.MediaTypeWithIdentifier(baseMT); mt != nil {
base = mt.Type
}
return &design.AttributeDefinition{Reference: base}
} | [
"func",
"newAttribute",
"(",
"baseMT",
"string",
")",
"*",
"design",
".",
"AttributeDefinition",
"{",
"var",
"base",
"design",
".",
"DataType",
"\n",
"if",
"mt",
":=",
"design",
".",
"Design",
".",
"MediaTypeWithIdentifier",
"(",
"baseMT",
")",
";",
"mt",
... | // newAttribute creates a new attribute definition using the media type with the given identifier
// as base type. | [
"newAttribute",
"creates",
"a",
"new",
"attribute",
"definition",
"using",
"the",
"media",
"type",
"with",
"the",
"given",
"identifier",
"as",
"base",
"type",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/action.go#L494-L500 |
166,963 | goadesign/goa | client/cli.go | WSWrite | func WSWrite(ws *websocket.Conn) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
t := scanner.Text()
ws.Write([]byte(t))
fmt.Printf(">> %s\n", t)
}
} | go | func WSWrite(ws *websocket.Conn) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
t := scanner.Text()
ws.Write([]byte(t))
fmt.Printf(">> %s\n", t)
}
} | [
"func",
"WSWrite",
"(",
"ws",
"*",
"websocket",
".",
"Conn",
")",
"{",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"os",
".",
"Stdin",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"t",
":=",
"scanner",
".",
"Text",
"(",
")",
"\n... | // WSWrite sends STDIN lines to a websocket server. | [
"WSWrite",
"sends",
"STDIN",
"lines",
"to",
"a",
"websocket",
"server",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/cli.go#L77-L84 |
166,964 | goadesign/goa | client/cli.go | WSRead | func WSRead(ws *websocket.Conn) {
msg := make([]byte, 512)
for {
n, err := ws.Read(msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("<< %s\n", msg[:n])
}
} | go | func WSRead(ws *websocket.Conn) {
msg := make([]byte, 512)
for {
n, err := ws.Read(msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("<< %s\n", msg[:n])
}
} | [
"func",
"WSRead",
"(",
"ws",
"*",
"websocket",
".",
"Conn",
")",
"{",
"msg",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"512",
")",
"\n",
"for",
"{",
"n",
",",
"err",
":=",
"ws",
".",
"Read",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // WSRead reads from a websocket and print the read messages to STDOUT. | [
"WSRead",
"reads",
"from",
"a",
"websocket",
"and",
"print",
"the",
"read",
"messages",
"to",
"STDOUT",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/client/cli.go#L87-L96 |
166,965 | goadesign/goa | goagen/meta/generator.go | NewGenerator | func NewGenerator(genfunc string, imports []*codegen.ImportSpec, flags map[string]string, customflags []string) (*Generator, error) {
var (
outDir, designPkgPath string
debug bool
)
if o, ok := flags["out"]; ok {
outDir = o
}
if d, ok := flags["design"]; ok {
designPkgPath = d
}
if d, ok := flags["debug"]; ok {
var err error
debug, err = strconv.ParseBool(d)
if err != nil {
return nil, fmt.Errorf("failed to parse debug flag: %s", err)
}
}
return &Generator{
Genfunc: genfunc,
Imports: imports,
Flags: flags,
CustomFlags: customflags,
OutDir: outDir,
DesignPkgPath: designPkgPath,
debug: debug,
}, nil
} | go | func NewGenerator(genfunc string, imports []*codegen.ImportSpec, flags map[string]string, customflags []string) (*Generator, error) {
var (
outDir, designPkgPath string
debug bool
)
if o, ok := flags["out"]; ok {
outDir = o
}
if d, ok := flags["design"]; ok {
designPkgPath = d
}
if d, ok := flags["debug"]; ok {
var err error
debug, err = strconv.ParseBool(d)
if err != nil {
return nil, fmt.Errorf("failed to parse debug flag: %s", err)
}
}
return &Generator{
Genfunc: genfunc,
Imports: imports,
Flags: flags,
CustomFlags: customflags,
OutDir: outDir,
DesignPkgPath: designPkgPath,
debug: debug,
}, nil
} | [
"func",
"NewGenerator",
"(",
"genfunc",
"string",
",",
"imports",
"[",
"]",
"*",
"codegen",
".",
"ImportSpec",
",",
"flags",
"map",
"[",
"string",
"]",
"string",
",",
"customflags",
"[",
"]",
"string",
")",
"(",
"*",
"Generator",
",",
"error",
")",
"{"... | // NewGenerator returns a meta generator that can run an actual Generator
// given its factory method and command line flags. | [
"NewGenerator",
"returns",
"a",
"meta",
"generator",
"that",
"can",
"run",
"an",
"actual",
"Generator",
"given",
"its",
"factory",
"method",
"and",
"command",
"line",
"flags",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/meta/generator.go#L51-L80 |
166,966 | goadesign/goa | goagen/meta/generator.go | Generate | func (m *Generator) Generate() ([]string, error) {
// Sanity checks
if m.OutDir == "" {
return nil, fmt.Errorf("missing output directory flag")
}
if m.DesignPkgPath == "" {
return nil, fmt.Errorf("missing design package flag")
}
// Create output directory
if err := os.MkdirAll(m.OutDir, 0755); err != nil {
return nil, err
}
// Create temporary workspace used for generation
wd, err := os.Getwd()
if err != nil {
return nil, err
}
tmpDir, err := ioutil.TempDir(wd, "goagen")
if err != nil {
if _, ok := err.(*os.PathError); ok {
err = fmt.Errorf(`invalid output directory path "%s"`, m.OutDir)
}
return nil, err
}
defer func() {
if !m.debug {
os.RemoveAll(tmpDir)
}
}()
if m.debug {
fmt.Printf("** Code generator source dir: %s\n", tmpDir)
}
pkgSourcePath, err := codegen.PackageSourcePath(m.DesignPkgPath)
if err != nil {
return nil, fmt.Errorf("invalid design package import path: %s", err)
}
pkgName, err := codegen.PackageName(pkgSourcePath)
if err != nil {
return nil, err
}
// Generate tool source code.
pkgPath := filepath.Join(tmpDir, pkgName)
p, err := codegen.PackageFor(pkgPath)
if err != nil {
return nil, err
}
m.generateToolSourceCode(p)
// Compile and run generated tool.
if m.debug {
fmt.Printf("** Compiling with:\n%s", strings.Join(os.Environ(), "\n"))
}
genbin, err := p.Compile("goagen")
if err != nil {
return nil, err
}
return m.spawn(genbin)
} | go | func (m *Generator) Generate() ([]string, error) {
// Sanity checks
if m.OutDir == "" {
return nil, fmt.Errorf("missing output directory flag")
}
if m.DesignPkgPath == "" {
return nil, fmt.Errorf("missing design package flag")
}
// Create output directory
if err := os.MkdirAll(m.OutDir, 0755); err != nil {
return nil, err
}
// Create temporary workspace used for generation
wd, err := os.Getwd()
if err != nil {
return nil, err
}
tmpDir, err := ioutil.TempDir(wd, "goagen")
if err != nil {
if _, ok := err.(*os.PathError); ok {
err = fmt.Errorf(`invalid output directory path "%s"`, m.OutDir)
}
return nil, err
}
defer func() {
if !m.debug {
os.RemoveAll(tmpDir)
}
}()
if m.debug {
fmt.Printf("** Code generator source dir: %s\n", tmpDir)
}
pkgSourcePath, err := codegen.PackageSourcePath(m.DesignPkgPath)
if err != nil {
return nil, fmt.Errorf("invalid design package import path: %s", err)
}
pkgName, err := codegen.PackageName(pkgSourcePath)
if err != nil {
return nil, err
}
// Generate tool source code.
pkgPath := filepath.Join(tmpDir, pkgName)
p, err := codegen.PackageFor(pkgPath)
if err != nil {
return nil, err
}
m.generateToolSourceCode(p)
// Compile and run generated tool.
if m.debug {
fmt.Printf("** Compiling with:\n%s", strings.Join(os.Environ(), "\n"))
}
genbin, err := p.Compile("goagen")
if err != nil {
return nil, err
}
return m.spawn(genbin)
} | [
"func",
"(",
"m",
"*",
"Generator",
")",
"Generate",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"// Sanity checks",
"if",
"m",
".",
"OutDir",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",... | // Generate compiles and runs the generator and returns the generated filenames. | [
"Generate",
"compiles",
"and",
"runs",
"the",
"generator",
"and",
"returns",
"the",
"generated",
"filenames",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/meta/generator.go#L83-L144 |
166,967 | goadesign/goa | goagen/meta/generator.go | spawn | func (m *Generator) spawn(genbin string) ([]string, error) {
var args []string
for k, v := range m.Flags {
if k == "debug" {
continue
}
args = append(args, fmt.Sprintf("--%s=%s", k, v))
}
sort.Strings(args)
args = append(args, "--version="+version.String())
args = append(args, m.CustomFlags...)
cmd := exec.Command(genbin, args...)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%s\n%s", err, string(out))
}
res := strings.Split(string(out), "\n")
for (len(res) > 0) && (res[len(res)-1] == "") {
res = res[:len(res)-1]
}
return res, nil
} | go | func (m *Generator) spawn(genbin string) ([]string, error) {
var args []string
for k, v := range m.Flags {
if k == "debug" {
continue
}
args = append(args, fmt.Sprintf("--%s=%s", k, v))
}
sort.Strings(args)
args = append(args, "--version="+version.String())
args = append(args, m.CustomFlags...)
cmd := exec.Command(genbin, args...)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%s\n%s", err, string(out))
}
res := strings.Split(string(out), "\n")
for (len(res) > 0) && (res[len(res)-1] == "") {
res = res[:len(res)-1]
}
return res, nil
} | [
"func",
"(",
"m",
"*",
"Generator",
")",
"spawn",
"(",
"genbin",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"args",
"[",
"]",
"string",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
".",
"Flags",
"{",
"if",
"k",
... | // spawn runs the compiled generator using the arguments initialized by Kingpin
// when parsing the command line. | [
"spawn",
"runs",
"the",
"compiled",
"generator",
"using",
"the",
"arguments",
"initialized",
"by",
"Kingpin",
"when",
"parsing",
"the",
"command",
"line",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/meta/generator.go#L179-L200 |
166,968 | goadesign/goa | middleware/request_id.go | init | func init() {
// algorithm taken from https://github.com/zenazn/goji/blob/master/web/middleware/request_id.go#L44-L50
var buf [12]byte
var b64 string
for len(b64) < 10 {
rand.Read(buf[:])
b64 = base64.StdEncoding.EncodeToString(buf[:])
b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
}
reqPrefix = string(b64[0:10])
} | go | func init() {
// algorithm taken from https://github.com/zenazn/goji/blob/master/web/middleware/request_id.go#L44-L50
var buf [12]byte
var b64 string
for len(b64) < 10 {
rand.Read(buf[:])
b64 = base64.StdEncoding.EncodeToString(buf[:])
b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
}
reqPrefix = string(b64[0:10])
} | [
"func",
"init",
"(",
")",
"{",
"// algorithm taken from https://github.com/zenazn/goji/blob/master/web/middleware/request_id.go#L44-L50",
"var",
"buf",
"[",
"12",
"]",
"byte",
"\n",
"var",
"b64",
"string",
"\n",
"for",
"len",
"(",
"b64",
")",
"<",
"10",
"{",
"rand",... | // Initialize common prefix on process startup. | [
"Initialize",
"common",
"prefix",
"on",
"process",
"startup",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/request_id.go#L31-L41 |
166,969 | goadesign/goa | logging/log15/adapter.go | Logger | func Logger(ctx context.Context) log15.Logger {
logger := goa.ContextLogger(ctx)
if a, ok := logger.(*adapter); ok {
return a.Logger
}
return nil
} | go | func Logger(ctx context.Context) log15.Logger {
logger := goa.ContextLogger(ctx)
if a, ok := logger.(*adapter); ok {
return a.Logger
}
return nil
} | [
"func",
"Logger",
"(",
"ctx",
"context",
".",
"Context",
")",
"log15",
".",
"Logger",
"{",
"logger",
":=",
"goa",
".",
"ContextLogger",
"(",
"ctx",
")",
"\n",
"if",
"a",
",",
"ok",
":=",
"logger",
".",
"(",
"*",
"adapter",
")",
";",
"ok",
"{",
"r... | // Logger returns the log15 logger stored in the given context if any, nil otherwise. | [
"Logger",
"returns",
"the",
"log15",
"logger",
"stored",
"in",
"the",
"given",
"context",
"if",
"any",
"nil",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/logging/log15/adapter.go#L34-L40 |
166,970 | goadesign/goa | logging/log15/adapter.go | Info | func (a *adapter) Info(msg string, data ...interface{}) {
a.Logger.Info(msg, data...)
} | go | func (a *adapter) Info(msg string, data ...interface{}) {
a.Logger.Info(msg, data...)
} | [
"func",
"(",
"a",
"*",
"adapter",
")",
"Info",
"(",
"msg",
"string",
",",
"data",
"...",
"interface",
"{",
"}",
")",
"{",
"a",
".",
"Logger",
".",
"Info",
"(",
"msg",
",",
"data",
"...",
")",
"\n",
"}"
] | // Info logs informational messages using log15. | [
"Info",
"logs",
"informational",
"messages",
"using",
"log15",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/logging/log15/adapter.go#L43-L45 |
166,971 | goadesign/goa | logging/log15/adapter.go | Error | func (a *adapter) Error(msg string, data ...interface{}) {
a.Logger.Error(msg, data...)
} | go | func (a *adapter) Error(msg string, data ...interface{}) {
a.Logger.Error(msg, data...)
} | [
"func",
"(",
"a",
"*",
"adapter",
")",
"Error",
"(",
"msg",
"string",
",",
"data",
"...",
"interface",
"{",
"}",
")",
"{",
"a",
".",
"Logger",
".",
"Error",
"(",
"msg",
",",
"data",
"...",
")",
"\n",
"}"
] | // Error logs error messages using log15. | [
"Error",
"logs",
"error",
"messages",
"using",
"log15",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/logging/log15/adapter.go#L48-L50 |
166,972 | goadesign/goa | design/validation.go | DifferentWildcards | func (r *routeInfo) DifferentWildcards(other *routeInfo) (res [][2]*wildCardInfo) {
for i, wc := range other.Wildcards {
if r.Wildcards[i].Name != wc.Name {
res = append(res, [2]*wildCardInfo{r.Wildcards[i], wc})
}
}
return
} | go | func (r *routeInfo) DifferentWildcards(other *routeInfo) (res [][2]*wildCardInfo) {
for i, wc := range other.Wildcards {
if r.Wildcards[i].Name != wc.Name {
res = append(res, [2]*wildCardInfo{r.Wildcards[i], wc})
}
}
return
} | [
"func",
"(",
"r",
"*",
"routeInfo",
")",
"DifferentWildcards",
"(",
"other",
"*",
"routeInfo",
")",
"(",
"res",
"[",
"]",
"[",
"2",
"]",
"*",
"wildCardInfo",
")",
"{",
"for",
"i",
",",
"wc",
":=",
"range",
"other",
".",
"Wildcards",
"{",
"if",
"r",... | // DifferentWildcards returns the list of wildcards in other that have a different name from the
// wildcard in target at the same position. | [
"DifferentWildcards",
"returns",
"the",
"list",
"of",
"wildcards",
"in",
"other",
"that",
"have",
"a",
"different",
"name",
"from",
"the",
"wildcard",
"in",
"target",
"at",
"the",
"same",
"position",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/validation.go#L56-L63 |
166,973 | goadesign/goa | design/validation.go | Validate | func (cors *CORSDefinition) Validate() *dslengine.ValidationErrors {
verr := new(dslengine.ValidationErrors)
if !cors.Regexp && strings.Count(cors.Origin, "*") > 1 {
verr.Add(cors, "invalid origin, can only contain one wildcard character")
}
if cors.Regexp {
_, err := regexp.Compile(cors.Origin)
if err != nil {
verr.Add(cors, "invalid origin, should be a valid regular expression")
}
}
return verr
} | go | func (cors *CORSDefinition) Validate() *dslengine.ValidationErrors {
verr := new(dslengine.ValidationErrors)
if !cors.Regexp && strings.Count(cors.Origin, "*") > 1 {
verr.Add(cors, "invalid origin, can only contain one wildcard character")
}
if cors.Regexp {
_, err := regexp.Compile(cors.Origin)
if err != nil {
verr.Add(cors, "invalid origin, should be a valid regular expression")
}
}
return verr
} | [
"func",
"(",
"cors",
"*",
"CORSDefinition",
")",
"Validate",
"(",
")",
"*",
"dslengine",
".",
"ValidationErrors",
"{",
"verr",
":=",
"new",
"(",
"dslengine",
".",
"ValidationErrors",
")",
"\n",
"if",
"!",
"cors",
".",
"Regexp",
"&&",
"strings",
".",
"Cou... | // Validate makes sure the CORS definition origin is valid. | [
"Validate",
"makes",
"sure",
"the",
"CORS",
"definition",
"origin",
"is",
"valid",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/validation.go#L262-L274 |
166,974 | goadesign/goa | design/validation.go | Validate | func (enc *EncodingDefinition) Validate() *dslengine.ValidationErrors {
verr := new(dslengine.ValidationErrors)
if len(enc.MIMETypes) == 0 {
verr.Add(enc, "missing MIME type")
return verr
}
for _, m := range enc.MIMETypes {
_, _, err := mime.ParseMediaType(m)
if err != nil {
verr.Add(enc, "invalid MIME type %#v: %s", m, err)
}
}
if len(enc.PackagePath) > 0 {
rel := filepath.FromSlash(enc.PackagePath)
dir, err := os.Getwd()
if err != nil {
verr.Add(enc, "couldn't retrieve working directory %s", err)
return verr
}
_, err = build.Default.Import(rel, dir, build.FindOnly)
if err != nil {
verr.Add(enc, "invalid Go package path %#v: %s", enc.PackagePath, err)
return verr
}
} else {
for _, m := range enc.MIMETypes {
if _, ok := KnownEncoders[m]; !ok {
knownMIMETypes := make([]string, len(KnownEncoders))
i := 0
for k := range KnownEncoders {
knownMIMETypes[i] = k
i++
}
sort.Strings(knownMIMETypes)
verr.Add(enc, "Encoders not known for all MIME types, use Package to specify encoder Go package. MIME types with known encoders are %s",
strings.Join(knownMIMETypes, ", "))
}
}
}
if enc.Function != "" && enc.PackagePath == "" {
verr.Add(enc, "Must specify encoder package page with PackagePath")
}
return verr
} | go | func (enc *EncodingDefinition) Validate() *dslengine.ValidationErrors {
verr := new(dslengine.ValidationErrors)
if len(enc.MIMETypes) == 0 {
verr.Add(enc, "missing MIME type")
return verr
}
for _, m := range enc.MIMETypes {
_, _, err := mime.ParseMediaType(m)
if err != nil {
verr.Add(enc, "invalid MIME type %#v: %s", m, err)
}
}
if len(enc.PackagePath) > 0 {
rel := filepath.FromSlash(enc.PackagePath)
dir, err := os.Getwd()
if err != nil {
verr.Add(enc, "couldn't retrieve working directory %s", err)
return verr
}
_, err = build.Default.Import(rel, dir, build.FindOnly)
if err != nil {
verr.Add(enc, "invalid Go package path %#v: %s", enc.PackagePath, err)
return verr
}
} else {
for _, m := range enc.MIMETypes {
if _, ok := KnownEncoders[m]; !ok {
knownMIMETypes := make([]string, len(KnownEncoders))
i := 0
for k := range KnownEncoders {
knownMIMETypes[i] = k
i++
}
sort.Strings(knownMIMETypes)
verr.Add(enc, "Encoders not known for all MIME types, use Package to specify encoder Go package. MIME types with known encoders are %s",
strings.Join(knownMIMETypes, ", "))
}
}
}
if enc.Function != "" && enc.PackagePath == "" {
verr.Add(enc, "Must specify encoder package page with PackagePath")
}
return verr
} | [
"func",
"(",
"enc",
"*",
"EncodingDefinition",
")",
"Validate",
"(",
")",
"*",
"dslengine",
".",
"ValidationErrors",
"{",
"verr",
":=",
"new",
"(",
"dslengine",
".",
"ValidationErrors",
")",
"\n",
"if",
"len",
"(",
"enc",
".",
"MIMETypes",
")",
"==",
"0"... | // Validate validates the encoding MIME type and Go package path if set. | [
"Validate",
"validates",
"the",
"encoding",
"MIME",
"type",
"and",
"Go",
"package",
"path",
"if",
"set",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/validation.go#L277-L320 |
166,975 | goadesign/goa | design/validation.go | Validate | func (f *FileServerDefinition) Validate() *dslengine.ValidationErrors {
verr := new(dslengine.ValidationErrors)
if f.FilePath == "" {
verr.Add(f, "File server must have a non empty file path")
}
if f.RequestPath == "" {
verr.Add(f, "File server must have a non empty route path")
}
if f.Parent == nil {
verr.Add(f, "missing parent resource")
}
matches := WildcardRegex.FindAllString(f.RequestPath, -1)
if len(matches) == 1 {
if !strings.HasSuffix(f.RequestPath, matches[0]) {
verr.Add(f, "invalid request path %s, must end with a wildcard starting with *", f.RequestPath)
}
}
if len(matches) > 2 {
verr.Add(f, "invalid request path, may only contain one wildcard")
}
return verr.AsError()
} | go | func (f *FileServerDefinition) Validate() *dslengine.ValidationErrors {
verr := new(dslengine.ValidationErrors)
if f.FilePath == "" {
verr.Add(f, "File server must have a non empty file path")
}
if f.RequestPath == "" {
verr.Add(f, "File server must have a non empty route path")
}
if f.Parent == nil {
verr.Add(f, "missing parent resource")
}
matches := WildcardRegex.FindAllString(f.RequestPath, -1)
if len(matches) == 1 {
if !strings.HasSuffix(f.RequestPath, matches[0]) {
verr.Add(f, "invalid request path %s, must end with a wildcard starting with *", f.RequestPath)
}
}
if len(matches) > 2 {
verr.Add(f, "invalid request path, may only contain one wildcard")
}
return verr.AsError()
} | [
"func",
"(",
"f",
"*",
"FileServerDefinition",
")",
"Validate",
"(",
")",
"*",
"dslengine",
".",
"ValidationErrors",
"{",
"verr",
":=",
"new",
"(",
"dslengine",
".",
"ValidationErrors",
")",
"\n",
"if",
"f",
".",
"FilePath",
"==",
"\"",
"\"",
"{",
"verr"... | // Validate checks the file server is properly initialized. | [
"Validate",
"checks",
"the",
"file",
"server",
"is",
"properly",
"initialized",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/validation.go#L377-L399 |
166,976 | goadesign/goa | logging.go | LogInfo | func LogInfo(ctx context.Context, msg string, keyvals ...interface{}) {
if l := ctx.Value(logKey); l != nil {
if logger, ok := l.(LogAdapter); ok {
logger.Info(msg, keyvals...)
}
}
} | go | func LogInfo(ctx context.Context, msg string, keyvals ...interface{}) {
if l := ctx.Value(logKey); l != nil {
if logger, ok := l.(LogAdapter); ok {
logger.Info(msg, keyvals...)
}
}
} | [
"func",
"LogInfo",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"string",
",",
"keyvals",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"l",
":=",
"ctx",
".",
"Value",
"(",
"logKey",
")",
";",
"l",
"!=",
"nil",
"{",
"if",
"logger",
",",
"ok... | // LogInfo extracts the logger from the given context and calls Info on it.
// This is intended for code that needs portable logging such as the internal code of goa and
// middleware. User code should use the log adapters instead. | [
"LogInfo",
"extracts",
"the",
"logger",
"from",
"the",
"given",
"context",
"and",
"calls",
"Info",
"on",
"it",
".",
"This",
"is",
"intended",
"for",
"code",
"that",
"needs",
"portable",
"logging",
"such",
"as",
"the",
"internal",
"code",
"of",
"goa",
"and"... | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/logging.go#L106-L112 |
166,977 | goadesign/goa | logging.go | LogError | func LogError(ctx context.Context, msg string, keyvals ...interface{}) {
if l := ctx.Value(logKey); l != nil {
if logger, ok := l.(LogAdapter); ok {
logger.Error(msg, keyvals...)
}
}
} | go | func LogError(ctx context.Context, msg string, keyvals ...interface{}) {
if l := ctx.Value(logKey); l != nil {
if logger, ok := l.(LogAdapter); ok {
logger.Error(msg, keyvals...)
}
}
} | [
"func",
"LogError",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"string",
",",
"keyvals",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"l",
":=",
"ctx",
".",
"Value",
"(",
"logKey",
")",
";",
"l",
"!=",
"nil",
"{",
"if",
"logger",
",",
"o... | // LogError extracts the logger from the given context and calls Error on it.
// This is intended for code that needs portable logging such as the internal code of goa and
// middleware. User code should use the log adapters instead. | [
"LogError",
"extracts",
"the",
"logger",
"from",
"the",
"given",
"context",
"and",
"calls",
"Error",
"on",
"it",
".",
"This",
"is",
"intended",
"for",
"code",
"that",
"needs",
"portable",
"logging",
"such",
"as",
"the",
"internal",
"code",
"of",
"goa",
"an... | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/logging.go#L117-L123 |
166,978 | goadesign/goa | middleware/log_response.go | Write | func (lrw *loggingResponseWriter) Write(buf []byte) (int, error) {
goa.LogInfo(lrw.ctx, "response", "body", string(buf))
return lrw.ResponseWriter.Write(buf)
} | go | func (lrw *loggingResponseWriter) Write(buf []byte) (int, error) {
goa.LogInfo(lrw.ctx, "response", "body", string(buf))
return lrw.ResponseWriter.Write(buf)
} | [
"func",
"(",
"lrw",
"*",
"loggingResponseWriter",
")",
"Write",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"goa",
".",
"LogInfo",
"(",
"lrw",
".",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"string",
"(",
"buf",
"... | // Write will write raw data to logger and response writer. | [
"Write",
"will",
"write",
"raw",
"data",
"to",
"logger",
"and",
"response",
"writer",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/log_response.go#L20-L23 |
166,979 | goadesign/goa | middleware/log_response.go | LogResponse | func LogResponse() goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// chain a new logging writer to the current response writer.
resp := goa.ContextResponse(ctx)
resp.SwitchWriter(
&loggingResponseWriter{
ResponseWriter: resp.SwitchWriter(nil),
ctx: ctx,
})
// next
return h(ctx, rw, req)
}
}
} | go | func LogResponse() goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// chain a new logging writer to the current response writer.
resp := goa.ContextResponse(ctx)
resp.SwitchWriter(
&loggingResponseWriter{
ResponseWriter: resp.SwitchWriter(nil),
ctx: ctx,
})
// next
return h(ctx, rw, req)
}
}
} | [
"func",
"LogResponse",
"(",
")",
"goa",
".",
"Middleware",
"{",
"return",
"func",
"(",
"h",
"goa",
".",
"Handler",
")",
"goa",
".",
"Handler",
"{",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"rw",
"http",
".",
"ResponseWriter",
",",
... | // LogResponse creates a response logger middleware.
// Only Logs the raw response data without accumulating any statistics. | [
"LogResponse",
"creates",
"a",
"response",
"logger",
"middleware",
".",
"Only",
"Logs",
"the",
"raw",
"response",
"data",
"without",
"accumulating",
"any",
"statistics",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/middleware/log_response.go#L27-L42 |
166,980 | goadesign/goa | design/apidsl/init.go | init | func init() {
design.Design = design.NewAPIDefinition()
design.GeneratedMediaTypes = make(design.MediaTypeRoot)
design.ProjectedMediaTypes = make(design.MediaTypeRoot)
dslengine.Register(design.Design)
dslengine.Register(design.GeneratedMediaTypes)
} | go | func init() {
design.Design = design.NewAPIDefinition()
design.GeneratedMediaTypes = make(design.MediaTypeRoot)
design.ProjectedMediaTypes = make(design.MediaTypeRoot)
dslengine.Register(design.Design)
dslengine.Register(design.GeneratedMediaTypes)
} | [
"func",
"init",
"(",
")",
"{",
"design",
".",
"Design",
"=",
"design",
".",
"NewAPIDefinition",
"(",
")",
"\n",
"design",
".",
"GeneratedMediaTypes",
"=",
"make",
"(",
"design",
".",
"MediaTypeRoot",
")",
"\n",
"design",
".",
"ProjectedMediaTypes",
"=",
"m... | // Setup API DSL roots. | [
"Setup",
"API",
"DSL",
"roots",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/init.go#L9-L15 |
166,981 | goadesign/goa | encoding/gogoprotobuf/encoding.go | NewDecoder | func NewDecoder(r io.Reader) goa.Decoder {
return &ProtoDecoder{
pBuf: proto.NewBuffer(nil),
bBuf: &bytes.Buffer{},
r: r,
}
} | go | func NewDecoder(r io.Reader) goa.Decoder {
return &ProtoDecoder{
pBuf: proto.NewBuffer(nil),
bBuf: &bytes.Buffer{},
r: r,
}
} | [
"func",
"NewDecoder",
"(",
"r",
"io",
".",
"Reader",
")",
"goa",
".",
"Decoder",
"{",
"return",
"&",
"ProtoDecoder",
"{",
"pBuf",
":",
"proto",
".",
"NewBuffer",
"(",
"nil",
")",
",",
"bBuf",
":",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
",",
"r",
... | // NewDecoder returns a new proto.Decoder that satisfies goa.Decoder | [
"NewDecoder",
"returns",
"a",
"new",
"proto",
".",
"Decoder",
"that",
"satisfies",
"goa",
".",
"Decoder"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/gogoprotobuf/encoding.go#L34-L40 |
166,982 | goadesign/goa | encoding/gogoprotobuf/encoding.go | Decode | func (dec *ProtoDecoder) Decode(v interface{}) error {
msg, ok := v.(proto.Message)
if !ok {
return errors.New("Cannot decode into struct that doesn't implement proto.Message")
}
var err error
// derekperkins TODO: pipe reader directly to proto.Buffer
if _, err = dec.bBuf.ReadFrom(dec.r); err != nil {
return err
}
dec.pBuf.SetBuf(dec.bBuf.Bytes())
return dec.pBuf.Unmarshal(msg)
} | go | func (dec *ProtoDecoder) Decode(v interface{}) error {
msg, ok := v.(proto.Message)
if !ok {
return errors.New("Cannot decode into struct that doesn't implement proto.Message")
}
var err error
// derekperkins TODO: pipe reader directly to proto.Buffer
if _, err = dec.bBuf.ReadFrom(dec.r); err != nil {
return err
}
dec.pBuf.SetBuf(dec.bBuf.Bytes())
return dec.pBuf.Unmarshal(msg)
} | [
"func",
"(",
"dec",
"*",
"ProtoDecoder",
")",
"Decode",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"msg",
",",
"ok",
":=",
"v",
".",
"(",
"proto",
".",
"Message",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\... | // Decode unmarshals an io.Reader into proto.Message v | [
"Decode",
"unmarshals",
"an",
"io",
".",
"Reader",
"into",
"proto",
".",
"Message",
"v"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/gogoprotobuf/encoding.go#L43-L58 |
166,983 | goadesign/goa | encoding/gogoprotobuf/encoding.go | Reset | func (dec *ProtoDecoder) Reset(r io.Reader) {
dec.pBuf.Reset()
dec.bBuf.Reset()
dec.r = r
} | go | func (dec *ProtoDecoder) Reset(r io.Reader) {
dec.pBuf.Reset()
dec.bBuf.Reset()
dec.r = r
} | [
"func",
"(",
"dec",
"*",
"ProtoDecoder",
")",
"Reset",
"(",
"r",
"io",
".",
"Reader",
")",
"{",
"dec",
".",
"pBuf",
".",
"Reset",
"(",
")",
"\n",
"dec",
".",
"bBuf",
".",
"Reset",
"(",
")",
"\n",
"dec",
".",
"r",
"=",
"r",
"\n",
"}"
] | // Reset stores the new reader and resets its bytes.Buffer and proto.Buffer | [
"Reset",
"stores",
"the",
"new",
"reader",
"and",
"resets",
"its",
"bytes",
".",
"Buffer",
"and",
"proto",
".",
"Buffer"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/gogoprotobuf/encoding.go#L61-L65 |
166,984 | goadesign/goa | encoding/gogoprotobuf/encoding.go | NewEncoder | func NewEncoder(w io.Writer) goa.Encoder {
return &ProtoEncoder{
pBuf: proto.NewBuffer(nil),
w: w,
}
} | go | func NewEncoder(w io.Writer) goa.Encoder {
return &ProtoEncoder{
pBuf: proto.NewBuffer(nil),
w: w,
}
} | [
"func",
"NewEncoder",
"(",
"w",
"io",
".",
"Writer",
")",
"goa",
".",
"Encoder",
"{",
"return",
"&",
"ProtoEncoder",
"{",
"pBuf",
":",
"proto",
".",
"NewBuffer",
"(",
"nil",
")",
",",
"w",
":",
"w",
",",
"}",
"\n",
"}"
] | // NewEncoder returns a new proto.Encoder that satisfies goa.Encoder | [
"NewEncoder",
"returns",
"a",
"new",
"proto",
".",
"Encoder",
"that",
"satisfies",
"goa",
".",
"Encoder"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/gogoprotobuf/encoding.go#L68-L73 |
166,985 | goadesign/goa | encoding/gogoprotobuf/encoding.go | Encode | func (enc *ProtoEncoder) Encode(v interface{}) error {
msg, ok := v.(proto.Message)
if !ok {
return errors.New("Cannot encode struct that doesn't implement proto.Message")
}
var err error
// derekperkins TODO: pipe marshal directly to writer
if err = enc.pBuf.Marshal(msg); err != nil {
return err
}
if _, err = enc.w.Write(enc.pBuf.Bytes()); err != nil {
return err
}
return nil
} | go | func (enc *ProtoEncoder) Encode(v interface{}) error {
msg, ok := v.(proto.Message)
if !ok {
return errors.New("Cannot encode struct that doesn't implement proto.Message")
}
var err error
// derekperkins TODO: pipe marshal directly to writer
if err = enc.pBuf.Marshal(msg); err != nil {
return err
}
if _, err = enc.w.Write(enc.pBuf.Bytes()); err != nil {
return err
}
return nil
} | [
"func",
"(",
"enc",
"*",
"ProtoEncoder",
")",
"Encode",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"msg",
",",
"ok",
":=",
"v",
".",
"(",
"proto",
".",
"Message",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\... | // Encode marshals a proto.Message and writes it to an io.Writer | [
"Encode",
"marshals",
"a",
"proto",
".",
"Message",
"and",
"writes",
"it",
"to",
"an",
"io",
".",
"Writer"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/gogoprotobuf/encoding.go#L76-L93 |
166,986 | goadesign/goa | encoding/gogoprotobuf/encoding.go | Reset | func (enc *ProtoEncoder) Reset(w io.Writer) {
enc.pBuf.Reset()
enc.w = w
} | go | func (enc *ProtoEncoder) Reset(w io.Writer) {
enc.pBuf.Reset()
enc.w = w
} | [
"func",
"(",
"enc",
"*",
"ProtoEncoder",
")",
"Reset",
"(",
"w",
"io",
".",
"Writer",
")",
"{",
"enc",
".",
"pBuf",
".",
"Reset",
"(",
")",
"\n",
"enc",
".",
"w",
"=",
"w",
"\n",
"}"
] | // Reset stores the new writer and resets its proto.Buffer | [
"Reset",
"stores",
"the",
"new",
"writer",
"and",
"resets",
"its",
"proto",
".",
"Buffer"
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/encoding/gogoprotobuf/encoding.go#L96-L99 |
166,987 | goadesign/goa | goagen/codegen/finalizer.go | NewFinalizer | func NewFinalizer() *Finalizer {
var (
f = &Finalizer{seen: make(map[*design.AttributeDefinition]map[*design.AttributeDefinition]*bytes.Buffer)}
err error
)
fm := template.FuncMap{
"tabs": Tabs,
"goify": Goify,
"gotyperef": GoTypeRef,
"add": Add,
"finalizeCode": f.Code,
}
f.assignmentT, err = template.New("assignment").Funcs(fm).Parse(assignmentTmpl)
if err != nil {
panic(err)
}
f.arrayAssignmentT, err = template.New("arrAssignment").Funcs(fm).Parse(arrayAssignmentTmpl)
if err != nil {
panic(err)
}
return f
} | go | func NewFinalizer() *Finalizer {
var (
f = &Finalizer{seen: make(map[*design.AttributeDefinition]map[*design.AttributeDefinition]*bytes.Buffer)}
err error
)
fm := template.FuncMap{
"tabs": Tabs,
"goify": Goify,
"gotyperef": GoTypeRef,
"add": Add,
"finalizeCode": f.Code,
}
f.assignmentT, err = template.New("assignment").Funcs(fm).Parse(assignmentTmpl)
if err != nil {
panic(err)
}
f.arrayAssignmentT, err = template.New("arrAssignment").Funcs(fm).Parse(arrayAssignmentTmpl)
if err != nil {
panic(err)
}
return f
} | [
"func",
"NewFinalizer",
"(",
")",
"*",
"Finalizer",
"{",
"var",
"(",
"f",
"=",
"&",
"Finalizer",
"{",
"seen",
":",
"make",
"(",
"map",
"[",
"*",
"design",
".",
"AttributeDefinition",
"]",
"map",
"[",
"*",
"design",
".",
"AttributeDefinition",
"]",
"*",... | // NewFinalizer instantiates a finalize code generator. | [
"NewFinalizer",
"instantiates",
"a",
"finalize",
"code",
"generator",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/finalizer.go#L19-L40 |
166,988 | goadesign/goa | goagen/codegen/finalizer.go | Code | func (f *Finalizer) Code(att *design.AttributeDefinition, target string, depth int) string {
buf := f.recurse(att, att, target, depth)
return buf.String()
} | go | func (f *Finalizer) Code(att *design.AttributeDefinition, target string, depth int) string {
buf := f.recurse(att, att, target, depth)
return buf.String()
} | [
"func",
"(",
"f",
"*",
"Finalizer",
")",
"Code",
"(",
"att",
"*",
"design",
".",
"AttributeDefinition",
",",
"target",
"string",
",",
"depth",
"int",
")",
"string",
"{",
"buf",
":=",
"f",
".",
"recurse",
"(",
"att",
",",
"att",
",",
"target",
",",
... | // Code produces Go code that sets the default values for fields recursively for the given
// attribute. | [
"Code",
"produces",
"Go",
"code",
"that",
"sets",
"the",
"default",
"values",
"for",
"fields",
"recursively",
"for",
"the",
"given",
"attribute",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/finalizer.go#L44-L47 |
166,989 | goadesign/goa | goagen/codegen/finalizer.go | PrintVal | func PrintVal(t design.DataType, val interface{}) string {
switch {
case t.IsPrimitive():
// For primitive types, simply print the value
s := fmt.Sprintf("%#v", val)
switch t {
case design.Number:
v := val
if i, ok := val.(int); ok {
v = float64(i)
}
s = fmt.Sprintf("%f", v)
case design.DateTime:
s = fmt.Sprintf("time.Parse(time.RFC3339, %s)", s)
}
return s
case t.IsHash():
// The input is a hash
h := t.ToHash()
hval := val.(map[interface{}]interface{})
if len(hval) == 0 {
return fmt.Sprintf("%s{}", GoTypeName(t, nil, 0, false))
}
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("%s{", GoTypeName(t, nil, 0, false)))
for k, v := range hval {
buffer.WriteString(fmt.Sprintf("%s: %s, ", PrintVal(h.KeyType.Type, k), PrintVal(h.ElemType.Type, v)))
}
buffer.Truncate(buffer.Len() - 2) // remove ", "
buffer.WriteString("}")
return buffer.String()
case t.IsArray():
// Input is an array
a := t.ToArray()
aval := val.([]interface{})
if len(aval) == 0 {
return fmt.Sprintf("%s{}", GoTypeName(t, nil, 0, false))
}
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("%s{", GoTypeName(t, nil, 0, false)))
for _, e := range aval {
buffer.WriteString(fmt.Sprintf("%s, ", PrintVal(a.ElemType.Type, e)))
}
buffer.Truncate(buffer.Len() - 2) // remove ", "
buffer.WriteString("}")
return buffer.String()
default:
// shouldn't happen as the value's compatibility is already checked.
panic("unknown type")
}
} | go | func PrintVal(t design.DataType, val interface{}) string {
switch {
case t.IsPrimitive():
// For primitive types, simply print the value
s := fmt.Sprintf("%#v", val)
switch t {
case design.Number:
v := val
if i, ok := val.(int); ok {
v = float64(i)
}
s = fmt.Sprintf("%f", v)
case design.DateTime:
s = fmt.Sprintf("time.Parse(time.RFC3339, %s)", s)
}
return s
case t.IsHash():
// The input is a hash
h := t.ToHash()
hval := val.(map[interface{}]interface{})
if len(hval) == 0 {
return fmt.Sprintf("%s{}", GoTypeName(t, nil, 0, false))
}
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("%s{", GoTypeName(t, nil, 0, false)))
for k, v := range hval {
buffer.WriteString(fmt.Sprintf("%s: %s, ", PrintVal(h.KeyType.Type, k), PrintVal(h.ElemType.Type, v)))
}
buffer.Truncate(buffer.Len() - 2) // remove ", "
buffer.WriteString("}")
return buffer.String()
case t.IsArray():
// Input is an array
a := t.ToArray()
aval := val.([]interface{})
if len(aval) == 0 {
return fmt.Sprintf("%s{}", GoTypeName(t, nil, 0, false))
}
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("%s{", GoTypeName(t, nil, 0, false)))
for _, e := range aval {
buffer.WriteString(fmt.Sprintf("%s, ", PrintVal(a.ElemType.Type, e)))
}
buffer.Truncate(buffer.Len() - 2) // remove ", "
buffer.WriteString("}")
return buffer.String()
default:
// shouldn't happen as the value's compatibility is already checked.
panic("unknown type")
}
} | [
"func",
"PrintVal",
"(",
"t",
"design",
".",
"DataType",
",",
"val",
"interface",
"{",
"}",
")",
"string",
"{",
"switch",
"{",
"case",
"t",
".",
"IsPrimitive",
"(",
")",
":",
"// For primitive types, simply print the value",
"s",
":=",
"fmt",
".",
"Sprintf",... | // PrintVal prints the given value corresponding to the given data type.
// The value is already checked for the compatibility with the data type. | [
"PrintVal",
"prints",
"the",
"given",
"value",
"corresponding",
"to",
"the",
"given",
"data",
"type",
".",
"The",
"value",
"is",
"already",
"checked",
"for",
"the",
"compatibility",
"with",
"the",
"data",
"type",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/goagen/codegen/finalizer.go#L112-L162 |
166,990 | goadesign/goa | logging/kit/adapter.go | Info | func (a *adapter) Info(msg string, data ...interface{}) {
ctx := []interface{}{"lvl", "info", "msg", msg}
ctx = append(ctx, data...)
a.Logger.Log(ctx...)
} | go | func (a *adapter) Info(msg string, data ...interface{}) {
ctx := []interface{}{"lvl", "info", "msg", msg}
ctx = append(ctx, data...)
a.Logger.Log(ctx...)
} | [
"func",
"(",
"a",
"*",
"adapter",
")",
"Info",
"(",
"msg",
"string",
",",
"data",
"...",
"interface",
"{",
"}",
")",
"{",
"ctx",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"msg",
"}",
"\n",
... | // Info logs informational messages using go-kit. | [
"Info",
"logs",
"informational",
"messages",
"using",
"go",
"-",
"kit",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/logging/kit/adapter.go#L44-L48 |
166,991 | goadesign/goa | logging/kit/adapter.go | New | func (a *adapter) New(data ...interface{}) goa.LogAdapter {
return &adapter{Logger: log.With(a.Logger, data...)}
} | go | func (a *adapter) New(data ...interface{}) goa.LogAdapter {
return &adapter{Logger: log.With(a.Logger, data...)}
} | [
"func",
"(",
"a",
"*",
"adapter",
")",
"New",
"(",
"data",
"...",
"interface",
"{",
"}",
")",
"goa",
".",
"LogAdapter",
"{",
"return",
"&",
"adapter",
"{",
"Logger",
":",
"log",
".",
"With",
"(",
"a",
".",
"Logger",
",",
"data",
"...",
")",
"}",
... | // New instantiates a new logger from the given context. | [
"New",
"instantiates",
"a",
"new",
"logger",
"from",
"the",
"given",
"context",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/logging/kit/adapter.go#L58-L60 |
166,992 | goadesign/goa | design/apidsl/current.go | encodingDefinition | func encodingDefinition() (*design.EncodingDefinition, bool) {
e, ok := dslengine.CurrentDefinition().(*design.EncodingDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return e, ok
} | go | func encodingDefinition() (*design.EncodingDefinition, bool) {
e, ok := dslengine.CurrentDefinition().(*design.EncodingDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return e, ok
} | [
"func",
"encodingDefinition",
"(",
")",
"(",
"*",
"design",
".",
"EncodingDefinition",
",",
"bool",
")",
"{",
"e",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"EncodingDefinition",
")",
"\n",
"if",
"!",... | // encodingDefinition returns true and current context if it is an EncodingDefinition,
// nil and false otherwise. | [
"encodingDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"an",
"EncodingDefinition",
"nil",
"and",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L27-L33 |
166,993 | goadesign/goa | design/apidsl/current.go | contactDefinition | func contactDefinition() (*design.ContactDefinition, bool) {
a, ok := dslengine.CurrentDefinition().(*design.ContactDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return a, ok
} | go | func contactDefinition() (*design.ContactDefinition, bool) {
a, ok := dslengine.CurrentDefinition().(*design.ContactDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return a, ok
} | [
"func",
"contactDefinition",
"(",
")",
"(",
"*",
"design",
".",
"ContactDefinition",
",",
"bool",
")",
"{",
"a",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"ContactDefinition",
")",
"\n",
"if",
"!",
... | // contactDefinition returns true and current context if it is an ContactDefinition,
// nil and false otherwise. | [
"contactDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"an",
"ContactDefinition",
"nil",
"and",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L37-L43 |
166,994 | goadesign/goa | design/apidsl/current.go | licenseDefinition | func licenseDefinition() (*design.LicenseDefinition, bool) {
l, ok := dslengine.CurrentDefinition().(*design.LicenseDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return l, ok
} | go | func licenseDefinition() (*design.LicenseDefinition, bool) {
l, ok := dslengine.CurrentDefinition().(*design.LicenseDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return l, ok
} | [
"func",
"licenseDefinition",
"(",
")",
"(",
"*",
"design",
".",
"LicenseDefinition",
",",
"bool",
")",
"{",
"l",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"LicenseDefinition",
")",
"\n",
"if",
"!",
... | // licenseDefinition returns true and current context if it is an APIDefinition,
// nil and false otherwise. | [
"licenseDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"an",
"APIDefinition",
"nil",
"and",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L47-L53 |
166,995 | goadesign/goa | design/apidsl/current.go | docsDefinition | func docsDefinition() (*design.DocsDefinition, bool) {
a, ok := dslengine.CurrentDefinition().(*design.DocsDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return a, ok
} | go | func docsDefinition() (*design.DocsDefinition, bool) {
a, ok := dslengine.CurrentDefinition().(*design.DocsDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return a, ok
} | [
"func",
"docsDefinition",
"(",
")",
"(",
"*",
"design",
".",
"DocsDefinition",
",",
"bool",
")",
"{",
"a",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"DocsDefinition",
")",
"\n",
"if",
"!",
"ok",
"... | // docsDefinition returns true and current context if it is a DocsDefinition,
// nil and false otherwise. | [
"docsDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"a",
"DocsDefinition",
"nil",
"and",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L57-L63 |
166,996 | goadesign/goa | design/apidsl/current.go | mediaTypeDefinition | func mediaTypeDefinition() (*design.MediaTypeDefinition, bool) {
m, ok := dslengine.CurrentDefinition().(*design.MediaTypeDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return m, ok
} | go | func mediaTypeDefinition() (*design.MediaTypeDefinition, bool) {
m, ok := dslengine.CurrentDefinition().(*design.MediaTypeDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return m, ok
} | [
"func",
"mediaTypeDefinition",
"(",
")",
"(",
"*",
"design",
".",
"MediaTypeDefinition",
",",
"bool",
")",
"{",
"m",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"MediaTypeDefinition",
")",
"\n",
"if",
"... | // mediaTypeDefinition returns true and current context if it is a MediaTypeDefinition,
// nil and false otherwise. | [
"mediaTypeDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"a",
"MediaTypeDefinition",
"nil",
"and",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L67-L73 |
166,997 | goadesign/goa | design/apidsl/current.go | typeDefinition | func typeDefinition() (*design.UserTypeDefinition, bool) {
m, ok := dslengine.CurrentDefinition().(*design.UserTypeDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return m, ok
} | go | func typeDefinition() (*design.UserTypeDefinition, bool) {
m, ok := dslengine.CurrentDefinition().(*design.UserTypeDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return m, ok
} | [
"func",
"typeDefinition",
"(",
")",
"(",
"*",
"design",
".",
"UserTypeDefinition",
",",
"bool",
")",
"{",
"m",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"UserTypeDefinition",
")",
"\n",
"if",
"!",
"... | // typeDefinition returns true and current context if it is a UserTypeDefinition,
// nil and false otherwise. | [
"typeDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"a",
"UserTypeDefinition",
"nil",
"and",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L77-L83 |
166,998 | goadesign/goa | design/apidsl/current.go | resourceDefinition | func resourceDefinition() (*design.ResourceDefinition, bool) {
r, ok := dslengine.CurrentDefinition().(*design.ResourceDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return r, ok
} | go | func resourceDefinition() (*design.ResourceDefinition, bool) {
r, ok := dslengine.CurrentDefinition().(*design.ResourceDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return r, ok
} | [
"func",
"resourceDefinition",
"(",
")",
"(",
"*",
"design",
".",
"ResourceDefinition",
",",
"bool",
")",
"{",
"r",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"ResourceDefinition",
")",
"\n",
"if",
"!",... | // resourceDefinition returns true and current context if it is a ResourceDefinition,
// nil and false otherwise. | [
"resourceDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"a",
"ResourceDefinition",
"nil",
"and",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L97-L103 |
166,999 | goadesign/goa | design/apidsl/current.go | corsDefinition | func corsDefinition() (*design.CORSDefinition, bool) {
cors, ok := dslengine.CurrentDefinition().(*design.CORSDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return cors, ok
} | go | func corsDefinition() (*design.CORSDefinition, bool) {
cors, ok := dslengine.CurrentDefinition().(*design.CORSDefinition)
if !ok {
dslengine.IncompatibleDSL()
}
return cors, ok
} | [
"func",
"corsDefinition",
"(",
")",
"(",
"*",
"design",
".",
"CORSDefinition",
",",
"bool",
")",
"{",
"cors",
",",
"ok",
":=",
"dslengine",
".",
"CurrentDefinition",
"(",
")",
".",
"(",
"*",
"design",
".",
"CORSDefinition",
")",
"\n",
"if",
"!",
"ok",
... | // corsDefinition returns true and current context if it is a CORSDefinition, nil And
// false otherwise. | [
"corsDefinition",
"returns",
"true",
"and",
"current",
"context",
"if",
"it",
"is",
"a",
"CORSDefinition",
"nil",
"And",
"false",
"otherwise",
"."
] | 90bd33edff1a4f17fab06d1f9e14e659075d1328 | https://github.com/goadesign/goa/blob/90bd33edff1a4f17fab06d1f9e14e659075d1328/design/apidsl/current.go#L107-L113 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.