repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
janos/web
|
templates/templates.go
|
WithTemplateFromStrings
|
func WithTemplateFromStrings(name string, strings ...string) Option {
return func(o *Options) { o.strings[name] = strings }
}
|
go
|
func WithTemplateFromStrings(name string, strings ...string) Option {
return func(o *Options) { o.strings[name] = strings }
}
|
[
"func",
"WithTemplateFromStrings",
"(",
"name",
"string",
",",
"strings",
"...",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"o",
".",
"strings",
"[",
"name",
"]",
"=",
"strings",
"}",
"\n",
"}"
] |
// WithTemplateFromStrings adds a template parsed from string.
|
[
"WithTemplateFromStrings",
"adds",
"a",
"template",
"parsed",
"from",
"string",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L101-L103
|
test
|
janos/web
|
templates/templates.go
|
WithTemplatesFromStrings
|
func WithTemplatesFromStrings(ts map[string][]string) Option {
return func(o *Options) {
for name, strings := range ts {
o.strings[name] = strings
}
}
}
|
go
|
func WithTemplatesFromStrings(ts map[string][]string) Option {
return func(o *Options) {
for name, strings := range ts {
o.strings[name] = strings
}
}
}
|
[
"func",
"WithTemplatesFromStrings",
"(",
"ts",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"for",
"name",
",",
"strings",
":=",
"range",
"ts",
"{",
"o",
".",
"strings",
"[",
"name",
"]",
"=",
"strings",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// WithTemplatesFromStrings adds a map of templates parsed from strings.
|
[
"WithTemplatesFromStrings",
"adds",
"a",
"map",
"of",
"templates",
"parsed",
"from",
"strings",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L106-L112
|
test
|
janos/web
|
templates/templates.go
|
WithFunction
|
func WithFunction(name string, fn interface{}) Option {
return func(o *Options) { o.functions[name] = fn }
}
|
go
|
func WithFunction(name string, fn interface{}) Option {
return func(o *Options) { o.functions[name] = fn }
}
|
[
"func",
"WithFunction",
"(",
"name",
"string",
",",
"fn",
"interface",
"{",
"}",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"o",
".",
"functions",
"[",
"name",
"]",
"=",
"fn",
"}",
"\n",
"}"
] |
// WithFunction adds a function to templates.
|
[
"WithFunction",
"adds",
"a",
"function",
"to",
"templates",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L115-L117
|
test
|
janos/web
|
templates/templates.go
|
WithFunctions
|
func WithFunctions(fns template.FuncMap) Option {
return func(o *Options) {
for name, fn := range fns {
o.functions[name] = fn
}
}
}
|
go
|
func WithFunctions(fns template.FuncMap) Option {
return func(o *Options) {
for name, fn := range fns {
o.functions[name] = fn
}
}
}
|
[
"func",
"WithFunctions",
"(",
"fns",
"template",
".",
"FuncMap",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"for",
"name",
",",
"fn",
":=",
"range",
"fns",
"{",
"o",
".",
"functions",
"[",
"name",
"]",
"=",
"fn",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// WithFunctions adds function map to templates.
|
[
"WithFunctions",
"adds",
"function",
"map",
"to",
"templates",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L120-L126
|
test
|
janos/web
|
templates/templates.go
|
WithDelims
|
func WithDelims(open, close string) Option {
return func(o *Options) {
o.delimOpen = open
o.delimClose = close
}
}
|
go
|
func WithDelims(open, close string) Option {
return func(o *Options) {
o.delimOpen = open
o.delimClose = close
}
}
|
[
"func",
"WithDelims",
"(",
"open",
",",
"close",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"o",
".",
"delimOpen",
"=",
"open",
"\n",
"o",
".",
"delimClose",
"=",
"close",
"\n",
"}",
"\n",
"}"
] |
// WithDelims sets the delimiters used in templates.
|
[
"WithDelims",
"sets",
"the",
"delimiters",
"used",
"in",
"templates",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L129-L134
|
test
|
janos/web
|
templates/templates.go
|
New
|
func New(opts ...Option) (t *Templates, err error) {
functions := template.FuncMap{}
for name, fn := range defaultFunctions {
functions[name] = fn
}
o := &Options{
fileFindFunc: func(f string) string {
return f
},
fileReadFunc: ioutil.ReadFile,
files: map[string][]string{},
functions: functions,
delimOpen: "{{",
delimClose: "}}",
logf: log.Printf,
}
for _, opt := range opts {
opt(o)
}
t = &Templates{
templates: map[string]*template.Template{},
contentType: o.contentType,
logf: o.logf,
}
for name, strings := range o.strings {
tpl, err := parseStrings(template.New("").Funcs(o.functions).Delims(o.delimOpen, o.delimClose), strings...)
if err != nil {
return nil, err
}
t.templates[name] = tpl
}
for name, files := range o.files {
fs := []string{}
for _, f := range files {
fs = append(fs, o.fileFindFunc(f))
}
tpl, err := parseFiles(o.fileReadFunc, template.New("").Funcs(o.functions).Delims(o.delimOpen, o.delimClose), fs...)
if err != nil {
return nil, err
}
t.templates[name] = tpl
}
return
}
|
go
|
func New(opts ...Option) (t *Templates, err error) {
functions := template.FuncMap{}
for name, fn := range defaultFunctions {
functions[name] = fn
}
o := &Options{
fileFindFunc: func(f string) string {
return f
},
fileReadFunc: ioutil.ReadFile,
files: map[string][]string{},
functions: functions,
delimOpen: "{{",
delimClose: "}}",
logf: log.Printf,
}
for _, opt := range opts {
opt(o)
}
t = &Templates{
templates: map[string]*template.Template{},
contentType: o.contentType,
logf: o.logf,
}
for name, strings := range o.strings {
tpl, err := parseStrings(template.New("").Funcs(o.functions).Delims(o.delimOpen, o.delimClose), strings...)
if err != nil {
return nil, err
}
t.templates[name] = tpl
}
for name, files := range o.files {
fs := []string{}
for _, f := range files {
fs = append(fs, o.fileFindFunc(f))
}
tpl, err := parseFiles(o.fileReadFunc, template.New("").Funcs(o.functions).Delims(o.delimOpen, o.delimClose), fs...)
if err != nil {
return nil, err
}
t.templates[name] = tpl
}
return
}
|
[
"func",
"New",
"(",
"opts",
"...",
"Option",
")",
"(",
"t",
"*",
"Templates",
",",
"err",
"error",
")",
"{",
"functions",
":=",
"template",
".",
"FuncMap",
"{",
"}",
"\n",
"for",
"name",
",",
"fn",
":=",
"range",
"defaultFunctions",
"{",
"functions",
"[",
"name",
"]",
"=",
"fn",
"\n",
"}",
"\n",
"o",
":=",
"&",
"Options",
"{",
"fileFindFunc",
":",
"func",
"(",
"f",
"string",
")",
"string",
"{",
"return",
"f",
"\n",
"}",
",",
"fileReadFunc",
":",
"ioutil",
".",
"ReadFile",
",",
"files",
":",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
",",
"functions",
":",
"functions",
",",
"delimOpen",
":",
"\"{{\"",
",",
"delimClose",
":",
"\"}}\"",
",",
"logf",
":",
"log",
".",
"Printf",
",",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"o",
")",
"\n",
"}",
"\n",
"t",
"=",
"&",
"Templates",
"{",
"templates",
":",
"map",
"[",
"string",
"]",
"*",
"template",
".",
"Template",
"{",
"}",
",",
"contentType",
":",
"o",
".",
"contentType",
",",
"logf",
":",
"o",
".",
"logf",
",",
"}",
"\n",
"for",
"name",
",",
"strings",
":=",
"range",
"o",
".",
"strings",
"{",
"tpl",
",",
"err",
":=",
"parseStrings",
"(",
"template",
".",
"New",
"(",
"\"\"",
")",
".",
"Funcs",
"(",
"o",
".",
"functions",
")",
".",
"Delims",
"(",
"o",
".",
"delimOpen",
",",
"o",
".",
"delimClose",
")",
",",
"strings",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"t",
".",
"templates",
"[",
"name",
"]",
"=",
"tpl",
"\n",
"}",
"\n",
"for",
"name",
",",
"files",
":=",
"range",
"o",
".",
"files",
"{",
"fs",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"fs",
"=",
"append",
"(",
"fs",
",",
"o",
".",
"fileFindFunc",
"(",
"f",
")",
")",
"\n",
"}",
"\n",
"tpl",
",",
"err",
":=",
"parseFiles",
"(",
"o",
".",
"fileReadFunc",
",",
"template",
".",
"New",
"(",
"\"\"",
")",
".",
"Funcs",
"(",
"o",
".",
"functions",
")",
".",
"Delims",
"(",
"o",
".",
"delimOpen",
",",
"o",
".",
"delimClose",
")",
",",
"fs",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"t",
".",
"templates",
"[",
"name",
"]",
"=",
"tpl",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// New creates a new instance of Templates and parses
// provided files and strings.
|
[
"New",
"creates",
"a",
"new",
"instance",
"of",
"Templates",
"and",
"parses",
"provided",
"files",
"and",
"strings",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L152-L196
|
test
|
janos/web
|
templates/templates.go
|
RespondWithStatus
|
func (t Templates) RespondWithStatus(w http.ResponseWriter, name string, data interface{}, status int) {
buf := bytes.Buffer{}
tpl, ok := t.templates[name]
if !ok {
panic(&Error{Err: ErrUnknownTemplate, Template: name})
}
if err := tpl.Execute(&buf, data); err != nil {
panic(err)
}
if t.contentType != "" {
w.Header().Set("Content-Type", t.contentType)
}
if status > 0 {
w.WriteHeader(status)
}
if _, err := buf.WriteTo(w); err != nil {
t.logf("respond %q: %v", name, err)
}
}
|
go
|
func (t Templates) RespondWithStatus(w http.ResponseWriter, name string, data interface{}, status int) {
buf := bytes.Buffer{}
tpl, ok := t.templates[name]
if !ok {
panic(&Error{Err: ErrUnknownTemplate, Template: name})
}
if err := tpl.Execute(&buf, data); err != nil {
panic(err)
}
if t.contentType != "" {
w.Header().Set("Content-Type", t.contentType)
}
if status > 0 {
w.WriteHeader(status)
}
if _, err := buf.WriteTo(w); err != nil {
t.logf("respond %q: %v", name, err)
}
}
|
[
"func",
"(",
"t",
"Templates",
")",
"RespondWithStatus",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"name",
"string",
",",
"data",
"interface",
"{",
"}",
",",
"status",
"int",
")",
"{",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"tpl",
",",
"ok",
":=",
"t",
".",
"templates",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"&",
"Error",
"{",
"Err",
":",
"ErrUnknownTemplate",
",",
"Template",
":",
"name",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tpl",
".",
"Execute",
"(",
"&",
"buf",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"contentType",
"!=",
"\"\"",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"t",
".",
"contentType",
")",
"\n",
"}",
"\n",
"if",
"status",
">",
"0",
"{",
"w",
".",
"WriteHeader",
"(",
"status",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"buf",
".",
"WriteTo",
"(",
"w",
")",
";",
"err",
"!=",
"nil",
"{",
"t",
".",
"logf",
"(",
"\"respond %q: %v\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// RespondWithStatus executes a template with provided data into buffer,
// then writes the the status and body to the response writer.
// A panic will be raised if the template does not exist or fails to execute.
|
[
"RespondWithStatus",
"executes",
"a",
"template",
"with",
"provided",
"data",
"into",
"buffer",
"then",
"writes",
"the",
"the",
"status",
"and",
"body",
"to",
"the",
"response",
"writer",
".",
"A",
"panic",
"will",
"be",
"raised",
"if",
"the",
"template",
"does",
"not",
"exist",
"or",
"fails",
"to",
"execute",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L224-L242
|
test
|
janos/web
|
templates/templates.go
|
RespondTemplate
|
func (t Templates) RespondTemplate(w http.ResponseWriter, name, templateName string, data interface{}) {
t.RespondTemplateWithStatus(w, name, templateName, data, 0)
}
|
go
|
func (t Templates) RespondTemplate(w http.ResponseWriter, name, templateName string, data interface{}) {
t.RespondTemplateWithStatus(w, name, templateName, data, 0)
}
|
[
"func",
"(",
"t",
"Templates",
")",
"RespondTemplate",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"name",
",",
"templateName",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"{",
"t",
".",
"RespondTemplateWithStatus",
"(",
"w",
",",
"name",
",",
"templateName",
",",
"data",
",",
"0",
")",
"\n",
"}"
] |
// RespondTemplate executes a named template with provided data into buffer,
// then writes the the body to the response writer.
// A panic will be raised if the template does not exist or fails to execute.
|
[
"RespondTemplate",
"executes",
"a",
"named",
"template",
"with",
"provided",
"data",
"into",
"buffer",
"then",
"writes",
"the",
"the",
"body",
"to",
"the",
"response",
"writer",
".",
"A",
"panic",
"will",
"be",
"raised",
"if",
"the",
"template",
"does",
"not",
"exist",
"or",
"fails",
"to",
"execute",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L247-L249
|
test
|
janos/web
|
templates/templates.go
|
Respond
|
func (t Templates) Respond(w http.ResponseWriter, name string, data interface{}) {
t.RespondWithStatus(w, name, data, 0)
}
|
go
|
func (t Templates) Respond(w http.ResponseWriter, name string, data interface{}) {
t.RespondWithStatus(w, name, data, 0)
}
|
[
"func",
"(",
"t",
"Templates",
")",
"Respond",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"name",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"{",
"t",
".",
"RespondWithStatus",
"(",
"w",
",",
"name",
",",
"data",
",",
"0",
")",
"\n",
"}"
] |
// Respond executes template with provided data into buffer,
// then writes the the body to the response writer.
// A panic will be raised if the template does not exist or fails to execute.
|
[
"Respond",
"executes",
"template",
"with",
"provided",
"data",
"into",
"buffer",
"then",
"writes",
"the",
"the",
"body",
"to",
"the",
"response",
"writer",
".",
"A",
"panic",
"will",
"be",
"raised",
"if",
"the",
"template",
"does",
"not",
"exist",
"or",
"fails",
"to",
"execute",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L254-L256
|
test
|
janos/web
|
templates/templates.go
|
RenderTemplate
|
func (t Templates) RenderTemplate(name, templateName string, data interface{}) (s string, err error) {
buf := bytes.Buffer{}
tpl, ok := t.templates[name]
if !ok {
return "", &Error{Err: ErrUnknownTemplate, Template: name}
}
if err := tpl.ExecuteTemplate(&buf, templateName, data); err != nil {
return "", err
}
return buf.String(), nil
}
|
go
|
func (t Templates) RenderTemplate(name, templateName string, data interface{}) (s string, err error) {
buf := bytes.Buffer{}
tpl, ok := t.templates[name]
if !ok {
return "", &Error{Err: ErrUnknownTemplate, Template: name}
}
if err := tpl.ExecuteTemplate(&buf, templateName, data); err != nil {
return "", err
}
return buf.String(), nil
}
|
[
"func",
"(",
"t",
"Templates",
")",
"RenderTemplate",
"(",
"name",
",",
"templateName",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"s",
"string",
",",
"err",
"error",
")",
"{",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"tpl",
",",
"ok",
":=",
"t",
".",
"templates",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"\"",
",",
"&",
"Error",
"{",
"Err",
":",
"ErrUnknownTemplate",
",",
"Template",
":",
"name",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tpl",
".",
"ExecuteTemplate",
"(",
"&",
"buf",
",",
"templateName",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// RenderTemplate executes a named template and returns the string.
|
[
"RenderTemplate",
"executes",
"a",
"named",
"template",
"and",
"returns",
"the",
"string",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L259-L269
|
test
|
janos/web
|
servers/quic/quic.go
|
New
|
func New(handler http.Handler, opts ...Option) (s *Server) {
o := &Options{}
for _, opt := range opts {
opt(o)
}
s = &Server{
Server: &h2quic.Server{
Server: &http.Server{
Handler: handler,
TLSConfig: o.tlsConfig,
},
},
}
return
}
|
go
|
func New(handler http.Handler, opts ...Option) (s *Server) {
o := &Options{}
for _, opt := range opts {
opt(o)
}
s = &Server{
Server: &h2quic.Server{
Server: &http.Server{
Handler: handler,
TLSConfig: o.tlsConfig,
},
},
}
return
}
|
[
"func",
"New",
"(",
"handler",
"http",
".",
"Handler",
",",
"opts",
"...",
"Option",
")",
"(",
"s",
"*",
"Server",
")",
"{",
"o",
":=",
"&",
"Options",
"{",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"o",
")",
"\n",
"}",
"\n",
"s",
"=",
"&",
"Server",
"{",
"Server",
":",
"&",
"h2quic",
".",
"Server",
"{",
"Server",
":",
"&",
"http",
".",
"Server",
"{",
"Handler",
":",
"handler",
",",
"TLSConfig",
":",
"o",
".",
"tlsConfig",
",",
"}",
",",
"}",
",",
"}",
"\n",
"return",
"\n",
"}"
] |
// New creates a new instance of Server.
|
[
"New",
"creates",
"a",
"new",
"instance",
"of",
"Server",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/quic/quic.go#L44-L58
|
test
|
janos/web
|
servers/quic/quic.go
|
ServeUDP
|
func (s *Server) ServeUDP(conn *net.UDPConn) (err error) {
s.Server.Server.Addr = conn.LocalAddr().String()
return s.Server.Serve(conn)
}
|
go
|
func (s *Server) ServeUDP(conn *net.UDPConn) (err error) {
s.Server.Server.Addr = conn.LocalAddr().String()
return s.Server.Serve(conn)
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"ServeUDP",
"(",
"conn",
"*",
"net",
".",
"UDPConn",
")",
"(",
"err",
"error",
")",
"{",
"s",
".",
"Server",
".",
"Server",
".",
"Addr",
"=",
"conn",
".",
"LocalAddr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"return",
"s",
".",
"Server",
".",
"Serve",
"(",
"conn",
")",
"\n",
"}"
] |
// ServeUDP serves requests over UDP connection.
|
[
"ServeUDP",
"serves",
"requests",
"over",
"UDP",
"connection",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/quic/quic.go#L61-L64
|
test
|
janos/web
|
servers/quic/quic.go
|
Shutdown
|
func (s *Server) Shutdown(_ context.Context) (err error) {
return s.Server.Close()
}
|
go
|
func (s *Server) Shutdown(_ context.Context) (err error) {
return s.Server.Close()
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"Shutdown",
"(",
"_",
"context",
".",
"Context",
")",
"(",
"err",
"error",
")",
"{",
"return",
"s",
".",
"Server",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Shutdown calls h2quic.Server.Close method.
|
[
"Shutdown",
"calls",
"h2quic",
".",
"Server",
".",
"Close",
"method",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/quic/quic.go#L67-L69
|
test
|
janos/web
|
servers/quic/quic.go
|
QuicHeadersHandler
|
func (s *Server) QuicHeadersHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.SetQuicHeaders(w.Header())
h.ServeHTTP(w, r)
})
}
|
go
|
func (s *Server) QuicHeadersHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.SetQuicHeaders(w.Header())
h.ServeHTTP(w, r)
})
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"QuicHeadersHandler",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"s",
".",
"SetQuicHeaders",
"(",
"w",
".",
"Header",
"(",
")",
")",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// QuicHeadersHandler should be used as a middleware to set
// quic related headers to TCP server that suggest alternative svc.
|
[
"QuicHeadersHandler",
"should",
"be",
"used",
"as",
"a",
"middleware",
"to",
"set",
"quic",
"related",
"headers",
"to",
"TCP",
"server",
"that",
"suggest",
"alternative",
"svc",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/quic/quic.go#L73-L78
|
test
|
janos/web
|
request.go
|
GetRequestIPs
|
func GetRequestIPs(r *http.Request) string {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
ips := []string{ip}
xfr := r.Header.Get("X-Forwarded-For")
if xfr != "" {
ips = append(ips, xfr)
}
xri := r.Header.Get("X-Real-Ip")
if xri != "" {
ips = append(ips, xri)
}
return strings.Join(ips, ", ")
}
|
go
|
func GetRequestIPs(r *http.Request) string {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
ips := []string{ip}
xfr := r.Header.Get("X-Forwarded-For")
if xfr != "" {
ips = append(ips, xfr)
}
xri := r.Header.Get("X-Real-Ip")
if xri != "" {
ips = append(ips, xri)
}
return strings.Join(ips, ", ")
}
|
[
"func",
"GetRequestIPs",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"ip",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"r",
".",
"RemoteAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ip",
"=",
"r",
".",
"RemoteAddr",
"\n",
"}",
"\n",
"ips",
":=",
"[",
"]",
"string",
"{",
"ip",
"}",
"\n",
"xfr",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"X-Forwarded-For\"",
")",
"\n",
"if",
"xfr",
"!=",
"\"\"",
"{",
"ips",
"=",
"append",
"(",
"ips",
",",
"xfr",
")",
"\n",
"}",
"\n",
"xri",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"X-Real-Ip\"",
")",
"\n",
"if",
"xri",
"!=",
"\"\"",
"{",
"ips",
"=",
"append",
"(",
"ips",
",",
"xri",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"ips",
",",
"\", \"",
")",
"\n",
"}"
] |
// GetRequestIPs returns all possible IPs found in HTTP request.
|
[
"GetRequestIPs",
"returns",
"all",
"possible",
"IPs",
"found",
"in",
"HTTP",
"request",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/request.go#L15-L30
|
test
|
janos/web
|
domain_redirect.go
|
DomainRedirectHandler
|
func DomainRedirectHandler(h http.Handler, domain, httpsPort string) http.Handler {
if domain == "" && httpsPort == "" {
return h
}
scheme := "http"
port := ""
if httpsPort != "" {
if _, err := strconv.Atoi(httpsPort); err == nil {
scheme = "https"
port = httpsPort
}
if _, p, err := net.SplitHostPort(httpsPort); err == nil {
scheme = "https"
port = p
}
}
if port == "443" {
port = ""
}
var altDomain string
if strings.HasPrefix("www.", domain) {
altDomain = strings.TrimPrefix(domain, "www.")
} else {
altDomain = "www." + domain
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
d, p, err := net.SplitHostPort(r.Host)
if err != nil {
d = r.Host
}
rs := r.URL.Scheme
if fs := r.Header.Get("X-Forwarded-Proto"); fs != "" {
rs = strings.ToLower(fs)
}
s := scheme
if rs == "https" {
s = "https"
}
if d == domain && rs == s {
h.ServeHTTP(w, r)
return
}
switch {
case s == "http" && p == "80":
p = ""
case s == "https" && p == "443":
p = ""
case port != "":
p = ":" + port
case p != "":
p = ":" + p
}
if d == altDomain {
http.Redirect(w, r, strings.Join([]string{s, "://", domain, p, r.RequestURI}, ""), http.StatusMovedPermanently)
return
}
http.Redirect(w, r, strings.Join([]string{s, "://", domain, p, r.RequestURI}, ""), http.StatusFound)
})
}
|
go
|
func DomainRedirectHandler(h http.Handler, domain, httpsPort string) http.Handler {
if domain == "" && httpsPort == "" {
return h
}
scheme := "http"
port := ""
if httpsPort != "" {
if _, err := strconv.Atoi(httpsPort); err == nil {
scheme = "https"
port = httpsPort
}
if _, p, err := net.SplitHostPort(httpsPort); err == nil {
scheme = "https"
port = p
}
}
if port == "443" {
port = ""
}
var altDomain string
if strings.HasPrefix("www.", domain) {
altDomain = strings.TrimPrefix(domain, "www.")
} else {
altDomain = "www." + domain
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
d, p, err := net.SplitHostPort(r.Host)
if err != nil {
d = r.Host
}
rs := r.URL.Scheme
if fs := r.Header.Get("X-Forwarded-Proto"); fs != "" {
rs = strings.ToLower(fs)
}
s := scheme
if rs == "https" {
s = "https"
}
if d == domain && rs == s {
h.ServeHTTP(w, r)
return
}
switch {
case s == "http" && p == "80":
p = ""
case s == "https" && p == "443":
p = ""
case port != "":
p = ":" + port
case p != "":
p = ":" + p
}
if d == altDomain {
http.Redirect(w, r, strings.Join([]string{s, "://", domain, p, r.RequestURI}, ""), http.StatusMovedPermanently)
return
}
http.Redirect(w, r, strings.Join([]string{s, "://", domain, p, r.RequestURI}, ""), http.StatusFound)
})
}
|
[
"func",
"DomainRedirectHandler",
"(",
"h",
"http",
".",
"Handler",
",",
"domain",
",",
"httpsPort",
"string",
")",
"http",
".",
"Handler",
"{",
"if",
"domain",
"==",
"\"\"",
"&&",
"httpsPort",
"==",
"\"\"",
"{",
"return",
"h",
"\n",
"}",
"\n",
"scheme",
":=",
"\"http\"",
"\n",
"port",
":=",
"\"\"",
"\n",
"if",
"httpsPort",
"!=",
"\"\"",
"{",
"if",
"_",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"httpsPort",
")",
";",
"err",
"==",
"nil",
"{",
"scheme",
"=",
"\"https\"",
"\n",
"port",
"=",
"httpsPort",
"\n",
"}",
"\n",
"if",
"_",
",",
"p",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"httpsPort",
")",
";",
"err",
"==",
"nil",
"{",
"scheme",
"=",
"\"https\"",
"\n",
"port",
"=",
"p",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"port",
"==",
"\"443\"",
"{",
"port",
"=",
"\"\"",
"\n",
"}",
"\n",
"var",
"altDomain",
"string",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"\"www.\"",
",",
"domain",
")",
"{",
"altDomain",
"=",
"strings",
".",
"TrimPrefix",
"(",
"domain",
",",
"\"www.\"",
")",
"\n",
"}",
"else",
"{",
"altDomain",
"=",
"\"www.\"",
"+",
"domain",
"\n",
"}",
"\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"d",
",",
"p",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"r",
".",
"Host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"d",
"=",
"r",
".",
"Host",
"\n",
"}",
"\n",
"rs",
":=",
"r",
".",
"URL",
".",
"Scheme",
"\n",
"if",
"fs",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"X-Forwarded-Proto\"",
")",
";",
"fs",
"!=",
"\"\"",
"{",
"rs",
"=",
"strings",
".",
"ToLower",
"(",
"fs",
")",
"\n",
"}",
"\n",
"s",
":=",
"scheme",
"\n",
"if",
"rs",
"==",
"\"https\"",
"{",
"s",
"=",
"\"https\"",
"\n",
"}",
"\n",
"if",
"d",
"==",
"domain",
"&&",
"rs",
"==",
"s",
"{",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"switch",
"{",
"case",
"s",
"==",
"\"http\"",
"&&",
"p",
"==",
"\"80\"",
":",
"p",
"=",
"\"\"",
"\n",
"case",
"s",
"==",
"\"https\"",
"&&",
"p",
"==",
"\"443\"",
":",
"p",
"=",
"\"\"",
"\n",
"case",
"port",
"!=",
"\"\"",
":",
"p",
"=",
"\":\"",
"+",
"port",
"\n",
"case",
"p",
"!=",
"\"\"",
":",
"p",
"=",
"\":\"",
"+",
"p",
"\n",
"}",
"\n",
"if",
"d",
"==",
"altDomain",
"{",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"s",
",",
"\"://\"",
",",
"domain",
",",
"p",
",",
"r",
".",
"RequestURI",
"}",
",",
"\"\"",
")",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"s",
",",
"\"://\"",
",",
"domain",
",",
"p",
",",
"r",
".",
"RequestURI",
"}",
",",
"\"\"",
")",
",",
"http",
".",
"StatusFound",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// DomainRedirectHandler responds with redirect url based on
// domain and httpsPort, othervise it executes the handler.
|
[
"DomainRedirectHandler",
"responds",
"with",
"redirect",
"url",
"based",
"on",
"domain",
"and",
"httpsPort",
"othervise",
"it",
"executes",
"the",
"handler",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/domain_redirect.go#L17-L76
|
test
|
janos/web
|
servers/servers.go
|
New
|
func New(opts ...Option) (s *Servers) {
s = &Servers{
logger: stdLogger{},
recover: func() {},
}
for _, opt := range opts {
opt(s)
}
return
}
|
go
|
func New(opts ...Option) (s *Servers) {
s = &Servers{
logger: stdLogger{},
recover: func() {},
}
for _, opt := range opts {
opt(s)
}
return
}
|
[
"func",
"New",
"(",
"opts",
"...",
"Option",
")",
"(",
"s",
"*",
"Servers",
")",
"{",
"s",
"=",
"&",
"Servers",
"{",
"logger",
":",
"stdLogger",
"{",
"}",
",",
"recover",
":",
"func",
"(",
")",
"{",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"s",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// New creates a new instance of Servers with applied options.
|
[
"New",
"creates",
"a",
"new",
"instance",
"of",
"Servers",
"with",
"applied",
"options",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L55-L64
|
test
|
janos/web
|
servers/servers.go
|
Add
|
func (s *Servers) Add(name, address string, srv Server) {
s.mu.Lock()
s.servers = append(s.servers, &server{
Server: srv,
name: name,
address: address,
})
s.mu.Unlock()
}
|
go
|
func (s *Servers) Add(name, address string, srv Server) {
s.mu.Lock()
s.servers = append(s.servers, &server{
Server: srv,
name: name,
address: address,
})
s.mu.Unlock()
}
|
[
"func",
"(",
"s",
"*",
"Servers",
")",
"Add",
"(",
"name",
",",
"address",
"string",
",",
"srv",
"Server",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"servers",
"=",
"append",
"(",
"s",
".",
"servers",
",",
"&",
"server",
"{",
"Server",
":",
"srv",
",",
"name",
":",
"name",
",",
"address",
":",
"address",
",",
"}",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// Add adds a new server instance by a custom name and with
// address to listen to.
|
[
"Add",
"adds",
"a",
"new",
"server",
"instance",
"by",
"a",
"custom",
"name",
"and",
"with",
"address",
"to",
"listen",
"to",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L123-L131
|
test
|
janos/web
|
servers/servers.go
|
TCPAddr
|
func (s *Servers) TCPAddr(name string) (a *net.TCPAddr) {
s.mu.Lock()
defer s.mu.Unlock()
for _, srv := range s.servers {
if srv.name == name {
return srv.tcpAddr
}
}
return nil
}
|
go
|
func (s *Servers) TCPAddr(name string) (a *net.TCPAddr) {
s.mu.Lock()
defer s.mu.Unlock()
for _, srv := range s.servers {
if srv.name == name {
return srv.tcpAddr
}
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Servers",
")",
"TCPAddr",
"(",
"name",
"string",
")",
"(",
"a",
"*",
"net",
".",
"TCPAddr",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"srv",
":=",
"range",
"s",
".",
"servers",
"{",
"if",
"srv",
".",
"name",
"==",
"name",
"{",
"return",
"srv",
".",
"tcpAddr",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// TCPAddr returns a TCP address of the listener that a server
// with a specific name is using. If there are more servers
// with the same name, the address of the first started server
// is returned.
|
[
"TCPAddr",
"returns",
"a",
"TCP",
"address",
"of",
"the",
"listener",
"that",
"a",
"server",
"with",
"a",
"specific",
"name",
"is",
"using",
".",
"If",
"there",
"are",
"more",
"servers",
"with",
"the",
"same",
"name",
"the",
"address",
"of",
"the",
"first",
"started",
"server",
"is",
"returned",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L203-L213
|
test
|
janos/web
|
servers/servers.go
|
UDPAddr
|
func (s *Servers) UDPAddr(name string) (a *net.UDPAddr) {
s.mu.Lock()
defer s.mu.Unlock()
for _, srv := range s.servers {
if srv.name == name {
return srv.udpAddr
}
}
return nil
}
|
go
|
func (s *Servers) UDPAddr(name string) (a *net.UDPAddr) {
s.mu.Lock()
defer s.mu.Unlock()
for _, srv := range s.servers {
if srv.name == name {
return srv.udpAddr
}
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Servers",
")",
"UDPAddr",
"(",
"name",
"string",
")",
"(",
"a",
"*",
"net",
".",
"UDPAddr",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"srv",
":=",
"range",
"s",
".",
"servers",
"{",
"if",
"srv",
".",
"name",
"==",
"name",
"{",
"return",
"srv",
".",
"udpAddr",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UDPAddr returns a UDP address of the listener that a server
// with a specific name is using. If there are more servers
// with the same name, the address of the first started server
// is returned.
|
[
"UDPAddr",
"returns",
"a",
"UDP",
"address",
"of",
"the",
"listener",
"that",
"a",
"server",
"with",
"a",
"specific",
"name",
"is",
"using",
".",
"If",
"there",
"are",
"more",
"servers",
"with",
"the",
"same",
"name",
"the",
"address",
"of",
"the",
"first",
"started",
"server",
"is",
"returned",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L219-L229
|
test
|
janos/web
|
servers/servers.go
|
Close
|
func (s *Servers) Close() {
wg := &sync.WaitGroup{}
for _, srv := range s.servers {
wg.Add(1)
go func(srv *server) {
defer s.recover()
defer wg.Done()
s.logger.Infof("%s closing", srv.label())
if err := srv.Close(); err != nil {
s.logger.Errorf("%s close: %v", srv.label(), err)
}
}(srv)
}
wg.Wait()
return
}
|
go
|
func (s *Servers) Close() {
wg := &sync.WaitGroup{}
for _, srv := range s.servers {
wg.Add(1)
go func(srv *server) {
defer s.recover()
defer wg.Done()
s.logger.Infof("%s closing", srv.label())
if err := srv.Close(); err != nil {
s.logger.Errorf("%s close: %v", srv.label(), err)
}
}(srv)
}
wg.Wait()
return
}
|
[
"func",
"(",
"s",
"*",
"Servers",
")",
"Close",
"(",
")",
"{",
"wg",
":=",
"&",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"_",
",",
"srv",
":=",
"range",
"s",
".",
"servers",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"srv",
"*",
"server",
")",
"{",
"defer",
"s",
".",
"recover",
"(",
")",
"\n",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"s",
".",
"logger",
".",
"Infof",
"(",
"\"%s closing\"",
",",
"srv",
".",
"label",
"(",
")",
")",
"\n",
"if",
"err",
":=",
"srv",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Errorf",
"(",
"\"%s close: %v\"",
",",
"srv",
".",
"label",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
"srv",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Close stops all servers, by calling Close method on each of them.
|
[
"Close",
"stops",
"all",
"servers",
"by",
"calling",
"Close",
"method",
"on",
"each",
"of",
"them",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L232-L248
|
test
|
janos/web
|
servers/servers.go
|
Shutdown
|
func (s *Servers) Shutdown(ctx context.Context) {
wg := &sync.WaitGroup{}
for _, srv := range s.servers {
wg.Add(1)
go func(srv *server) {
defer s.recover()
defer wg.Done()
s.logger.Infof("%s shutting down", srv.label())
if err := srv.Shutdown(ctx); err != nil {
s.logger.Errorf("%s shutdown: %v", srv.label(), err)
}
}(srv)
}
wg.Wait()
return
}
|
go
|
func (s *Servers) Shutdown(ctx context.Context) {
wg := &sync.WaitGroup{}
for _, srv := range s.servers {
wg.Add(1)
go func(srv *server) {
defer s.recover()
defer wg.Done()
s.logger.Infof("%s shutting down", srv.label())
if err := srv.Shutdown(ctx); err != nil {
s.logger.Errorf("%s shutdown: %v", srv.label(), err)
}
}(srv)
}
wg.Wait()
return
}
|
[
"func",
"(",
"s",
"*",
"Servers",
")",
"Shutdown",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"wg",
":=",
"&",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"_",
",",
"srv",
":=",
"range",
"s",
".",
"servers",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"srv",
"*",
"server",
")",
"{",
"defer",
"s",
".",
"recover",
"(",
")",
"\n",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"s",
".",
"logger",
".",
"Infof",
"(",
"\"%s shutting down\"",
",",
"srv",
".",
"label",
"(",
")",
")",
"\n",
"if",
"err",
":=",
"srv",
".",
"Shutdown",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Errorf",
"(",
"\"%s shutdown: %v\"",
",",
"srv",
".",
"label",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
"srv",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Shutdown gracefully stops all servers, by calling Shutdown method on each of them.
|
[
"Shutdown",
"gracefully",
"stops",
"all",
"servers",
"by",
"calling",
"Shutdown",
"method",
"on",
"each",
"of",
"them",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L251-L267
|
test
|
janos/web
|
https_redirect.go
|
Accept
|
func (l TLSListener) Accept() (net.Conn, error) {
c, err := l.AcceptTCP()
if err != nil {
return nil, err
}
c.SetKeepAlive(true)
c.SetKeepAlivePeriod(3 * time.Minute)
b := make([]byte, 1)
_, err = c.Read(b)
if err != nil {
c.Close()
if err != io.EOF {
return nil, err
}
}
con := &conn{
Conn: c,
b: b[0],
e: err,
f: true,
}
if b[0] == 22 {
return tls.Server(con, l.TLSConfig), nil
}
return con, nil
}
|
go
|
func (l TLSListener) Accept() (net.Conn, error) {
c, err := l.AcceptTCP()
if err != nil {
return nil, err
}
c.SetKeepAlive(true)
c.SetKeepAlivePeriod(3 * time.Minute)
b := make([]byte, 1)
_, err = c.Read(b)
if err != nil {
c.Close()
if err != io.EOF {
return nil, err
}
}
con := &conn{
Conn: c,
b: b[0],
e: err,
f: true,
}
if b[0] == 22 {
return tls.Server(con, l.TLSConfig), nil
}
return con, nil
}
|
[
"func",
"(",
"l",
"TLSListener",
")",
"Accept",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"l",
".",
"AcceptTCP",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"c",
".",
"SetKeepAlive",
"(",
"true",
")",
"\n",
"c",
".",
"SetKeepAlivePeriod",
"(",
"3",
"*",
"time",
".",
"Minute",
")",
"\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"1",
")",
"\n",
"_",
",",
"err",
"=",
"c",
".",
"Read",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"io",
".",
"EOF",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"con",
":=",
"&",
"conn",
"{",
"Conn",
":",
"c",
",",
"b",
":",
"b",
"[",
"0",
"]",
",",
"e",
":",
"err",
",",
"f",
":",
"true",
",",
"}",
"\n",
"if",
"b",
"[",
"0",
"]",
"==",
"22",
"{",
"return",
"tls",
".",
"Server",
"(",
"con",
",",
"l",
".",
"TLSConfig",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"con",
",",
"nil",
"\n",
"}"
] |
// Accept accepts TCP connection, sets keep alive and checks if a client
// requested an encrypted connection.
|
[
"Accept",
"accepts",
"TCP",
"connection",
"sets",
"keep",
"alive",
"and",
"checks",
"if",
"a",
"client",
"requested",
"an",
"encrypted",
"connection",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/https_redirect.go#L52-L81
|
test
|
janos/web
|
static_files.go
|
NewStaticFilesHandler
|
func NewStaticFilesHandler(h http.Handler, prefix string, fs http.FileSystem) http.Handler {
fileserver := http.StripPrefix(prefix, http.FileServer(fs))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
filename := strings.TrimPrefix(r.URL.Path, prefix)
_, err := fs.Open(filename)
if err != nil {
h.ServeHTTP(w, r)
return
}
fileserver.ServeHTTP(w, r)
})
}
|
go
|
func NewStaticFilesHandler(h http.Handler, prefix string, fs http.FileSystem) http.Handler {
fileserver := http.StripPrefix(prefix, http.FileServer(fs))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
filename := strings.TrimPrefix(r.URL.Path, prefix)
_, err := fs.Open(filename)
if err != nil {
h.ServeHTTP(w, r)
return
}
fileserver.ServeHTTP(w, r)
})
}
|
[
"func",
"NewStaticFilesHandler",
"(",
"h",
"http",
".",
"Handler",
",",
"prefix",
"string",
",",
"fs",
"http",
".",
"FileSystem",
")",
"http",
".",
"Handler",
"{",
"fileserver",
":=",
"http",
".",
"StripPrefix",
"(",
"prefix",
",",
"http",
".",
"FileServer",
"(",
"fs",
")",
")",
"\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"filename",
":=",
"strings",
".",
"TrimPrefix",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"prefix",
")",
"\n",
"_",
",",
"err",
":=",
"fs",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"fileserver",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// NewStaticFilesHandler serves a file under specified filesystem if it
// can be opened, otherwise it serves HTTP from a specified handler.
|
[
"NewStaticFilesHandler",
"serves",
"a",
"file",
"under",
"specified",
"filesystem",
"if",
"it",
"can",
"be",
"opened",
"otherwise",
"it",
"serves",
"HTTP",
"from",
"a",
"specified",
"handler",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/static_files.go#L15-L26
|
test
|
janos/web
|
auth.go
|
ServeHTTP
|
func (h AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
valid, entity, err := h.authenticate(r)
if err != nil {
h.error(w, r, err)
return
}
if h.PostAuthFunc != nil {
rr, err := h.PostAuthFunc(w, r, valid, entity)
if err != nil {
h.error(w, r, err)
return
}
if rr != nil {
r = rr
}
}
if !valid {
h.unauthorized(w, r)
return
}
if h.Handler != nil {
h.Handler.ServeHTTP(w, r)
}
}
|
go
|
func (h AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
valid, entity, err := h.authenticate(r)
if err != nil {
h.error(w, r, err)
return
}
if h.PostAuthFunc != nil {
rr, err := h.PostAuthFunc(w, r, valid, entity)
if err != nil {
h.error(w, r, err)
return
}
if rr != nil {
r = rr
}
}
if !valid {
h.unauthorized(w, r)
return
}
if h.Handler != nil {
h.Handler.ServeHTTP(w, r)
}
}
|
[
"func",
"(",
"h",
"AuthHandler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"valid",
",",
"entity",
",",
"err",
":=",
"h",
".",
"authenticate",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"error",
"(",
"w",
",",
"r",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"h",
".",
"PostAuthFunc",
"!=",
"nil",
"{",
"rr",
",",
"err",
":=",
"h",
".",
"PostAuthFunc",
"(",
"w",
",",
"r",
",",
"valid",
",",
"entity",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"error",
"(",
"w",
",",
"r",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"rr",
"!=",
"nil",
"{",
"r",
"=",
"rr",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"valid",
"{",
"h",
".",
"unauthorized",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"h",
".",
"Handler",
"!=",
"nil",
"{",
"h",
".",
"Handler",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// ServeHTTP serves an HTTP response for a request.
|
[
"ServeHTTP",
"serves",
"an",
"HTTP",
"response",
"for",
"a",
"request",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/auth.go#L64-L88
|
test
|
janos/web
|
client/http/http_client.go
|
MarshalJSON
|
func (o Options) MarshalJSON() ([]byte, error) {
return json.Marshal(optionsJSON{
Timeout: marshal.Duration(o.Timeout),
KeepAlive: marshal.Duration(o.KeepAlive),
TLSHandshakeTimeout: marshal.Duration(o.TLSHandshakeTimeout),
TLSSkipVerify: o.TLSSkipVerify,
RetryTimeMax: marshal.Duration(o.RetryTimeMax),
RetrySleepMax: marshal.Duration(o.RetrySleepMax),
RetrySleepBase: marshal.Duration(o.RetrySleepBase),
})
}
|
go
|
func (o Options) MarshalJSON() ([]byte, error) {
return json.Marshal(optionsJSON{
Timeout: marshal.Duration(o.Timeout),
KeepAlive: marshal.Duration(o.KeepAlive),
TLSHandshakeTimeout: marshal.Duration(o.TLSHandshakeTimeout),
TLSSkipVerify: o.TLSSkipVerify,
RetryTimeMax: marshal.Duration(o.RetryTimeMax),
RetrySleepMax: marshal.Duration(o.RetrySleepMax),
RetrySleepBase: marshal.Duration(o.RetrySleepBase),
})
}
|
[
"func",
"(",
"o",
"Options",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"json",
".",
"Marshal",
"(",
"optionsJSON",
"{",
"Timeout",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"Timeout",
")",
",",
"KeepAlive",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"KeepAlive",
")",
",",
"TLSHandshakeTimeout",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"TLSHandshakeTimeout",
")",
",",
"TLSSkipVerify",
":",
"o",
".",
"TLSSkipVerify",
",",
"RetryTimeMax",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"RetryTimeMax",
")",
",",
"RetrySleepMax",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"RetrySleepMax",
")",
",",
"RetrySleepBase",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"RetrySleepBase",
")",
",",
"}",
")",
"\n",
"}"
] |
// MarshalJSON implements of json.Marshaler interface.
// It marshals string representations of time.Duration.
|
[
"MarshalJSON",
"implements",
"of",
"json",
".",
"Marshaler",
"interface",
".",
"It",
"marshals",
"string",
"representations",
"of",
"time",
".",
"Duration",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/http/http_client.go#L137-L147
|
test
|
janos/web
|
client/http/http_client.go
|
UnmarshalJSON
|
func (o *Options) UnmarshalJSON(data []byte) error {
v := &optionsJSON{}
if err := json.Unmarshal(data, v); err != nil {
return err
}
*o = Options{
Timeout: v.Timeout.Duration(),
KeepAlive: v.KeepAlive.Duration(),
TLSHandshakeTimeout: v.TLSHandshakeTimeout.Duration(),
TLSSkipVerify: v.TLSSkipVerify,
RetryTimeMax: v.RetryTimeMax.Duration(),
RetrySleepMax: v.RetrySleepMax.Duration(),
RetrySleepBase: v.RetrySleepBase.Duration(),
}
return nil
}
|
go
|
func (o *Options) UnmarshalJSON(data []byte) error {
v := &optionsJSON{}
if err := json.Unmarshal(data, v); err != nil {
return err
}
*o = Options{
Timeout: v.Timeout.Duration(),
KeepAlive: v.KeepAlive.Duration(),
TLSHandshakeTimeout: v.TLSHandshakeTimeout.Duration(),
TLSSkipVerify: v.TLSSkipVerify,
RetryTimeMax: v.RetryTimeMax.Duration(),
RetrySleepMax: v.RetrySleepMax.Duration(),
RetrySleepBase: v.RetrySleepBase.Duration(),
}
return nil
}
|
[
"func",
"(",
"o",
"*",
"Options",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"v",
":=",
"&",
"optionsJSON",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"o",
"=",
"Options",
"{",
"Timeout",
":",
"v",
".",
"Timeout",
".",
"Duration",
"(",
")",
",",
"KeepAlive",
":",
"v",
".",
"KeepAlive",
".",
"Duration",
"(",
")",
",",
"TLSHandshakeTimeout",
":",
"v",
".",
"TLSHandshakeTimeout",
".",
"Duration",
"(",
")",
",",
"TLSSkipVerify",
":",
"v",
".",
"TLSSkipVerify",
",",
"RetryTimeMax",
":",
"v",
".",
"RetryTimeMax",
".",
"Duration",
"(",
")",
",",
"RetrySleepMax",
":",
"v",
".",
"RetrySleepMax",
".",
"Duration",
"(",
")",
",",
"RetrySleepBase",
":",
"v",
".",
"RetrySleepBase",
".",
"Duration",
"(",
")",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON implements json.Unamrshaler interface.
// It parses time.Duration as strings.
|
[
"UnmarshalJSON",
"implements",
"json",
".",
"Unamrshaler",
"interface",
".",
"It",
"parses",
"time",
".",
"Duration",
"as",
"strings",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/http/http_client.go#L151-L166
|
test
|
janos/web
|
client/http/http_client.go
|
MarshalYAML
|
func (o Options) MarshalYAML() (interface{}, error) {
return optionsJSON{
Timeout: marshal.Duration(o.Timeout),
KeepAlive: marshal.Duration(o.KeepAlive),
TLSHandshakeTimeout: marshal.Duration(o.TLSHandshakeTimeout),
TLSSkipVerify: o.TLSSkipVerify,
RetryTimeMax: marshal.Duration(o.RetryTimeMax),
RetrySleepMax: marshal.Duration(o.RetrySleepMax),
RetrySleepBase: marshal.Duration(o.RetrySleepBase),
}, nil
}
|
go
|
func (o Options) MarshalYAML() (interface{}, error) {
return optionsJSON{
Timeout: marshal.Duration(o.Timeout),
KeepAlive: marshal.Duration(o.KeepAlive),
TLSHandshakeTimeout: marshal.Duration(o.TLSHandshakeTimeout),
TLSSkipVerify: o.TLSSkipVerify,
RetryTimeMax: marshal.Duration(o.RetryTimeMax),
RetrySleepMax: marshal.Duration(o.RetrySleepMax),
RetrySleepBase: marshal.Duration(o.RetrySleepBase),
}, nil
}
|
[
"func",
"(",
"o",
"Options",
")",
"MarshalYAML",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"optionsJSON",
"{",
"Timeout",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"Timeout",
")",
",",
"KeepAlive",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"KeepAlive",
")",
",",
"TLSHandshakeTimeout",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"TLSHandshakeTimeout",
")",
",",
"TLSSkipVerify",
":",
"o",
".",
"TLSSkipVerify",
",",
"RetryTimeMax",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"RetryTimeMax",
")",
",",
"RetrySleepMax",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"RetrySleepMax",
")",
",",
"RetrySleepBase",
":",
"marshal",
".",
"Duration",
"(",
"o",
".",
"RetrySleepBase",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// MarshalYAML implements of yaml.Marshaler interface.
// It marshals string representations of time.Duration.
|
[
"MarshalYAML",
"implements",
"of",
"yaml",
".",
"Marshaler",
"interface",
".",
"It",
"marshals",
"string",
"representations",
"of",
"time",
".",
"Duration",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/http/http_client.go#L170-L180
|
test
|
janos/web
|
client/http/http_client.go
|
UnmarshalYAML
|
func (o *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {
v := &optionsJSON{}
if err := unmarshal(v); err != nil {
return err
}
*o = Options{
Timeout: v.Timeout.Duration(),
KeepAlive: v.KeepAlive.Duration(),
TLSHandshakeTimeout: v.TLSHandshakeTimeout.Duration(),
TLSSkipVerify: v.TLSSkipVerify,
RetryTimeMax: v.RetryTimeMax.Duration(),
RetrySleepMax: v.RetrySleepMax.Duration(),
RetrySleepBase: v.RetrySleepBase.Duration(),
}
return nil
}
|
go
|
func (o *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {
v := &optionsJSON{}
if err := unmarshal(v); err != nil {
return err
}
*o = Options{
Timeout: v.Timeout.Duration(),
KeepAlive: v.KeepAlive.Duration(),
TLSHandshakeTimeout: v.TLSHandshakeTimeout.Duration(),
TLSSkipVerify: v.TLSSkipVerify,
RetryTimeMax: v.RetryTimeMax.Duration(),
RetrySleepMax: v.RetrySleepMax.Duration(),
RetrySleepBase: v.RetrySleepBase.Duration(),
}
return nil
}
|
[
"func",
"(",
"o",
"*",
"Options",
")",
"UnmarshalYAML",
"(",
"unmarshal",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"v",
":=",
"&",
"optionsJSON",
"{",
"}",
"\n",
"if",
"err",
":=",
"unmarshal",
"(",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"o",
"=",
"Options",
"{",
"Timeout",
":",
"v",
".",
"Timeout",
".",
"Duration",
"(",
")",
",",
"KeepAlive",
":",
"v",
".",
"KeepAlive",
".",
"Duration",
"(",
")",
",",
"TLSHandshakeTimeout",
":",
"v",
".",
"TLSHandshakeTimeout",
".",
"Duration",
"(",
")",
",",
"TLSSkipVerify",
":",
"v",
".",
"TLSSkipVerify",
",",
"RetryTimeMax",
":",
"v",
".",
"RetryTimeMax",
".",
"Duration",
"(",
")",
",",
"RetrySleepMax",
":",
"v",
".",
"RetrySleepMax",
".",
"Duration",
"(",
")",
",",
"RetrySleepBase",
":",
"v",
".",
"RetrySleepBase",
".",
"Duration",
"(",
")",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalYAML implements yaml.Unamrshaler interface.
// It parses time.Duration as strings.
|
[
"UnmarshalYAML",
"implements",
"yaml",
".",
"Unamrshaler",
"interface",
".",
"It",
"parses",
"time",
".",
"Duration",
"as",
"strings",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/http/http_client.go#L184-L199
|
test
|
janos/web
|
log/access/access_log.go
|
NewHandler
|
func NewHandler(h http.Handler, logger *logging.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
rl := &responseLogger{w, 0, 0}
h.ServeHTTP(rl, r)
referrer := r.Referer()
if referrer == "" {
referrer = "-"
}
userAgent := r.UserAgent()
if userAgent == "" {
userAgent = "-"
}
ips := []string{}
xfr := r.Header.Get("X-Forwarded-For")
if xfr != "" {
ips = append(ips, xfr)
}
xri := r.Header.Get("X-Real-Ip")
if xri != "" {
ips = append(ips, xri)
}
xips := "-"
if len(ips) > 0 {
xips = strings.Join(ips, ", ")
}
var level logging.Level
switch {
case rl.status >= 500:
level = logging.ERROR
case rl.status >= 400:
level = logging.WARNING
case rl.status >= 300:
level = logging.INFO
case rl.status >= 200:
level = logging.INFO
default:
level = logging.DEBUG
}
logger.Logf(level, "%s \"%s\" \"%v %s %v\" %d %d %f \"%s\" \"%s\"", r.RemoteAddr, xips, r.Method, r.RequestURI, r.Proto, rl.status, rl.size, time.Since(startTime).Seconds(), referrer, userAgent)
})
}
|
go
|
func NewHandler(h http.Handler, logger *logging.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
rl := &responseLogger{w, 0, 0}
h.ServeHTTP(rl, r)
referrer := r.Referer()
if referrer == "" {
referrer = "-"
}
userAgent := r.UserAgent()
if userAgent == "" {
userAgent = "-"
}
ips := []string{}
xfr := r.Header.Get("X-Forwarded-For")
if xfr != "" {
ips = append(ips, xfr)
}
xri := r.Header.Get("X-Real-Ip")
if xri != "" {
ips = append(ips, xri)
}
xips := "-"
if len(ips) > 0 {
xips = strings.Join(ips, ", ")
}
var level logging.Level
switch {
case rl.status >= 500:
level = logging.ERROR
case rl.status >= 400:
level = logging.WARNING
case rl.status >= 300:
level = logging.INFO
case rl.status >= 200:
level = logging.INFO
default:
level = logging.DEBUG
}
logger.Logf(level, "%s \"%s\" \"%v %s %v\" %d %d %f \"%s\" \"%s\"", r.RemoteAddr, xips, r.Method, r.RequestURI, r.Proto, rl.status, rl.size, time.Since(startTime).Seconds(), referrer, userAgent)
})
}
|
[
"func",
"NewHandler",
"(",
"h",
"http",
".",
"Handler",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"rl",
":=",
"&",
"responseLogger",
"{",
"w",
",",
"0",
",",
"0",
"}",
"\n",
"h",
".",
"ServeHTTP",
"(",
"rl",
",",
"r",
")",
"\n",
"referrer",
":=",
"r",
".",
"Referer",
"(",
")",
"\n",
"if",
"referrer",
"==",
"\"\"",
"{",
"referrer",
"=",
"\"-\"",
"\n",
"}",
"\n",
"userAgent",
":=",
"r",
".",
"UserAgent",
"(",
")",
"\n",
"if",
"userAgent",
"==",
"\"\"",
"{",
"userAgent",
"=",
"\"-\"",
"\n",
"}",
"\n",
"ips",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"xfr",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"X-Forwarded-For\"",
")",
"\n",
"if",
"xfr",
"!=",
"\"\"",
"{",
"ips",
"=",
"append",
"(",
"ips",
",",
"xfr",
")",
"\n",
"}",
"\n",
"xri",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"X-Real-Ip\"",
")",
"\n",
"if",
"xri",
"!=",
"\"\"",
"{",
"ips",
"=",
"append",
"(",
"ips",
",",
"xri",
")",
"\n",
"}",
"\n",
"xips",
":=",
"\"-\"",
"\n",
"if",
"len",
"(",
"ips",
")",
">",
"0",
"{",
"xips",
"=",
"strings",
".",
"Join",
"(",
"ips",
",",
"\", \"",
")",
"\n",
"}",
"\n",
"var",
"level",
"logging",
".",
"Level",
"\n",
"switch",
"{",
"case",
"rl",
".",
"status",
">=",
"500",
":",
"level",
"=",
"logging",
".",
"ERROR",
"\n",
"case",
"rl",
".",
"status",
">=",
"400",
":",
"level",
"=",
"logging",
".",
"WARNING",
"\n",
"case",
"rl",
".",
"status",
">=",
"300",
":",
"level",
"=",
"logging",
".",
"INFO",
"\n",
"case",
"rl",
".",
"status",
">=",
"200",
":",
"level",
"=",
"logging",
".",
"INFO",
"\n",
"default",
":",
"level",
"=",
"logging",
".",
"DEBUG",
"\n",
"}",
"\n",
"logger",
".",
"Logf",
"(",
"level",
",",
"\"%s \\\"%s\\\" \\\"%v %s %v\\\" %d %d %f \\\"%s\\\" \\\"%s\\\"\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"r",
".",
"RemoteAddr",
",",
"xips",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// NewHandler returns a handler that logs HTTP requests.
// It logs information about remote address, X-Forwarded-For or X-Real-Ip,
// HTTP method, request URI, HTTP protocol, HTTP response status, total bytes
// written to http.ResponseWriter, response duration, HTTP referrer and
// HTTP client user agent.
|
[
"NewHandler",
"returns",
"a",
"handler",
"that",
"logs",
"HTTP",
"requests",
".",
"It",
"logs",
"information",
"about",
"remote",
"address",
"X",
"-",
"Forwarded",
"-",
"For",
"or",
"X",
"-",
"Real",
"-",
"Ip",
"HTTP",
"method",
"request",
"URI",
"HTTP",
"protocol",
"HTTP",
"response",
"status",
"total",
"bytes",
"written",
"to",
"http",
".",
"ResponseWriter",
"response",
"duration",
"HTTP",
"referrer",
"and",
"HTTP",
"client",
"user",
"agent",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/log/access/access_log.go#L58-L99
|
test
|
janos/web
|
recovery/recovery.go
|
WithPanicResponse
|
func WithPanicResponse(body, contentType string) Option {
return func(o *Handler) {
o.panicBody = body
o.panicContentType = contentType
}
}
|
go
|
func WithPanicResponse(body, contentType string) Option {
return func(o *Handler) {
o.panicBody = body
o.panicContentType = contentType
}
}
|
[
"func",
"WithPanicResponse",
"(",
"body",
",",
"contentType",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Handler",
")",
"{",
"o",
".",
"panicBody",
"=",
"body",
"\n",
"o",
".",
"panicContentType",
"=",
"contentType",
"\n",
"}",
"\n",
"}"
] |
// WithPanicResponse sets a fixed body and its content type HTTP header
// that will be returned as HTTP response on panic event.
// If WithPanicResponseHandler is defined, this options are ignored.
|
[
"WithPanicResponse",
"sets",
"a",
"fixed",
"body",
"and",
"its",
"content",
"type",
"HTTP",
"header",
"that",
"will",
"be",
"returned",
"as",
"HTTP",
"response",
"on",
"panic",
"event",
".",
"If",
"WithPanicResponseHandler",
"is",
"defined",
"this",
"options",
"are",
"ignored",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/recovery/recovery.go#L38-L43
|
test
|
janos/web
|
recovery/recovery.go
|
WithPanicResponseHandler
|
func WithPanicResponseHandler(h http.Handler) Option {
return func(o *Handler) { o.panicResponseHandler = h }
}
|
go
|
func WithPanicResponseHandler(h http.Handler) Option {
return func(o *Handler) { o.panicResponseHandler = h }
}
|
[
"func",
"WithPanicResponseHandler",
"(",
"h",
"http",
".",
"Handler",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Handler",
")",
"{",
"o",
".",
"panicResponseHandler",
"=",
"h",
"}",
"\n",
"}"
] |
// WithPanicResponseHandler sets http.Handler that will be executed on
// panic event. It is useful when the response has dynamic content.
// If the content is static it is better to use WithPanicResponse option
// instead. This option has a precedence upon WithPanicResponse.
|
[
"WithPanicResponseHandler",
"sets",
"http",
".",
"Handler",
"that",
"will",
"be",
"executed",
"on",
"panic",
"event",
".",
"It",
"is",
"useful",
"when",
"the",
"response",
"has",
"dynamic",
"content",
".",
"If",
"the",
"content",
"is",
"static",
"it",
"is",
"better",
"to",
"use",
"WithPanicResponse",
"option",
"instead",
".",
"This",
"option",
"has",
"a",
"precedence",
"upon",
"WithPanicResponse",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/recovery/recovery.go#L49-L51
|
test
|
janos/web
|
recovery/recovery.go
|
New
|
func New(handler http.Handler, options ...Option) (h *Handler) {
h = &Handler{
handler: handler,
logf: log.Printf,
}
for _, option := range options {
option(h)
}
return
}
|
go
|
func New(handler http.Handler, options ...Option) (h *Handler) {
h = &Handler{
handler: handler,
logf: log.Printf,
}
for _, option := range options {
option(h)
}
return
}
|
[
"func",
"New",
"(",
"handler",
"http",
".",
"Handler",
",",
"options",
"...",
"Option",
")",
"(",
"h",
"*",
"Handler",
")",
"{",
"h",
"=",
"&",
"Handler",
"{",
"handler",
":",
"handler",
",",
"logf",
":",
"log",
".",
"Printf",
",",
"}",
"\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"h",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// New creates a new Handler from the handler that is wrapped and
// protected with recover function.
|
[
"New",
"creates",
"a",
"new",
"Handler",
"from",
"the",
"handler",
"that",
"is",
"wrapped",
"and",
"protected",
"with",
"recover",
"function",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/recovery/recovery.go#L65-L74
|
test
|
janos/web
|
recovery/recovery.go
|
ServeHTTP
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
debugMsg := fmt.Sprintf(
"%s\n\n%#v\n\n%#v",
debug.Stack(),
r.URL,
r.Header,
)
if h.label != "" {
debugMsg = h.label + "\n\n" + debugMsg
}
h.logf("http recovery handler: %s %s: %s\n%s", r.Method, r.URL.String(), err, debugMsg)
if h.notifier != nil {
go func() {
defer func() {
if err := recover(); err != nil {
h.logf("http recovery handler: notify panic: %v", err)
}
}()
if err := h.notifier.Notify(
fmt.Sprint(
"Panic ",
r.Method,
" ",
r.URL.String(),
": ", err,
),
debugMsg,
); err != nil {
h.logf("http recovery handler: notify: %v", err)
}
}()
}
if h.panicResponseHandler != nil {
h.panicResponseHandler.ServeHTTP(w, r)
return
}
if h.panicContentType != "" {
w.Header().Set("Content-Type", h.panicContentType)
}
w.WriteHeader(http.StatusInternalServerError)
if h.panicBody != "" {
fmt.Fprintln(w, h.panicBody)
}
}
}()
h.handler.ServeHTTP(w, r)
}
|
go
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
debugMsg := fmt.Sprintf(
"%s\n\n%#v\n\n%#v",
debug.Stack(),
r.URL,
r.Header,
)
if h.label != "" {
debugMsg = h.label + "\n\n" + debugMsg
}
h.logf("http recovery handler: %s %s: %s\n%s", r.Method, r.URL.String(), err, debugMsg)
if h.notifier != nil {
go func() {
defer func() {
if err := recover(); err != nil {
h.logf("http recovery handler: notify panic: %v", err)
}
}()
if err := h.notifier.Notify(
fmt.Sprint(
"Panic ",
r.Method,
" ",
r.URL.String(),
": ", err,
),
debugMsg,
); err != nil {
h.logf("http recovery handler: notify: %v", err)
}
}()
}
if h.panicResponseHandler != nil {
h.panicResponseHandler.ServeHTTP(w, r)
return
}
if h.panicContentType != "" {
w.Header().Set("Content-Type", h.panicContentType)
}
w.WriteHeader(http.StatusInternalServerError)
if h.panicBody != "" {
fmt.Fprintln(w, h.panicBody)
}
}
}()
h.handler.ServeHTTP(w, r)
}
|
[
"func",
"(",
"h",
"Handler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"debugMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s\\n\\n%#v\\n\\n%#v\"",
",",
"\\n",
",",
"\\n",
",",
"\\n",
",",
")",
"\n",
"\\n",
"\n",
"debug",
".",
"Stack",
"(",
")",
"\n",
"r",
".",
"URL",
"\n",
"r",
".",
"Header",
"\n",
"if",
"h",
".",
"label",
"!=",
"\"\"",
"{",
"debugMsg",
"=",
"h",
".",
"label",
"+",
"\"\\n\\n\"",
"+",
"\\n",
"\n",
"}",
"\n",
"\\n",
"\n",
"debugMsg",
"\n",
"}",
"\n",
"}",
"h",
".",
"logf",
"(",
"\"http recovery handler: %s %s: %s\\n%s\"",
",",
"\\n",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
".",
"String",
"(",
")",
",",
"err",
")",
"\n",
"debugMsg",
"\n",
"}"
] |
// ServeHTTP implements http.Handler interface.
|
[
"ServeHTTP",
"implements",
"http",
".",
"Handler",
"interface",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/recovery/recovery.go#L77-L130
|
test
|
janos/web
|
templates/functions.go
|
NewContextFunc
|
func NewContextFunc(m map[string]interface{}) func(string) interface{} {
return func(key string) interface{} {
if value, ok := m[key]; ok {
return value
}
return nil
}
}
|
go
|
func NewContextFunc(m map[string]interface{}) func(string) interface{} {
return func(key string) interface{} {
if value, ok := m[key]; ok {
return value
}
return nil
}
}
|
[
"func",
"NewContextFunc",
"(",
"m",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"func",
"(",
"string",
")",
"interface",
"{",
"}",
"{",
"return",
"func",
"(",
"key",
"string",
")",
"interface",
"{",
"}",
"{",
"if",
"value",
",",
"ok",
":=",
"m",
"[",
"key",
"]",
";",
"ok",
"{",
"return",
"value",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// NewContextFunc creates a new function that can be used to store
// and access arbitrary data by keys.
|
[
"NewContextFunc",
"creates",
"a",
"new",
"function",
"that",
"can",
"be",
"used",
"to",
"store",
"and",
"access",
"arbitrary",
"data",
"by",
"keys",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/functions.go#L18-L25
|
test
|
janos/web
|
client/api/error_registry.go
|
NewMapErrorRegistry
|
func NewMapErrorRegistry(errors map[int]error, handlers map[int]func(body []byte) error) *MapErrorRegistry {
if errors == nil {
errors = map[int]error{}
}
if handlers == nil {
handlers = map[int]func(body []byte) error{}
}
return &MapErrorRegistry{
errors: errors,
handlers: handlers,
}
}
|
go
|
func NewMapErrorRegistry(errors map[int]error, handlers map[int]func(body []byte) error) *MapErrorRegistry {
if errors == nil {
errors = map[int]error{}
}
if handlers == nil {
handlers = map[int]func(body []byte) error{}
}
return &MapErrorRegistry{
errors: errors,
handlers: handlers,
}
}
|
[
"func",
"NewMapErrorRegistry",
"(",
"errors",
"map",
"[",
"int",
"]",
"error",
",",
"handlers",
"map",
"[",
"int",
"]",
"func",
"(",
"body",
"[",
"]",
"byte",
")",
"error",
")",
"*",
"MapErrorRegistry",
"{",
"if",
"errors",
"==",
"nil",
"{",
"errors",
"=",
"map",
"[",
"int",
"]",
"error",
"{",
"}",
"\n",
"}",
"\n",
"if",
"handlers",
"==",
"nil",
"{",
"handlers",
"=",
"map",
"[",
"int",
"]",
"func",
"(",
"body",
"[",
"]",
"byte",
")",
"error",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"MapErrorRegistry",
"{",
"errors",
":",
"errors",
",",
"handlers",
":",
"handlers",
",",
"}",
"\n",
"}"
] |
// NewMapErrorRegistry creates a new instance of MapErrorRegistry.
|
[
"NewMapErrorRegistry",
"creates",
"a",
"new",
"instance",
"of",
"MapErrorRegistry",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L32-L43
|
test
|
janos/web
|
client/api/error_registry.go
|
AddError
|
func (r *MapErrorRegistry) AddError(code int, err error) error {
if _, ok := r.errors[code]; ok {
return ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return ErrErrorAlreadyRegistered
}
r.errors[code] = err
return nil
}
|
go
|
func (r *MapErrorRegistry) AddError(code int, err error) error {
if _, ok := r.errors[code]; ok {
return ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return ErrErrorAlreadyRegistered
}
r.errors[code] = err
return nil
}
|
[
"func",
"(",
"r",
"*",
"MapErrorRegistry",
")",
"AddError",
"(",
"code",
"int",
",",
"err",
"error",
")",
"error",
"{",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"errors",
"[",
"code",
"]",
";",
"ok",
"{",
"return",
"ErrErrorAlreadyRegistered",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"handlers",
"[",
"code",
"]",
";",
"ok",
"{",
"return",
"ErrErrorAlreadyRegistered",
"\n",
"}",
"\n",
"r",
".",
"errors",
"[",
"code",
"]",
"=",
"err",
"\n",
"return",
"nil",
"\n",
"}"
] |
// AddError adds a new error with a code to the registry.
// It there already is an error or handler with the same code,
// ErrErrorAlreadyRegistered will be returned.
|
[
"AddError",
"adds",
"a",
"new",
"error",
"with",
"a",
"code",
"to",
"the",
"registry",
".",
"It",
"there",
"already",
"is",
"an",
"error",
"or",
"handler",
"with",
"the",
"same",
"code",
"ErrErrorAlreadyRegistered",
"will",
"be",
"returned",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L48-L57
|
test
|
janos/web
|
client/api/error_registry.go
|
AddMessageError
|
func (r *MapErrorRegistry) AddMessageError(code int, message string) (*Error, error) {
if _, ok := r.errors[code]; ok {
return nil, ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return nil, ErrErrorAlreadyRegistered
}
err := &Error{
Message: message,
Code: code,
}
r.errors[code] = err
return err, nil
}
|
go
|
func (r *MapErrorRegistry) AddMessageError(code int, message string) (*Error, error) {
if _, ok := r.errors[code]; ok {
return nil, ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return nil, ErrErrorAlreadyRegistered
}
err := &Error{
Message: message,
Code: code,
}
r.errors[code] = err
return err, nil
}
|
[
"func",
"(",
"r",
"*",
"MapErrorRegistry",
")",
"AddMessageError",
"(",
"code",
"int",
",",
"message",
"string",
")",
"(",
"*",
"Error",
",",
"error",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"errors",
"[",
"code",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"ErrErrorAlreadyRegistered",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"handlers",
"[",
"code",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"ErrErrorAlreadyRegistered",
"\n",
"}",
"\n",
"err",
":=",
"&",
"Error",
"{",
"Message",
":",
"message",
",",
"Code",
":",
"code",
",",
"}",
"\n",
"r",
".",
"errors",
"[",
"code",
"]",
"=",
"err",
"\n",
"return",
"err",
",",
"nil",
"\n",
"}"
] |
// AddMessageError adds a new Error isntance with a code and message
// to the registry.
// It there already is an error or handler with the same code,
// ErrErrorAlreadyRegistered will be returned.
|
[
"AddMessageError",
"adds",
"a",
"new",
"Error",
"isntance",
"with",
"a",
"code",
"and",
"message",
"to",
"the",
"registry",
".",
"It",
"there",
"already",
"is",
"an",
"error",
"or",
"handler",
"with",
"the",
"same",
"code",
"ErrErrorAlreadyRegistered",
"will",
"be",
"returned",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L63-L76
|
test
|
janos/web
|
client/api/error_registry.go
|
MustAddError
|
func (r *MapErrorRegistry) MustAddError(code int, err error) {
if e := r.AddError(code, err); e != nil {
panic(e)
}
}
|
go
|
func (r *MapErrorRegistry) MustAddError(code int, err error) {
if e := r.AddError(code, err); e != nil {
panic(e)
}
}
|
[
"func",
"(",
"r",
"*",
"MapErrorRegistry",
")",
"MustAddError",
"(",
"code",
"int",
",",
"err",
"error",
")",
"{",
"if",
"e",
":=",
"r",
".",
"AddError",
"(",
"code",
",",
"err",
")",
";",
"e",
"!=",
"nil",
"{",
"panic",
"(",
"e",
")",
"\n",
"}",
"\n",
"}"
] |
// MustAddError calls AddError and panics in case of an error.
|
[
"MustAddError",
"calls",
"AddError",
"and",
"panics",
"in",
"case",
"of",
"an",
"error",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L79-L83
|
test
|
janos/web
|
client/api/error_registry.go
|
MustAddMessageError
|
func (r *MapErrorRegistry) MustAddMessageError(code int, message string) *Error {
err, e := r.AddMessageError(code, message)
if e != nil {
panic(e)
}
return err
}
|
go
|
func (r *MapErrorRegistry) MustAddMessageError(code int, message string) *Error {
err, e := r.AddMessageError(code, message)
if e != nil {
panic(e)
}
return err
}
|
[
"func",
"(",
"r",
"*",
"MapErrorRegistry",
")",
"MustAddMessageError",
"(",
"code",
"int",
",",
"message",
"string",
")",
"*",
"Error",
"{",
"err",
",",
"e",
":=",
"r",
".",
"AddMessageError",
"(",
"code",
",",
"message",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"panic",
"(",
"e",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// MustAddMessageError calls AddMessageError and panics in case of an error.
|
[
"MustAddMessageError",
"calls",
"AddMessageError",
"and",
"panics",
"in",
"case",
"of",
"an",
"error",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L86-L92
|
test
|
janos/web
|
client/api/error_registry.go
|
AddHandler
|
func (r *MapErrorRegistry) AddHandler(code int, handler func(body []byte) error) error {
if _, ok := r.errors[code]; ok {
return ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return ErrErrorAlreadyRegistered
}
r.handlers[code] = handler
return nil
}
|
go
|
func (r *MapErrorRegistry) AddHandler(code int, handler func(body []byte) error) error {
if _, ok := r.errors[code]; ok {
return ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return ErrErrorAlreadyRegistered
}
r.handlers[code] = handler
return nil
}
|
[
"func",
"(",
"r",
"*",
"MapErrorRegistry",
")",
"AddHandler",
"(",
"code",
"int",
",",
"handler",
"func",
"(",
"body",
"[",
"]",
"byte",
")",
"error",
")",
"error",
"{",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"errors",
"[",
"code",
"]",
";",
"ok",
"{",
"return",
"ErrErrorAlreadyRegistered",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"handlers",
"[",
"code",
"]",
";",
"ok",
"{",
"return",
"ErrErrorAlreadyRegistered",
"\n",
"}",
"\n",
"r",
".",
"handlers",
"[",
"code",
"]",
"=",
"handler",
"\n",
"return",
"nil",
"\n",
"}"
] |
// AddHandler adds a new error handler with a code to the registry.
// It there already is an error or handler with the same code,
// ErrErrorAlreadyRegistered will be returned.
|
[
"AddHandler",
"adds",
"a",
"new",
"error",
"handler",
"with",
"a",
"code",
"to",
"the",
"registry",
".",
"It",
"there",
"already",
"is",
"an",
"error",
"or",
"handler",
"with",
"the",
"same",
"code",
"ErrErrorAlreadyRegistered",
"will",
"be",
"returned",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L102-L111
|
test
|
janos/web
|
client/api/error_registry.go
|
MustAddHandler
|
func (r *MapErrorRegistry) MustAddHandler(code int, handler func(body []byte) error) {
if err := r.AddHandler(code, handler); err != nil {
panic(err)
}
}
|
go
|
func (r *MapErrorRegistry) MustAddHandler(code int, handler func(body []byte) error) {
if err := r.AddHandler(code, handler); err != nil {
panic(err)
}
}
|
[
"func",
"(",
"r",
"*",
"MapErrorRegistry",
")",
"MustAddHandler",
"(",
"code",
"int",
",",
"handler",
"func",
"(",
"body",
"[",
"]",
"byte",
")",
"error",
")",
"{",
"if",
"err",
":=",
"r",
".",
"AddHandler",
"(",
"code",
",",
"handler",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// MustAddHandler calls AddHandler and panics in case of an error.
|
[
"MustAddHandler",
"calls",
"AddHandler",
"and",
"panics",
"in",
"case",
"of",
"an",
"error",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L114-L118
|
test
|
janos/web
|
client/api/error_registry.go
|
Handler
|
func (r MapErrorRegistry) Handler(code int) func(body []byte) error {
return r.handlers[code]
}
|
go
|
func (r MapErrorRegistry) Handler(code int) func(body []byte) error {
return r.handlers[code]
}
|
[
"func",
"(",
"r",
"MapErrorRegistry",
")",
"Handler",
"(",
"code",
"int",
")",
"func",
"(",
"body",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"r",
".",
"handlers",
"[",
"code",
"]",
"\n",
"}"
] |
// Handler returns a handler that is registered under the provided code.
|
[
"Handler",
"returns",
"a",
"handler",
"that",
"is",
"registered",
"under",
"the",
"provided",
"code",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L121-L123
|
test
|
janos/web
|
client/api/api_client.go
|
New
|
func New(endpoint string, errorRegistry ErrorRegistry) *Client {
return &Client{
Endpoint: endpoint,
ErrorRegistry: errorRegistry,
KeyHeader: DefaultKeyHeader,
HTTPClient: http.DefaultClient,
}
}
|
go
|
func New(endpoint string, errorRegistry ErrorRegistry) *Client {
return &Client{
Endpoint: endpoint,
ErrorRegistry: errorRegistry,
KeyHeader: DefaultKeyHeader,
HTTPClient: http.DefaultClient,
}
}
|
[
"func",
"New",
"(",
"endpoint",
"string",
",",
"errorRegistry",
"ErrorRegistry",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"Endpoint",
":",
"endpoint",
",",
"ErrorRegistry",
":",
"errorRegistry",
",",
"KeyHeader",
":",
"DefaultKeyHeader",
",",
"HTTPClient",
":",
"http",
".",
"DefaultClient",
",",
"}",
"\n",
"}"
] |
// New returns a new instance of Client with default values.
|
[
"New",
"returns",
"a",
"new",
"instance",
"of",
"Client",
"with",
"default",
"values",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L57-L64
|
test
|
janos/web
|
client/api/api_client.go
|
Request
|
func (c Client) Request(method, path string, query url.Values, body io.Reader, accept []string) (resp *http.Response, err error) {
return c.RequestContext(nil, method, path, query, body, accept)
}
|
go
|
func (c Client) Request(method, path string, query url.Values, body io.Reader, accept []string) (resp *http.Response, err error) {
return c.RequestContext(nil, method, path, query, body, accept)
}
|
[
"func",
"(",
"c",
"Client",
")",
"Request",
"(",
"method",
",",
"path",
"string",
",",
"query",
"url",
".",
"Values",
",",
"body",
"io",
".",
"Reader",
",",
"accept",
"[",
"]",
"string",
")",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"return",
"c",
".",
"RequestContext",
"(",
"nil",
",",
"method",
",",
"path",
",",
"query",
",",
"body",
",",
"accept",
")",
"\n",
"}"
] |
// Request makes a HTTP request based on Client configuration and
// arguments provided.
|
[
"Request",
"makes",
"a",
"HTTP",
"request",
"based",
"on",
"Client",
"configuration",
"and",
"arguments",
"provided",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L169-L171
|
test
|
janos/web
|
client/api/api_client.go
|
JSONContext
|
func (c Client) JSONContext(ctx context.Context, method, path string, query url.Values, body io.Reader, response interface{}) (err error) {
resp, err := c.RequestContext(ctx, method, path, query, body, []string{"application/json"})
if err != nil {
return
}
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
if response != nil {
if resp.ContentLength == 0 {
return errors.New("empty response body")
}
contentType := resp.Header.Get("Content-Type")
if !strings.Contains(contentType, "application/json") {
return fmt.Errorf("unsupported content type: %s", contentType)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err = JSONUnmarshal(body, &response); err != nil {
return
}
}
return
}
|
go
|
func (c Client) JSONContext(ctx context.Context, method, path string, query url.Values, body io.Reader, response interface{}) (err error) {
resp, err := c.RequestContext(ctx, method, path, query, body, []string{"application/json"})
if err != nil {
return
}
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
if response != nil {
if resp.ContentLength == 0 {
return errors.New("empty response body")
}
contentType := resp.Header.Get("Content-Type")
if !strings.Contains(contentType, "application/json") {
return fmt.Errorf("unsupported content type: %s", contentType)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err = JSONUnmarshal(body, &response); err != nil {
return
}
}
return
}
|
[
"func",
"(",
"c",
"Client",
")",
"JSONContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"method",
",",
"path",
"string",
",",
"query",
"url",
".",
"Values",
",",
"body",
"io",
".",
"Reader",
",",
"response",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"c",
".",
"RequestContext",
"(",
"ctx",
",",
"method",
",",
"path",
",",
"query",
",",
"body",
",",
"[",
"]",
"string",
"{",
"\"application/json\"",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"resp",
".",
"Body",
")",
"\n",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"if",
"response",
"!=",
"nil",
"{",
"if",
"resp",
".",
"ContentLength",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"empty response body\"",
")",
"\n",
"}",
"\n",
"contentType",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"Content-Type\"",
")",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"contentType",
",",
"\"application/json\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unsupported content type: %s\"",
",",
"contentType",
")",
"\n",
"}",
"\n",
"var",
"body",
"[",
"]",
"byte",
"\n",
"body",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"JSONUnmarshal",
"(",
"body",
",",
"&",
"response",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// JSONContext provides the same functionality as JSON with Context instance passing to http.Request.
|
[
"JSONContext",
"provides",
"the",
"same",
"functionality",
"as",
"JSON",
"with",
"Context",
"instance",
"passing",
"to",
"http",
".",
"Request",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L174-L203
|
test
|
janos/web
|
client/api/api_client.go
|
StreamContext
|
func (c Client) StreamContext(ctx context.Context, method, path string, query url.Values, body io.Reader, accept []string) (data io.ReadCloser, contentType string, err error) {
resp, err := c.RequestContext(ctx, method, path, query, body, accept)
if err != nil {
return
}
contentType = resp.Header.Get("Content-Type")
data = resp.Body
return
}
|
go
|
func (c Client) StreamContext(ctx context.Context, method, path string, query url.Values, body io.Reader, accept []string) (data io.ReadCloser, contentType string, err error) {
resp, err := c.RequestContext(ctx, method, path, query, body, accept)
if err != nil {
return
}
contentType = resp.Header.Get("Content-Type")
data = resp.Body
return
}
|
[
"func",
"(",
"c",
"Client",
")",
"StreamContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"method",
",",
"path",
"string",
",",
"query",
"url",
".",
"Values",
",",
"body",
"io",
".",
"Reader",
",",
"accept",
"[",
"]",
"string",
")",
"(",
"data",
"io",
".",
"ReadCloser",
",",
"contentType",
"string",
",",
"err",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"c",
".",
"RequestContext",
"(",
"ctx",
",",
"method",
",",
"path",
",",
"query",
",",
"body",
",",
"accept",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"contentType",
"=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"Content-Type\"",
")",
"\n",
"data",
"=",
"resp",
".",
"Body",
"\n",
"return",
"\n",
"}"
] |
// StreamContext provides the same functionality as Stream with Context instance passing to http.Request.
|
[
"StreamContext",
"provides",
"the",
"same",
"functionality",
"as",
"Stream",
"with",
"Context",
"instance",
"passing",
"to",
"http",
".",
"Request",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L212-L221
|
test
|
janos/web
|
client/api/api_client.go
|
Stream
|
func (c Client) Stream(method, path string, query url.Values, body io.Reader, accept []string) (data io.ReadCloser, contentType string, err error) {
return c.StreamContext(nil, method, path, query, body, accept)
}
|
go
|
func (c Client) Stream(method, path string, query url.Values, body io.Reader, accept []string) (data io.ReadCloser, contentType string, err error) {
return c.StreamContext(nil, method, path, query, body, accept)
}
|
[
"func",
"(",
"c",
"Client",
")",
"Stream",
"(",
"method",
",",
"path",
"string",
",",
"query",
"url",
".",
"Values",
",",
"body",
"io",
".",
"Reader",
",",
"accept",
"[",
"]",
"string",
")",
"(",
"data",
"io",
".",
"ReadCloser",
",",
"contentType",
"string",
",",
"err",
"error",
")",
"{",
"return",
"c",
".",
"StreamContext",
"(",
"nil",
",",
"method",
",",
"path",
",",
"query",
",",
"body",
",",
"accept",
")",
"\n",
"}"
] |
// Stream makes a HTTP request and returns request body as io.ReadCloser,
// to be able to read long running responses. Returned io.ReadCloser must be
// closed at the end of read. To reuse HTTP connection, make sure that the
// whole data is read before closing the reader.
|
[
"Stream",
"makes",
"a",
"HTTP",
"request",
"and",
"returns",
"request",
"body",
"as",
"io",
".",
"ReadCloser",
"to",
"be",
"able",
"to",
"read",
"long",
"running",
"responses",
".",
"Returned",
"io",
".",
"ReadCloser",
"must",
"be",
"closed",
"at",
"the",
"end",
"of",
"read",
".",
"To",
"reuse",
"HTTP",
"connection",
"make",
"sure",
"that",
"the",
"whole",
"data",
"is",
"read",
"before",
"closing",
"the",
"reader",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L227-L229
|
test
|
janos/web
|
client/api/api_client.go
|
JSONUnmarshal
|
func JSONUnmarshal(data []byte, v interface{}) error {
if err := json.Unmarshal(data, v); err != nil {
switch e := err.(type) {
case *json.SyntaxError:
line, col := getLineColFromOffset(data, e.Offset)
return fmt.Errorf("json %s, line: %d, column: %d", e, line, col)
case *json.UnmarshalTypeError:
line, col := getLineColFromOffset(data, e.Offset)
return fmt.Errorf("expected json %s value but got %s, line: %d, column: %d", e.Type, e.Value, line, col)
}
return err
}
return nil
}
|
go
|
func JSONUnmarshal(data []byte, v interface{}) error {
if err := json.Unmarshal(data, v); err != nil {
switch e := err.(type) {
case *json.SyntaxError:
line, col := getLineColFromOffset(data, e.Offset)
return fmt.Errorf("json %s, line: %d, column: %d", e, line, col)
case *json.UnmarshalTypeError:
line, col := getLineColFromOffset(data, e.Offset)
return fmt.Errorf("expected json %s value but got %s, line: %d, column: %d", e.Type, e.Value, line, col)
}
return err
}
return nil
}
|
[
"func",
"JSONUnmarshal",
"(",
"data",
"[",
"]",
"byte",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"e",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"json",
".",
"SyntaxError",
":",
"line",
",",
"col",
":=",
"getLineColFromOffset",
"(",
"data",
",",
"e",
".",
"Offset",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"json %s, line: %d, column: %d\"",
",",
"e",
",",
"line",
",",
"col",
")",
"\n",
"case",
"*",
"json",
".",
"UnmarshalTypeError",
":",
"line",
",",
"col",
":=",
"getLineColFromOffset",
"(",
"data",
",",
"e",
".",
"Offset",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"expected json %s value but got %s, line: %d, column: %d\"",
",",
"e",
".",
"Type",
",",
"e",
".",
"Value",
",",
"line",
",",
"col",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// JSONUnmarshal decodes data into v and returns json.SyntaxError and
// json.UnmarshalTypeError formated with additional information.
|
[
"JSONUnmarshal",
"decodes",
"data",
"into",
"v",
"and",
"returns",
"json",
".",
"SyntaxError",
"and",
"json",
".",
"UnmarshalTypeError",
"formated",
"with",
"additional",
"information",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L233-L246
|
test
|
janos/web
|
servers/http/http.go
|
ServeTCP
|
func (s *Server) ServeTCP(ln net.Listener) (err error) {
if l, ok := ln.(*net.TCPListener); ok {
ln = tcpKeepAliveListener{TCPListener: l}
}
if s.TLSConfig != nil {
ln = tls.NewListener(ln, s.TLSConfig)
}
err = s.Server.Serve(ln)
if err == http.ErrServerClosed {
return nil
}
return
}
|
go
|
func (s *Server) ServeTCP(ln net.Listener) (err error) {
if l, ok := ln.(*net.TCPListener); ok {
ln = tcpKeepAliveListener{TCPListener: l}
}
if s.TLSConfig != nil {
ln = tls.NewListener(ln, s.TLSConfig)
}
err = s.Server.Serve(ln)
if err == http.ErrServerClosed {
return nil
}
return
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"ServeTCP",
"(",
"ln",
"net",
".",
"Listener",
")",
"(",
"err",
"error",
")",
"{",
"if",
"l",
",",
"ok",
":=",
"ln",
".",
"(",
"*",
"net",
".",
"TCPListener",
")",
";",
"ok",
"{",
"ln",
"=",
"tcpKeepAliveListener",
"{",
"TCPListener",
":",
"l",
"}",
"\n",
"}",
"\n",
"if",
"s",
".",
"TLSConfig",
"!=",
"nil",
"{",
"ln",
"=",
"tls",
".",
"NewListener",
"(",
"ln",
",",
"s",
".",
"TLSConfig",
")",
"\n",
"}",
"\n",
"err",
"=",
"s",
".",
"Server",
".",
"Serve",
"(",
"ln",
")",
"\n",
"if",
"err",
"==",
"http",
".",
"ErrServerClosed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// ServeTCP executes http.Server.Serve method.
// If the provided listener is net.TCPListener, keep alive
// will be enabled. If server is configured with TLS,
// a tls.Listener will be created with provided listener.
|
[
"ServeTCP",
"executes",
"http",
".",
"Server",
".",
"Serve",
"method",
".",
"If",
"the",
"provided",
"listener",
"is",
"net",
".",
"TCPListener",
"keep",
"alive",
"will",
"be",
"enabled",
".",
"If",
"server",
"is",
"configured",
"with",
"TLS",
"a",
"tls",
".",
"Listener",
"will",
"be",
"created",
"with",
"provided",
"listener",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/http/http.go#L61-L74
|
test
|
janos/web
|
servers/grpc/grpc.go
|
ServeTCP
|
func (s *Server) ServeTCP(ln net.Listener) (err error) {
return s.Server.Serve(ln)
}
|
go
|
func (s *Server) ServeTCP(ln net.Listener) (err error) {
return s.Server.Serve(ln)
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"ServeTCP",
"(",
"ln",
"net",
".",
"Listener",
")",
"(",
"err",
"error",
")",
"{",
"return",
"s",
".",
"Server",
".",
"Serve",
"(",
"ln",
")",
"\n",
"}"
] |
// ServeTCP serves request on TCP listener.
|
[
"ServeTCP",
"serves",
"request",
"on",
"TCP",
"listener",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/grpc/grpc.go#L35-L37
|
test
|
janos/web
|
servers/grpc/grpc.go
|
Shutdown
|
func (s *Server) Shutdown(ctx context.Context) (err error) {
s.Server.GracefulStop()
return
}
|
go
|
func (s *Server) Shutdown(ctx context.Context) (err error) {
s.Server.GracefulStop()
return
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"Shutdown",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"err",
"error",
")",
"{",
"s",
".",
"Server",
".",
"GracefulStop",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Shutdown executes grpc.Server.GracefulStop method.
|
[
"Shutdown",
"executes",
"grpc",
".",
"Server",
".",
"GracefulStop",
"method",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/grpc/grpc.go#L46-L49
|
test
|
janos/web
|
method.go
|
HandleMethods
|
func HandleMethods(methods map[string]http.Handler, body string, contentType string, w http.ResponseWriter, r *http.Request) {
if handler, ok := methods[r.Method]; ok {
handler.ServeHTTP(w, r)
} else {
allow := []string{}
for k := range methods {
allow = append(allow, k)
}
sort.Strings(allow)
w.Header().Set("Allow", strings.Join(allow, ", "))
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
} else {
w.Header().Set("Content-Type", contentType)
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintln(w, body)
}
}
}
|
go
|
func HandleMethods(methods map[string]http.Handler, body string, contentType string, w http.ResponseWriter, r *http.Request) {
if handler, ok := methods[r.Method]; ok {
handler.ServeHTTP(w, r)
} else {
allow := []string{}
for k := range methods {
allow = append(allow, k)
}
sort.Strings(allow)
w.Header().Set("Allow", strings.Join(allow, ", "))
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
} else {
w.Header().Set("Content-Type", contentType)
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintln(w, body)
}
}
}
|
[
"func",
"HandleMethods",
"(",
"methods",
"map",
"[",
"string",
"]",
"http",
".",
"Handler",
",",
"body",
"string",
",",
"contentType",
"string",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"handler",
",",
"ok",
":=",
"methods",
"[",
"r",
".",
"Method",
"]",
";",
"ok",
"{",
"handler",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"else",
"{",
"allow",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"k",
":=",
"range",
"methods",
"{",
"allow",
"=",
"append",
"(",
"allow",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"allow",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Allow\"",
",",
"strings",
".",
"Join",
"(",
"allow",
",",
"\", \"",
")",
")",
"\n",
"if",
"r",
".",
"Method",
"==",
"\"OPTIONS\"",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"contentType",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"body",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// HandleMethods uses a corresponding Handler based on HTTP request method.
// If Handler is not found, a method not allowed HTTP response is returned
// with specified body and Content-Type header.
|
[
"HandleMethods",
"uses",
"a",
"corresponding",
"Handler",
"based",
"on",
"HTTP",
"request",
"method",
".",
"If",
"Handler",
"is",
"not",
"found",
"a",
"method",
"not",
"allowed",
"HTTP",
"response",
"is",
"returned",
"with",
"specified",
"body",
"and",
"Content",
"-",
"Type",
"header",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/method.go#L18-L36
|
test
|
janos/web
|
set_headers.go
|
NewSetHeadersHandler
|
func NewSetHeadersHandler(h http.Handler, headers map[string]string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for header, value := range headers {
w.Header().Set(header, value)
}
h.ServeHTTP(w, r)
})
}
|
go
|
func NewSetHeadersHandler(h http.Handler, headers map[string]string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for header, value := range headers {
w.Header().Set(header, value)
}
h.ServeHTTP(w, r)
})
}
|
[
"func",
"NewSetHeadersHandler",
"(",
"h",
"http",
".",
"Handler",
",",
"headers",
"map",
"[",
"string",
"]",
"string",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"for",
"header",
",",
"value",
":=",
"range",
"headers",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"header",
",",
"value",
")",
"\n",
"}",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// NewSetHeadersHandler sets provied headers on HTTP response.
|
[
"NewSetHeadersHandler",
"sets",
"provied",
"headers",
"on",
"HTTP",
"response",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/set_headers.go#L23-L30
|
test
|
janos/web
|
file-server/server.go
|
New
|
func New(root, dir string, options *Options) *Server {
if options == nil {
options = &Options{}
}
return &Server{
Options: *options,
root: root,
dir: dir,
hashes: map[string]string{},
mu: &sync.RWMutex{},
}
}
|
go
|
func New(root, dir string, options *Options) *Server {
if options == nil {
options = &Options{}
}
return &Server{
Options: *options,
root: root,
dir: dir,
hashes: map[string]string{},
mu: &sync.RWMutex{},
}
}
|
[
"func",
"New",
"(",
"root",
",",
"dir",
"string",
",",
"options",
"*",
"Options",
")",
"*",
"Server",
"{",
"if",
"options",
"==",
"nil",
"{",
"options",
"=",
"&",
"Options",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Server",
"{",
"Options",
":",
"*",
"options",
",",
"root",
":",
"root",
",",
"dir",
":",
"dir",
",",
"hashes",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
",",
"mu",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"}",
"\n",
"}"
] |
// New initializes a new instance of Server.
|
[
"New",
"initializes",
"a",
"new",
"instance",
"of",
"Server",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/file-server/server.go#L29-L42
|
test
|
janos/web
|
file-server/server.go
|
HashedPath
|
func (s *Server) HashedPath(p string) (string, error) {
if s.Hasher == nil {
return path.Join(s.root, p), nil
}
h, cont, err := s.hash(p)
if err != nil {
if cont {
h, _, err = s.hashFromFilename(p)
}
if err != nil {
return "", err
}
}
return path.Join(s.root, s.hashedPath(p, h)), nil
}
|
go
|
func (s *Server) HashedPath(p string) (string, error) {
if s.Hasher == nil {
return path.Join(s.root, p), nil
}
h, cont, err := s.hash(p)
if err != nil {
if cont {
h, _, err = s.hashFromFilename(p)
}
if err != nil {
return "", err
}
}
return path.Join(s.root, s.hashedPath(p, h)), nil
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"HashedPath",
"(",
"p",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"s",
".",
"Hasher",
"==",
"nil",
"{",
"return",
"path",
".",
"Join",
"(",
"s",
".",
"root",
",",
"p",
")",
",",
"nil",
"\n",
"}",
"\n",
"h",
",",
"cont",
",",
"err",
":=",
"s",
".",
"hash",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"cont",
"{",
"h",
",",
"_",
",",
"err",
"=",
"s",
".",
"hashFromFilename",
"(",
"p",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"path",
".",
"Join",
"(",
"s",
".",
"root",
",",
"s",
".",
"hashedPath",
"(",
"p",
",",
"h",
")",
")",
",",
"nil",
"\n",
"}"
] |
// HashedPath returns a URL path with hash injected into the filename.
|
[
"HashedPath",
"returns",
"a",
"URL",
"path",
"with",
"hash",
"injected",
"into",
"the",
"filename",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/file-server/server.go#L140-L154
|
test
|
janos/web
|
maintenance/maintenance.go
|
New
|
func New(options ...Option) (s *Service) {
s = &Service{
logger: stdLogger{},
}
for _, option := range options {
option(s)
}
if s.store == nil {
s.store = NewMemoryStore()
}
return
}
|
go
|
func New(options ...Option) (s *Service) {
s = &Service{
logger: stdLogger{},
}
for _, option := range options {
option(s)
}
if s.store == nil {
s.store = NewMemoryStore()
}
return
}
|
[
"func",
"New",
"(",
"options",
"...",
"Option",
")",
"(",
"s",
"*",
"Service",
")",
"{",
"s",
"=",
"&",
"Service",
"{",
"logger",
":",
"stdLogger",
"{",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"s",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"store",
"==",
"nil",
"{",
"s",
".",
"store",
"=",
"NewMemoryStore",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// New creates a new instance of Handler.
// The first argument is the handler that will be executed
// when maintenance mode is off.
|
[
"New",
"creates",
"a",
"new",
"instance",
"of",
"Handler",
".",
"The",
"first",
"argument",
"is",
"the",
"handler",
"that",
"will",
"be",
"executed",
"when",
"maintenance",
"mode",
"is",
"off",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L197-L208
|
test
|
janos/web
|
maintenance/maintenance.go
|
HTMLHandler
|
func (s Service) HTMLHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
on, err := s.store.Status()
if err != nil {
s.logger.Errorf("maintenance status: %v", err)
}
if on || err != nil {
if s.HTML.Handler != nil {
s.HTML.Handler.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Type", HTMLContentType)
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, s.HTML.Body)
return
}
h.ServeHTTP(w, r)
})
}
|
go
|
func (s Service) HTMLHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
on, err := s.store.Status()
if err != nil {
s.logger.Errorf("maintenance status: %v", err)
}
if on || err != nil {
if s.HTML.Handler != nil {
s.HTML.Handler.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Type", HTMLContentType)
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, s.HTML.Body)
return
}
h.ServeHTTP(w, r)
})
}
|
[
"func",
"(",
"s",
"Service",
")",
"HTMLHandler",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"on",
",",
"err",
":=",
"s",
".",
"store",
".",
"Status",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Errorf",
"(",
"\"maintenance status: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"on",
"||",
"err",
"!=",
"nil",
"{",
"if",
"s",
".",
"HTML",
".",
"Handler",
"!=",
"nil",
"{",
"s",
".",
"HTML",
".",
"Handler",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"HTMLContentType",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"s",
".",
"HTML",
".",
"Body",
")",
"\n",
"return",
"\n",
"}",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// HTMLHandler is a HTTP middleware that should be used
// alongide HTML pages.
|
[
"HTMLHandler",
"is",
"a",
"HTTP",
"middleware",
"that",
"should",
"be",
"used",
"alongide",
"HTML",
"pages",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L212-L230
|
test
|
janos/web
|
maintenance/maintenance.go
|
Status
|
func (s Service) Status() (on bool, err error) {
return s.store.Status()
}
|
go
|
func (s Service) Status() (on bool, err error) {
return s.store.Status()
}
|
[
"func",
"(",
"s",
"Service",
")",
"Status",
"(",
")",
"(",
"on",
"bool",
",",
"err",
"error",
")",
"{",
"return",
"s",
".",
"store",
".",
"Status",
"(",
")",
"\n",
"}"
] |
// Status returns whether the maintenance mode is enabled.
|
[
"Status",
"returns",
"whether",
"the",
"maintenance",
"mode",
"is",
"enabled",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L277-L279
|
test
|
janos/web
|
maintenance/maintenance.go
|
StatusHandler
|
func (s Service) StatusHandler(w http.ResponseWriter, r *http.Request) {
on, err := s.store.Status()
if err != nil {
s.logger.Errorf("maintenance status: %s", err)
jsonInternalServerErrorResponse(w)
return
}
jsonStatusResponse(w, on)
}
|
go
|
func (s Service) StatusHandler(w http.ResponseWriter, r *http.Request) {
on, err := s.store.Status()
if err != nil {
s.logger.Errorf("maintenance status: %s", err)
jsonInternalServerErrorResponse(w)
return
}
jsonStatusResponse(w, on)
}
|
[
"func",
"(",
"s",
"Service",
")",
"StatusHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"on",
",",
"err",
":=",
"s",
".",
"store",
".",
"Status",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Errorf",
"(",
"\"maintenance status: %s\"",
",",
"err",
")",
"\n",
"jsonInternalServerErrorResponse",
"(",
"w",
")",
"\n",
"return",
"\n",
"}",
"\n",
"jsonStatusResponse",
"(",
"w",
",",
"on",
")",
"\n",
"}"
] |
// StatusHandler can be used in JSON-encoded HTTP API
// to check the status of maintenance.
|
[
"StatusHandler",
"can",
"be",
"used",
"in",
"JSON",
"-",
"encoded",
"HTTP",
"API",
"to",
"check",
"the",
"status",
"of",
"maintenance",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L283-L291
|
test
|
janos/web
|
maintenance/maintenance.go
|
OnHandler
|
func (s Service) OnHandler(w http.ResponseWriter, r *http.Request) {
changed, err := s.store.On()
if err != nil {
s.logger.Errorf("maintenance on: %s", err)
jsonInternalServerErrorResponse(w)
return
}
if changed {
s.logger.Infof("maintenance on")
jsonCreatedResponse(w)
return
}
jsonOKResponse(w)
}
|
go
|
func (s Service) OnHandler(w http.ResponseWriter, r *http.Request) {
changed, err := s.store.On()
if err != nil {
s.logger.Errorf("maintenance on: %s", err)
jsonInternalServerErrorResponse(w)
return
}
if changed {
s.logger.Infof("maintenance on")
jsonCreatedResponse(w)
return
}
jsonOKResponse(w)
}
|
[
"func",
"(",
"s",
"Service",
")",
"OnHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"changed",
",",
"err",
":=",
"s",
".",
"store",
".",
"On",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Errorf",
"(",
"\"maintenance on: %s\"",
",",
"err",
")",
"\n",
"jsonInternalServerErrorResponse",
"(",
"w",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"changed",
"{",
"s",
".",
"logger",
".",
"Infof",
"(",
"\"maintenance on\"",
")",
"\n",
"jsonCreatedResponse",
"(",
"w",
")",
"\n",
"return",
"\n",
"}",
"\n",
"jsonOKResponse",
"(",
"w",
")",
"\n",
"}"
] |
// OnHandler can be used in JSON-encoded HTTP API to enable maintenance.
// It returns HTTP Status Created if the maintenance is enabled.
// If the maintenance is already enabled, it returns HTTP Status OK.
|
[
"OnHandler",
"can",
"be",
"used",
"in",
"JSON",
"-",
"encoded",
"HTTP",
"API",
"to",
"enable",
"maintenance",
".",
"It",
"returns",
"HTTP",
"Status",
"Created",
"if",
"the",
"maintenance",
"is",
"enabled",
".",
"If",
"the",
"maintenance",
"is",
"already",
"enabled",
"it",
"returns",
"HTTP",
"Status",
"OK",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L296-L309
|
test
|
janos/web
|
maintenance/maintenance.go
|
OffHandler
|
func (s Service) OffHandler(w http.ResponseWriter, r *http.Request) {
changed, err := s.store.Off()
if err != nil {
s.logger.Errorf("maintenance off: %s", err)
jsonInternalServerErrorResponse(w)
return
}
if changed {
s.logger.Infof("maintenance off")
}
jsonOKResponse(w)
}
|
go
|
func (s Service) OffHandler(w http.ResponseWriter, r *http.Request) {
changed, err := s.store.Off()
if err != nil {
s.logger.Errorf("maintenance off: %s", err)
jsonInternalServerErrorResponse(w)
return
}
if changed {
s.logger.Infof("maintenance off")
}
jsonOKResponse(w)
}
|
[
"func",
"(",
"s",
"Service",
")",
"OffHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"changed",
",",
"err",
":=",
"s",
".",
"store",
".",
"Off",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Errorf",
"(",
"\"maintenance off: %s\"",
",",
"err",
")",
"\n",
"jsonInternalServerErrorResponse",
"(",
"w",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"changed",
"{",
"s",
".",
"logger",
".",
"Infof",
"(",
"\"maintenance off\"",
")",
"\n",
"}",
"\n",
"jsonOKResponse",
"(",
"w",
")",
"\n",
"}"
] |
// OffHandler can be used in JSON-encoded HTTP API to disable maintenance.
|
[
"OffHandler",
"can",
"be",
"used",
"in",
"JSON",
"-",
"encoded",
"HTTP",
"API",
"to",
"disable",
"maintenance",
"."
] |
0fb0203103deb84424510a8d5166ac00700f2b0e
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L312-L323
|
test
|
taskcluster/taskcluster-client-go
|
tcnotify/types.go
|
MarshalJSON
|
func (this *PostIRCMessageRequest) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *PostIRCMessageRequest) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"PostIRCMessageRequest",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// PostIRCMessageRequest is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"PostIRCMessageRequest",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcnotify/types.go#L194-L197
|
test
|
taskcluster/taskcluster-client-go
|
tcqueue/types.go
|
MarshalJSON
|
func (this *PostArtifactRequest) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *PostArtifactRequest) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"PostArtifactRequest",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// PostArtifactRequest is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"PostArtifactRequest",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcqueue/types.go#L2457-L2460
|
test
|
taskcluster/taskcluster-client-go
|
tcqueue/types.go
|
MarshalJSON
|
func (this *PostArtifactResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *PostArtifactResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"PostArtifactResponse",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// PostArtifactResponse is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"PostArtifactResponse",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcqueue/types.go#L2473-L2476
|
test
|
taskcluster/taskcluster-client-go
|
tchooksevents/types.go
|
MarshalJSON
|
func (this *HookChangedMessage) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *HookChangedMessage) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"HookChangedMessage",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// HookChangedMessage is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"HookChangedMessage",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooksevents/types.go#L36-L39
|
test
|
taskcluster/taskcluster-client-go
|
tchooks/types.go
|
MarshalJSON
|
func (this *TriggerHookRequest) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *TriggerHookRequest) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"TriggerHookRequest",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// TriggerHookRequest is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"TriggerHookRequest",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/types.go#L598-L601
|
test
|
taskcluster/taskcluster-client-go
|
tchooks/types.go
|
MarshalJSON
|
func (this *TriggerHookResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *TriggerHookResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"TriggerHookResponse",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// TriggerHookResponse is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"TriggerHookResponse",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/types.go#L614-L617
|
test
|
taskcluster/taskcluster-client-go
|
tchooks/types.go
|
UnmarshalJSON
|
func (this *TriggerHookResponse) UnmarshalJSON(data []byte) error {
if this == nil {
return errors.New("TriggerHookResponse: UnmarshalJSON on nil pointer")
}
*this = append((*this)[0:0], data...)
return nil
}
|
go
|
func (this *TriggerHookResponse) UnmarshalJSON(data []byte) error {
if this == nil {
return errors.New("TriggerHookResponse: UnmarshalJSON on nil pointer")
}
*this = append((*this)[0:0], data...)
return nil
}
|
[
"func",
"(",
"this",
"*",
"TriggerHookResponse",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"this",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"TriggerHookResponse: UnmarshalJSON on nil pointer\"",
")",
"\n",
"}",
"\n",
"*",
"this",
"=",
"append",
"(",
"(",
"*",
"this",
")",
"[",
"0",
":",
"0",
"]",
",",
"data",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON is a copy of the json.RawMessage implementation.
|
[
"UnmarshalJSON",
"is",
"a",
"copy",
"of",
"the",
"json",
".",
"RawMessage",
"implementation",
"."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/types.go#L620-L626
|
test
|
taskcluster/taskcluster-client-go
|
tcec2manager/types.go
|
MarshalJSON
|
func (this *LaunchInfo) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *LaunchInfo) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"LaunchInfo",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// LaunchInfo is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"LaunchInfo",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/types.go#L494-L497
|
test
|
taskcluster/taskcluster-client-go
|
tcec2manager/types.go
|
MarshalJSON
|
func (this *Var) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *Var) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"Var",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// Var is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"Var",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/types.go#L510-L513
|
test
|
taskcluster/taskcluster-client-go
|
tcec2manager/types.go
|
MarshalJSON
|
func (this *Var1) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *Var1) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"Var1",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// Var1 is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"Var1",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/types.go#L526-L529
|
test
|
taskcluster/taskcluster-client-go
|
tcec2manager/types.go
|
MarshalJSON
|
func (this *Var3) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *Var3) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"Var3",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// Var3 is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"Var3",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/types.go#L542-L545
|
test
|
taskcluster/taskcluster-client-go
|
time.go
|
MarshalJSON
|
func (t Time) MarshalJSON() ([]byte, error) {
if y := time.Time(t).Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("queue.Time.MarshalJSON: year outside of range [0,9999]")
}
return []byte(`"` + t.String() + `"`), nil
}
|
go
|
func (t Time) MarshalJSON() ([]byte, error) {
if y := time.Time(t).Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("queue.Time.MarshalJSON: year outside of range [0,9999]")
}
return []byte(`"` + t.String() + `"`), nil
}
|
[
"func",
"(",
"t",
"Time",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"y",
":=",
"time",
".",
"Time",
"(",
"t",
")",
".",
"Year",
"(",
")",
";",
"y",
"<",
"0",
"||",
"y",
">=",
"10000",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"queue.Time.MarshalJSON: year outside of range [0,9999]\"",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"(",
"`\"`",
"+",
"t",
".",
"String",
"(",
")",
"+",
"`\"`",
")",
",",
"nil",
"\n",
"}"
] |
// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
|
[
"MarshalJSON",
"implements",
"the",
"json",
".",
"Marshaler",
"interface",
".",
"The",
"time",
"is",
"a",
"quoted",
"string",
"in",
"RFC",
"3339",
"format",
"with",
"sub",
"-",
"second",
"precision",
"added",
"if",
"present",
"."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/time.go#L19-L26
|
test
|
taskcluster/taskcluster-client-go
|
time.go
|
UnmarshalJSON
|
func (t *Time) UnmarshalJSON(data []byte) (err error) {
// Fractional seconds are handled implicitly by Parse.
x := new(time.Time)
*x, err = time.Parse(`"`+time.RFC3339+`"`, string(data))
*t = Time(*x)
return
}
|
go
|
func (t *Time) UnmarshalJSON(data []byte) (err error) {
// Fractional seconds are handled implicitly by Parse.
x := new(time.Time)
*x, err = time.Parse(`"`+time.RFC3339+`"`, string(data))
*t = Time(*x)
return
}
|
[
"func",
"(",
"t",
"*",
"Time",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"x",
":=",
"new",
"(",
"time",
".",
"Time",
")",
"\n",
"*",
"x",
",",
"err",
"=",
"time",
".",
"Parse",
"(",
"`\"`",
"+",
"time",
".",
"RFC3339",
"+",
"`\"`",
",",
"string",
"(",
"data",
")",
")",
"\n",
"*",
"t",
"=",
"Time",
"(",
"*",
"x",
")",
"\n",
"return",
"\n",
"}"
] |
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in RFC 3339 format.
|
[
"UnmarshalJSON",
"implements",
"the",
"json",
".",
"Unmarshaler",
"interface",
".",
"The",
"time",
"is",
"expected",
"to",
"be",
"a",
"quoted",
"string",
"in",
"RFC",
"3339",
"format",
"."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/time.go#L30-L36
|
test
|
taskcluster/taskcluster-client-go
|
readwriteseeker/readwriteseeker.go
|
Write
|
func (rws *ReadWriteSeeker) Write(p []byte) (n int, err error) {
minCap := rws.pos + len(p)
if minCap > cap(rws.buf) { // Make sure buf has enough capacity:
buf2 := make([]byte, len(rws.buf), minCap+len(p)) // add some extra
copy(buf2, rws.buf)
rws.buf = buf2
}
if minCap > len(rws.buf) {
rws.buf = rws.buf[:minCap]
}
copy(rws.buf[rws.pos:], p)
rws.pos += len(p)
return len(p), nil
}
|
go
|
func (rws *ReadWriteSeeker) Write(p []byte) (n int, err error) {
minCap := rws.pos + len(p)
if minCap > cap(rws.buf) { // Make sure buf has enough capacity:
buf2 := make([]byte, len(rws.buf), minCap+len(p)) // add some extra
copy(buf2, rws.buf)
rws.buf = buf2
}
if minCap > len(rws.buf) {
rws.buf = rws.buf[:minCap]
}
copy(rws.buf[rws.pos:], p)
rws.pos += len(p)
return len(p), nil
}
|
[
"func",
"(",
"rws",
"*",
"ReadWriteSeeker",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"minCap",
":=",
"rws",
".",
"pos",
"+",
"len",
"(",
"p",
")",
"\n",
"if",
"minCap",
">",
"cap",
"(",
"rws",
".",
"buf",
")",
"{",
"buf2",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"rws",
".",
"buf",
")",
",",
"minCap",
"+",
"len",
"(",
"p",
")",
")",
"\n",
"copy",
"(",
"buf2",
",",
"rws",
".",
"buf",
")",
"\n",
"rws",
".",
"buf",
"=",
"buf2",
"\n",
"}",
"\n",
"if",
"minCap",
">",
"len",
"(",
"rws",
".",
"buf",
")",
"{",
"rws",
".",
"buf",
"=",
"rws",
".",
"buf",
"[",
":",
"minCap",
"]",
"\n",
"}",
"\n",
"copy",
"(",
"rws",
".",
"buf",
"[",
"rws",
".",
"pos",
":",
"]",
",",
"p",
")",
"\n",
"rws",
".",
"pos",
"+=",
"len",
"(",
"p",
")",
"\n",
"return",
"len",
"(",
"p",
")",
",",
"nil",
"\n",
"}"
] |
// Write implements the io.Writer interface
|
[
"Write",
"implements",
"the",
"io",
".",
"Writer",
"interface"
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/readwriteseeker/readwriteseeker.go#L15-L28
|
test
|
taskcluster/taskcluster-client-go
|
readwriteseeker/readwriteseeker.go
|
Seek
|
func (rws *ReadWriteSeeker) Seek(offset int64, whence int) (int64, error) {
newPos, offs := 0, int(offset)
switch whence {
case io.SeekStart:
newPos = offs
case io.SeekCurrent:
newPos = rws.pos + offs
case io.SeekEnd:
newPos = len(rws.buf) + offs
}
if newPos < 0 {
return 0, errors.New("negative result pos")
}
rws.pos = newPos
return int64(newPos), nil
}
|
go
|
func (rws *ReadWriteSeeker) Seek(offset int64, whence int) (int64, error) {
newPos, offs := 0, int(offset)
switch whence {
case io.SeekStart:
newPos = offs
case io.SeekCurrent:
newPos = rws.pos + offs
case io.SeekEnd:
newPos = len(rws.buf) + offs
}
if newPos < 0 {
return 0, errors.New("negative result pos")
}
rws.pos = newPos
return int64(newPos), nil
}
|
[
"func",
"(",
"rws",
"*",
"ReadWriteSeeker",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"newPos",
",",
"offs",
":=",
"0",
",",
"int",
"(",
"offset",
")",
"\n",
"switch",
"whence",
"{",
"case",
"io",
".",
"SeekStart",
":",
"newPos",
"=",
"offs",
"\n",
"case",
"io",
".",
"SeekCurrent",
":",
"newPos",
"=",
"rws",
".",
"pos",
"+",
"offs",
"\n",
"case",
"io",
".",
"SeekEnd",
":",
"newPos",
"=",
"len",
"(",
"rws",
".",
"buf",
")",
"+",
"offs",
"\n",
"}",
"\n",
"if",
"newPos",
"<",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"negative result pos\"",
")",
"\n",
"}",
"\n",
"rws",
".",
"pos",
"=",
"newPos",
"\n",
"return",
"int64",
"(",
"newPos",
")",
",",
"nil",
"\n",
"}"
] |
// Seek implements the io.Seeker interface
|
[
"Seek",
"implements",
"the",
"io",
".",
"Seeker",
"interface"
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/readwriteseeker/readwriteseeker.go#L31-L46
|
test
|
taskcluster/taskcluster-client-go
|
readwriteseeker/readwriteseeker.go
|
Read
|
func (rws *ReadWriteSeeker) Read(b []byte) (n int, err error) {
if rws.pos >= len(rws.buf) {
return 0, io.EOF
}
n = copy(b, rws.buf[rws.pos:])
rws.pos += n
return
}
|
go
|
func (rws *ReadWriteSeeker) Read(b []byte) (n int, err error) {
if rws.pos >= len(rws.buf) {
return 0, io.EOF
}
n = copy(b, rws.buf[rws.pos:])
rws.pos += n
return
}
|
[
"func",
"(",
"rws",
"*",
"ReadWriteSeeker",
")",
"Read",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"rws",
".",
"pos",
">=",
"len",
"(",
"rws",
".",
"buf",
")",
"{",
"return",
"0",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"n",
"=",
"copy",
"(",
"b",
",",
"rws",
".",
"buf",
"[",
"rws",
".",
"pos",
":",
"]",
")",
"\n",
"rws",
".",
"pos",
"+=",
"n",
"\n",
"return",
"\n",
"}"
] |
// Read implements the io.Reader interface
|
[
"Read",
"implements",
"the",
"io",
".",
"Reader",
"interface"
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/readwriteseeker/readwriteseeker.go#L54-L61
|
test
|
taskcluster/taskcluster-client-go
|
tcawsprovisioner/types.go
|
MarshalJSON
|
func (this *LaunchSpecsResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *LaunchSpecsResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"LaunchSpecsResponse",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// LaunchSpecsResponse is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"LaunchSpecsResponse",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/types.go#L555-L558
|
test
|
taskcluster/taskcluster-client-go
|
tcawsprovisioner/types.go
|
MarshalJSON
|
func (this *RegionLaunchSpec) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *RegionLaunchSpec) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"RegionLaunchSpec",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// RegionLaunchSpec is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"RegionLaunchSpec",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/types.go#L571-L574
|
test
|
taskcluster/taskcluster-client-go
|
codegenerator/model/model.go
|
GenerateCode
|
func (apiDefs APIDefinitions) GenerateCode(goOutputDir, modelData string, downloaded time.Time) {
downloadedTime = downloaded
for i := range apiDefs {
apiDefs[i].PackageName = "tc" + strings.ToLower(apiDefs[i].Data.Name())
// Used throughout docs, and also methods that use the class, we need a
// variable name to be used when referencing the go type. It should not
// clash with either the package name or the go type of the principle
// member of the package (e.g. awsprovisioner.AwsProvisioner). We'll
// lowercase the name (e.g. awsProvisioner) and if that clashes with
// either package or principle member, we'll just use my<Name>. This
// results in e.g. `var myQueue queue.Queue`, but `var awsProvisioner
// awsprovisioner.AwsProvisioner`.
apiDefs[i].ExampleVarName = strings.ToLower(string(apiDefs[i].Data.Name()[0])) + apiDefs[i].Data.Name()[1:]
if apiDefs[i].ExampleVarName == apiDefs[i].Data.Name() || apiDefs[i].ExampleVarName == apiDefs[i].PackageName {
apiDefs[i].ExampleVarName = "my" + apiDefs[i].Data.Name()
}
apiDefs[i].PackagePath = filepath.Join(goOutputDir, apiDefs[i].PackageName)
err = os.MkdirAll(apiDefs[i].PackagePath, 0755)
exitOnFail(err)
fmt.Printf("Generating go types for %s\n", apiDefs[i].PackageName)
job := &jsonschema2go.Job{
Package: apiDefs[i].PackageName,
URLs: apiDefs[i].schemaURLs,
ExportTypes: true,
TypeNameBlacklist: apiDefs[i].members,
DisableNestedStructs: true,
}
result, err := job.Execute()
exitOnFail(err)
apiDefs[i].schemas = result.SchemaSet
typesSourceFile := filepath.Join(apiDefs[i].PackagePath, "types.go")
FormatSourceAndSave(typesSourceFile, result.SourceCode)
fmt.Printf("Generating functions and methods for %s\n", job.Package)
content := `
// The following code is AUTO-GENERATED. Please DO NOT edit.
// To update this generated code, run the following command:
// in the /codegenerator/model subdirectory of this project,
// making sure that ` + "`${GOPATH}/bin` is in your `PATH`" + `:
//
// go install && go generate
//
// This package was generated from the schema defined at
// ` + apiDefs[i].URL + `
`
content += apiDefs[i].generateAPICode()
sourceFile := filepath.Join(apiDefs[i].PackagePath, apiDefs[i].PackageName+".go")
FormatSourceAndSave(sourceFile, []byte(content))
}
content := "Generated: " + strconv.FormatInt(downloadedTime.Unix(), 10) + "\n"
content += "The following file is an auto-generated static dump of the API models at time of code generation.\n"
content += "It is provided here for reference purposes, but is not used by any code.\n"
content += "\n"
for i := range apiDefs {
content += text.Underline(apiDefs[i].URL)
content += apiDefs[i].Data.String() + "\n\n"
for _, url := range apiDefs[i].schemas.SortedSanitizedURLs() {
content += text.Underline(url)
content += apiDefs[i].schemas.SubSchema(url).String() + "\n\n"
}
}
exitOnFail(ioutil.WriteFile(modelData, []byte(content), 0644))
}
|
go
|
func (apiDefs APIDefinitions) GenerateCode(goOutputDir, modelData string, downloaded time.Time) {
downloadedTime = downloaded
for i := range apiDefs {
apiDefs[i].PackageName = "tc" + strings.ToLower(apiDefs[i].Data.Name())
// Used throughout docs, and also methods that use the class, we need a
// variable name to be used when referencing the go type. It should not
// clash with either the package name or the go type of the principle
// member of the package (e.g. awsprovisioner.AwsProvisioner). We'll
// lowercase the name (e.g. awsProvisioner) and if that clashes with
// either package or principle member, we'll just use my<Name>. This
// results in e.g. `var myQueue queue.Queue`, but `var awsProvisioner
// awsprovisioner.AwsProvisioner`.
apiDefs[i].ExampleVarName = strings.ToLower(string(apiDefs[i].Data.Name()[0])) + apiDefs[i].Data.Name()[1:]
if apiDefs[i].ExampleVarName == apiDefs[i].Data.Name() || apiDefs[i].ExampleVarName == apiDefs[i].PackageName {
apiDefs[i].ExampleVarName = "my" + apiDefs[i].Data.Name()
}
apiDefs[i].PackagePath = filepath.Join(goOutputDir, apiDefs[i].PackageName)
err = os.MkdirAll(apiDefs[i].PackagePath, 0755)
exitOnFail(err)
fmt.Printf("Generating go types for %s\n", apiDefs[i].PackageName)
job := &jsonschema2go.Job{
Package: apiDefs[i].PackageName,
URLs: apiDefs[i].schemaURLs,
ExportTypes: true,
TypeNameBlacklist: apiDefs[i].members,
DisableNestedStructs: true,
}
result, err := job.Execute()
exitOnFail(err)
apiDefs[i].schemas = result.SchemaSet
typesSourceFile := filepath.Join(apiDefs[i].PackagePath, "types.go")
FormatSourceAndSave(typesSourceFile, result.SourceCode)
fmt.Printf("Generating functions and methods for %s\n", job.Package)
content := `
// The following code is AUTO-GENERATED. Please DO NOT edit.
// To update this generated code, run the following command:
// in the /codegenerator/model subdirectory of this project,
// making sure that ` + "`${GOPATH}/bin` is in your `PATH`" + `:
//
// go install && go generate
//
// This package was generated from the schema defined at
// ` + apiDefs[i].URL + `
`
content += apiDefs[i].generateAPICode()
sourceFile := filepath.Join(apiDefs[i].PackagePath, apiDefs[i].PackageName+".go")
FormatSourceAndSave(sourceFile, []byte(content))
}
content := "Generated: " + strconv.FormatInt(downloadedTime.Unix(), 10) + "\n"
content += "The following file is an auto-generated static dump of the API models at time of code generation.\n"
content += "It is provided here for reference purposes, but is not used by any code.\n"
content += "\n"
for i := range apiDefs {
content += text.Underline(apiDefs[i].URL)
content += apiDefs[i].Data.String() + "\n\n"
for _, url := range apiDefs[i].schemas.SortedSanitizedURLs() {
content += text.Underline(url)
content += apiDefs[i].schemas.SubSchema(url).String() + "\n\n"
}
}
exitOnFail(ioutil.WriteFile(modelData, []byte(content), 0644))
}
|
[
"func",
"(",
"apiDefs",
"APIDefinitions",
")",
"GenerateCode",
"(",
"goOutputDir",
",",
"modelData",
"string",
",",
"downloaded",
"time",
".",
"Time",
")",
"{",
"downloadedTime",
"=",
"downloaded",
"\n",
"for",
"i",
":=",
"range",
"apiDefs",
"{",
"apiDefs",
"[",
"i",
"]",
".",
"PackageName",
"=",
"\"tc\"",
"+",
"strings",
".",
"ToLower",
"(",
"apiDefs",
"[",
"i",
"]",
".",
"Data",
".",
"Name",
"(",
")",
")",
"\n",
"apiDefs",
"[",
"i",
"]",
".",
"ExampleVarName",
"=",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"apiDefs",
"[",
"i",
"]",
".",
"Data",
".",
"Name",
"(",
")",
"[",
"0",
"]",
")",
")",
"+",
"apiDefs",
"[",
"i",
"]",
".",
"Data",
".",
"Name",
"(",
")",
"[",
"1",
":",
"]",
"\n",
"if",
"apiDefs",
"[",
"i",
"]",
".",
"ExampleVarName",
"==",
"apiDefs",
"[",
"i",
"]",
".",
"Data",
".",
"Name",
"(",
")",
"||",
"apiDefs",
"[",
"i",
"]",
".",
"ExampleVarName",
"==",
"apiDefs",
"[",
"i",
"]",
".",
"PackageName",
"{",
"apiDefs",
"[",
"i",
"]",
".",
"ExampleVarName",
"=",
"\"my\"",
"+",
"apiDefs",
"[",
"i",
"]",
".",
"Data",
".",
"Name",
"(",
")",
"\n",
"}",
"\n",
"apiDefs",
"[",
"i",
"]",
".",
"PackagePath",
"=",
"filepath",
".",
"Join",
"(",
"goOutputDir",
",",
"apiDefs",
"[",
"i",
"]",
".",
"PackageName",
")",
"\n",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"apiDefs",
"[",
"i",
"]",
".",
"PackagePath",
",",
"0755",
")",
"\n",
"exitOnFail",
"(",
"err",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"Generating go types for %s\\n\"",
",",
"\\n",
")",
"\n",
"apiDefs",
"[",
"i",
"]",
".",
"PackageName",
"\n",
"job",
":=",
"&",
"jsonschema2go",
".",
"Job",
"{",
"Package",
":",
"apiDefs",
"[",
"i",
"]",
".",
"PackageName",
",",
"URLs",
":",
"apiDefs",
"[",
"i",
"]",
".",
"schemaURLs",
",",
"ExportTypes",
":",
"true",
",",
"TypeNameBlacklist",
":",
"apiDefs",
"[",
"i",
"]",
".",
"members",
",",
"DisableNestedStructs",
":",
"true",
",",
"}",
"\n",
"result",
",",
"err",
":=",
"job",
".",
"Execute",
"(",
")",
"\n",
"exitOnFail",
"(",
"err",
")",
"\n",
"apiDefs",
"[",
"i",
"]",
".",
"schemas",
"=",
"result",
".",
"SchemaSet",
"\n",
"typesSourceFile",
":=",
"filepath",
".",
"Join",
"(",
"apiDefs",
"[",
"i",
"]",
".",
"PackagePath",
",",
"\"types.go\"",
")",
"\n",
"FormatSourceAndSave",
"(",
"typesSourceFile",
",",
"result",
".",
"SourceCode",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"Generating functions and methods for %s\\n\"",
",",
"\\n",
")",
"\n",
"job",
".",
"Package",
"\n",
"content",
":=",
"`// The following code is AUTO-GENERATED. Please DO NOT edit.// To update this generated code, run the following command:// in the /codegenerator/model subdirectory of this project,// making sure that `",
"+",
"\"`${GOPATH}/bin` is in your `PATH`\"",
"+",
"`://// go install && go generate//// This package was generated from the schema defined at// `",
"+",
"apiDefs",
"[",
"i",
"]",
".",
"URL",
"+",
"``",
"\n",
"content",
"+=",
"apiDefs",
"[",
"i",
"]",
".",
"generateAPICode",
"(",
")",
"\n",
"}",
"\n",
"sourceFile",
":=",
"filepath",
".",
"Join",
"(",
"apiDefs",
"[",
"i",
"]",
".",
"PackagePath",
",",
"apiDefs",
"[",
"i",
"]",
".",
"PackageName",
"+",
"\".go\"",
")",
"\n",
"FormatSourceAndSave",
"(",
"sourceFile",
",",
"[",
"]",
"byte",
"(",
"content",
")",
")",
"\n",
"content",
":=",
"\"Generated: \"",
"+",
"strconv",
".",
"FormatInt",
"(",
"downloadedTime",
".",
"Unix",
"(",
")",
",",
"10",
")",
"+",
"\"\\n\"",
"\n",
"\\n",
"\n",
"content",
"+=",
"\"The following file is an auto-generated static dump of the API models at time of code generation.\\n\"",
"\n",
"\\n",
"\n",
"}"
] |
// GenerateCode takes the objects loaded into memory in LoadAPIs
// and writes them out as go code.
|
[
"GenerateCode",
"takes",
"the",
"objects",
"loaded",
"into",
"memory",
"in",
"LoadAPIs",
"and",
"writes",
"them",
"out",
"as",
"go",
"code",
"."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/codegenerator/model/model.go#L200-L266
|
test
|
taskcluster/taskcluster-client-go
|
codegenerator/model/api.go
|
postPopulate
|
func (entry *APIEntry) postPopulate(apiDef *APIDefinition) {
if x := &entry.Parent.apiDef.schemaURLs; entry.Input != "" {
entry.InputURL = tcurls.Schema(tcclient.RootURLFromEnvVars(), entry.Parent.ServiceName, entry.Input)
*x = append(*x, entry.InputURL)
}
if x := &entry.Parent.apiDef.schemaURLs; entry.Output != "" {
entry.OutputURL = tcurls.Schema(tcclient.RootURLFromEnvVars(), entry.Parent.ServiceName, entry.Output)
*x = append(*x, entry.OutputURL)
}
}
|
go
|
func (entry *APIEntry) postPopulate(apiDef *APIDefinition) {
if x := &entry.Parent.apiDef.schemaURLs; entry.Input != "" {
entry.InputURL = tcurls.Schema(tcclient.RootURLFromEnvVars(), entry.Parent.ServiceName, entry.Input)
*x = append(*x, entry.InputURL)
}
if x := &entry.Parent.apiDef.schemaURLs; entry.Output != "" {
entry.OutputURL = tcurls.Schema(tcclient.RootURLFromEnvVars(), entry.Parent.ServiceName, entry.Output)
*x = append(*x, entry.OutputURL)
}
}
|
[
"func",
"(",
"entry",
"*",
"APIEntry",
")",
"postPopulate",
"(",
"apiDef",
"*",
"APIDefinition",
")",
"{",
"if",
"x",
":=",
"&",
"entry",
".",
"Parent",
".",
"apiDef",
".",
"schemaURLs",
";",
"entry",
".",
"Input",
"!=",
"\"\"",
"{",
"entry",
".",
"InputURL",
"=",
"tcurls",
".",
"Schema",
"(",
"tcclient",
".",
"RootURLFromEnvVars",
"(",
")",
",",
"entry",
".",
"Parent",
".",
"ServiceName",
",",
"entry",
".",
"Input",
")",
"\n",
"*",
"x",
"=",
"append",
"(",
"*",
"x",
",",
"entry",
".",
"InputURL",
")",
"\n",
"}",
"\n",
"if",
"x",
":=",
"&",
"entry",
".",
"Parent",
".",
"apiDef",
".",
"schemaURLs",
";",
"entry",
".",
"Output",
"!=",
"\"\"",
"{",
"entry",
".",
"OutputURL",
"=",
"tcurls",
".",
"Schema",
"(",
"tcclient",
".",
"RootURLFromEnvVars",
"(",
")",
",",
"entry",
".",
"Parent",
".",
"ServiceName",
",",
"entry",
".",
"Output",
")",
"\n",
"*",
"x",
"=",
"append",
"(",
"*",
"x",
",",
"entry",
".",
"OutputURL",
")",
"\n",
"}",
"\n",
"}"
] |
// Add entry.Input and entry.Output to schemaURLs, if they are set
|
[
"Add",
"entry",
".",
"Input",
"and",
"entry",
".",
"Output",
"to",
"schemaURLs",
"if",
"they",
"are",
"set"
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/codegenerator/model/api.go#L244-L253
|
test
|
taskcluster/taskcluster-client-go
|
creds.go
|
CreateTemporaryCredentials
|
func (permaCreds *Credentials) CreateTemporaryCredentials(duration time.Duration, scopes ...string) (tempCreds *Credentials, err error) {
return permaCreds.CreateNamedTemporaryCredentials("", duration, scopes...)
}
|
go
|
func (permaCreds *Credentials) CreateTemporaryCredentials(duration time.Duration, scopes ...string) (tempCreds *Credentials, err error) {
return permaCreds.CreateNamedTemporaryCredentials("", duration, scopes...)
}
|
[
"func",
"(",
"permaCreds",
"*",
"Credentials",
")",
"CreateTemporaryCredentials",
"(",
"duration",
"time",
".",
"Duration",
",",
"scopes",
"...",
"string",
")",
"(",
"tempCreds",
"*",
"Credentials",
",",
"err",
"error",
")",
"{",
"return",
"permaCreds",
".",
"CreateNamedTemporaryCredentials",
"(",
"\"\"",
",",
"duration",
",",
"scopes",
"...",
")",
"\n",
"}"
] |
// CreateTemporaryCredentials is an alias for CreateNamedTemporaryCredentials
// with an empty name.
|
[
"CreateTemporaryCredentials",
"is",
"an",
"alias",
"for",
"CreateNamedTemporaryCredentials",
"with",
"an",
"empty",
"name",
"."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/creds.go#L153-L155
|
test
|
taskcluster/taskcluster-client-go
|
http.go
|
setURL
|
func setURL(client *Client, route string, query url.Values) (u *url.URL, err error) {
URL := client.BaseURL
// See https://bugzil.la/1484702
// Avoid double separator; routes must start with `/`, so baseURL shouldn't
// end with `/`.
if strings.HasSuffix(URL, "/") {
URL = URL[:len(URL)-1]
}
URL += route
u, err = url.Parse(URL)
if err != nil {
return nil, fmt.Errorf("Cannot parse url: '%v', is BaseURL (%v) set correctly?\n%v\n", URL, client.BaseURL, err)
}
if query != nil {
u.RawQuery = query.Encode()
}
return
}
|
go
|
func setURL(client *Client, route string, query url.Values) (u *url.URL, err error) {
URL := client.BaseURL
// See https://bugzil.la/1484702
// Avoid double separator; routes must start with `/`, so baseURL shouldn't
// end with `/`.
if strings.HasSuffix(URL, "/") {
URL = URL[:len(URL)-1]
}
URL += route
u, err = url.Parse(URL)
if err != nil {
return nil, fmt.Errorf("Cannot parse url: '%v', is BaseURL (%v) set correctly?\n%v\n", URL, client.BaseURL, err)
}
if query != nil {
u.RawQuery = query.Encode()
}
return
}
|
[
"func",
"setURL",
"(",
"client",
"*",
"Client",
",",
"route",
"string",
",",
"query",
"url",
".",
"Values",
")",
"(",
"u",
"*",
"url",
".",
"URL",
",",
"err",
"error",
")",
"{",
"URL",
":=",
"client",
".",
"BaseURL",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"URL",
",",
"\"/\"",
")",
"{",
"URL",
"=",
"URL",
"[",
":",
"len",
"(",
"URL",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"URL",
"+=",
"route",
"\n",
"u",
",",
"err",
"=",
"url",
".",
"Parse",
"(",
"URL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Cannot parse url: '%v', is BaseURL (%v) set correctly?\\n%v\\n\"",
",",
"\\n",
",",
"\\n",
",",
"URL",
")",
"\n",
"}",
"\n",
"client",
".",
"BaseURL",
"\n",
"err",
"\n",
"}"
] |
// utility function to create a URL object based on given data
|
[
"utility",
"function",
"to",
"create",
"a",
"URL",
"object",
"based",
"on",
"given",
"data"
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L85-L102
|
test
|
taskcluster/taskcluster-client-go
|
http.go
|
SignRequest
|
func (c *Credentials) SignRequest(req *http.Request) (err error) {
// s, err := c.SignHeader(req.Method, req.URL.String(), hash)
// req.Header.Set("Authorization", s)
// return err
credentials := &hawk.Credentials{
ID: c.ClientID,
Key: c.AccessToken,
Hash: sha256.New,
}
reqAuth := hawk.NewRequestAuth(req, credentials, 0)
reqAuth.Ext, err = getExtHeader(c)
if err != nil {
return fmt.Errorf("Internal error: was not able to generate hawk ext header from provided credentials:\n%s\n%s", c, err)
}
req.Header.Set("Authorization", reqAuth.RequestHeader())
return nil
}
|
go
|
func (c *Credentials) SignRequest(req *http.Request) (err error) {
// s, err := c.SignHeader(req.Method, req.URL.String(), hash)
// req.Header.Set("Authorization", s)
// return err
credentials := &hawk.Credentials{
ID: c.ClientID,
Key: c.AccessToken,
Hash: sha256.New,
}
reqAuth := hawk.NewRequestAuth(req, credentials, 0)
reqAuth.Ext, err = getExtHeader(c)
if err != nil {
return fmt.Errorf("Internal error: was not able to generate hawk ext header from provided credentials:\n%s\n%s", c, err)
}
req.Header.Set("Authorization", reqAuth.RequestHeader())
return nil
}
|
[
"func",
"(",
"c",
"*",
"Credentials",
")",
"SignRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"err",
"error",
")",
"{",
"credentials",
":=",
"&",
"hawk",
".",
"Credentials",
"{",
"ID",
":",
"c",
".",
"ClientID",
",",
"Key",
":",
"c",
".",
"AccessToken",
",",
"Hash",
":",
"sha256",
".",
"New",
",",
"}",
"\n",
"reqAuth",
":=",
"hawk",
".",
"NewRequestAuth",
"(",
"req",
",",
"credentials",
",",
"0",
")",
"\n",
"reqAuth",
".",
"Ext",
",",
"err",
"=",
"getExtHeader",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Internal error: was not able to generate hawk ext header from provided credentials:\\n%s\\n%s\"",
",",
"\\n",
",",
"\\n",
")",
"\n",
"}",
"\n",
"c",
"\n",
"err",
"\n",
"}"
] |
// SignRequest will add an Authorization header
|
[
"SignRequest",
"will",
"add",
"an",
"Authorization",
"header"
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L175-L192
|
test
|
taskcluster/taskcluster-client-go
|
http.go
|
APICall
|
func (client *Client) APICall(payload interface{}, method, route string, result interface{}, query url.Values) (interface{}, *CallSummary, error) {
rawPayload := []byte{}
var err error
if reflect.ValueOf(payload).IsValid() && !reflect.ValueOf(payload).IsNil() {
rawPayload, err = json.Marshal(payload)
if err != nil {
cs := &CallSummary{
HTTPRequestObject: payload,
}
return result,
cs,
&APICallException{
CallSummary: cs,
RootCause: err,
}
}
}
callSummary, err := client.Request(rawPayload, method, route, query)
callSummary.HTTPRequestObject = payload
if err != nil {
// If context failed during this request, then we should just return that error
if client.Context != nil && client.Context.Err() != nil {
return result, callSummary, client.Context.Err()
}
return result,
callSummary,
&APICallException{
CallSummary: callSummary,
RootCause: err,
}
}
// if result is passed in as nil, it means the API defines no response body
// json
if reflect.ValueOf(result).IsValid() && !reflect.ValueOf(result).IsNil() {
err = json.Unmarshal([]byte(callSummary.HTTPResponseBody), &result)
}
if err != nil {
return result,
callSummary,
&APICallException{
CallSummary: callSummary,
RootCause: err,
}
}
return result, callSummary, nil
}
|
go
|
func (client *Client) APICall(payload interface{}, method, route string, result interface{}, query url.Values) (interface{}, *CallSummary, error) {
rawPayload := []byte{}
var err error
if reflect.ValueOf(payload).IsValid() && !reflect.ValueOf(payload).IsNil() {
rawPayload, err = json.Marshal(payload)
if err != nil {
cs := &CallSummary{
HTTPRequestObject: payload,
}
return result,
cs,
&APICallException{
CallSummary: cs,
RootCause: err,
}
}
}
callSummary, err := client.Request(rawPayload, method, route, query)
callSummary.HTTPRequestObject = payload
if err != nil {
// If context failed during this request, then we should just return that error
if client.Context != nil && client.Context.Err() != nil {
return result, callSummary, client.Context.Err()
}
return result,
callSummary,
&APICallException{
CallSummary: callSummary,
RootCause: err,
}
}
// if result is passed in as nil, it means the API defines no response body
// json
if reflect.ValueOf(result).IsValid() && !reflect.ValueOf(result).IsNil() {
err = json.Unmarshal([]byte(callSummary.HTTPResponseBody), &result)
}
if err != nil {
return result,
callSummary,
&APICallException{
CallSummary: callSummary,
RootCause: err,
}
}
return result, callSummary, nil
}
|
[
"func",
"(",
"client",
"*",
"Client",
")",
"APICall",
"(",
"payload",
"interface",
"{",
"}",
",",
"method",
",",
"route",
"string",
",",
"result",
"interface",
"{",
"}",
",",
"query",
"url",
".",
"Values",
")",
"(",
"interface",
"{",
"}",
",",
"*",
"CallSummary",
",",
"error",
")",
"{",
"rawPayload",
":=",
"[",
"]",
"byte",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"reflect",
".",
"ValueOf",
"(",
"payload",
")",
".",
"IsValid",
"(",
")",
"&&",
"!",
"reflect",
".",
"ValueOf",
"(",
"payload",
")",
".",
"IsNil",
"(",
")",
"{",
"rawPayload",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"payload",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"cs",
":=",
"&",
"CallSummary",
"{",
"HTTPRequestObject",
":",
"payload",
",",
"}",
"\n",
"return",
"result",
",",
"cs",
",",
"&",
"APICallException",
"{",
"CallSummary",
":",
"cs",
",",
"RootCause",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"callSummary",
",",
"err",
":=",
"client",
".",
"Request",
"(",
"rawPayload",
",",
"method",
",",
"route",
",",
"query",
")",
"\n",
"callSummary",
".",
"HTTPRequestObject",
"=",
"payload",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"client",
".",
"Context",
"!=",
"nil",
"&&",
"client",
".",
"Context",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"result",
",",
"callSummary",
",",
"client",
".",
"Context",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"callSummary",
",",
"&",
"APICallException",
"{",
"CallSummary",
":",
"callSummary",
",",
"RootCause",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"if",
"reflect",
".",
"ValueOf",
"(",
"result",
")",
".",
"IsValid",
"(",
")",
"&&",
"!",
"reflect",
".",
"ValueOf",
"(",
"result",
")",
".",
"IsNil",
"(",
")",
"{",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"callSummary",
".",
"HTTPResponseBody",
")",
",",
"&",
"result",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"callSummary",
",",
"&",
"APICallException",
"{",
"CallSummary",
":",
"callSummary",
",",
"RootCause",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"callSummary",
",",
"nil",
"\n",
"}"
] |
// APICall is the generic REST API calling method which performs all REST API
// calls for this library. Each auto-generated REST API method simply is a
// wrapper around this method, calling it with specific specific arguments.
|
[
"APICall",
"is",
"the",
"generic",
"REST",
"API",
"calling",
"method",
"which",
"performs",
"all",
"REST",
"API",
"calls",
"for",
"this",
"library",
".",
"Each",
"auto",
"-",
"generated",
"REST",
"API",
"method",
"simply",
"is",
"a",
"wrapper",
"around",
"this",
"method",
"calling",
"it",
"with",
"specific",
"specific",
"arguments",
"."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L206-L252
|
test
|
taskcluster/taskcluster-client-go
|
http.go
|
SignedURL
|
func (client *Client) SignedURL(route string, query url.Values, duration time.Duration) (u *url.URL, err error) {
u, err = setURL(client, route, query)
if err != nil {
return
}
credentials := &hawk.Credentials{
ID: client.Credentials.ClientID,
Key: client.Credentials.AccessToken,
Hash: sha256.New,
}
reqAuth, err := hawk.NewURLAuth(u.String(), credentials, duration)
if err != nil {
return
}
reqAuth.Ext, err = getExtHeader(client.Credentials)
if err != nil {
return
}
bewitSignature := reqAuth.Bewit()
if query == nil {
query = url.Values{}
}
query.Set("bewit", bewitSignature)
u.RawQuery = query.Encode()
return
}
|
go
|
func (client *Client) SignedURL(route string, query url.Values, duration time.Duration) (u *url.URL, err error) {
u, err = setURL(client, route, query)
if err != nil {
return
}
credentials := &hawk.Credentials{
ID: client.Credentials.ClientID,
Key: client.Credentials.AccessToken,
Hash: sha256.New,
}
reqAuth, err := hawk.NewURLAuth(u.String(), credentials, duration)
if err != nil {
return
}
reqAuth.Ext, err = getExtHeader(client.Credentials)
if err != nil {
return
}
bewitSignature := reqAuth.Bewit()
if query == nil {
query = url.Values{}
}
query.Set("bewit", bewitSignature)
u.RawQuery = query.Encode()
return
}
|
[
"func",
"(",
"client",
"*",
"Client",
")",
"SignedURL",
"(",
"route",
"string",
",",
"query",
"url",
".",
"Values",
",",
"duration",
"time",
".",
"Duration",
")",
"(",
"u",
"*",
"url",
".",
"URL",
",",
"err",
"error",
")",
"{",
"u",
",",
"err",
"=",
"setURL",
"(",
"client",
",",
"route",
",",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"credentials",
":=",
"&",
"hawk",
".",
"Credentials",
"{",
"ID",
":",
"client",
".",
"Credentials",
".",
"ClientID",
",",
"Key",
":",
"client",
".",
"Credentials",
".",
"AccessToken",
",",
"Hash",
":",
"sha256",
".",
"New",
",",
"}",
"\n",
"reqAuth",
",",
"err",
":=",
"hawk",
".",
"NewURLAuth",
"(",
"u",
".",
"String",
"(",
")",
",",
"credentials",
",",
"duration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"reqAuth",
".",
"Ext",
",",
"err",
"=",
"getExtHeader",
"(",
"client",
".",
"Credentials",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"bewitSignature",
":=",
"reqAuth",
".",
"Bewit",
"(",
")",
"\n",
"if",
"query",
"==",
"nil",
"{",
"query",
"=",
"url",
".",
"Values",
"{",
"}",
"\n",
"}",
"\n",
"query",
".",
"Set",
"(",
"\"bewit\"",
",",
"bewitSignature",
")",
"\n",
"u",
".",
"RawQuery",
"=",
"query",
".",
"Encode",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// SignedURL creates a signed URL using the given Client, where route is the
// url path relative to the BaseURL stored in the Client, query is the set of
// query string parameters, if any, and duration is the amount of time that the
// signed URL should remain valid for.
|
[
"SignedURL",
"creates",
"a",
"signed",
"URL",
"using",
"the",
"given",
"Client",
"where",
"route",
"is",
"the",
"url",
"path",
"relative",
"to",
"the",
"BaseURL",
"stored",
"in",
"the",
"Client",
"query",
"is",
"the",
"set",
"of",
"query",
"string",
"parameters",
"if",
"any",
"and",
"duration",
"is",
"the",
"amount",
"of",
"time",
"that",
"the",
"signed",
"URL",
"should",
"remain",
"valid",
"for",
"."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L258-L283
|
test
|
taskcluster/taskcluster-client-go
|
tcauth/types.go
|
MarshalJSON
|
func (this *HawkSignatureAuthenticationResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
go
|
func (this *HawkSignatureAuthenticationResponse) MarshalJSON() ([]byte, error) {
x := json.RawMessage(*this)
return (&x).MarshalJSON()
}
|
[
"func",
"(",
"this",
"*",
"HawkSignatureAuthenticationResponse",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
":=",
"json",
".",
"RawMessage",
"(",
"*",
"this",
")",
"\n",
"return",
"(",
"&",
"x",
")",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON calls json.RawMessage method of the same name. Required since
// HawkSignatureAuthenticationResponse is of type json.RawMessage...
|
[
"MarshalJSON",
"calls",
"json",
".",
"RawMessage",
"method",
"of",
"the",
"same",
"name",
".",
"Required",
"since",
"HawkSignatureAuthenticationResponse",
"is",
"of",
"type",
"json",
".",
"RawMessage",
"..."
] |
ef6acd428ae5844a933792ed6479d0e7dca61ef8
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/types.go#L912-L915
|
test
|
bitgoin/lyra2rev2
|
bmw.go
|
bmw256
|
func bmw256(input []byte) []byte {
b := new()
buf := make([]byte, 64)
copy(buf, input)
buf[len(input)] = 0x80
bitLen := uint64(len(input)) << 3
binary.LittleEndian.PutUint64(buf[56:], bitLen)
for i := 0; i < 16; i++ {
b.m[i] = binary.LittleEndian.Uint32(buf[i*4:])
}
b.compress(b.m)
b.h, b.h2 = b.h2, b.h
copy(b.h, final)
b.compress(b.h2)
output := make([]byte, 32)
outlen := len(output) >> 2
for i := 0; i < outlen; i++ {
j := 16 - outlen + i
binary.LittleEndian.PutUint32(output[4*i:], b.h[j])
}
return output
}
|
go
|
func bmw256(input []byte) []byte {
b := new()
buf := make([]byte, 64)
copy(buf, input)
buf[len(input)] = 0x80
bitLen := uint64(len(input)) << 3
binary.LittleEndian.PutUint64(buf[56:], bitLen)
for i := 0; i < 16; i++ {
b.m[i] = binary.LittleEndian.Uint32(buf[i*4:])
}
b.compress(b.m)
b.h, b.h2 = b.h2, b.h
copy(b.h, final)
b.compress(b.h2)
output := make([]byte, 32)
outlen := len(output) >> 2
for i := 0; i < outlen; i++ {
j := 16 - outlen + i
binary.LittleEndian.PutUint32(output[4*i:], b.h[j])
}
return output
}
|
[
"func",
"bmw256",
"(",
"input",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"b",
":=",
"new",
"(",
"type_identifier",
")",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"64",
")",
"\n",
"copy",
"(",
"buf",
",",
"input",
")",
"\n",
"buf",
"[",
"len",
"(",
"input",
")",
"]",
"=",
"0x80",
"\n",
"bitLen",
":=",
"uint64",
"(",
"len",
"(",
"input",
")",
")",
"<<",
"3",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint64",
"(",
"buf",
"[",
"56",
":",
"]",
",",
"bitLen",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"16",
";",
"i",
"++",
"{",
"b",
".",
"m",
"[",
"i",
"]",
"=",
"binary",
".",
"LittleEndian",
".",
"Uint32",
"(",
"buf",
"[",
"i",
"*",
"4",
":",
"]",
")",
"\n",
"}",
"\n",
"b",
".",
"compress",
"(",
"b",
".",
"m",
")",
"\n",
"b",
".",
"h",
",",
"b",
".",
"h2",
"=",
"b",
".",
"h2",
",",
"b",
".",
"h",
"\n",
"copy",
"(",
"b",
".",
"h",
",",
"final",
")",
"\n",
"b",
".",
"compress",
"(",
"b",
".",
"h2",
")",
"\n",
"output",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"outlen",
":=",
"len",
"(",
"output",
")",
">>",
"2",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"outlen",
";",
"i",
"++",
"{",
"j",
":=",
"16",
"-",
"outlen",
"+",
"i",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"output",
"[",
"4",
"*",
"i",
":",
"]",
",",
"b",
".",
"h",
"[",
"j",
"]",
")",
"\n",
"}",
"\n",
"return",
"output",
"\n",
"}"
] |
//bmw256 calculates and returns bmw256 of input.
//length of input must be 32 bytes.
|
[
"bmw256",
"calculates",
"and",
"returns",
"bmw256",
"of",
"input",
".",
"length",
"of",
"input",
"must",
"be",
"32",
"bytes",
"."
] |
bae9ad2043bb55facb14c4918e909f88a7d3ed84
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/bmw.go#L131-L152
|
test
|
bitgoin/lyra2rev2
|
cubehash.go
|
NewCubeHash
|
func NewCubeHash() *CubeHash {
c := &CubeHash{}
c.x0 = iv[0]
c.x1 = iv[1]
c.x2 = iv[2]
c.x3 = iv[3]
c.x4 = iv[4]
c.x5 = iv[5]
c.x6 = iv[6]
c.x7 = iv[7]
c.x8 = iv[8]
c.x9 = iv[9]
c.xa = iv[10]
c.xb = iv[11]
c.xc = iv[12]
c.xd = iv[13]
c.xe = iv[14]
c.xf = iv[15]
c.xg = iv[16]
c.xh = iv[17]
c.xi = iv[18]
c.xj = iv[19]
c.xk = iv[20]
c.xl = iv[21]
c.xm = iv[22]
c.xn = iv[23]
c.xo = iv[24]
c.xp = iv[25]
c.xq = iv[26]
c.xr = iv[27]
c.xs = iv[28]
c.xt = iv[29]
c.xu = iv[30]
c.xv = iv[31]
return c
}
|
go
|
func NewCubeHash() *CubeHash {
c := &CubeHash{}
c.x0 = iv[0]
c.x1 = iv[1]
c.x2 = iv[2]
c.x3 = iv[3]
c.x4 = iv[4]
c.x5 = iv[5]
c.x6 = iv[6]
c.x7 = iv[7]
c.x8 = iv[8]
c.x9 = iv[9]
c.xa = iv[10]
c.xb = iv[11]
c.xc = iv[12]
c.xd = iv[13]
c.xe = iv[14]
c.xf = iv[15]
c.xg = iv[16]
c.xh = iv[17]
c.xi = iv[18]
c.xj = iv[19]
c.xk = iv[20]
c.xl = iv[21]
c.xm = iv[22]
c.xn = iv[23]
c.xo = iv[24]
c.xp = iv[25]
c.xq = iv[26]
c.xr = iv[27]
c.xs = iv[28]
c.xt = iv[29]
c.xu = iv[30]
c.xv = iv[31]
return c
}
|
[
"func",
"NewCubeHash",
"(",
")",
"*",
"CubeHash",
"{",
"c",
":=",
"&",
"CubeHash",
"{",
"}",
"\n",
"c",
".",
"x0",
"=",
"iv",
"[",
"0",
"]",
"\n",
"c",
".",
"x1",
"=",
"iv",
"[",
"1",
"]",
"\n",
"c",
".",
"x2",
"=",
"iv",
"[",
"2",
"]",
"\n",
"c",
".",
"x3",
"=",
"iv",
"[",
"3",
"]",
"\n",
"c",
".",
"x4",
"=",
"iv",
"[",
"4",
"]",
"\n",
"c",
".",
"x5",
"=",
"iv",
"[",
"5",
"]",
"\n",
"c",
".",
"x6",
"=",
"iv",
"[",
"6",
"]",
"\n",
"c",
".",
"x7",
"=",
"iv",
"[",
"7",
"]",
"\n",
"c",
".",
"x8",
"=",
"iv",
"[",
"8",
"]",
"\n",
"c",
".",
"x9",
"=",
"iv",
"[",
"9",
"]",
"\n",
"c",
".",
"xa",
"=",
"iv",
"[",
"10",
"]",
"\n",
"c",
".",
"xb",
"=",
"iv",
"[",
"11",
"]",
"\n",
"c",
".",
"xc",
"=",
"iv",
"[",
"12",
"]",
"\n",
"c",
".",
"xd",
"=",
"iv",
"[",
"13",
"]",
"\n",
"c",
".",
"xe",
"=",
"iv",
"[",
"14",
"]",
"\n",
"c",
".",
"xf",
"=",
"iv",
"[",
"15",
"]",
"\n",
"c",
".",
"xg",
"=",
"iv",
"[",
"16",
"]",
"\n",
"c",
".",
"xh",
"=",
"iv",
"[",
"17",
"]",
"\n",
"c",
".",
"xi",
"=",
"iv",
"[",
"18",
"]",
"\n",
"c",
".",
"xj",
"=",
"iv",
"[",
"19",
"]",
"\n",
"c",
".",
"xk",
"=",
"iv",
"[",
"20",
"]",
"\n",
"c",
".",
"xl",
"=",
"iv",
"[",
"21",
"]",
"\n",
"c",
".",
"xm",
"=",
"iv",
"[",
"22",
"]",
"\n",
"c",
".",
"xn",
"=",
"iv",
"[",
"23",
"]",
"\n",
"c",
".",
"xo",
"=",
"iv",
"[",
"24",
"]",
"\n",
"c",
".",
"xp",
"=",
"iv",
"[",
"25",
"]",
"\n",
"c",
".",
"xq",
"=",
"iv",
"[",
"26",
"]",
"\n",
"c",
".",
"xr",
"=",
"iv",
"[",
"27",
"]",
"\n",
"c",
".",
"xs",
"=",
"iv",
"[",
"28",
"]",
"\n",
"c",
".",
"xt",
"=",
"iv",
"[",
"29",
"]",
"\n",
"c",
".",
"xu",
"=",
"iv",
"[",
"30",
"]",
"\n",
"c",
".",
"xv",
"=",
"iv",
"[",
"31",
"]",
"\n",
"return",
"c",
"\n",
"}"
] |
//NewCubeHash initializes anrd retuns Cubuhash struct.
|
[
"NewCubeHash",
"initializes",
"anrd",
"retuns",
"Cubuhash",
"struct",
"."
] |
bae9ad2043bb55facb14c4918e909f88a7d3ed84
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/cubehash.go#L88-L124
|
test
|
bitgoin/lyra2rev2
|
cubehash.go
|
cubehash256
|
func cubehash256(data []byte) []byte {
c := NewCubeHash()
buf := make([]byte, 32)
buf[0] = 0x80
c.inputBlock(data)
c.sixteenRounds()
c.inputBlock(buf)
c.sixteenRounds()
c.xv ^= 1
for j := 0; j < 10; j++ {
c.sixteenRounds()
}
out := make([]byte, 32)
binary.LittleEndian.PutUint32(out[0:], c.x0)
binary.LittleEndian.PutUint32(out[4:], c.x1)
binary.LittleEndian.PutUint32(out[8:], c.x2)
binary.LittleEndian.PutUint32(out[12:], c.x3)
binary.LittleEndian.PutUint32(out[16:], c.x4)
binary.LittleEndian.PutUint32(out[20:], c.x5)
binary.LittleEndian.PutUint32(out[24:], c.x6)
binary.LittleEndian.PutUint32(out[28:], c.x7)
return out
}
|
go
|
func cubehash256(data []byte) []byte {
c := NewCubeHash()
buf := make([]byte, 32)
buf[0] = 0x80
c.inputBlock(data)
c.sixteenRounds()
c.inputBlock(buf)
c.sixteenRounds()
c.xv ^= 1
for j := 0; j < 10; j++ {
c.sixteenRounds()
}
out := make([]byte, 32)
binary.LittleEndian.PutUint32(out[0:], c.x0)
binary.LittleEndian.PutUint32(out[4:], c.x1)
binary.LittleEndian.PutUint32(out[8:], c.x2)
binary.LittleEndian.PutUint32(out[12:], c.x3)
binary.LittleEndian.PutUint32(out[16:], c.x4)
binary.LittleEndian.PutUint32(out[20:], c.x5)
binary.LittleEndian.PutUint32(out[24:], c.x6)
binary.LittleEndian.PutUint32(out[28:], c.x7)
return out
}
|
[
"func",
"cubehash256",
"(",
"data",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"c",
":=",
"NewCubeHash",
"(",
")",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"buf",
"[",
"0",
"]",
"=",
"0x80",
"\n",
"c",
".",
"inputBlock",
"(",
"data",
")",
"\n",
"c",
".",
"sixteenRounds",
"(",
")",
"\n",
"c",
".",
"inputBlock",
"(",
"buf",
")",
"\n",
"c",
".",
"sixteenRounds",
"(",
")",
"\n",
"c",
".",
"xv",
"^=",
"1",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"10",
";",
"j",
"++",
"{",
"c",
".",
"sixteenRounds",
"(",
")",
"\n",
"}",
"\n",
"out",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"0",
":",
"]",
",",
"c",
".",
"x0",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"4",
":",
"]",
",",
"c",
".",
"x1",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"8",
":",
"]",
",",
"c",
".",
"x2",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"12",
":",
"]",
",",
"c",
".",
"x3",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"16",
":",
"]",
",",
"c",
".",
"x4",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"20",
":",
"]",
",",
"c",
".",
"x5",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"24",
":",
"]",
",",
"c",
".",
"x6",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"out",
"[",
"28",
":",
"]",
",",
"c",
".",
"x7",
")",
"\n",
"return",
"out",
"\n",
"}"
] |
//cubehash56 calculates cubuhash256.
//length of data must be 32 bytes.
|
[
"cubehash56",
"calculates",
"cubuhash256",
".",
"length",
"of",
"data",
"must",
"be",
"32",
"bytes",
"."
] |
bae9ad2043bb55facb14c4918e909f88a7d3ed84
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/cubehash.go#L337-L359
|
test
|
bitgoin/lyra2rev2
|
lyra2re2.go
|
Sum
|
func Sum(data []byte) ([]byte, error) {
blake := blake256.New()
if _, err := blake.Write(data); err != nil {
return nil, err
}
resultBlake := blake.Sum(nil)
keccak := sha3.NewKeccak256()
if _, err := keccak.Write(resultBlake); err != nil {
return nil, err
}
resultkeccak := keccak.Sum(nil)
resultcube := cubehash256(resultkeccak)
lyra2result := make([]byte, 32)
lyra2(lyra2result, resultcube, resultcube, 1, 4, 4)
var skeinresult [32]byte
skein.Sum256(&skeinresult, lyra2result, nil)
resultcube2 := cubehash256(skeinresult[:])
resultbmw := bmw256(resultcube2)
return resultbmw, nil
}
|
go
|
func Sum(data []byte) ([]byte, error) {
blake := blake256.New()
if _, err := blake.Write(data); err != nil {
return nil, err
}
resultBlake := blake.Sum(nil)
keccak := sha3.NewKeccak256()
if _, err := keccak.Write(resultBlake); err != nil {
return nil, err
}
resultkeccak := keccak.Sum(nil)
resultcube := cubehash256(resultkeccak)
lyra2result := make([]byte, 32)
lyra2(lyra2result, resultcube, resultcube, 1, 4, 4)
var skeinresult [32]byte
skein.Sum256(&skeinresult, lyra2result, nil)
resultcube2 := cubehash256(skeinresult[:])
resultbmw := bmw256(resultcube2)
return resultbmw, nil
}
|
[
"func",
"Sum",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"blake",
":=",
"blake256",
".",
"New",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"blake",
".",
"Write",
"(",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"resultBlake",
":=",
"blake",
".",
"Sum",
"(",
"nil",
")",
"\n",
"keccak",
":=",
"sha3",
".",
"NewKeccak256",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"keccak",
".",
"Write",
"(",
"resultBlake",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"resultkeccak",
":=",
"keccak",
".",
"Sum",
"(",
"nil",
")",
"\n",
"resultcube",
":=",
"cubehash256",
"(",
"resultkeccak",
")",
"\n",
"lyra2result",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"lyra2",
"(",
"lyra2result",
",",
"resultcube",
",",
"resultcube",
",",
"1",
",",
"4",
",",
"4",
")",
"\n",
"var",
"skeinresult",
"[",
"32",
"]",
"byte",
"\n",
"skein",
".",
"Sum256",
"(",
"&",
"skeinresult",
",",
"lyra2result",
",",
"nil",
")",
"\n",
"resultcube2",
":=",
"cubehash256",
"(",
"skeinresult",
"[",
":",
"]",
")",
"\n",
"resultbmw",
":=",
"bmw256",
"(",
"resultcube2",
")",
"\n",
"return",
"resultbmw",
",",
"nil",
"\n",
"}"
] |
//Sum returns the result of Lyra2re2 hash.
|
[
"Sum",
"returns",
"the",
"result",
"of",
"Lyra2re2",
"hash",
"."
] |
bae9ad2043bb55facb14c4918e909f88a7d3ed84
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2re2.go#L38-L59
|
test
|
bitgoin/lyra2rev2
|
lyra2.go
|
squeeze
|
func squeeze(state []uint64, out []byte) {
tmp := make([]byte, blockLenBytes)
for j := 0; j < len(out)/blockLenBytes+1; j++ {
for i := 0; i < blockLenInt64; i++ {
binary.LittleEndian.PutUint64(tmp[i*8:], state[i])
}
copy(out[j*blockLenBytes:], tmp) //be care in case of len(out[i:])<len(tmp)
blake2bLyra(state)
}
}
|
go
|
func squeeze(state []uint64, out []byte) {
tmp := make([]byte, blockLenBytes)
for j := 0; j < len(out)/blockLenBytes+1; j++ {
for i := 0; i < blockLenInt64; i++ {
binary.LittleEndian.PutUint64(tmp[i*8:], state[i])
}
copy(out[j*blockLenBytes:], tmp) //be care in case of len(out[i:])<len(tmp)
blake2bLyra(state)
}
}
|
[
"func",
"squeeze",
"(",
"state",
"[",
"]",
"uint64",
",",
"out",
"[",
"]",
"byte",
")",
"{",
"tmp",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"blockLenBytes",
")",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"len",
"(",
"out",
")",
"/",
"blockLenBytes",
"+",
"1",
";",
"j",
"++",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"blockLenInt64",
";",
"i",
"++",
"{",
"binary",
".",
"LittleEndian",
".",
"PutUint64",
"(",
"tmp",
"[",
"i",
"*",
"8",
":",
"]",
",",
"state",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"copy",
"(",
"out",
"[",
"j",
"*",
"blockLenBytes",
":",
"]",
",",
"tmp",
")",
"\n",
"blake2bLyra",
"(",
"state",
")",
"\n",
"}",
"\n",
"}"
] |
/**
* squeeze Performs a squeeze operation, using Blake2b's G function as the
* internal permutation
*
* @param state The current state of the sponge
* @param out Array that will receive the data squeezed
* @param len The number of bytes to be squeezed into the "out" array
*/
|
[
"squeeze",
"Performs",
"a",
"squeeze",
"operation",
"using",
"Blake2b",
"s",
"G",
"function",
"as",
"the",
"internal",
"permutation"
] |
bae9ad2043bb55facb14c4918e909f88a7d3ed84
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L135-L144
|
test
|
bitgoin/lyra2rev2
|
lyra2.go
|
reducedSqueezeRow0
|
func reducedSqueezeRow0(state []uint64, rowOut []uint64, nCols int) {
ptr := (nCols - 1) * blockLenInt64
//M[row][C-1-col] = H.reduced_squeeze()
for i := 0; i < nCols; i++ {
ptrWord := rowOut[ptr:] //In Lyra2: pointer to M[0][C-1]
ptrWord[0] = state[0]
ptrWord[1] = state[1]
ptrWord[2] = state[2]
ptrWord[3] = state[3]
ptrWord[4] = state[4]
ptrWord[5] = state[5]
ptrWord[6] = state[6]
ptrWord[7] = state[7]
ptrWord[8] = state[8]
ptrWord[9] = state[9]
ptrWord[10] = state[10]
ptrWord[11] = state[11]
//Goes to next block (column) that will receive the squeezed data
ptr -= blockLenInt64
//Applies the reduced-round transformation f to the sponge's state
reducedBlake2bLyra(state)
}
}
|
go
|
func reducedSqueezeRow0(state []uint64, rowOut []uint64, nCols int) {
ptr := (nCols - 1) * blockLenInt64
//M[row][C-1-col] = H.reduced_squeeze()
for i := 0; i < nCols; i++ {
ptrWord := rowOut[ptr:] //In Lyra2: pointer to M[0][C-1]
ptrWord[0] = state[0]
ptrWord[1] = state[1]
ptrWord[2] = state[2]
ptrWord[3] = state[3]
ptrWord[4] = state[4]
ptrWord[5] = state[5]
ptrWord[6] = state[6]
ptrWord[7] = state[7]
ptrWord[8] = state[8]
ptrWord[9] = state[9]
ptrWord[10] = state[10]
ptrWord[11] = state[11]
//Goes to next block (column) that will receive the squeezed data
ptr -= blockLenInt64
//Applies the reduced-round transformation f to the sponge's state
reducedBlake2bLyra(state)
}
}
|
[
"func",
"reducedSqueezeRow0",
"(",
"state",
"[",
"]",
"uint64",
",",
"rowOut",
"[",
"]",
"uint64",
",",
"nCols",
"int",
")",
"{",
"ptr",
":=",
"(",
"nCols",
"-",
"1",
")",
"*",
"blockLenInt64",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"nCols",
";",
"i",
"++",
"{",
"ptrWord",
":=",
"rowOut",
"[",
"ptr",
":",
"]",
"\n",
"ptrWord",
"[",
"0",
"]",
"=",
"state",
"[",
"0",
"]",
"\n",
"ptrWord",
"[",
"1",
"]",
"=",
"state",
"[",
"1",
"]",
"\n",
"ptrWord",
"[",
"2",
"]",
"=",
"state",
"[",
"2",
"]",
"\n",
"ptrWord",
"[",
"3",
"]",
"=",
"state",
"[",
"3",
"]",
"\n",
"ptrWord",
"[",
"4",
"]",
"=",
"state",
"[",
"4",
"]",
"\n",
"ptrWord",
"[",
"5",
"]",
"=",
"state",
"[",
"5",
"]",
"\n",
"ptrWord",
"[",
"6",
"]",
"=",
"state",
"[",
"6",
"]",
"\n",
"ptrWord",
"[",
"7",
"]",
"=",
"state",
"[",
"7",
"]",
"\n",
"ptrWord",
"[",
"8",
"]",
"=",
"state",
"[",
"8",
"]",
"\n",
"ptrWord",
"[",
"9",
"]",
"=",
"state",
"[",
"9",
"]",
"\n",
"ptrWord",
"[",
"10",
"]",
"=",
"state",
"[",
"10",
"]",
"\n",
"ptrWord",
"[",
"11",
"]",
"=",
"state",
"[",
"11",
"]",
"\n",
"ptr",
"-=",
"blockLenInt64",
"\n",
"reducedBlake2bLyra",
"(",
"state",
")",
"\n",
"}",
"\n",
"}"
] |
/**
* reducedSqueezeRow0 erforms a reduced squeeze operation for a single row, from the highest to
* the lowest index, using the reduced-round Blake2b's G function as the
* internal permutation
*
* @param state The current state of the sponge
* @param rowOut Row to receive the data squeezed
*/
|
[
"reducedSqueezeRow0",
"erforms",
"a",
"reduced",
"squeeze",
"operation",
"for",
"a",
"single",
"row",
"from",
"the",
"highest",
"to",
"the",
"lowest",
"index",
"using",
"the",
"reduced",
"-",
"round",
"Blake2b",
"s",
"G",
"function",
"as",
"the",
"internal",
"permutation"
] |
bae9ad2043bb55facb14c4918e909f88a7d3ed84
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L204-L228
|
test
|
bitgoin/lyra2rev2
|
lyra2.go
|
reducedDuplexRow1
|
func reducedDuplexRow1(state []uint64, rowIn []uint64, rowOut []uint64, nCols int) {
ptrIn := 0
ptrOut := (nCols - 1) * blockLenInt64
for i := 0; i < nCols; i++ {
ptrWordIn := rowIn[ptrIn:] //In Lyra2: pointer to prev
ptrWordOut := rowOut[ptrOut:] //In Lyra2: pointer to row
//Absorbing "M[prev][col]"
state[0] ^= (ptrWordIn[0])
state[1] ^= (ptrWordIn[1])
state[2] ^= (ptrWordIn[2])
state[3] ^= (ptrWordIn[3])
state[4] ^= (ptrWordIn[4])
state[5] ^= (ptrWordIn[5])
state[6] ^= (ptrWordIn[6])
state[7] ^= (ptrWordIn[7])
state[8] ^= (ptrWordIn[8])
state[9] ^= (ptrWordIn[9])
state[10] ^= (ptrWordIn[10])
state[11] ^= (ptrWordIn[11])
//Applies the reduced-round transformation f to the sponge's state
reducedBlake2bLyra(state)
//M[row][C-1-col] = M[prev][col] XOR rand
ptrWordOut[0] = ptrWordIn[0] ^ state[0]
ptrWordOut[1] = ptrWordIn[1] ^ state[1]
ptrWordOut[2] = ptrWordIn[2] ^ state[2]
ptrWordOut[3] = ptrWordIn[3] ^ state[3]
ptrWordOut[4] = ptrWordIn[4] ^ state[4]
ptrWordOut[5] = ptrWordIn[5] ^ state[5]
ptrWordOut[6] = ptrWordIn[6] ^ state[6]
ptrWordOut[7] = ptrWordIn[7] ^ state[7]
ptrWordOut[8] = ptrWordIn[8] ^ state[8]
ptrWordOut[9] = ptrWordIn[9] ^ state[9]
ptrWordOut[10] = ptrWordIn[10] ^ state[10]
ptrWordOut[11] = ptrWordIn[11] ^ state[11]
//Input: next column (i.e., next block in sequence)
ptrIn += blockLenInt64
//Output: goes to previous column
ptrOut -= blockLenInt64
}
}
|
go
|
func reducedDuplexRow1(state []uint64, rowIn []uint64, rowOut []uint64, nCols int) {
ptrIn := 0
ptrOut := (nCols - 1) * blockLenInt64
for i := 0; i < nCols; i++ {
ptrWordIn := rowIn[ptrIn:] //In Lyra2: pointer to prev
ptrWordOut := rowOut[ptrOut:] //In Lyra2: pointer to row
//Absorbing "M[prev][col]"
state[0] ^= (ptrWordIn[0])
state[1] ^= (ptrWordIn[1])
state[2] ^= (ptrWordIn[2])
state[3] ^= (ptrWordIn[3])
state[4] ^= (ptrWordIn[4])
state[5] ^= (ptrWordIn[5])
state[6] ^= (ptrWordIn[6])
state[7] ^= (ptrWordIn[7])
state[8] ^= (ptrWordIn[8])
state[9] ^= (ptrWordIn[9])
state[10] ^= (ptrWordIn[10])
state[11] ^= (ptrWordIn[11])
//Applies the reduced-round transformation f to the sponge's state
reducedBlake2bLyra(state)
//M[row][C-1-col] = M[prev][col] XOR rand
ptrWordOut[0] = ptrWordIn[0] ^ state[0]
ptrWordOut[1] = ptrWordIn[1] ^ state[1]
ptrWordOut[2] = ptrWordIn[2] ^ state[2]
ptrWordOut[3] = ptrWordIn[3] ^ state[3]
ptrWordOut[4] = ptrWordIn[4] ^ state[4]
ptrWordOut[5] = ptrWordIn[5] ^ state[5]
ptrWordOut[6] = ptrWordIn[6] ^ state[6]
ptrWordOut[7] = ptrWordIn[7] ^ state[7]
ptrWordOut[8] = ptrWordIn[8] ^ state[8]
ptrWordOut[9] = ptrWordIn[9] ^ state[9]
ptrWordOut[10] = ptrWordIn[10] ^ state[10]
ptrWordOut[11] = ptrWordIn[11] ^ state[11]
//Input: next column (i.e., next block in sequence)
ptrIn += blockLenInt64
//Output: goes to previous column
ptrOut -= blockLenInt64
}
}
|
[
"func",
"reducedDuplexRow1",
"(",
"state",
"[",
"]",
"uint64",
",",
"rowIn",
"[",
"]",
"uint64",
",",
"rowOut",
"[",
"]",
"uint64",
",",
"nCols",
"int",
")",
"{",
"ptrIn",
":=",
"0",
"\n",
"ptrOut",
":=",
"(",
"nCols",
"-",
"1",
")",
"*",
"blockLenInt64",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"nCols",
";",
"i",
"++",
"{",
"ptrWordIn",
":=",
"rowIn",
"[",
"ptrIn",
":",
"]",
"\n",
"ptrWordOut",
":=",
"rowOut",
"[",
"ptrOut",
":",
"]",
"\n",
"state",
"[",
"0",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"0",
"]",
")",
"\n",
"state",
"[",
"1",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"1",
"]",
")",
"\n",
"state",
"[",
"2",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"2",
"]",
")",
"\n",
"state",
"[",
"3",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"3",
"]",
")",
"\n",
"state",
"[",
"4",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"4",
"]",
")",
"\n",
"state",
"[",
"5",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"5",
"]",
")",
"\n",
"state",
"[",
"6",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"6",
"]",
")",
"\n",
"state",
"[",
"7",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"7",
"]",
")",
"\n",
"state",
"[",
"8",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"8",
"]",
")",
"\n",
"state",
"[",
"9",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"9",
"]",
")",
"\n",
"state",
"[",
"10",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"10",
"]",
")",
"\n",
"state",
"[",
"11",
"]",
"^=",
"(",
"ptrWordIn",
"[",
"11",
"]",
")",
"\n",
"reducedBlake2bLyra",
"(",
"state",
")",
"\n",
"ptrWordOut",
"[",
"0",
"]",
"=",
"ptrWordIn",
"[",
"0",
"]",
"^",
"state",
"[",
"0",
"]",
"\n",
"ptrWordOut",
"[",
"1",
"]",
"=",
"ptrWordIn",
"[",
"1",
"]",
"^",
"state",
"[",
"1",
"]",
"\n",
"ptrWordOut",
"[",
"2",
"]",
"=",
"ptrWordIn",
"[",
"2",
"]",
"^",
"state",
"[",
"2",
"]",
"\n",
"ptrWordOut",
"[",
"3",
"]",
"=",
"ptrWordIn",
"[",
"3",
"]",
"^",
"state",
"[",
"3",
"]",
"\n",
"ptrWordOut",
"[",
"4",
"]",
"=",
"ptrWordIn",
"[",
"4",
"]",
"^",
"state",
"[",
"4",
"]",
"\n",
"ptrWordOut",
"[",
"5",
"]",
"=",
"ptrWordIn",
"[",
"5",
"]",
"^",
"state",
"[",
"5",
"]",
"\n",
"ptrWordOut",
"[",
"6",
"]",
"=",
"ptrWordIn",
"[",
"6",
"]",
"^",
"state",
"[",
"6",
"]",
"\n",
"ptrWordOut",
"[",
"7",
"]",
"=",
"ptrWordIn",
"[",
"7",
"]",
"^",
"state",
"[",
"7",
"]",
"\n",
"ptrWordOut",
"[",
"8",
"]",
"=",
"ptrWordIn",
"[",
"8",
"]",
"^",
"state",
"[",
"8",
"]",
"\n",
"ptrWordOut",
"[",
"9",
"]",
"=",
"ptrWordIn",
"[",
"9",
"]",
"^",
"state",
"[",
"9",
"]",
"\n",
"ptrWordOut",
"[",
"10",
"]",
"=",
"ptrWordIn",
"[",
"10",
"]",
"^",
"state",
"[",
"10",
"]",
"\n",
"ptrWordOut",
"[",
"11",
"]",
"=",
"ptrWordIn",
"[",
"11",
"]",
"^",
"state",
"[",
"11",
"]",
"\n",
"ptrIn",
"+=",
"blockLenInt64",
"\n",
"ptrOut",
"-=",
"blockLenInt64",
"\n",
"}",
"\n",
"}"
] |
/**
* reducedDuplexRow1 Performs a reduced duplex operation for a single row, from the highest to
* the lowest index, using the reduced-round Blake2b's G function as the
* internal permutation
*
* @param state The current state of the sponge
* @param rowIn Row to feed the sponge
* @param rowOut Row to receive the sponge's output
*/
|
[
"reducedDuplexRow1",
"Performs",
"a",
"reduced",
"duplex",
"operation",
"for",
"a",
"single",
"row",
"from",
"the",
"highest",
"to",
"the",
"lowest",
"index",
"using",
"the",
"reduced",
"-",
"round",
"Blake2b",
"s",
"G",
"function",
"as",
"the",
"internal",
"permutation"
] |
bae9ad2043bb55facb14c4918e909f88a7d3ed84
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L239-L282
|
test
|
lestrrat-go/xslate
|
loader/reader.go
|
NewReaderByteCodeLoader
|
func NewReaderByteCodeLoader(p parser.Parser, c compiler.Compiler) *ReaderByteCodeLoader {
return &ReaderByteCodeLoader{NewFlags(), p, c}
}
|
go
|
func NewReaderByteCodeLoader(p parser.Parser, c compiler.Compiler) *ReaderByteCodeLoader {
return &ReaderByteCodeLoader{NewFlags(), p, c}
}
|
[
"func",
"NewReaderByteCodeLoader",
"(",
"p",
"parser",
".",
"Parser",
",",
"c",
"compiler",
".",
"Compiler",
")",
"*",
"ReaderByteCodeLoader",
"{",
"return",
"&",
"ReaderByteCodeLoader",
"{",
"NewFlags",
"(",
")",
",",
"p",
",",
"c",
"}",
"\n",
"}"
] |
// NewReaderByteCodeLoader creates a new object
|
[
"NewReaderByteCodeLoader",
"creates",
"a",
"new",
"object"
] |
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/reader.go#L14-L16
|
test
|
lestrrat-go/xslate
|
loader/reader.go
|
LoadReader
|
func (l *ReaderByteCodeLoader) LoadReader(name string, rdr io.Reader) (*vm.ByteCode, error) {
ast, err := l.Parser.ParseReader(name, rdr)
if err != nil {
return nil, err
}
if l.ShouldDumpAST() {
fmt.Fprintf(os.Stderr, "AST:\n%s\n", ast)
}
bc, err := l.Compiler.Compile(ast)
if err != nil {
return nil, err
}
return bc, nil
}
|
go
|
func (l *ReaderByteCodeLoader) LoadReader(name string, rdr io.Reader) (*vm.ByteCode, error) {
ast, err := l.Parser.ParseReader(name, rdr)
if err != nil {
return nil, err
}
if l.ShouldDumpAST() {
fmt.Fprintf(os.Stderr, "AST:\n%s\n", ast)
}
bc, err := l.Compiler.Compile(ast)
if err != nil {
return nil, err
}
return bc, nil
}
|
[
"func",
"(",
"l",
"*",
"ReaderByteCodeLoader",
")",
"LoadReader",
"(",
"name",
"string",
",",
"rdr",
"io",
".",
"Reader",
")",
"(",
"*",
"vm",
".",
"ByteCode",
",",
"error",
")",
"{",
"ast",
",",
"err",
":=",
"l",
".",
"Parser",
".",
"ParseReader",
"(",
"name",
",",
"rdr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"l",
".",
"ShouldDumpAST",
"(",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"AST:\\n%s\\n\"",
",",
"\\n",
")",
"\n",
"}",
"\n",
"\\n",
"\n",
"ast",
"\n",
"bc",
",",
"err",
":=",
"l",
".",
"Compiler",
".",
"Compile",
"(",
"ast",
")",
"\n",
"}"
] |
// LoadReader takes a io.Reader and compiles it into vm.ByteCode
|
[
"LoadReader",
"takes",
"a",
"io",
".",
"Reader",
"and",
"compiles",
"it",
"into",
"vm",
".",
"ByteCode"
] |
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/reader.go#L19-L35
|
test
|
fgrid/uuid
|
v3.go
|
NewV3
|
func NewV3(namespace *UUID, name []byte) *UUID {
uuid := newByHash(md5.New(), namespace, name)
uuid[6] = (uuid[6] & 0x0f) | 0x30
return uuid
}
|
go
|
func NewV3(namespace *UUID, name []byte) *UUID {
uuid := newByHash(md5.New(), namespace, name)
uuid[6] = (uuid[6] & 0x0f) | 0x30
return uuid
}
|
[
"func",
"NewV3",
"(",
"namespace",
"*",
"UUID",
",",
"name",
"[",
"]",
"byte",
")",
"*",
"UUID",
"{",
"uuid",
":=",
"newByHash",
"(",
"md5",
".",
"New",
"(",
")",
",",
"namespace",
",",
"name",
")",
"\n",
"uuid",
"[",
"6",
"]",
"=",
"(",
"uuid",
"[",
"6",
"]",
"&",
"0x0f",
")",
"|",
"0x30",
"\n",
"return",
"uuid",
"\n",
"}"
] |
// NewV3 creates a new UUID with variant 3 as described in RFC 4122.
// Variant 3 based namespace-uuid and name and MD-5 hash calculation.
|
[
"NewV3",
"creates",
"a",
"new",
"UUID",
"with",
"variant",
"3",
"as",
"described",
"in",
"RFC",
"4122",
".",
"Variant",
"3",
"based",
"namespace",
"-",
"uuid",
"and",
"name",
"and",
"MD",
"-",
"5",
"hash",
"calculation",
"."
] |
6f72a2d331c927473b9b19f590d43ccb5018c844
|
https://github.com/fgrid/uuid/blob/6f72a2d331c927473b9b19f590d43ccb5018c844/v3.go#L10-L14
|
test
|
lestrrat-go/xslate
|
vm/ops.go
|
txLiteral
|
func txLiteral(st *State) {
st.sa = st.CurrentOp().Arg()
st.Advance()
}
|
go
|
func txLiteral(st *State) {
st.sa = st.CurrentOp().Arg()
st.Advance()
}
|
[
"func",
"txLiteral",
"(",
"st",
"*",
"State",
")",
"{",
"st",
".",
"sa",
"=",
"st",
".",
"CurrentOp",
"(",
")",
".",
"Arg",
"(",
")",
"\n",
"st",
".",
"Advance",
"(",
")",
"\n",
"}"
] |
// Sets literal in op arg to register sa
|
[
"Sets",
"literal",
"in",
"op",
"arg",
"to",
"register",
"sa"
] |
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L207-L210
|
test
|
lestrrat-go/xslate
|
vm/ops.go
|
txFetchSymbol
|
func txFetchSymbol(st *State) {
// Need to handle local vars?
key := st.CurrentOp().Arg()
vars := st.Vars()
if v, ok := vars.Get(key); ok {
st.sa = v
} else {
st.sa = nil
}
st.Advance()
}
|
go
|
func txFetchSymbol(st *State) {
// Need to handle local vars?
key := st.CurrentOp().Arg()
vars := st.Vars()
if v, ok := vars.Get(key); ok {
st.sa = v
} else {
st.sa = nil
}
st.Advance()
}
|
[
"func",
"txFetchSymbol",
"(",
"st",
"*",
"State",
")",
"{",
"key",
":=",
"st",
".",
"CurrentOp",
"(",
")",
".",
"Arg",
"(",
")",
"\n",
"vars",
":=",
"st",
".",
"Vars",
"(",
")",
"\n",
"if",
"v",
",",
"ok",
":=",
"vars",
".",
"Get",
"(",
"key",
")",
";",
"ok",
"{",
"st",
".",
"sa",
"=",
"v",
"\n",
"}",
"else",
"{",
"st",
".",
"sa",
"=",
"nil",
"\n",
"}",
"\n",
"st",
".",
"Advance",
"(",
")",
"\n",
"}"
] |
// Fetches a symbol specified in op arg from template variables.
// XXX need to handle local vars?
|
[
"Fetches",
"a",
"symbol",
"specified",
"in",
"op",
"arg",
"from",
"template",
"variables",
".",
"XXX",
"need",
"to",
"handle",
"local",
"vars?"
] |
6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L214-L224
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.