id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
10,200 | blang/vfs | mountfs/mountfs.go | Mkdir | func (fs MountFS) Mkdir(name string, perm os.FileMode) error {
mount, innerPath := findMount(name, fs.mounts, fs.rootFS, string(fs.PathSeparator()))
return mount.Mkdir(innerPath, perm)
} | go | func (fs MountFS) Mkdir(name string, perm os.FileMode) error {
mount, innerPath := findMount(name, fs.mounts, fs.rootFS, string(fs.PathSeparator()))
return mount.Mkdir(innerPath, perm)
} | [
"func",
"(",
"fs",
"MountFS",
")",
"Mkdir",
"(",
"name",
"string",
",",
"perm",
"os",
".",
"FileMode",
")",
"error",
"{",
"mount",
",",
"innerPath",
":=",
"findMount",
"(",
"name",
",",
"fs",
".",
"mounts",
",",
"fs",
".",
"rootFS",
",",
"string",
"(",
"fs",
".",
"PathSeparator",
"(",
")",
")",
")",
"\n",
"return",
"mount",
".",
"Mkdir",
"(",
"innerPath",
",",
"perm",
")",
"\n",
"}"
]
| // Mkdir creates a directory | [
"Mkdir",
"creates",
"a",
"directory"
]
| 2c3e2278e174a74f31ff8bf6f47b43ecb358a870 | https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/mountfs/mountfs.go#L125-L128 |
10,201 | blang/vfs | mountfs/mountfs.go | Stat | func (fs MountFS) Stat(name string) (os.FileInfo, error) {
mount, innerPath := findMount(name, fs.mounts, fs.rootFS, string(fs.PathSeparator()))
fi, err := mount.Stat(innerPath)
if innerPath == "/" {
return innerFileInfo{FileInfo: fi, name: filepath.Base(name)}, err
}
return fi, err
} | go | func (fs MountFS) Stat(name string) (os.FileInfo, error) {
mount, innerPath := findMount(name, fs.mounts, fs.rootFS, string(fs.PathSeparator()))
fi, err := mount.Stat(innerPath)
if innerPath == "/" {
return innerFileInfo{FileInfo: fi, name: filepath.Base(name)}, err
}
return fi, err
} | [
"func",
"(",
"fs",
"MountFS",
")",
"Stat",
"(",
"name",
"string",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"mount",
",",
"innerPath",
":=",
"findMount",
"(",
"name",
",",
"fs",
".",
"mounts",
",",
"fs",
".",
"rootFS",
",",
"string",
"(",
"fs",
".",
"PathSeparator",
"(",
")",
")",
")",
"\n",
"fi",
",",
"err",
":=",
"mount",
".",
"Stat",
"(",
"innerPath",
")",
"\n",
"if",
"innerPath",
"==",
"\"",
"\"",
"{",
"return",
"innerFileInfo",
"{",
"FileInfo",
":",
"fi",
",",
"name",
":",
"filepath",
".",
"Base",
"(",
"name",
")",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"fi",
",",
"err",
"\n",
"}"
]
| // Stat returns the fileinfo of a file | [
"Stat",
"returns",
"the",
"fileinfo",
"of",
"a",
"file"
]
| 2c3e2278e174a74f31ff8bf6f47b43ecb358a870 | https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/mountfs/mountfs.go#L140-L147 |
10,202 | blang/vfs | filesystem.go | MkdirAll | func MkdirAll(fs Filesystem, path string, perm os.FileMode) error {
if dir, err := fs.Stat(path); err == nil {
if dir.IsDir() {
return nil
}
return &os.PathError{"mkdir", path, ErrNotDirectory}
}
parts := SplitPath(path, string(fs.PathSeparator()))
if len(parts) > 1 {
// Create parent
err := MkdirAll(fs, strings.Join(parts[0:len(parts)-1], string(fs.PathSeparator())), perm)
if err != nil {
return err
}
}
// Parent now exists; invoke Mkdir and use its result.
err := fs.Mkdir(path, perm)
if err != nil {
// Handle arguments like "foo/." by
// double-checking that directory doesn't exist.
dir, err1 := fs.Lstat(path)
if err1 == nil && dir.IsDir() {
return nil
}
return err
}
return nil
} | go | func MkdirAll(fs Filesystem, path string, perm os.FileMode) error {
if dir, err := fs.Stat(path); err == nil {
if dir.IsDir() {
return nil
}
return &os.PathError{"mkdir", path, ErrNotDirectory}
}
parts := SplitPath(path, string(fs.PathSeparator()))
if len(parts) > 1 {
// Create parent
err := MkdirAll(fs, strings.Join(parts[0:len(parts)-1], string(fs.PathSeparator())), perm)
if err != nil {
return err
}
}
// Parent now exists; invoke Mkdir and use its result.
err := fs.Mkdir(path, perm)
if err != nil {
// Handle arguments like "foo/." by
// double-checking that directory doesn't exist.
dir, err1 := fs.Lstat(path)
if err1 == nil && dir.IsDir() {
return nil
}
return err
}
return nil
} | [
"func",
"MkdirAll",
"(",
"fs",
"Filesystem",
",",
"path",
"string",
",",
"perm",
"os",
".",
"FileMode",
")",
"error",
"{",
"if",
"dir",
",",
"err",
":=",
"fs",
".",
"Stat",
"(",
"path",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"dir",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"os",
".",
"PathError",
"{",
"\"",
"\"",
",",
"path",
",",
"ErrNotDirectory",
"}",
"\n",
"}",
"\n\n",
"parts",
":=",
"SplitPath",
"(",
"path",
",",
"string",
"(",
"fs",
".",
"PathSeparator",
"(",
")",
")",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
">",
"1",
"{",
"// Create parent",
"err",
":=",
"MkdirAll",
"(",
"fs",
",",
"strings",
".",
"Join",
"(",
"parts",
"[",
"0",
":",
"len",
"(",
"parts",
")",
"-",
"1",
"]",
",",
"string",
"(",
"fs",
".",
"PathSeparator",
"(",
")",
")",
")",
",",
"perm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Parent now exists; invoke Mkdir and use its result.",
"err",
":=",
"fs",
".",
"Mkdir",
"(",
"path",
",",
"perm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Handle arguments like \"foo/.\" by",
"// double-checking that directory doesn't exist.",
"dir",
",",
"err1",
":=",
"fs",
".",
"Lstat",
"(",
"path",
")",
"\n",
"if",
"err1",
"==",
"nil",
"&&",
"dir",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // MkdirAll creates a directory named path on the given Filesystem,
// along with any necessary parents, and returns nil,
// or else returns an error.
// The permission bits perm are used for all
// directories that MkdirAll creates.
// If path is already a directory, MkdirAll does nothing
// and returns nil. | [
"MkdirAll",
"creates",
"a",
"directory",
"named",
"path",
"on",
"the",
"given",
"Filesystem",
"along",
"with",
"any",
"necessary",
"parents",
"and",
"returns",
"nil",
"or",
"else",
"returns",
"an",
"error",
".",
"The",
"permission",
"bits",
"perm",
"are",
"used",
"for",
"all",
"directories",
"that",
"MkdirAll",
"creates",
".",
"If",
"path",
"is",
"already",
"a",
"directory",
"MkdirAll",
"does",
"nothing",
"and",
"returns",
"nil",
"."
]
| 2c3e2278e174a74f31ff8bf6f47b43ecb358a870 | https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/filesystem.go#L72-L101 |
10,203 | blang/vfs | filesystem.go | RemoveAll | func RemoveAll(fs Filesystem, path string) error {
if err := fs.Remove(path); err == nil || os.IsNotExist(err) {
return nil
}
// We could not delete it, so might be a directory
fis, err := fs.ReadDir(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
// Remove contents & return first error.
err = nil
for _, fi := range fis {
err1 := RemoveAll(fs, path+string(fs.PathSeparator())+fi.Name())
if err == nil {
err = err1
}
}
// Remove directory itself.
err1 := fs.Remove(path)
if err1 == nil || os.IsNotExist(err1) {
return nil
}
if err == nil {
err = err1
}
return err
} | go | func RemoveAll(fs Filesystem, path string) error {
if err := fs.Remove(path); err == nil || os.IsNotExist(err) {
return nil
}
// We could not delete it, so might be a directory
fis, err := fs.ReadDir(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
// Remove contents & return first error.
err = nil
for _, fi := range fis {
err1 := RemoveAll(fs, path+string(fs.PathSeparator())+fi.Name())
if err == nil {
err = err1
}
}
// Remove directory itself.
err1 := fs.Remove(path)
if err1 == nil || os.IsNotExist(err1) {
return nil
}
if err == nil {
err = err1
}
return err
} | [
"func",
"RemoveAll",
"(",
"fs",
"Filesystem",
",",
"path",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"fs",
".",
"Remove",
"(",
"path",
")",
";",
"err",
"==",
"nil",
"||",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// We could not delete it, so might be a directory",
"fis",
",",
"err",
":=",
"fs",
".",
"ReadDir",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Remove contents & return first error.",
"err",
"=",
"nil",
"\n",
"for",
"_",
",",
"fi",
":=",
"range",
"fis",
"{",
"err1",
":=",
"RemoveAll",
"(",
"fs",
",",
"path",
"+",
"string",
"(",
"fs",
".",
"PathSeparator",
"(",
")",
")",
"+",
"fi",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"err1",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Remove directory itself.",
"err1",
":=",
"fs",
".",
"Remove",
"(",
"path",
")",
"\n",
"if",
"err1",
"==",
"nil",
"||",
"os",
".",
"IsNotExist",
"(",
"err1",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"err1",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
]
| // RemoveAll removes path and any children it contains.
// It removes everything it can but returns the first error
// it encounters. If the path does not exist, RemoveAll
// returns nil. | [
"RemoveAll",
"removes",
"path",
"and",
"any",
"children",
"it",
"contains",
".",
"It",
"removes",
"everything",
"it",
"can",
"but",
"returns",
"the",
"first",
"error",
"it",
"encounters",
".",
"If",
"the",
"path",
"does",
"not",
"exist",
"RemoveAll",
"returns",
"nil",
"."
]
| 2c3e2278e174a74f31ff8bf6f47b43ecb358a870 | https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/filesystem.go#L107-L139 |
10,204 | openshift/osin | tokengen.go | GenerateAuthorizeToken | func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) {
token := uuid.NewRandom()
return base64.RawURLEncoding.EncodeToString([]byte(token)), nil
} | go | func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) {
token := uuid.NewRandom()
return base64.RawURLEncoding.EncodeToString([]byte(token)), nil
} | [
"func",
"(",
"a",
"*",
"AuthorizeTokenGenDefault",
")",
"GenerateAuthorizeToken",
"(",
"data",
"*",
"AuthorizeData",
")",
"(",
"ret",
"string",
",",
"err",
"error",
")",
"{",
"token",
":=",
"uuid",
".",
"NewRandom",
"(",
")",
"\n",
"return",
"base64",
".",
"RawURLEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
"(",
"token",
")",
")",
",",
"nil",
"\n",
"}"
]
| // GenerateAuthorizeToken generates a base64-encoded UUID code | [
"GenerateAuthorizeToken",
"generates",
"a",
"base64",
"-",
"encoded",
"UUID",
"code"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/tokengen.go#L14-L17 |
10,205 | openshift/osin | tokengen.go | GenerateAccessToken | func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error) {
token := uuid.NewRandom()
accesstoken = base64.RawURLEncoding.EncodeToString([]byte(token))
if generaterefresh {
rtoken := uuid.NewRandom()
refreshtoken = base64.RawURLEncoding.EncodeToString([]byte(rtoken))
}
return
} | go | func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error) {
token := uuid.NewRandom()
accesstoken = base64.RawURLEncoding.EncodeToString([]byte(token))
if generaterefresh {
rtoken := uuid.NewRandom()
refreshtoken = base64.RawURLEncoding.EncodeToString([]byte(rtoken))
}
return
} | [
"func",
"(",
"a",
"*",
"AccessTokenGenDefault",
")",
"GenerateAccessToken",
"(",
"data",
"*",
"AccessData",
",",
"generaterefresh",
"bool",
")",
"(",
"accesstoken",
"string",
",",
"refreshtoken",
"string",
",",
"err",
"error",
")",
"{",
"token",
":=",
"uuid",
".",
"NewRandom",
"(",
")",
"\n",
"accesstoken",
"=",
"base64",
".",
"RawURLEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
"(",
"token",
")",
")",
"\n\n",
"if",
"generaterefresh",
"{",
"rtoken",
":=",
"uuid",
".",
"NewRandom",
"(",
")",
"\n",
"refreshtoken",
"=",
"base64",
".",
"RawURLEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
"(",
"rtoken",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
]
| // GenerateAccessToken generates base64-encoded UUID access and refresh tokens | [
"GenerateAccessToken",
"generates",
"base64",
"-",
"encoded",
"UUID",
"access",
"and",
"refresh",
"tokens"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/tokengen.go#L24-L33 |
10,206 | openshift/osin | urivalidate.go | ParseUrls | func ParseUrls(baseUrl, redirectUrl string) (retBaseUrl, retRedirectUrl *url.URL, err error) {
var base, redirect *url.URL
// parse base url
if base, err = url.Parse(baseUrl); err != nil {
return nil, nil, err
}
// parse redirect url
if redirect, err = url.Parse(redirectUrl); err != nil {
return nil, nil, err
}
// must not have fragment
if base.Fragment != "" || redirect.Fragment != "" {
return nil, nil, newUriValidationError("url must not include fragment.", baseUrl, redirectUrl)
}
// Scheme must match
if redirect.Scheme != base.Scheme {
return nil, nil, newUriValidationError("scheme mismatch", baseUrl, redirectUrl)
}
// Host must match
if redirect.Host != base.Host {
return nil, nil, newUriValidationError("host mismatch", baseUrl, redirectUrl)
}
// resolve references to base url
retBaseUrl = (&url.URL{Scheme: base.Scheme, Host: base.Host, Path: "/"}).ResolveReference(&url.URL{Path: base.Path})
retRedirectUrl = (&url.URL{Scheme: base.Scheme, Host: base.Host, Path: "/"}).ResolveReference(&url.URL{Path: redirect.Path, RawQuery: redirect.RawQuery})
return
} | go | func ParseUrls(baseUrl, redirectUrl string) (retBaseUrl, retRedirectUrl *url.URL, err error) {
var base, redirect *url.URL
// parse base url
if base, err = url.Parse(baseUrl); err != nil {
return nil, nil, err
}
// parse redirect url
if redirect, err = url.Parse(redirectUrl); err != nil {
return nil, nil, err
}
// must not have fragment
if base.Fragment != "" || redirect.Fragment != "" {
return nil, nil, newUriValidationError("url must not include fragment.", baseUrl, redirectUrl)
}
// Scheme must match
if redirect.Scheme != base.Scheme {
return nil, nil, newUriValidationError("scheme mismatch", baseUrl, redirectUrl)
}
// Host must match
if redirect.Host != base.Host {
return nil, nil, newUriValidationError("host mismatch", baseUrl, redirectUrl)
}
// resolve references to base url
retBaseUrl = (&url.URL{Scheme: base.Scheme, Host: base.Host, Path: "/"}).ResolveReference(&url.URL{Path: base.Path})
retRedirectUrl = (&url.URL{Scheme: base.Scheme, Host: base.Host, Path: "/"}).ResolveReference(&url.URL{Path: redirect.Path, RawQuery: redirect.RawQuery})
return
} | [
"func",
"ParseUrls",
"(",
"baseUrl",
",",
"redirectUrl",
"string",
")",
"(",
"retBaseUrl",
",",
"retRedirectUrl",
"*",
"url",
".",
"URL",
",",
"err",
"error",
")",
"{",
"var",
"base",
",",
"redirect",
"*",
"url",
".",
"URL",
"\n",
"// parse base url",
"if",
"base",
",",
"err",
"=",
"url",
".",
"Parse",
"(",
"baseUrl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// parse redirect url",
"if",
"redirect",
",",
"err",
"=",
"url",
".",
"Parse",
"(",
"redirectUrl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// must not have fragment",
"if",
"base",
".",
"Fragment",
"!=",
"\"",
"\"",
"||",
"redirect",
".",
"Fragment",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
",",
"newUriValidationError",
"(",
"\"",
"\"",
",",
"baseUrl",
",",
"redirectUrl",
")",
"\n",
"}",
"\n\n",
"// Scheme must match",
"if",
"redirect",
".",
"Scheme",
"!=",
"base",
".",
"Scheme",
"{",
"return",
"nil",
",",
"nil",
",",
"newUriValidationError",
"(",
"\"",
"\"",
",",
"baseUrl",
",",
"redirectUrl",
")",
"\n",
"}",
"\n\n",
"// Host must match",
"if",
"redirect",
".",
"Host",
"!=",
"base",
".",
"Host",
"{",
"return",
"nil",
",",
"nil",
",",
"newUriValidationError",
"(",
"\"",
"\"",
",",
"baseUrl",
",",
"redirectUrl",
")",
"\n",
"}",
"\n\n",
"// resolve references to base url",
"retBaseUrl",
"=",
"(",
"&",
"url",
".",
"URL",
"{",
"Scheme",
":",
"base",
".",
"Scheme",
",",
"Host",
":",
"base",
".",
"Host",
",",
"Path",
":",
"\"",
"\"",
"}",
")",
".",
"ResolveReference",
"(",
"&",
"url",
".",
"URL",
"{",
"Path",
":",
"base",
".",
"Path",
"}",
")",
"\n",
"retRedirectUrl",
"=",
"(",
"&",
"url",
".",
"URL",
"{",
"Scheme",
":",
"base",
".",
"Scheme",
",",
"Host",
":",
"base",
".",
"Host",
",",
"Path",
":",
"\"",
"\"",
"}",
")",
".",
"ResolveReference",
"(",
"&",
"url",
".",
"URL",
"{",
"Path",
":",
"redirect",
".",
"Path",
",",
"RawQuery",
":",
"redirect",
".",
"RawQuery",
"}",
")",
"\n",
"return",
"\n",
"}"
]
| // Parse urls, resolving uri references to base url | [
"Parse",
"urls",
"resolving",
"uri",
"references",
"to",
"base",
"url"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/urivalidate.go#L22-L53 |
10,207 | openshift/osin | urivalidate.go | ValidateUriList | func ValidateUriList(baseUriList string, redirectUri string, separator string) (realRedirectUri string, err error) {
// make a list of uris
var slist []string
if separator != "" {
slist = strings.Split(baseUriList, separator)
} else {
slist = make([]string, 0)
slist = append(slist, baseUriList)
}
for _, sitem := range slist {
realRedirectUri, err = ValidateUri(sitem, redirectUri)
// validated, return no error
if err == nil {
return realRedirectUri, nil
}
// if there was an error that is not a validation error, return it
if _, iok := err.(UriValidationError); !iok {
return "", err
}
}
return "", newUriValidationError("urls don't validate", baseUriList, redirectUri)
} | go | func ValidateUriList(baseUriList string, redirectUri string, separator string) (realRedirectUri string, err error) {
// make a list of uris
var slist []string
if separator != "" {
slist = strings.Split(baseUriList, separator)
} else {
slist = make([]string, 0)
slist = append(slist, baseUriList)
}
for _, sitem := range slist {
realRedirectUri, err = ValidateUri(sitem, redirectUri)
// validated, return no error
if err == nil {
return realRedirectUri, nil
}
// if there was an error that is not a validation error, return it
if _, iok := err.(UriValidationError); !iok {
return "", err
}
}
return "", newUriValidationError("urls don't validate", baseUriList, redirectUri)
} | [
"func",
"ValidateUriList",
"(",
"baseUriList",
"string",
",",
"redirectUri",
"string",
",",
"separator",
"string",
")",
"(",
"realRedirectUri",
"string",
",",
"err",
"error",
")",
"{",
"// make a list of uris",
"var",
"slist",
"[",
"]",
"string",
"\n",
"if",
"separator",
"!=",
"\"",
"\"",
"{",
"slist",
"=",
"strings",
".",
"Split",
"(",
"baseUriList",
",",
"separator",
")",
"\n",
"}",
"else",
"{",
"slist",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"slist",
"=",
"append",
"(",
"slist",
",",
"baseUriList",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"sitem",
":=",
"range",
"slist",
"{",
"realRedirectUri",
",",
"err",
"=",
"ValidateUri",
"(",
"sitem",
",",
"redirectUri",
")",
"\n",
"// validated, return no error",
"if",
"err",
"==",
"nil",
"{",
"return",
"realRedirectUri",
",",
"nil",
"\n",
"}",
"\n\n",
"// if there was an error that is not a validation error, return it",
"if",
"_",
",",
"iok",
":=",
"err",
".",
"(",
"UriValidationError",
")",
";",
"!",
"iok",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"newUriValidationError",
"(",
"\"",
"\"",
",",
"baseUriList",
",",
"redirectUri",
")",
"\n",
"}"
]
| // ValidateUriList validates that redirectUri is contained in baseUriList.
// baseUriList may be a string separated by separator.
// If separator is blank, validate only 1 URI. | [
"ValidateUriList",
"validates",
"that",
"redirectUri",
"is",
"contained",
"in",
"baseUriList",
".",
"baseUriList",
"may",
"be",
"a",
"string",
"separated",
"by",
"separator",
".",
"If",
"separator",
"is",
"blank",
"validate",
"only",
"1",
"URI",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/urivalidate.go#L58-L82 |
10,208 | openshift/osin | urivalidate.go | ValidateUri | func ValidateUri(baseUri string, redirectUri string) (realRedirectUri string, err error) {
if baseUri == "" || redirectUri == "" {
return "", errors.New("urls cannot be blank.")
}
base, redirect, err := ParseUrls(baseUri, redirectUri)
if err != nil {
return "", err
}
// allow exact path matches
if base.Path == redirect.Path {
return redirect.String(), nil
}
// ensure prefix matches are actually subpaths
requiredPrefix := strings.TrimRight(base.Path, "/") + "/"
if !strings.HasPrefix(redirect.Path, requiredPrefix) {
return "", newUriValidationError("path prefix doesn't match", baseUri, redirectUri)
}
return redirect.String(),nil
} | go | func ValidateUri(baseUri string, redirectUri string) (realRedirectUri string, err error) {
if baseUri == "" || redirectUri == "" {
return "", errors.New("urls cannot be blank.")
}
base, redirect, err := ParseUrls(baseUri, redirectUri)
if err != nil {
return "", err
}
// allow exact path matches
if base.Path == redirect.Path {
return redirect.String(), nil
}
// ensure prefix matches are actually subpaths
requiredPrefix := strings.TrimRight(base.Path, "/") + "/"
if !strings.HasPrefix(redirect.Path, requiredPrefix) {
return "", newUriValidationError("path prefix doesn't match", baseUri, redirectUri)
}
return redirect.String(),nil
} | [
"func",
"ValidateUri",
"(",
"baseUri",
"string",
",",
"redirectUri",
"string",
")",
"(",
"realRedirectUri",
"string",
",",
"err",
"error",
")",
"{",
"if",
"baseUri",
"==",
"\"",
"\"",
"||",
"redirectUri",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"base",
",",
"redirect",
",",
"err",
":=",
"ParseUrls",
"(",
"baseUri",
",",
"redirectUri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"// allow exact path matches",
"if",
"base",
".",
"Path",
"==",
"redirect",
".",
"Path",
"{",
"return",
"redirect",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"// ensure prefix matches are actually subpaths",
"requiredPrefix",
":=",
"strings",
".",
"TrimRight",
"(",
"base",
".",
"Path",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"redirect",
".",
"Path",
",",
"requiredPrefix",
")",
"{",
"return",
"\"",
"\"",
",",
"newUriValidationError",
"(",
"\"",
"\"",
",",
"baseUri",
",",
"redirectUri",
")",
"\n",
"}",
"\n\n",
"return",
"redirect",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
]
| // ValidateUri validates that redirectUri is contained in baseUri | [
"ValidateUri",
"validates",
"that",
"redirectUri",
"is",
"contained",
"in",
"baseUri"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/urivalidate.go#L85-L107 |
10,209 | openshift/osin | urivalidate.go | FirstUri | func FirstUri(baseUriList string, separator string) string {
if separator != "" {
slist := strings.Split(baseUriList, separator)
if len(slist) > 0 {
return slist[0]
}
} else {
return baseUriList
}
return ""
} | go | func FirstUri(baseUriList string, separator string) string {
if separator != "" {
slist := strings.Split(baseUriList, separator)
if len(slist) > 0 {
return slist[0]
}
} else {
return baseUriList
}
return ""
} | [
"func",
"FirstUri",
"(",
"baseUriList",
"string",
",",
"separator",
"string",
")",
"string",
"{",
"if",
"separator",
"!=",
"\"",
"\"",
"{",
"slist",
":=",
"strings",
".",
"Split",
"(",
"baseUriList",
",",
"separator",
")",
"\n",
"if",
"len",
"(",
"slist",
")",
">",
"0",
"{",
"return",
"slist",
"[",
"0",
"]",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"baseUriList",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"\n",
"}"
]
| // Returns the first uri from an uri list | [
"Returns",
"the",
"first",
"uri",
"from",
"an",
"uri",
"list"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/urivalidate.go#L110-L121 |
10,210 | openshift/osin | response.go | SetError | func (r *Response) SetError(id string, description string) {
r.SetErrorUri(id, description, "", "")
} | go | func (r *Response) SetError(id string, description string) {
r.SetErrorUri(id, description, "", "")
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"SetError",
"(",
"id",
"string",
",",
"description",
"string",
")",
"{",
"r",
".",
"SetErrorUri",
"(",
"id",
",",
"description",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}"
]
| // SetError sets an error id and description on the Response
// state and uri are left blank | [
"SetError",
"sets",
"an",
"error",
"id",
"and",
"description",
"on",
"the",
"Response",
"state",
"and",
"uri",
"are",
"left",
"blank"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/response.go#L60-L62 |
10,211 | openshift/osin | response.go | SetErrorState | func (r *Response) SetErrorState(id string, description string, state string) {
r.SetErrorUri(id, description, "", state)
} | go | func (r *Response) SetErrorState(id string, description string, state string) {
r.SetErrorUri(id, description, "", state)
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"SetErrorState",
"(",
"id",
"string",
",",
"description",
"string",
",",
"state",
"string",
")",
"{",
"r",
".",
"SetErrorUri",
"(",
"id",
",",
"description",
",",
"\"",
"\"",
",",
"state",
")",
"\n",
"}"
]
| // SetErrorState sets an error id, description, and state on the Response
// uri is left blank | [
"SetErrorState",
"sets",
"an",
"error",
"id",
"description",
"and",
"state",
"on",
"the",
"Response",
"uri",
"is",
"left",
"blank"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/response.go#L66-L68 |
10,212 | openshift/osin | response.go | SetErrorUri | func (r *Response) SetErrorUri(id string, description string, uri string, state string) {
// get default error message
if description == "" {
description = deferror.Get(id)
}
// set error parameters
r.IsError = true
r.ErrorId = id
r.StatusCode = r.ErrorStatusCode
if r.StatusCode != 200 {
r.StatusText = description
} else {
r.StatusText = ""
}
r.Output = make(ResponseData) // clear output
r.Output["error"] = id
r.Output["error_description"] = description
if uri != "" {
r.Output["error_uri"] = uri
}
if state != "" {
r.Output["state"] = state
}
} | go | func (r *Response) SetErrorUri(id string, description string, uri string, state string) {
// get default error message
if description == "" {
description = deferror.Get(id)
}
// set error parameters
r.IsError = true
r.ErrorId = id
r.StatusCode = r.ErrorStatusCode
if r.StatusCode != 200 {
r.StatusText = description
} else {
r.StatusText = ""
}
r.Output = make(ResponseData) // clear output
r.Output["error"] = id
r.Output["error_description"] = description
if uri != "" {
r.Output["error_uri"] = uri
}
if state != "" {
r.Output["state"] = state
}
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"SetErrorUri",
"(",
"id",
"string",
",",
"description",
"string",
",",
"uri",
"string",
",",
"state",
"string",
")",
"{",
"// get default error message",
"if",
"description",
"==",
"\"",
"\"",
"{",
"description",
"=",
"deferror",
".",
"Get",
"(",
"id",
")",
"\n",
"}",
"\n\n",
"// set error parameters",
"r",
".",
"IsError",
"=",
"true",
"\n",
"r",
".",
"ErrorId",
"=",
"id",
"\n",
"r",
".",
"StatusCode",
"=",
"r",
".",
"ErrorStatusCode",
"\n",
"if",
"r",
".",
"StatusCode",
"!=",
"200",
"{",
"r",
".",
"StatusText",
"=",
"description",
"\n",
"}",
"else",
"{",
"r",
".",
"StatusText",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"r",
".",
"Output",
"=",
"make",
"(",
"ResponseData",
")",
"// clear output",
"\n",
"r",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"id",
"\n",
"r",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"description",
"\n",
"if",
"uri",
"!=",
"\"",
"\"",
"{",
"r",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"uri",
"\n",
"}",
"\n",
"if",
"state",
"!=",
"\"",
"\"",
"{",
"r",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"state",
"\n",
"}",
"\n",
"}"
]
| // SetErrorUri sets an error id, description, state, and uri on the Response | [
"SetErrorUri",
"sets",
"an",
"error",
"id",
"description",
"state",
"and",
"uri",
"on",
"the",
"Response"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/response.go#L71-L95 |
10,213 | openshift/osin | response.go | SetRedirect | func (r *Response) SetRedirect(url string) {
// set redirect parameters
r.Type = REDIRECT
r.URL = url
} | go | func (r *Response) SetRedirect(url string) {
// set redirect parameters
r.Type = REDIRECT
r.URL = url
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"SetRedirect",
"(",
"url",
"string",
")",
"{",
"// set redirect parameters",
"r",
".",
"Type",
"=",
"REDIRECT",
"\n",
"r",
".",
"URL",
"=",
"url",
"\n",
"}"
]
| // SetRedirect changes the response to redirect to the given url | [
"SetRedirect",
"changes",
"the",
"response",
"to",
"redirect",
"to",
"the",
"given",
"url"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/response.go#L98-L102 |
10,214 | openshift/osin | response.go | GetRedirectUrl | func (r *Response) GetRedirectUrl() (string, error) {
if r.Type != REDIRECT {
return "", errors.New("Not a redirect response")
}
u, err := url.Parse(r.URL)
if err != nil {
return "", err
}
var q url.Values
if r.RedirectInFragment {
// start with empty set for fragment
q = url.Values{}
} else {
// add parameters to existing query
q = u.Query()
}
// add parameters
for n, v := range r.Output {
q.Set(n, fmt.Sprint(v))
}
// https://tools.ietf.org/html/rfc6749#section-4.2.2
// Fragment should be encoded as application/x-www-form-urlencoded (%-escaped, spaces are represented as '+')
// The stdlib URL#String() doesn't make that easy to accomplish, so build this ourselves
if r.RedirectInFragment {
u.Fragment = ""
redirectURI := u.String() + "#" + q.Encode()
return redirectURI, nil
}
// Otherwise, update the query and encode normally
u.RawQuery = q.Encode()
u.Fragment = ""
return u.String(), nil
} | go | func (r *Response) GetRedirectUrl() (string, error) {
if r.Type != REDIRECT {
return "", errors.New("Not a redirect response")
}
u, err := url.Parse(r.URL)
if err != nil {
return "", err
}
var q url.Values
if r.RedirectInFragment {
// start with empty set for fragment
q = url.Values{}
} else {
// add parameters to existing query
q = u.Query()
}
// add parameters
for n, v := range r.Output {
q.Set(n, fmt.Sprint(v))
}
// https://tools.ietf.org/html/rfc6749#section-4.2.2
// Fragment should be encoded as application/x-www-form-urlencoded (%-escaped, spaces are represented as '+')
// The stdlib URL#String() doesn't make that easy to accomplish, so build this ourselves
if r.RedirectInFragment {
u.Fragment = ""
redirectURI := u.String() + "#" + q.Encode()
return redirectURI, nil
}
// Otherwise, update the query and encode normally
u.RawQuery = q.Encode()
u.Fragment = ""
return u.String(), nil
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"GetRedirectUrl",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"r",
".",
"Type",
"!=",
"REDIRECT",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"r",
".",
"URL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"q",
"url",
".",
"Values",
"\n",
"if",
"r",
".",
"RedirectInFragment",
"{",
"// start with empty set for fragment",
"q",
"=",
"url",
".",
"Values",
"{",
"}",
"\n",
"}",
"else",
"{",
"// add parameters to existing query",
"q",
"=",
"u",
".",
"Query",
"(",
")",
"\n",
"}",
"\n\n",
"// add parameters",
"for",
"n",
",",
"v",
":=",
"range",
"r",
".",
"Output",
"{",
"q",
".",
"Set",
"(",
"n",
",",
"fmt",
".",
"Sprint",
"(",
"v",
")",
")",
"\n",
"}",
"\n\n",
"// https://tools.ietf.org/html/rfc6749#section-4.2.2",
"// Fragment should be encoded as application/x-www-form-urlencoded (%-escaped, spaces are represented as '+')",
"// The stdlib URL#String() doesn't make that easy to accomplish, so build this ourselves",
"if",
"r",
".",
"RedirectInFragment",
"{",
"u",
".",
"Fragment",
"=",
"\"",
"\"",
"\n",
"redirectURI",
":=",
"u",
".",
"String",
"(",
")",
"+",
"\"",
"\"",
"+",
"q",
".",
"Encode",
"(",
")",
"\n",
"return",
"redirectURI",
",",
"nil",
"\n",
"}",
"\n\n",
"// Otherwise, update the query and encode normally",
"u",
".",
"RawQuery",
"=",
"q",
".",
"Encode",
"(",
")",
"\n",
"u",
".",
"Fragment",
"=",
"\"",
"\"",
"\n",
"return",
"u",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
]
| // GetRedirectUrl returns the redirect url with all query string parameters | [
"GetRedirectUrl",
"returns",
"the",
"redirect",
"url",
"with",
"all",
"query",
"string",
"parameters"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/response.go#L110-L147 |
10,215 | openshift/osin | response_json.go | OutputJSON | func OutputJSON(rs *Response, w http.ResponseWriter, r *http.Request) error {
// Add headers
for i, k := range rs.Headers {
for _, v := range k {
w.Header().Add(i, v)
}
}
if rs.Type == REDIRECT {
// Output redirect with parameters
u, err := rs.GetRedirectUrl()
if err != nil {
return err
}
w.Header().Add("Location", u)
w.WriteHeader(302)
} else {
// set content type if the response doesn't already have one associated with it
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(rs.StatusCode)
encoder := json.NewEncoder(w)
err := encoder.Encode(rs.Output)
if err != nil {
return err
}
}
return nil
} | go | func OutputJSON(rs *Response, w http.ResponseWriter, r *http.Request) error {
// Add headers
for i, k := range rs.Headers {
for _, v := range k {
w.Header().Add(i, v)
}
}
if rs.Type == REDIRECT {
// Output redirect with parameters
u, err := rs.GetRedirectUrl()
if err != nil {
return err
}
w.Header().Add("Location", u)
w.WriteHeader(302)
} else {
// set content type if the response doesn't already have one associated with it
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(rs.StatusCode)
encoder := json.NewEncoder(w)
err := encoder.Encode(rs.Output)
if err != nil {
return err
}
}
return nil
} | [
"func",
"OutputJSON",
"(",
"rs",
"*",
"Response",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"// Add headers",
"for",
"i",
",",
"k",
":=",
"range",
"rs",
".",
"Headers",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"k",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"i",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"rs",
".",
"Type",
"==",
"REDIRECT",
"{",
"// Output redirect with parameters",
"u",
",",
"err",
":=",
"rs",
".",
"GetRedirectUrl",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"u",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"302",
")",
"\n",
"}",
"else",
"{",
"// set content type if the response doesn't already have one associated with it",
"if",
"w",
".",
"Header",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"rs",
".",
"StatusCode",
")",
"\n\n",
"encoder",
":=",
"json",
".",
"NewEncoder",
"(",
"w",
")",
"\n",
"err",
":=",
"encoder",
".",
"Encode",
"(",
"rs",
".",
"Output",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // OutputJSON encodes the Response to JSON and writes to the http.ResponseWriter | [
"OutputJSON",
"encodes",
"the",
"Response",
"to",
"JSON",
"and",
"writes",
"to",
"the",
"http",
".",
"ResponseWriter"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/response_json.go#L9-L39 |
10,216 | openshift/osin | config.go | Exists | func (t AllowedAuthorizeType) Exists(rt AuthorizeRequestType) bool {
for _, k := range t {
if k == rt {
return true
}
}
return false
} | go | func (t AllowedAuthorizeType) Exists(rt AuthorizeRequestType) bool {
for _, k := range t {
if k == rt {
return true
}
}
return false
} | [
"func",
"(",
"t",
"AllowedAuthorizeType",
")",
"Exists",
"(",
"rt",
"AuthorizeRequestType",
")",
"bool",
"{",
"for",
"_",
",",
"k",
":=",
"range",
"t",
"{",
"if",
"k",
"==",
"rt",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
]
| // Exists returns true if the auth type exists in the list | [
"Exists",
"returns",
"true",
"if",
"the",
"auth",
"type",
"exists",
"in",
"the",
"list"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/config.go#L7-L14 |
10,217 | openshift/osin | config.go | Exists | func (t AllowedAccessType) Exists(rt AccessRequestType) bool {
for _, k := range t {
if k == rt {
return true
}
}
return false
} | go | func (t AllowedAccessType) Exists(rt AccessRequestType) bool {
for _, k := range t {
if k == rt {
return true
}
}
return false
} | [
"func",
"(",
"t",
"AllowedAccessType",
")",
"Exists",
"(",
"rt",
"AccessRequestType",
")",
"bool",
"{",
"for",
"_",
",",
"k",
":=",
"range",
"t",
"{",
"if",
"k",
"==",
"rt",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
]
| // Exists returns true if the access type exists in the list | [
"Exists",
"returns",
"true",
"if",
"the",
"access",
"type",
"exists",
"in",
"the",
"list"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/config.go#L20-L27 |
10,218 | openshift/osin | config.go | NewServerConfig | func NewServerConfig() *ServerConfig {
return &ServerConfig{
AuthorizationExpiration: 250,
AccessExpiration: 3600,
TokenType: "Bearer",
AllowedAuthorizeTypes: AllowedAuthorizeType{CODE},
AllowedAccessTypes: AllowedAccessType{AUTHORIZATION_CODE},
ErrorStatusCode: 200,
AllowClientSecretInParams: false,
AllowGetAccessRequest: false,
RetainTokenAfterRefresh: false,
}
} | go | func NewServerConfig() *ServerConfig {
return &ServerConfig{
AuthorizationExpiration: 250,
AccessExpiration: 3600,
TokenType: "Bearer",
AllowedAuthorizeTypes: AllowedAuthorizeType{CODE},
AllowedAccessTypes: AllowedAccessType{AUTHORIZATION_CODE},
ErrorStatusCode: 200,
AllowClientSecretInParams: false,
AllowGetAccessRequest: false,
RetainTokenAfterRefresh: false,
}
} | [
"func",
"NewServerConfig",
"(",
")",
"*",
"ServerConfig",
"{",
"return",
"&",
"ServerConfig",
"{",
"AuthorizationExpiration",
":",
"250",
",",
"AccessExpiration",
":",
"3600",
",",
"TokenType",
":",
"\"",
"\"",
",",
"AllowedAuthorizeTypes",
":",
"AllowedAuthorizeType",
"{",
"CODE",
"}",
",",
"AllowedAccessTypes",
":",
"AllowedAccessType",
"{",
"AUTHORIZATION_CODE",
"}",
",",
"ErrorStatusCode",
":",
"200",
",",
"AllowClientSecretInParams",
":",
"false",
",",
"AllowGetAccessRequest",
":",
"false",
",",
"RetainTokenAfterRefresh",
":",
"false",
",",
"}",
"\n",
"}"
]
| // NewServerConfig returns a new ServerConfig with default configuration | [
"NewServerConfig",
"returns",
"a",
"new",
"ServerConfig",
"with",
"default",
"configuration"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/config.go#L70-L82 |
10,219 | openshift/osin | server.go | NewServer | func NewServer(config *ServerConfig, storage Storage) *Server {
return &Server{
Config: config,
Storage: storage,
AuthorizeTokenGen: &AuthorizeTokenGenDefault{},
AccessTokenGen: &AccessTokenGenDefault{},
Now: time.Now,
Logger: &LoggerDefault{},
}
} | go | func NewServer(config *ServerConfig, storage Storage) *Server {
return &Server{
Config: config,
Storage: storage,
AuthorizeTokenGen: &AuthorizeTokenGenDefault{},
AccessTokenGen: &AccessTokenGenDefault{},
Now: time.Now,
Logger: &LoggerDefault{},
}
} | [
"func",
"NewServer",
"(",
"config",
"*",
"ServerConfig",
",",
"storage",
"Storage",
")",
"*",
"Server",
"{",
"return",
"&",
"Server",
"{",
"Config",
":",
"config",
",",
"Storage",
":",
"storage",
",",
"AuthorizeTokenGen",
":",
"&",
"AuthorizeTokenGenDefault",
"{",
"}",
",",
"AccessTokenGen",
":",
"&",
"AccessTokenGenDefault",
"{",
"}",
",",
"Now",
":",
"time",
".",
"Now",
",",
"Logger",
":",
"&",
"LoggerDefault",
"{",
"}",
",",
"}",
"\n",
"}"
]
| // NewServer creates a new server instance | [
"NewServer",
"creates",
"a",
"new",
"server",
"instance"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/server.go#L18-L27 |
10,220 | openshift/osin | server.go | NewResponse | func (s *Server) NewResponse() *Response {
r := NewResponse(s.Storage)
r.ErrorStatusCode = s.Config.ErrorStatusCode
return r
} | go | func (s *Server) NewResponse() *Response {
r := NewResponse(s.Storage)
r.ErrorStatusCode = s.Config.ErrorStatusCode
return r
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"NewResponse",
"(",
")",
"*",
"Response",
"{",
"r",
":=",
"NewResponse",
"(",
"s",
".",
"Storage",
")",
"\n",
"r",
".",
"ErrorStatusCode",
"=",
"s",
".",
"Config",
".",
"ErrorStatusCode",
"\n",
"return",
"r",
"\n",
"}"
]
| // NewResponse creates a new response for the server | [
"NewResponse",
"creates",
"a",
"new",
"response",
"for",
"the",
"server"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/server.go#L30-L34 |
10,221 | openshift/osin | info.go | HandleInfoRequest | func (s *Server) HandleInfoRequest(w *Response, r *http.Request) *InfoRequest {
r.ParseForm()
bearer := CheckBearerAuth(r)
if bearer == nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, nil, "handle_info_request=%s", "bearer is nil")
return nil
}
// generate info request
ret := &InfoRequest{
Code: bearer.Code,
}
if ret.Code == "" {
s.setErrorAndLog(w, E_INVALID_REQUEST, nil, "handle_info_request=%s", "code is nil")
return nil
}
var err error
// load access data
ret.AccessData, err = w.Storage.LoadAccess(ret.Code)
if err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "handle_info_request=%s", "failed to load access data")
return nil
}
if ret.AccessData == nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, nil, "handle_info_request=%s", "access data is nil")
return nil
}
if ret.AccessData.Client == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "handle_info_request=%s", "access data client is nil")
return nil
}
if ret.AccessData.Client.GetRedirectUri() == "" {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "handle_info_request=%s", "access data client redirect uri is empty")
return nil
}
if ret.AccessData.IsExpiredAt(s.Now()) {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "handle_info_request=%s", "access data is expired")
return nil
}
return ret
} | go | func (s *Server) HandleInfoRequest(w *Response, r *http.Request) *InfoRequest {
r.ParseForm()
bearer := CheckBearerAuth(r)
if bearer == nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, nil, "handle_info_request=%s", "bearer is nil")
return nil
}
// generate info request
ret := &InfoRequest{
Code: bearer.Code,
}
if ret.Code == "" {
s.setErrorAndLog(w, E_INVALID_REQUEST, nil, "handle_info_request=%s", "code is nil")
return nil
}
var err error
// load access data
ret.AccessData, err = w.Storage.LoadAccess(ret.Code)
if err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "handle_info_request=%s", "failed to load access data")
return nil
}
if ret.AccessData == nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, nil, "handle_info_request=%s", "access data is nil")
return nil
}
if ret.AccessData.Client == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "handle_info_request=%s", "access data client is nil")
return nil
}
if ret.AccessData.Client.GetRedirectUri() == "" {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "handle_info_request=%s", "access data client redirect uri is empty")
return nil
}
if ret.AccessData.IsExpiredAt(s.Now()) {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "handle_info_request=%s", "access data is expired")
return nil
}
return ret
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"HandleInfoRequest",
"(",
"w",
"*",
"Response",
",",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"InfoRequest",
"{",
"r",
".",
"ParseForm",
"(",
")",
"\n",
"bearer",
":=",
"CheckBearerAuth",
"(",
"r",
")",
"\n",
"if",
"bearer",
"==",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// generate info request",
"ret",
":=",
"&",
"InfoRequest",
"{",
"Code",
":",
"bearer",
".",
"Code",
",",
"}",
"\n\n",
"if",
"ret",
".",
"Code",
"==",
"\"",
"\"",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n\n",
"// load access data",
"ret",
".",
"AccessData",
",",
"err",
"=",
"w",
".",
"Storage",
".",
"LoadAccess",
"(",
"ret",
".",
"Code",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"ret",
".",
"AccessData",
"==",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"ret",
".",
"AccessData",
".",
"Client",
"==",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_UNAUTHORIZED_CLIENT",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"ret",
".",
"AccessData",
".",
"Client",
".",
"GetRedirectUri",
"(",
")",
"==",
"\"",
"\"",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_UNAUTHORIZED_CLIENT",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"ret",
".",
"AccessData",
".",
"IsExpiredAt",
"(",
"s",
".",
"Now",
"(",
")",
")",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_GRANT",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"ret",
"\n",
"}"
]
| // HandleInfoRequest is an http.HandlerFunc for server information
// NOT an RFC specification. | [
"HandleInfoRequest",
"is",
"an",
"http",
".",
"HandlerFunc",
"for",
"server",
"information",
"NOT",
"an",
"RFC",
"specification",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/info.go#L16-L60 |
10,222 | openshift/osin | info.go | FinishInfoRequest | func (s *Server) FinishInfoRequest(w *Response, r *http.Request, ir *InfoRequest) {
// don't process if is already an error
if w.IsError {
return
}
// output data
w.Output["client_id"] = ir.AccessData.Client.GetId()
w.Output["access_token"] = ir.AccessData.AccessToken
w.Output["token_type"] = s.Config.TokenType
w.Output["expires_in"] = ir.AccessData.CreatedAt.Add(time.Duration(ir.AccessData.ExpiresIn)*time.Second).Sub(s.Now()) / time.Second
if ir.AccessData.RefreshToken != "" {
w.Output["refresh_token"] = ir.AccessData.RefreshToken
}
if ir.AccessData.Scope != "" {
w.Output["scope"] = ir.AccessData.Scope
}
} | go | func (s *Server) FinishInfoRequest(w *Response, r *http.Request, ir *InfoRequest) {
// don't process if is already an error
if w.IsError {
return
}
// output data
w.Output["client_id"] = ir.AccessData.Client.GetId()
w.Output["access_token"] = ir.AccessData.AccessToken
w.Output["token_type"] = s.Config.TokenType
w.Output["expires_in"] = ir.AccessData.CreatedAt.Add(time.Duration(ir.AccessData.ExpiresIn)*time.Second).Sub(s.Now()) / time.Second
if ir.AccessData.RefreshToken != "" {
w.Output["refresh_token"] = ir.AccessData.RefreshToken
}
if ir.AccessData.Scope != "" {
w.Output["scope"] = ir.AccessData.Scope
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"FinishInfoRequest",
"(",
"w",
"*",
"Response",
",",
"r",
"*",
"http",
".",
"Request",
",",
"ir",
"*",
"InfoRequest",
")",
"{",
"// don't process if is already an error",
"if",
"w",
".",
"IsError",
"{",
"return",
"\n",
"}",
"\n\n",
"// output data",
"w",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"ir",
".",
"AccessData",
".",
"Client",
".",
"GetId",
"(",
")",
"\n",
"w",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"ir",
".",
"AccessData",
".",
"AccessToken",
"\n",
"w",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"s",
".",
"Config",
".",
"TokenType",
"\n",
"w",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"ir",
".",
"AccessData",
".",
"CreatedAt",
".",
"Add",
"(",
"time",
".",
"Duration",
"(",
"ir",
".",
"AccessData",
".",
"ExpiresIn",
")",
"*",
"time",
".",
"Second",
")",
".",
"Sub",
"(",
"s",
".",
"Now",
"(",
")",
")",
"/",
"time",
".",
"Second",
"\n",
"if",
"ir",
".",
"AccessData",
".",
"RefreshToken",
"!=",
"\"",
"\"",
"{",
"w",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"ir",
".",
"AccessData",
".",
"RefreshToken",
"\n",
"}",
"\n",
"if",
"ir",
".",
"AccessData",
".",
"Scope",
"!=",
"\"",
"\"",
"{",
"w",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"ir",
".",
"AccessData",
".",
"Scope",
"\n",
"}",
"\n",
"}"
]
| // FinishInfoRequest finalizes the request handled by HandleInfoRequest | [
"FinishInfoRequest",
"finalizes",
"the",
"request",
"handled",
"by",
"HandleInfoRequest"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/info.go#L63-L80 |
10,223 | openshift/osin | access.go | HandleAccessRequest | func (s *Server) HandleAccessRequest(w *Response, r *http.Request) *AccessRequest {
// Only allow GET or POST
if r.Method == "GET" {
if !s.Config.AllowGetAccessRequest {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Request must be POST"), "access_request=%s", "GET request not allowed")
return nil
}
} else if r.Method != "POST" {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Request must be POST"), "access_request=%s", "request must be POST")
return nil
}
err := r.ParseForm()
if err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "access_request=%s", "parsing error")
return nil
}
grantType := AccessRequestType(r.FormValue("grant_type"))
if s.Config.AllowedAccessTypes.Exists(grantType) {
switch grantType {
case AUTHORIZATION_CODE:
return s.handleAuthorizationCodeRequest(w, r)
case REFRESH_TOKEN:
return s.handleRefreshTokenRequest(w, r)
case PASSWORD:
return s.handlePasswordRequest(w, r)
case CLIENT_CREDENTIALS:
return s.handleClientCredentialsRequest(w, r)
case ASSERTION:
return s.handleAssertionRequest(w, r)
}
}
s.setErrorAndLog(w, E_UNSUPPORTED_GRANT_TYPE, nil, "access_request=%s", "unknown grant type")
return nil
} | go | func (s *Server) HandleAccessRequest(w *Response, r *http.Request) *AccessRequest {
// Only allow GET or POST
if r.Method == "GET" {
if !s.Config.AllowGetAccessRequest {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Request must be POST"), "access_request=%s", "GET request not allowed")
return nil
}
} else if r.Method != "POST" {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Request must be POST"), "access_request=%s", "request must be POST")
return nil
}
err := r.ParseForm()
if err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "access_request=%s", "parsing error")
return nil
}
grantType := AccessRequestType(r.FormValue("grant_type"))
if s.Config.AllowedAccessTypes.Exists(grantType) {
switch grantType {
case AUTHORIZATION_CODE:
return s.handleAuthorizationCodeRequest(w, r)
case REFRESH_TOKEN:
return s.handleRefreshTokenRequest(w, r)
case PASSWORD:
return s.handlePasswordRequest(w, r)
case CLIENT_CREDENTIALS:
return s.handleClientCredentialsRequest(w, r)
case ASSERTION:
return s.handleAssertionRequest(w, r)
}
}
s.setErrorAndLog(w, E_UNSUPPORTED_GRANT_TYPE, nil, "access_request=%s", "unknown grant type")
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"HandleAccessRequest",
"(",
"w",
"*",
"Response",
",",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"AccessRequest",
"{",
"// Only allow GET or POST",
"if",
"r",
".",
"Method",
"==",
"\"",
"\"",
"{",
"if",
"!",
"s",
".",
"Config",
".",
"AllowGetAccessRequest",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"else",
"if",
"r",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"err",
":=",
"r",
".",
"ParseForm",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"grantType",
":=",
"AccessRequestType",
"(",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"s",
".",
"Config",
".",
"AllowedAccessTypes",
".",
"Exists",
"(",
"grantType",
")",
"{",
"switch",
"grantType",
"{",
"case",
"AUTHORIZATION_CODE",
":",
"return",
"s",
".",
"handleAuthorizationCodeRequest",
"(",
"w",
",",
"r",
")",
"\n",
"case",
"REFRESH_TOKEN",
":",
"return",
"s",
".",
"handleRefreshTokenRequest",
"(",
"w",
",",
"r",
")",
"\n",
"case",
"PASSWORD",
":",
"return",
"s",
".",
"handlePasswordRequest",
"(",
"w",
",",
"r",
")",
"\n",
"case",
"CLIENT_CREDENTIALS",
":",
"return",
"s",
".",
"handleClientCredentialsRequest",
"(",
"w",
",",
"r",
")",
"\n",
"case",
"ASSERTION",
":",
"return",
"s",
".",
"handleAssertionRequest",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_UNSUPPORTED_GRANT_TYPE",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
]
| // HandleAccessRequest is the http.HandlerFunc for handling access token requests | [
"HandleAccessRequest",
"is",
"the",
"http",
".",
"HandlerFunc",
"for",
"handling",
"access",
"token",
"requests"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/access.go#L114-L150 |
10,224 | openshift/osin | access.go | getClient | func (s Server) getClient(auth *BasicAuth, storage Storage, w *Response) Client {
client, err := storage.GetClient(auth.Username)
if err == ErrNotFound {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "not found")
return nil
}
if err != nil {
s.setErrorAndLog(w, E_SERVER_ERROR, err, "get_client=%s", "error finding client")
return nil
}
if client == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "client is nil")
return nil
}
if !CheckClientSecret(client, auth.Password) {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s, client_id=%v", "client check failed", client.GetId())
return nil
}
if client.GetRedirectUri() == "" {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "client redirect uri is empty")
return nil
}
return client
} | go | func (s Server) getClient(auth *BasicAuth, storage Storage, w *Response) Client {
client, err := storage.GetClient(auth.Username)
if err == ErrNotFound {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "not found")
return nil
}
if err != nil {
s.setErrorAndLog(w, E_SERVER_ERROR, err, "get_client=%s", "error finding client")
return nil
}
if client == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "client is nil")
return nil
}
if !CheckClientSecret(client, auth.Password) {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s, client_id=%v", "client check failed", client.GetId())
return nil
}
if client.GetRedirectUri() == "" {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "client redirect uri is empty")
return nil
}
return client
} | [
"func",
"(",
"s",
"Server",
")",
"getClient",
"(",
"auth",
"*",
"BasicAuth",
",",
"storage",
"Storage",
",",
"w",
"*",
"Response",
")",
"Client",
"{",
"client",
",",
"err",
":=",
"storage",
".",
"GetClient",
"(",
"auth",
".",
"Username",
")",
"\n",
"if",
"err",
"==",
"ErrNotFound",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_UNAUTHORIZED_CLIENT",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_SERVER_ERROR",
",",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"client",
"==",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_UNAUTHORIZED_CLIENT",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"!",
"CheckClientSecret",
"(",
"client",
",",
"auth",
".",
"Password",
")",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_UNAUTHORIZED_CLIENT",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"client",
".",
"GetId",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"client",
".",
"GetRedirectUri",
"(",
")",
"==",
"\"",
"\"",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_UNAUTHORIZED_CLIENT",
",",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"client",
"\n",
"}"
]
| // Helper Functions
// getClient looks up and authenticates the basic auth using the given
// storage. Sets an error on the response if auth fails or a server error occurs. | [
"Helper",
"Functions",
"getClient",
"looks",
"up",
"and",
"authenticates",
"the",
"basic",
"auth",
"using",
"the",
"given",
"storage",
".",
"Sets",
"an",
"error",
"on",
"the",
"response",
"if",
"auth",
"fails",
"or",
"a",
"server",
"error",
"occurs",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/access.go#L529-L554 |
10,225 | openshift/osin | authorize.go | IsExpiredAt | func (d *AuthorizeData) IsExpiredAt(t time.Time) bool {
return d.ExpireAt().Before(t)
} | go | func (d *AuthorizeData) IsExpiredAt(t time.Time) bool {
return d.ExpireAt().Before(t)
} | [
"func",
"(",
"d",
"*",
"AuthorizeData",
")",
"IsExpiredAt",
"(",
"t",
"time",
".",
"Time",
")",
"bool",
"{",
"return",
"d",
".",
"ExpireAt",
"(",
")",
".",
"Before",
"(",
"t",
")",
"\n",
"}"
]
| // IsExpired is true if authorization expires at time 't' | [
"IsExpired",
"is",
"true",
"if",
"authorization",
"expires",
"at",
"time",
"t"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/authorize.go#L90-L92 |
10,226 | openshift/osin | authorize.go | ExpireAt | func (d *AuthorizeData) ExpireAt() time.Time {
return d.CreatedAt.Add(time.Duration(d.ExpiresIn) * time.Second)
} | go | func (d *AuthorizeData) ExpireAt() time.Time {
return d.CreatedAt.Add(time.Duration(d.ExpiresIn) * time.Second)
} | [
"func",
"(",
"d",
"*",
"AuthorizeData",
")",
"ExpireAt",
"(",
")",
"time",
".",
"Time",
"{",
"return",
"d",
".",
"CreatedAt",
".",
"Add",
"(",
"time",
".",
"Duration",
"(",
"d",
".",
"ExpiresIn",
")",
"*",
"time",
".",
"Second",
")",
"\n",
"}"
]
| // ExpireAt returns the expiration date | [
"ExpireAt",
"returns",
"the",
"expiration",
"date"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/authorize.go#L95-L97 |
10,227 | openshift/osin | example/openidconnect/openidconnect.go | handleDiscovery | func handleDiscovery(w http.ResponseWriter, r *http.Request) {
// For other example see: https://accounts.google.com/.well-known/openid-configuration
data := map[string]interface{}{
"issuer": issuer,
"authorization_endpoint": issuer + "/authorize",
"token_endpoint": issuer + "/token",
"jwks_uri": issuer + "/publickeys",
"response_types_supported": []string{"code"},
"subject_types_supported": []string{"public"},
"id_token_signing_alg_values_supported": []string{"RS256"},
"scopes_supported": []string{"openid", "email", "profile"},
"token_endpoint_auth_methods_supported": []string{"client_secret_basic"},
"claims_supported": []string{
"aud", "email", "email_verified", "exp",
"family_name", "given_name", "iat", "iss",
"locale", "name", "sub",
},
}
raw, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Printf("failed to marshal data: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
w.Write(raw)
} | go | func handleDiscovery(w http.ResponseWriter, r *http.Request) {
// For other example see: https://accounts.google.com/.well-known/openid-configuration
data := map[string]interface{}{
"issuer": issuer,
"authorization_endpoint": issuer + "/authorize",
"token_endpoint": issuer + "/token",
"jwks_uri": issuer + "/publickeys",
"response_types_supported": []string{"code"},
"subject_types_supported": []string{"public"},
"id_token_signing_alg_values_supported": []string{"RS256"},
"scopes_supported": []string{"openid", "email", "profile"},
"token_endpoint_auth_methods_supported": []string{"client_secret_basic"},
"claims_supported": []string{
"aud", "email", "email_verified", "exp",
"family_name", "given_name", "iat", "iss",
"locale", "name", "sub",
},
}
raw, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Printf("failed to marshal data: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
w.Write(raw)
} | [
"func",
"handleDiscovery",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"// For other example see: https://accounts.google.com/.well-known/openid-configuration",
"data",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"issuer",
",",
"\"",
"\"",
":",
"issuer",
"+",
"\"",
"\"",
",",
"\"",
"\"",
":",
"issuer",
"+",
"\"",
"\"",
",",
"\"",
"\"",
":",
"issuer",
"+",
"\"",
"\"",
",",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
",",
"}",
"\n\n",
"raw",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"data",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"raw",
")",
")",
")",
"\n",
"w",
".",
"Write",
"(",
"raw",
")",
"\n",
"}"
]
| // handleDiscovery returns the OpenID Connect discovery object, allowing clients
// to discover OAuth2 resources. | [
"handleDiscovery",
"returns",
"the",
"OpenID",
"Connect",
"discovery",
"object",
"allowing",
"clients",
"to",
"discover",
"OAuth2",
"resources",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/example/openidconnect/openidconnect.go#L100-L128 |
10,228 | openshift/osin | example/openidconnect/openidconnect.go | handlePublicKeys | func handlePublicKeys(w http.ResponseWriter, r *http.Request) {
raw, err := json.MarshalIndent(publicKeys, "", " ")
if err != nil {
log.Printf("failed to marshal data: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
w.Write(raw)
} | go | func handlePublicKeys(w http.ResponseWriter, r *http.Request) {
raw, err := json.MarshalIndent(publicKeys, "", " ")
if err != nil {
log.Printf("failed to marshal data: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
w.Write(raw)
} | [
"func",
"handlePublicKeys",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"raw",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"publicKeys",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"raw",
")",
")",
")",
"\n",
"w",
".",
"Write",
"(",
"raw",
")",
"\n",
"}"
]
| // handlePublicKeys publishes the public part of this server's signing keys.
// This allows clients to verify the signature of ID Tokens. | [
"handlePublicKeys",
"publishes",
"the",
"public",
"part",
"of",
"this",
"server",
"s",
"signing",
"keys",
".",
"This",
"allows",
"clients",
"to",
"verify",
"the",
"signature",
"of",
"ID",
"Tokens",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/example/openidconnect/openidconnect.go#L132-L142 |
10,229 | openshift/osin | example/openidconnect/openidconnect.go | encodeIDToken | func encodeIDToken(resp *osin.Response, idToken *IDToken, singer jose.Signer) {
resp.InternalError = func() error {
payload, err := json.Marshal(idToken)
if err != nil {
return fmt.Errorf("failed to marshal token: %v", err)
}
jws, err := jwtSigner.Sign(payload)
if err != nil {
return fmt.Errorf("failed to sign token: %v", err)
}
raw, err := jws.CompactSerialize()
if err != nil {
return fmt.Errorf("failed to serialize token: %v", err)
}
resp.Output["id_token"] = raw
return nil
}()
// Record errors as internal server errors.
if resp.InternalError != nil {
resp.IsError = true
resp.ErrorId = osin.E_SERVER_ERROR
}
} | go | func encodeIDToken(resp *osin.Response, idToken *IDToken, singer jose.Signer) {
resp.InternalError = func() error {
payload, err := json.Marshal(idToken)
if err != nil {
return fmt.Errorf("failed to marshal token: %v", err)
}
jws, err := jwtSigner.Sign(payload)
if err != nil {
return fmt.Errorf("failed to sign token: %v", err)
}
raw, err := jws.CompactSerialize()
if err != nil {
return fmt.Errorf("failed to serialize token: %v", err)
}
resp.Output["id_token"] = raw
return nil
}()
// Record errors as internal server errors.
if resp.InternalError != nil {
resp.IsError = true
resp.ErrorId = osin.E_SERVER_ERROR
}
} | [
"func",
"encodeIDToken",
"(",
"resp",
"*",
"osin",
".",
"Response",
",",
"idToken",
"*",
"IDToken",
",",
"singer",
"jose",
".",
"Signer",
")",
"{",
"resp",
".",
"InternalError",
"=",
"func",
"(",
")",
"error",
"{",
"payload",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"idToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"jws",
",",
"err",
":=",
"jwtSigner",
".",
"Sign",
"(",
"payload",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"raw",
",",
"err",
":=",
"jws",
".",
"CompactSerialize",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"resp",
".",
"Output",
"[",
"\"",
"\"",
"]",
"=",
"raw",
"\n",
"return",
"nil",
"\n",
"}",
"(",
")",
"\n\n",
"// Record errors as internal server errors.",
"if",
"resp",
".",
"InternalError",
"!=",
"nil",
"{",
"resp",
".",
"IsError",
"=",
"true",
"\n",
"resp",
".",
"ErrorId",
"=",
"osin",
".",
"E_SERVER_ERROR",
"\n",
"}",
"\n",
"}"
]
| // encodeIDToken serializes and signs an ID Token then adds a field to the token response. | [
"encodeIDToken",
"serializes",
"and",
"signs",
"an",
"ID",
"Token",
"then",
"adds",
"a",
"field",
"to",
"the",
"token",
"response",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/example/openidconnect/openidconnect.go#L220-L243 |
10,230 | openshift/osin | util.go | CheckClientSecret | func CheckClientSecret(client Client, secret string) bool {
switch client := client.(type) {
case ClientSecretMatcher:
// Prefer the more secure method of giving the secret to the client for comparison
return client.ClientSecretMatches(secret)
default:
// Fallback to the less secure method of extracting the plain text secret from the client for comparison
return client.GetSecret() == secret
}
} | go | func CheckClientSecret(client Client, secret string) bool {
switch client := client.(type) {
case ClientSecretMatcher:
// Prefer the more secure method of giving the secret to the client for comparison
return client.ClientSecretMatches(secret)
default:
// Fallback to the less secure method of extracting the plain text secret from the client for comparison
return client.GetSecret() == secret
}
} | [
"func",
"CheckClientSecret",
"(",
"client",
"Client",
",",
"secret",
"string",
")",
"bool",
"{",
"switch",
"client",
":=",
"client",
".",
"(",
"type",
")",
"{",
"case",
"ClientSecretMatcher",
":",
"// Prefer the more secure method of giving the secret to the client for comparison",
"return",
"client",
".",
"ClientSecretMatches",
"(",
"secret",
")",
"\n",
"default",
":",
"// Fallback to the less secure method of extracting the plain text secret from the client for comparison",
"return",
"client",
".",
"GetSecret",
"(",
")",
"==",
"secret",
"\n",
"}",
"\n",
"}"
]
| // CheckClientSecret determines whether the given secret matches a secret held by the client.
// Public clients return true for a secret of "" | [
"CheckClientSecret",
"determines",
"whether",
"the",
"given",
"secret",
"matches",
"a",
"secret",
"held",
"by",
"the",
"client",
".",
"Public",
"clients",
"return",
"true",
"for",
"a",
"secret",
"of"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/util.go#L24-L33 |
10,231 | openshift/osin | util.go | CheckBasicAuth | func CheckBasicAuth(r *http.Request) (*BasicAuth, error) {
if r.Header.Get("Authorization") == "" {
return nil, nil
}
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 || s[0] != "Basic" {
return nil, errors.New("Invalid authorization header")
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return nil, err
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return nil, errors.New("Invalid authorization message")
}
// Decode the client_id and client_secret pairs as per
// https://tools.ietf.org/html/rfc6749#section-2.3.1
username, err := url.QueryUnescape(pair[0])
if err != nil {
return nil, err
}
password, err := url.QueryUnescape(pair[1])
if err != nil {
return nil, err
}
return &BasicAuth{Username: username, Password: password}, nil
} | go | func CheckBasicAuth(r *http.Request) (*BasicAuth, error) {
if r.Header.Get("Authorization") == "" {
return nil, nil
}
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 || s[0] != "Basic" {
return nil, errors.New("Invalid authorization header")
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return nil, err
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return nil, errors.New("Invalid authorization message")
}
// Decode the client_id and client_secret pairs as per
// https://tools.ietf.org/html/rfc6749#section-2.3.1
username, err := url.QueryUnescape(pair[0])
if err != nil {
return nil, err
}
password, err := url.QueryUnescape(pair[1])
if err != nil {
return nil, err
}
return &BasicAuth{Username: username, Password: password}, nil
} | [
"func",
"CheckBasicAuth",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"BasicAuth",
",",
"error",
")",
"{",
"if",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"s",
":=",
"strings",
".",
"SplitN",
"(",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"s",
")",
"!=",
"2",
"||",
"s",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"s",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"pair",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"b",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"pair",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Decode the client_id and client_secret pairs as per",
"// https://tools.ietf.org/html/rfc6749#section-2.3.1",
"username",
",",
"err",
":=",
"url",
".",
"QueryUnescape",
"(",
"pair",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"password",
",",
"err",
":=",
"url",
".",
"QueryUnescape",
"(",
"pair",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"BasicAuth",
"{",
"Username",
":",
"username",
",",
"Password",
":",
"password",
"}",
",",
"nil",
"\n",
"}"
]
| // Return authorization header data | [
"Return",
"authorization",
"header",
"data"
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/util.go#L36-L69 |
10,232 | openshift/osin | util.go | CheckBearerAuth | func CheckBearerAuth(r *http.Request) *BearerAuth {
authHeader := r.Header.Get("Authorization")
authForm := r.FormValue("code")
if authHeader == "" && authForm == "" {
return nil
}
token := authForm
if authHeader != "" {
s := strings.SplitN(authHeader, " ", 2)
if (len(s) != 2 || strings.ToLower(s[0]) != "bearer") && token == "" {
return nil
}
//Use authorization header token only if token type is bearer else query string access token would be returned
if len(s) > 0 && strings.ToLower(s[0]) == "bearer" {
token = s[1]
}
}
return &BearerAuth{Code: token}
} | go | func CheckBearerAuth(r *http.Request) *BearerAuth {
authHeader := r.Header.Get("Authorization")
authForm := r.FormValue("code")
if authHeader == "" && authForm == "" {
return nil
}
token := authForm
if authHeader != "" {
s := strings.SplitN(authHeader, " ", 2)
if (len(s) != 2 || strings.ToLower(s[0]) != "bearer") && token == "" {
return nil
}
//Use authorization header token only if token type is bearer else query string access token would be returned
if len(s) > 0 && strings.ToLower(s[0]) == "bearer" {
token = s[1]
}
}
return &BearerAuth{Code: token}
} | [
"func",
"CheckBearerAuth",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"BearerAuth",
"{",
"authHeader",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"authForm",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"authHeader",
"==",
"\"",
"\"",
"&&",
"authForm",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"token",
":=",
"authForm",
"\n",
"if",
"authHeader",
"!=",
"\"",
"\"",
"{",
"s",
":=",
"strings",
".",
"SplitN",
"(",
"authHeader",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"(",
"len",
"(",
"s",
")",
"!=",
"2",
"||",
"strings",
".",
"ToLower",
"(",
"s",
"[",
"0",
"]",
")",
"!=",
"\"",
"\"",
")",
"&&",
"token",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"//Use authorization header token only if token type is bearer else query string access token would be returned",
"if",
"len",
"(",
"s",
")",
">",
"0",
"&&",
"strings",
".",
"ToLower",
"(",
"s",
"[",
"0",
"]",
")",
"==",
"\"",
"\"",
"{",
"token",
"=",
"s",
"[",
"1",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"BearerAuth",
"{",
"Code",
":",
"token",
"}",
"\n",
"}"
]
| // Return "Bearer" token from request. The header has precedence over query string. | [
"Return",
"Bearer",
"token",
"from",
"request",
".",
"The",
"header",
"has",
"precedence",
"over",
"query",
"string",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/util.go#L72-L90 |
10,233 | openshift/osin | util.go | getClientAuth | func (s Server) getClientAuth(w *Response, r *http.Request, allowQueryParams bool) *BasicAuth {
if allowQueryParams {
// Allow for auth without password
if _, hasSecret := r.Form["client_secret"]; hasSecret {
auth := &BasicAuth{
Username: r.FormValue("client_id"),
Password: r.FormValue("client_secret"),
}
if auth.Username != "" {
return auth
}
}
}
auth, err := CheckBasicAuth(r)
if err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "get_client_auth=%s", "check auth error")
return nil
}
if auth == nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Client authentication not sent"), "get_client_auth=%s", "client authentication not sent")
return nil
}
return auth
} | go | func (s Server) getClientAuth(w *Response, r *http.Request, allowQueryParams bool) *BasicAuth {
if allowQueryParams {
// Allow for auth without password
if _, hasSecret := r.Form["client_secret"]; hasSecret {
auth := &BasicAuth{
Username: r.FormValue("client_id"),
Password: r.FormValue("client_secret"),
}
if auth.Username != "" {
return auth
}
}
}
auth, err := CheckBasicAuth(r)
if err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "get_client_auth=%s", "check auth error")
return nil
}
if auth == nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Client authentication not sent"), "get_client_auth=%s", "client authentication not sent")
return nil
}
return auth
} | [
"func",
"(",
"s",
"Server",
")",
"getClientAuth",
"(",
"w",
"*",
"Response",
",",
"r",
"*",
"http",
".",
"Request",
",",
"allowQueryParams",
"bool",
")",
"*",
"BasicAuth",
"{",
"if",
"allowQueryParams",
"{",
"// Allow for auth without password",
"if",
"_",
",",
"hasSecret",
":=",
"r",
".",
"Form",
"[",
"\"",
"\"",
"]",
";",
"hasSecret",
"{",
"auth",
":=",
"&",
"BasicAuth",
"{",
"Username",
":",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
",",
"Password",
":",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"if",
"auth",
".",
"Username",
"!=",
"\"",
"\"",
"{",
"return",
"auth",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"auth",
",",
"err",
":=",
"CheckBasicAuth",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"auth",
"==",
"nil",
"{",
"s",
".",
"setErrorAndLog",
"(",
"w",
",",
"E_INVALID_REQUEST",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"auth",
"\n",
"}"
]
| // getClientAuth checks client basic authentication in params if allowed,
// otherwise gets it from the header.
// Sets an error on the response if no auth is present or a server error occurs. | [
"getClientAuth",
"checks",
"client",
"basic",
"authentication",
"in",
"params",
"if",
"allowed",
"otherwise",
"gets",
"it",
"from",
"the",
"header",
".",
"Sets",
"an",
"error",
"on",
"the",
"response",
"if",
"no",
"auth",
"is",
"present",
"or",
"a",
"server",
"error",
"occurs",
"."
]
| 0f3357bb07e801ea62327872d19913969001dd7a | https://github.com/openshift/osin/blob/0f3357bb07e801ea62327872d19913969001dd7a/util.go#L95-L120 |
10,234 | go-openapi/runtime | middleware/denco/router.go | Build | func (rt *Router) Build(records []Record) error {
statics, params := makeRecords(records)
if len(params) > MaxSize {
return fmt.Errorf("denco: too many records")
}
if rt.SizeHint < 0 {
rt.SizeHint = 0
for _, p := range params {
size := 0
for _, k := range p.Key {
if k == ParamCharacter || k == WildcardCharacter {
size++
}
}
if size > rt.SizeHint {
rt.SizeHint = size
}
}
}
for _, r := range statics {
rt.static[r.Key] = r.Value
}
if err := rt.param.build(params, 1, 0, make(map[int]struct{})); err != nil {
return err
}
return nil
} | go | func (rt *Router) Build(records []Record) error {
statics, params := makeRecords(records)
if len(params) > MaxSize {
return fmt.Errorf("denco: too many records")
}
if rt.SizeHint < 0 {
rt.SizeHint = 0
for _, p := range params {
size := 0
for _, k := range p.Key {
if k == ParamCharacter || k == WildcardCharacter {
size++
}
}
if size > rt.SizeHint {
rt.SizeHint = size
}
}
}
for _, r := range statics {
rt.static[r.Key] = r.Value
}
if err := rt.param.build(params, 1, 0, make(map[int]struct{})); err != nil {
return err
}
return nil
} | [
"func",
"(",
"rt",
"*",
"Router",
")",
"Build",
"(",
"records",
"[",
"]",
"Record",
")",
"error",
"{",
"statics",
",",
"params",
":=",
"makeRecords",
"(",
"records",
")",
"\n",
"if",
"len",
"(",
"params",
")",
">",
"MaxSize",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"rt",
".",
"SizeHint",
"<",
"0",
"{",
"rt",
".",
"SizeHint",
"=",
"0",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"params",
"{",
"size",
":=",
"0",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"p",
".",
"Key",
"{",
"if",
"k",
"==",
"ParamCharacter",
"||",
"k",
"==",
"WildcardCharacter",
"{",
"size",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"size",
">",
"rt",
".",
"SizeHint",
"{",
"rt",
".",
"SizeHint",
"=",
"size",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"statics",
"{",
"rt",
".",
"static",
"[",
"r",
".",
"Key",
"]",
"=",
"r",
".",
"Value",
"\n",
"}",
"\n",
"if",
"err",
":=",
"rt",
".",
"param",
".",
"build",
"(",
"params",
",",
"1",
",",
"0",
",",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // Build builds URL router from records. | [
"Build",
"builds",
"URL",
"router",
"from",
"records",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L65-L91 |
10,235 | go-openapi/runtime | middleware/denco/router.go | Get | func (ps Params) Get(name string) string {
for _, p := range ps {
if p.Name == name {
return p.Value
}
}
return ""
} | go | func (ps Params) Get(name string) string {
for _, p := range ps {
if p.Name == name {
return p.Value
}
}
return ""
} | [
"func",
"(",
"ps",
"Params",
")",
"Get",
"(",
"name",
"string",
")",
"string",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"ps",
"{",
"if",
"p",
".",
"Name",
"==",
"name",
"{",
"return",
"p",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
]
| // Get gets the first value associated with the given name.
// If there are no values associated with the key, Get returns "". | [
"Get",
"gets",
"the",
"first",
"value",
"associated",
"with",
"the",
"given",
"name",
".",
"If",
"there",
"are",
"no",
"values",
"associated",
"with",
"the",
"key",
"Get",
"returns",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L104-L111 |
10,236 | go-openapi/runtime | middleware/denco/router.go | build | func (da *doubleArray) build(srcs []*record, idx, depth int, usedBase map[int]struct{}) error {
sort.Stable(recordSlice(srcs))
base, siblings, leaf, err := da.arrange(srcs, idx, depth, usedBase)
if err != nil {
return err
}
if leaf != nil {
nd, err := makeNode(leaf)
if err != nil {
return err
}
da.bc[idx].SetBase(len(da.node))
da.node = append(da.node, nd)
}
for _, sib := range siblings {
da.setCheck(nextIndex(base, sib.c), sib.c)
}
for _, sib := range siblings {
records := srcs[sib.start:sib.end]
switch sib.c {
case ParamCharacter:
for _, r := range records {
next := NextSeparator(r.Key, depth+1)
name := r.Key[depth+1 : next]
r.paramNames = append(r.paramNames, name)
r.Key = r.Key[next:]
}
da.bc[idx].SetSingleParam()
if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil {
return err
}
case WildcardCharacter:
r := records[0]
name := r.Key[depth+1 : len(r.Key)-1]
r.paramNames = append(r.paramNames, name)
r.Key = ""
da.bc[idx].SetWildcardParam()
if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil {
return err
}
default:
if err := da.build(records, nextIndex(base, sib.c), depth+1, usedBase); err != nil {
return err
}
}
}
return nil
} | go | func (da *doubleArray) build(srcs []*record, idx, depth int, usedBase map[int]struct{}) error {
sort.Stable(recordSlice(srcs))
base, siblings, leaf, err := da.arrange(srcs, idx, depth, usedBase)
if err != nil {
return err
}
if leaf != nil {
nd, err := makeNode(leaf)
if err != nil {
return err
}
da.bc[idx].SetBase(len(da.node))
da.node = append(da.node, nd)
}
for _, sib := range siblings {
da.setCheck(nextIndex(base, sib.c), sib.c)
}
for _, sib := range siblings {
records := srcs[sib.start:sib.end]
switch sib.c {
case ParamCharacter:
for _, r := range records {
next := NextSeparator(r.Key, depth+1)
name := r.Key[depth+1 : next]
r.paramNames = append(r.paramNames, name)
r.Key = r.Key[next:]
}
da.bc[idx].SetSingleParam()
if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil {
return err
}
case WildcardCharacter:
r := records[0]
name := r.Key[depth+1 : len(r.Key)-1]
r.paramNames = append(r.paramNames, name)
r.Key = ""
da.bc[idx].SetWildcardParam()
if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil {
return err
}
default:
if err := da.build(records, nextIndex(base, sib.c), depth+1, usedBase); err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"da",
"*",
"doubleArray",
")",
"build",
"(",
"srcs",
"[",
"]",
"*",
"record",
",",
"idx",
",",
"depth",
"int",
",",
"usedBase",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"error",
"{",
"sort",
".",
"Stable",
"(",
"recordSlice",
"(",
"srcs",
")",
")",
"\n",
"base",
",",
"siblings",
",",
"leaf",
",",
"err",
":=",
"da",
".",
"arrange",
"(",
"srcs",
",",
"idx",
",",
"depth",
",",
"usedBase",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"leaf",
"!=",
"nil",
"{",
"nd",
",",
"err",
":=",
"makeNode",
"(",
"leaf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"da",
".",
"bc",
"[",
"idx",
"]",
".",
"SetBase",
"(",
"len",
"(",
"da",
".",
"node",
")",
")",
"\n",
"da",
".",
"node",
"=",
"append",
"(",
"da",
".",
"node",
",",
"nd",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"sib",
":=",
"range",
"siblings",
"{",
"da",
".",
"setCheck",
"(",
"nextIndex",
"(",
"base",
",",
"sib",
".",
"c",
")",
",",
"sib",
".",
"c",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"sib",
":=",
"range",
"siblings",
"{",
"records",
":=",
"srcs",
"[",
"sib",
".",
"start",
":",
"sib",
".",
"end",
"]",
"\n",
"switch",
"sib",
".",
"c",
"{",
"case",
"ParamCharacter",
":",
"for",
"_",
",",
"r",
":=",
"range",
"records",
"{",
"next",
":=",
"NextSeparator",
"(",
"r",
".",
"Key",
",",
"depth",
"+",
"1",
")",
"\n",
"name",
":=",
"r",
".",
"Key",
"[",
"depth",
"+",
"1",
":",
"next",
"]",
"\n",
"r",
".",
"paramNames",
"=",
"append",
"(",
"r",
".",
"paramNames",
",",
"name",
")",
"\n",
"r",
".",
"Key",
"=",
"r",
".",
"Key",
"[",
"next",
":",
"]",
"\n",
"}",
"\n",
"da",
".",
"bc",
"[",
"idx",
"]",
".",
"SetSingleParam",
"(",
")",
"\n",
"if",
"err",
":=",
"da",
".",
"build",
"(",
"records",
",",
"nextIndex",
"(",
"base",
",",
"sib",
".",
"c",
")",
",",
"0",
",",
"usedBase",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"case",
"WildcardCharacter",
":",
"r",
":=",
"records",
"[",
"0",
"]",
"\n",
"name",
":=",
"r",
".",
"Key",
"[",
"depth",
"+",
"1",
":",
"len",
"(",
"r",
".",
"Key",
")",
"-",
"1",
"]",
"\n",
"r",
".",
"paramNames",
"=",
"append",
"(",
"r",
".",
"paramNames",
",",
"name",
")",
"\n",
"r",
".",
"Key",
"=",
"\"",
"\"",
"\n",
"da",
".",
"bc",
"[",
"idx",
"]",
".",
"SetWildcardParam",
"(",
")",
"\n",
"if",
"err",
":=",
"da",
".",
"build",
"(",
"records",
",",
"nextIndex",
"(",
"base",
",",
"sib",
".",
"c",
")",
",",
"0",
",",
"usedBase",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"default",
":",
"if",
"err",
":=",
"da",
".",
"build",
"(",
"records",
",",
"nextIndex",
"(",
"base",
",",
"sib",
".",
"c",
")",
",",
"depth",
"+",
"1",
",",
"usedBase",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // build builds double-array from records. | [
"build",
"builds",
"double",
"-",
"array",
"from",
"records",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L217-L264 |
10,237 | go-openapi/runtime | middleware/denco/router.go | setBase | func (da *doubleArray) setBase(i, base int) {
da.bc[i].SetBase(base)
} | go | func (da *doubleArray) setBase(i, base int) {
da.bc[i].SetBase(base)
} | [
"func",
"(",
"da",
"*",
"doubleArray",
")",
"setBase",
"(",
"i",
",",
"base",
"int",
")",
"{",
"da",
".",
"bc",
"[",
"i",
"]",
".",
"SetBase",
"(",
"base",
")",
"\n",
"}"
]
| // setBase sets BASE. | [
"setBase",
"sets",
"BASE",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L267-L269 |
10,238 | go-openapi/runtime | middleware/denco/router.go | setCheck | func (da *doubleArray) setCheck(i int, check byte) {
da.bc[i].SetCheck(check)
} | go | func (da *doubleArray) setCheck(i int, check byte) {
da.bc[i].SetCheck(check)
} | [
"func",
"(",
"da",
"*",
"doubleArray",
")",
"setCheck",
"(",
"i",
"int",
",",
"check",
"byte",
")",
"{",
"da",
".",
"bc",
"[",
"i",
"]",
".",
"SetCheck",
"(",
"check",
")",
"\n",
"}"
]
| // setCheck sets CHECK. | [
"setCheck",
"sets",
"CHECK",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L272-L274 |
10,239 | go-openapi/runtime | middleware/denco/router.go | makeNode | func makeNode(r *record) (*node, error) {
dups := make(map[string]bool)
for _, name := range r.paramNames {
if dups[name] {
return nil, fmt.Errorf("denco: path parameter `%v' is duplicated in the key `%v'", name, r.Key)
}
dups[name] = true
}
return &node{data: r.Value, paramNames: r.paramNames}, nil
} | go | func makeNode(r *record) (*node, error) {
dups := make(map[string]bool)
for _, name := range r.paramNames {
if dups[name] {
return nil, fmt.Errorf("denco: path parameter `%v' is duplicated in the key `%v'", name, r.Key)
}
dups[name] = true
}
return &node{data: r.Value, paramNames: r.paramNames}, nil
} | [
"func",
"makeNode",
"(",
"r",
"*",
"record",
")",
"(",
"*",
"node",
",",
"error",
")",
"{",
"dups",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"r",
".",
"paramNames",
"{",
"if",
"dups",
"[",
"name",
"]",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"r",
".",
"Key",
")",
"\n",
"}",
"\n",
"dups",
"[",
"name",
"]",
"=",
"true",
"\n",
"}",
"\n",
"return",
"&",
"node",
"{",
"data",
":",
"r",
".",
"Value",
",",
"paramNames",
":",
"r",
".",
"paramNames",
"}",
",",
"nil",
"\n",
"}"
]
| // makeNode returns a new node from record. | [
"makeNode",
"returns",
"a",
"new",
"node",
"from",
"record",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L337-L346 |
10,240 | go-openapi/runtime | middleware/denco/router.go | NewRecord | func NewRecord(key string, value interface{}) Record {
return Record{
Key: key,
Value: value,
}
} | go | func NewRecord(key string, value interface{}) Record {
return Record{
Key: key,
Value: value,
}
} | [
"func",
"NewRecord",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"Record",
"{",
"return",
"Record",
"{",
"Key",
":",
"key",
",",
"Value",
":",
"value",
",",
"}",
"\n",
"}"
]
| // NewRecord returns a new Record. | [
"NewRecord",
"returns",
"a",
"new",
"Record",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L408-L413 |
10,241 | go-openapi/runtime | middleware/denco/router.go | makeRecords | func makeRecords(srcs []Record) (statics, params []*record) {
spChars := string([]byte{ParamCharacter, WildcardCharacter})
termChar := string(TerminationCharacter)
for _, r := range srcs {
if strings.ContainsAny(r.Key, spChars) {
r.Key += termChar
params = append(params, &record{Record: r})
} else {
statics = append(statics, &record{Record: r})
}
}
return statics, params
} | go | func makeRecords(srcs []Record) (statics, params []*record) {
spChars := string([]byte{ParamCharacter, WildcardCharacter})
termChar := string(TerminationCharacter)
for _, r := range srcs {
if strings.ContainsAny(r.Key, spChars) {
r.Key += termChar
params = append(params, &record{Record: r})
} else {
statics = append(statics, &record{Record: r})
}
}
return statics, params
} | [
"func",
"makeRecords",
"(",
"srcs",
"[",
"]",
"Record",
")",
"(",
"statics",
",",
"params",
"[",
"]",
"*",
"record",
")",
"{",
"spChars",
":=",
"string",
"(",
"[",
"]",
"byte",
"{",
"ParamCharacter",
",",
"WildcardCharacter",
"}",
")",
"\n",
"termChar",
":=",
"string",
"(",
"TerminationCharacter",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"srcs",
"{",
"if",
"strings",
".",
"ContainsAny",
"(",
"r",
".",
"Key",
",",
"spChars",
")",
"{",
"r",
".",
"Key",
"+=",
"termChar",
"\n",
"params",
"=",
"append",
"(",
"params",
",",
"&",
"record",
"{",
"Record",
":",
"r",
"}",
")",
"\n",
"}",
"else",
"{",
"statics",
"=",
"append",
"(",
"statics",
",",
"&",
"record",
"{",
"Record",
":",
"r",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"statics",
",",
"params",
"\n",
"}"
]
| // makeRecords returns the records that use to build Double-Arrays. | [
"makeRecords",
"returns",
"the",
"records",
"that",
"use",
"to",
"build",
"Double",
"-",
"Arrays",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L422-L434 |
10,242 | go-openapi/runtime | middleware/denco/router.go | Less | func (rs recordSlice) Less(i, j int) bool {
return rs[i].Key < rs[j].Key
} | go | func (rs recordSlice) Less(i, j int) bool {
return rs[i].Key < rs[j].Key
} | [
"func",
"(",
"rs",
"recordSlice",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"rs",
"[",
"i",
"]",
".",
"Key",
"<",
"rs",
"[",
"j",
"]",
".",
"Key",
"\n",
"}"
]
| // Less implements the sort.Interface.Less. | [
"Less",
"implements",
"the",
"sort",
".",
"Interface",
".",
"Less",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L445-L447 |
10,243 | go-openapi/runtime | middleware/denco/router.go | Swap | func (rs recordSlice) Swap(i, j int) {
rs[i], rs[j] = rs[j], rs[i]
} | go | func (rs recordSlice) Swap(i, j int) {
rs[i], rs[j] = rs[j], rs[i]
} | [
"func",
"(",
"rs",
"recordSlice",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"rs",
"[",
"i",
"]",
",",
"rs",
"[",
"j",
"]",
"=",
"rs",
"[",
"j",
"]",
",",
"rs",
"[",
"i",
"]",
"\n",
"}"
]
| // Swap implements the sort.Interface.Swap. | [
"Swap",
"implements",
"the",
"sort",
".",
"Interface",
".",
"Swap",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/denco/router.go#L450-L452 |
10,244 | go-openapi/runtime | client/auth_info.go | BasicAuth | func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return r.SetHeaderParam("Authorization", "Basic "+encoded)
})
} | go | func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return r.SetHeaderParam("Authorization", "Basic "+encoded)
})
} | [
"func",
"BasicAuth",
"(",
"username",
",",
"password",
"string",
")",
"runtime",
".",
"ClientAuthInfoWriter",
"{",
"return",
"runtime",
".",
"ClientAuthInfoWriterFunc",
"(",
"func",
"(",
"r",
"runtime",
".",
"ClientRequest",
",",
"_",
"strfmt",
".",
"Registry",
")",
"error",
"{",
"encoded",
":=",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
"(",
"username",
"+",
"\"",
"\"",
"+",
"password",
")",
")",
"\n",
"return",
"r",
".",
"SetHeaderParam",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"encoded",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // BasicAuth provides a basic auth info writer | [
"BasicAuth",
"provides",
"a",
"basic",
"auth",
"info",
"writer"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/auth_info.go#L32-L37 |
10,245 | go-openapi/runtime | client/auth_info.go | APIKeyAuth | func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter {
if in == "query" {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return r.SetQueryParam(name, value)
})
}
if in == "header" {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return r.SetHeaderParam(name, value)
})
}
return nil
} | go | func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter {
if in == "query" {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return r.SetQueryParam(name, value)
})
}
if in == "header" {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return r.SetHeaderParam(name, value)
})
}
return nil
} | [
"func",
"APIKeyAuth",
"(",
"name",
",",
"in",
",",
"value",
"string",
")",
"runtime",
".",
"ClientAuthInfoWriter",
"{",
"if",
"in",
"==",
"\"",
"\"",
"{",
"return",
"runtime",
".",
"ClientAuthInfoWriterFunc",
"(",
"func",
"(",
"r",
"runtime",
".",
"ClientRequest",
",",
"_",
"strfmt",
".",
"Registry",
")",
"error",
"{",
"return",
"r",
".",
"SetQueryParam",
"(",
"name",
",",
"value",
")",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"if",
"in",
"==",
"\"",
"\"",
"{",
"return",
"runtime",
".",
"ClientAuthInfoWriterFunc",
"(",
"func",
"(",
"r",
"runtime",
".",
"ClientRequest",
",",
"_",
"strfmt",
".",
"Registry",
")",
"error",
"{",
"return",
"r",
".",
"SetHeaderParam",
"(",
"name",
",",
"value",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // APIKeyAuth provides an API key auth info writer | [
"APIKeyAuth",
"provides",
"an",
"API",
"key",
"auth",
"info",
"writer"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/auth_info.go#L40-L53 |
10,246 | go-openapi/runtime | client/auth_info.go | BearerToken | func BearerToken(token string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return r.SetHeaderParam("Authorization", "Bearer "+token)
})
} | go | func BearerToken(token string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return r.SetHeaderParam("Authorization", "Bearer "+token)
})
} | [
"func",
"BearerToken",
"(",
"token",
"string",
")",
"runtime",
".",
"ClientAuthInfoWriter",
"{",
"return",
"runtime",
".",
"ClientAuthInfoWriterFunc",
"(",
"func",
"(",
"r",
"runtime",
".",
"ClientRequest",
",",
"_",
"strfmt",
".",
"Registry",
")",
"error",
"{",
"return",
"r",
".",
"SetHeaderParam",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"token",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // BearerToken provides a header based oauth2 bearer access token auth info writer | [
"BearerToken",
"provides",
"a",
"header",
"based",
"oauth2",
"bearer",
"access",
"token",
"auth",
"info",
"writer"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/auth_info.go#L56-L60 |
10,247 | go-openapi/runtime | file.go | Read | func (f *File) Read(p []byte) (n int, err error) {
return f.Data.Read(p)
} | go | func (f *File) Read(p []byte) (n int, err error) {
return f.Data.Read(p)
} | [
"func",
"(",
"f",
"*",
"File",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"return",
"f",
".",
"Data",
".",
"Read",
"(",
"p",
")",
"\n",
"}"
]
| // Read bytes from the file | [
"Read",
"bytes",
"from",
"the",
"file"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/file.go#L26-L28 |
10,248 | go-openapi/runtime | client_response.go | ReadResponse | func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (interface{}, error) {
return read(resp, consumer)
} | go | func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (interface{}, error) {
return read(resp, consumer)
} | [
"func",
"(",
"read",
"ClientResponseReaderFunc",
")",
"ReadResponse",
"(",
"resp",
"ClientResponse",
",",
"consumer",
"Consumer",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"read",
"(",
"resp",
",",
"consumer",
")",
"\n",
"}"
]
| // ReadResponse reads the response | [
"ReadResponse",
"reads",
"the",
"response"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client_response.go#L35-L37 |
10,249 | go-openapi/runtime | client_response.go | NewAPIError | func NewAPIError(opName string, payload interface{}, code int) *APIError {
return &APIError{
OperationName: opName,
Response: payload,
Code: code,
}
} | go | func NewAPIError(opName string, payload interface{}, code int) *APIError {
return &APIError{
OperationName: opName,
Response: payload,
Code: code,
}
} | [
"func",
"NewAPIError",
"(",
"opName",
"string",
",",
"payload",
"interface",
"{",
"}",
",",
"code",
"int",
")",
"*",
"APIError",
"{",
"return",
"&",
"APIError",
"{",
"OperationName",
":",
"opName",
",",
"Response",
":",
"payload",
",",
"Code",
":",
"code",
",",
"}",
"\n",
"}"
]
| // NewAPIError creates a new API error | [
"NewAPIError",
"creates",
"a",
"new",
"API",
"error"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client_response.go#L46-L52 |
10,250 | go-openapi/runtime | middleware/untyped/api.go | NewAPI | func NewAPI(spec *loads.Document) *API {
var an *analysis.Spec
if spec != nil && spec.Spec() != nil {
an = analysis.New(spec.Spec())
}
api := &API{
spec: spec,
analyzer: an,
consumers: make(map[string]runtime.Consumer, 10),
producers: make(map[string]runtime.Producer, 10),
authenticators: make(map[string]runtime.Authenticator),
operations: make(map[string]map[string]runtime.OperationHandler),
ServeError: errors.ServeError,
Models: make(map[string]func() interface{}),
formats: strfmt.NewFormats(),
}
return api.WithJSONDefaults()
} | go | func NewAPI(spec *loads.Document) *API {
var an *analysis.Spec
if spec != nil && spec.Spec() != nil {
an = analysis.New(spec.Spec())
}
api := &API{
spec: spec,
analyzer: an,
consumers: make(map[string]runtime.Consumer, 10),
producers: make(map[string]runtime.Producer, 10),
authenticators: make(map[string]runtime.Authenticator),
operations: make(map[string]map[string]runtime.OperationHandler),
ServeError: errors.ServeError,
Models: make(map[string]func() interface{}),
formats: strfmt.NewFormats(),
}
return api.WithJSONDefaults()
} | [
"func",
"NewAPI",
"(",
"spec",
"*",
"loads",
".",
"Document",
")",
"*",
"API",
"{",
"var",
"an",
"*",
"analysis",
".",
"Spec",
"\n",
"if",
"spec",
"!=",
"nil",
"&&",
"spec",
".",
"Spec",
"(",
")",
"!=",
"nil",
"{",
"an",
"=",
"analysis",
".",
"New",
"(",
"spec",
".",
"Spec",
"(",
")",
")",
"\n",
"}",
"\n",
"api",
":=",
"&",
"API",
"{",
"spec",
":",
"spec",
",",
"analyzer",
":",
"an",
",",
"consumers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"runtime",
".",
"Consumer",
",",
"10",
")",
",",
"producers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"runtime",
".",
"Producer",
",",
"10",
")",
",",
"authenticators",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"runtime",
".",
"Authenticator",
")",
",",
"operations",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"runtime",
".",
"OperationHandler",
")",
",",
"ServeError",
":",
"errors",
".",
"ServeError",
",",
"Models",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"func",
"(",
")",
"interface",
"{",
"}",
")",
",",
"formats",
":",
"strfmt",
".",
"NewFormats",
"(",
")",
",",
"}",
"\n",
"return",
"api",
".",
"WithJSONDefaults",
"(",
")",
"\n",
"}"
]
| // NewAPI creates the default untyped API | [
"NewAPI",
"creates",
"the",
"default",
"untyped",
"API"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L32-L49 |
10,251 | go-openapi/runtime | middleware/untyped/api.go | WithJSONDefaults | func (d *API) WithJSONDefaults() *API {
d.DefaultConsumes = runtime.JSONMime
d.DefaultProduces = runtime.JSONMime
d.consumers[runtime.JSONMime] = runtime.JSONConsumer()
d.producers[runtime.JSONMime] = runtime.JSONProducer()
return d
} | go | func (d *API) WithJSONDefaults() *API {
d.DefaultConsumes = runtime.JSONMime
d.DefaultProduces = runtime.JSONMime
d.consumers[runtime.JSONMime] = runtime.JSONConsumer()
d.producers[runtime.JSONMime] = runtime.JSONProducer()
return d
} | [
"func",
"(",
"d",
"*",
"API",
")",
"WithJSONDefaults",
"(",
")",
"*",
"API",
"{",
"d",
".",
"DefaultConsumes",
"=",
"runtime",
".",
"JSONMime",
"\n",
"d",
".",
"DefaultProduces",
"=",
"runtime",
".",
"JSONMime",
"\n",
"d",
".",
"consumers",
"[",
"runtime",
".",
"JSONMime",
"]",
"=",
"runtime",
".",
"JSONConsumer",
"(",
")",
"\n",
"d",
".",
"producers",
"[",
"runtime",
".",
"JSONMime",
"]",
"=",
"runtime",
".",
"JSONProducer",
"(",
")",
"\n",
"return",
"d",
"\n",
"}"
]
| // WithJSONDefaults loads the json defaults for this api | [
"WithJSONDefaults",
"loads",
"the",
"json",
"defaults",
"for",
"this",
"api"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L68-L74 |
10,252 | go-openapi/runtime | middleware/untyped/api.go | WithoutJSONDefaults | func (d *API) WithoutJSONDefaults() *API {
d.DefaultConsumes = ""
d.DefaultProduces = ""
delete(d.consumers, runtime.JSONMime)
delete(d.producers, runtime.JSONMime)
return d
} | go | func (d *API) WithoutJSONDefaults() *API {
d.DefaultConsumes = ""
d.DefaultProduces = ""
delete(d.consumers, runtime.JSONMime)
delete(d.producers, runtime.JSONMime)
return d
} | [
"func",
"(",
"d",
"*",
"API",
")",
"WithoutJSONDefaults",
"(",
")",
"*",
"API",
"{",
"d",
".",
"DefaultConsumes",
"=",
"\"",
"\"",
"\n",
"d",
".",
"DefaultProduces",
"=",
"\"",
"\"",
"\n",
"delete",
"(",
"d",
".",
"consumers",
",",
"runtime",
".",
"JSONMime",
")",
"\n",
"delete",
"(",
"d",
".",
"producers",
",",
"runtime",
".",
"JSONMime",
")",
"\n",
"return",
"d",
"\n",
"}"
]
| // WithoutJSONDefaults clears the json defaults for this api | [
"WithoutJSONDefaults",
"clears",
"the",
"json",
"defaults",
"for",
"this",
"api"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L77-L83 |
10,253 | go-openapi/runtime | middleware/untyped/api.go | Formats | func (d *API) Formats() strfmt.Registry {
if d.formats == nil {
d.formats = strfmt.NewFormats()
}
return d.formats
} | go | func (d *API) Formats() strfmt.Registry {
if d.formats == nil {
d.formats = strfmt.NewFormats()
}
return d.formats
} | [
"func",
"(",
"d",
"*",
"API",
")",
"Formats",
"(",
")",
"strfmt",
".",
"Registry",
"{",
"if",
"d",
".",
"formats",
"==",
"nil",
"{",
"d",
".",
"formats",
"=",
"strfmt",
".",
"NewFormats",
"(",
")",
"\n",
"}",
"\n",
"return",
"d",
".",
"formats",
"\n",
"}"
]
| // Formats returns the registered string formats | [
"Formats",
"returns",
"the",
"registered",
"string",
"formats"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L86-L91 |
10,254 | go-openapi/runtime | middleware/untyped/api.go | RegisterAuth | func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) {
if d.authenticators == nil {
d.authenticators = make(map[string]runtime.Authenticator)
}
d.authenticators[scheme] = handler
} | go | func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) {
if d.authenticators == nil {
d.authenticators = make(map[string]runtime.Authenticator)
}
d.authenticators[scheme] = handler
} | [
"func",
"(",
"d",
"*",
"API",
")",
"RegisterAuth",
"(",
"scheme",
"string",
",",
"handler",
"runtime",
".",
"Authenticator",
")",
"{",
"if",
"d",
".",
"authenticators",
"==",
"nil",
"{",
"d",
".",
"authenticators",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"runtime",
".",
"Authenticator",
")",
"\n",
"}",
"\n",
"d",
".",
"authenticators",
"[",
"scheme",
"]",
"=",
"handler",
"\n",
"}"
]
| // RegisterAuth registers an auth handler in this api | [
"RegisterAuth",
"registers",
"an",
"auth",
"handler",
"in",
"this",
"api"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L102-L107 |
10,255 | go-openapi/runtime | middleware/untyped/api.go | RegisterConsumer | func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) {
if d.consumers == nil {
d.consumers = make(map[string]runtime.Consumer, 10)
}
d.consumers[strings.ToLower(mediaType)] = handler
} | go | func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) {
if d.consumers == nil {
d.consumers = make(map[string]runtime.Consumer, 10)
}
d.consumers[strings.ToLower(mediaType)] = handler
} | [
"func",
"(",
"d",
"*",
"API",
")",
"RegisterConsumer",
"(",
"mediaType",
"string",
",",
"handler",
"runtime",
".",
"Consumer",
")",
"{",
"if",
"d",
".",
"consumers",
"==",
"nil",
"{",
"d",
".",
"consumers",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"runtime",
".",
"Consumer",
",",
"10",
")",
"\n",
"}",
"\n",
"d",
".",
"consumers",
"[",
"strings",
".",
"ToLower",
"(",
"mediaType",
")",
"]",
"=",
"handler",
"\n",
"}"
]
| // RegisterConsumer registers a consumer for a media type. | [
"RegisterConsumer",
"registers",
"a",
"consumer",
"for",
"a",
"media",
"type",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L115-L120 |
10,256 | go-openapi/runtime | middleware/untyped/api.go | RegisterProducer | func (d *API) RegisterProducer(mediaType string, handler runtime.Producer) {
if d.producers == nil {
d.producers = make(map[string]runtime.Producer, 10)
}
d.producers[strings.ToLower(mediaType)] = handler
} | go | func (d *API) RegisterProducer(mediaType string, handler runtime.Producer) {
if d.producers == nil {
d.producers = make(map[string]runtime.Producer, 10)
}
d.producers[strings.ToLower(mediaType)] = handler
} | [
"func",
"(",
"d",
"*",
"API",
")",
"RegisterProducer",
"(",
"mediaType",
"string",
",",
"handler",
"runtime",
".",
"Producer",
")",
"{",
"if",
"d",
".",
"producers",
"==",
"nil",
"{",
"d",
".",
"producers",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"runtime",
".",
"Producer",
",",
"10",
")",
"\n",
"}",
"\n",
"d",
".",
"producers",
"[",
"strings",
".",
"ToLower",
"(",
"mediaType",
")",
"]",
"=",
"handler",
"\n",
"}"
]
| // RegisterProducer registers a producer for a media type | [
"RegisterProducer",
"registers",
"a",
"producer",
"for",
"a",
"media",
"type"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L123-L128 |
10,257 | go-openapi/runtime | middleware/untyped/api.go | RegisterOperation | func (d *API) RegisterOperation(method, path string, handler runtime.OperationHandler) {
if d.operations == nil {
d.operations = make(map[string]map[string]runtime.OperationHandler, 30)
}
um := strings.ToUpper(method)
if b, ok := d.operations[um]; !ok || b == nil {
d.operations[um] = make(map[string]runtime.OperationHandler)
}
d.operations[um][path] = handler
} | go | func (d *API) RegisterOperation(method, path string, handler runtime.OperationHandler) {
if d.operations == nil {
d.operations = make(map[string]map[string]runtime.OperationHandler, 30)
}
um := strings.ToUpper(method)
if b, ok := d.operations[um]; !ok || b == nil {
d.operations[um] = make(map[string]runtime.OperationHandler)
}
d.operations[um][path] = handler
} | [
"func",
"(",
"d",
"*",
"API",
")",
"RegisterOperation",
"(",
"method",
",",
"path",
"string",
",",
"handler",
"runtime",
".",
"OperationHandler",
")",
"{",
"if",
"d",
".",
"operations",
"==",
"nil",
"{",
"d",
".",
"operations",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"runtime",
".",
"OperationHandler",
",",
"30",
")",
"\n",
"}",
"\n",
"um",
":=",
"strings",
".",
"ToUpper",
"(",
"method",
")",
"\n",
"if",
"b",
",",
"ok",
":=",
"d",
".",
"operations",
"[",
"um",
"]",
";",
"!",
"ok",
"||",
"b",
"==",
"nil",
"{",
"d",
".",
"operations",
"[",
"um",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"runtime",
".",
"OperationHandler",
")",
"\n",
"}",
"\n",
"d",
".",
"operations",
"[",
"um",
"]",
"[",
"path",
"]",
"=",
"handler",
"\n",
"}"
]
| // RegisterOperation registers an operation handler for an operation name | [
"RegisterOperation",
"registers",
"an",
"operation",
"handler",
"for",
"an",
"operation",
"name"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L131-L140 |
10,258 | go-openapi/runtime | middleware/untyped/api.go | OperationHandlerFor | func (d *API) OperationHandlerFor(method, path string) (runtime.OperationHandler, bool) {
if d.operations == nil {
return nil, false
}
if pi, ok := d.operations[strings.ToUpper(method)]; ok {
h, ok := pi[path]
return h, ok
}
return nil, false
} | go | func (d *API) OperationHandlerFor(method, path string) (runtime.OperationHandler, bool) {
if d.operations == nil {
return nil, false
}
if pi, ok := d.operations[strings.ToUpper(method)]; ok {
h, ok := pi[path]
return h, ok
}
return nil, false
} | [
"func",
"(",
"d",
"*",
"API",
")",
"OperationHandlerFor",
"(",
"method",
",",
"path",
"string",
")",
"(",
"runtime",
".",
"OperationHandler",
",",
"bool",
")",
"{",
"if",
"d",
".",
"operations",
"==",
"nil",
"{",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"if",
"pi",
",",
"ok",
":=",
"d",
".",
"operations",
"[",
"strings",
".",
"ToUpper",
"(",
"method",
")",
"]",
";",
"ok",
"{",
"h",
",",
"ok",
":=",
"pi",
"[",
"path",
"]",
"\n",
"return",
"h",
",",
"ok",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
]
| // OperationHandlerFor returns the operation handler for the specified id if it can be found | [
"OperationHandlerFor",
"returns",
"the",
"operation",
"handler",
"for",
"the",
"specified",
"id",
"if",
"it",
"can",
"be",
"found"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L143-L152 |
10,259 | go-openapi/runtime | middleware/untyped/api.go | validate | func (d *API) validate() error {
var consumes []string
for k := range d.consumers {
consumes = append(consumes, k)
}
var produces []string
for k := range d.producers {
produces = append(produces, k)
}
var authenticators []string
for k := range d.authenticators {
authenticators = append(authenticators, k)
}
var operations []string
for m, v := range d.operations {
for p := range v {
operations = append(operations, fmt.Sprintf("%s %s", strings.ToUpper(m), p))
}
}
var definedAuths []string
for k := range d.spec.Spec().SecurityDefinitions {
definedAuths = append(definedAuths, k)
}
if err := d.verify("consumes", consumes, d.analyzer.RequiredConsumes()); err != nil {
return err
}
if err := d.verify("produces", produces, d.analyzer.RequiredProduces()); err != nil {
return err
}
if err := d.verify("operation", operations, d.analyzer.OperationMethodPaths()); err != nil {
return err
}
requiredAuths := d.analyzer.RequiredSecuritySchemes()
if err := d.verify("auth scheme", authenticators, requiredAuths); err != nil {
return err
}
if err := d.verify("security definitions", definedAuths, requiredAuths); err != nil {
return err
}
return nil
} | go | func (d *API) validate() error {
var consumes []string
for k := range d.consumers {
consumes = append(consumes, k)
}
var produces []string
for k := range d.producers {
produces = append(produces, k)
}
var authenticators []string
for k := range d.authenticators {
authenticators = append(authenticators, k)
}
var operations []string
for m, v := range d.operations {
for p := range v {
operations = append(operations, fmt.Sprintf("%s %s", strings.ToUpper(m), p))
}
}
var definedAuths []string
for k := range d.spec.Spec().SecurityDefinitions {
definedAuths = append(definedAuths, k)
}
if err := d.verify("consumes", consumes, d.analyzer.RequiredConsumes()); err != nil {
return err
}
if err := d.verify("produces", produces, d.analyzer.RequiredProduces()); err != nil {
return err
}
if err := d.verify("operation", operations, d.analyzer.OperationMethodPaths()); err != nil {
return err
}
requiredAuths := d.analyzer.RequiredSecuritySchemes()
if err := d.verify("auth scheme", authenticators, requiredAuths); err != nil {
return err
}
if err := d.verify("security definitions", definedAuths, requiredAuths); err != nil {
return err
}
return nil
} | [
"func",
"(",
"d",
"*",
"API",
")",
"validate",
"(",
")",
"error",
"{",
"var",
"consumes",
"[",
"]",
"string",
"\n",
"for",
"k",
":=",
"range",
"d",
".",
"consumers",
"{",
"consumes",
"=",
"append",
"(",
"consumes",
",",
"k",
")",
"\n",
"}",
"\n\n",
"var",
"produces",
"[",
"]",
"string",
"\n",
"for",
"k",
":=",
"range",
"d",
".",
"producers",
"{",
"produces",
"=",
"append",
"(",
"produces",
",",
"k",
")",
"\n",
"}",
"\n\n",
"var",
"authenticators",
"[",
"]",
"string",
"\n",
"for",
"k",
":=",
"range",
"d",
".",
"authenticators",
"{",
"authenticators",
"=",
"append",
"(",
"authenticators",
",",
"k",
")",
"\n",
"}",
"\n\n",
"var",
"operations",
"[",
"]",
"string",
"\n",
"for",
"m",
",",
"v",
":=",
"range",
"d",
".",
"operations",
"{",
"for",
"p",
":=",
"range",
"v",
"{",
"operations",
"=",
"append",
"(",
"operations",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"strings",
".",
"ToUpper",
"(",
"m",
")",
",",
"p",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"definedAuths",
"[",
"]",
"string",
"\n",
"for",
"k",
":=",
"range",
"d",
".",
"spec",
".",
"Spec",
"(",
")",
".",
"SecurityDefinitions",
"{",
"definedAuths",
"=",
"append",
"(",
"definedAuths",
",",
"k",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"d",
".",
"verify",
"(",
"\"",
"\"",
",",
"consumes",
",",
"d",
".",
"analyzer",
".",
"RequiredConsumes",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"verify",
"(",
"\"",
"\"",
",",
"produces",
",",
"d",
".",
"analyzer",
".",
"RequiredProduces",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"verify",
"(",
"\"",
"\"",
",",
"operations",
",",
"d",
".",
"analyzer",
".",
"OperationMethodPaths",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"requiredAuths",
":=",
"d",
".",
"analyzer",
".",
"RequiredSecuritySchemes",
"(",
")",
"\n",
"if",
"err",
":=",
"d",
".",
"verify",
"(",
"\"",
"\"",
",",
"authenticators",
",",
"requiredAuths",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"verify",
"(",
"\"",
"\"",
",",
"definedAuths",
",",
"requiredAuths",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // validateWith validates the registrations in this API against the provided spec analyzer | [
"validateWith",
"validates",
"the",
"registrations",
"in",
"this",
"API",
"against",
"the",
"provided",
"spec",
"analyzer"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/untyped/api.go#L198-L244 |
10,260 | go-openapi/runtime | middleware/router.go | Get | func (r RouteParams) Get(name string) string {
vv, _, _ := r.GetOK(name)
if len(vv) > 0 {
return vv[len(vv)-1]
}
return ""
} | go | func (r RouteParams) Get(name string) string {
vv, _, _ := r.GetOK(name)
if len(vv) > 0 {
return vv[len(vv)-1]
}
return ""
} | [
"func",
"(",
"r",
"RouteParams",
")",
"Get",
"(",
"name",
"string",
")",
"string",
"{",
"vv",
",",
"_",
",",
"_",
":=",
"r",
".",
"GetOK",
"(",
"name",
")",
"\n",
"if",
"len",
"(",
"vv",
")",
">",
"0",
"{",
"return",
"vv",
"[",
"len",
"(",
"vv",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
]
| // Get gets the value for the route param for the specified key | [
"Get",
"gets",
"the",
"value",
"for",
"the",
"route",
"param",
"for",
"the",
"specified",
"key"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/router.go#L47-L53 |
10,261 | go-openapi/runtime | middleware/router.go | NewRouter | func NewRouter(ctx *Context, next http.Handler) http.Handler {
if ctx.router == nil {
ctx.router = DefaultRouter(ctx.spec, ctx.api)
}
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if _, rCtx, ok := ctx.RouteInfo(r); ok {
next.ServeHTTP(rw, rCtx)
return
}
// Not found, check if it exists in the other methods first
if others := ctx.AllowedMethods(r); len(others) > 0 {
ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others))
return
}
ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.EscapedPath()))
})
} | go | func NewRouter(ctx *Context, next http.Handler) http.Handler {
if ctx.router == nil {
ctx.router = DefaultRouter(ctx.spec, ctx.api)
}
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if _, rCtx, ok := ctx.RouteInfo(r); ok {
next.ServeHTTP(rw, rCtx)
return
}
// Not found, check if it exists in the other methods first
if others := ctx.AllowedMethods(r); len(others) > 0 {
ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others))
return
}
ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.EscapedPath()))
})
} | [
"func",
"NewRouter",
"(",
"ctx",
"*",
"Context",
",",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"if",
"ctx",
".",
"router",
"==",
"nil",
"{",
"ctx",
".",
"router",
"=",
"DefaultRouter",
"(",
"ctx",
".",
"spec",
",",
"ctx",
".",
"api",
")",
"\n",
"}",
"\n\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"_",
",",
"rCtx",
",",
"ok",
":=",
"ctx",
".",
"RouteInfo",
"(",
"r",
")",
";",
"ok",
"{",
"next",
".",
"ServeHTTP",
"(",
"rw",
",",
"rCtx",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Not found, check if it exists in the other methods first",
"if",
"others",
":=",
"ctx",
".",
"AllowedMethods",
"(",
"r",
")",
";",
"len",
"(",
"others",
")",
">",
"0",
"{",
"ctx",
".",
"Respond",
"(",
"rw",
",",
"r",
",",
"ctx",
".",
"analyzer",
".",
"RequiredProduces",
"(",
")",
",",
"nil",
",",
"errors",
".",
"MethodNotAllowed",
"(",
"r",
".",
"Method",
",",
"others",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"ctx",
".",
"Respond",
"(",
"rw",
",",
"r",
",",
"ctx",
".",
"analyzer",
".",
"RequiredProduces",
"(",
")",
",",
"nil",
",",
"errors",
".",
"NotFound",
"(",
"\"",
"\"",
",",
"r",
".",
"URL",
".",
"EscapedPath",
"(",
")",
")",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // NewRouter creates a new context aware router middleware | [
"NewRouter",
"creates",
"a",
"new",
"context",
"aware",
"router",
"middleware"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/router.go#L69-L88 |
10,262 | go-openapi/runtime | middleware/router.go | DefaultRouter | func DefaultRouter(spec *loads.Document, api RoutableAPI) Router {
builder := newDefaultRouteBuilder(spec, api)
if spec != nil {
for method, paths := range builder.analyzer.Operations() {
for path, operation := range paths {
fp := fpath.Join(spec.BasePath(), path)
debugLog("adding route %s %s %q", method, fp, operation.ID)
builder.AddRoute(method, fp, operation)
}
}
}
return builder.Build()
} | go | func DefaultRouter(spec *loads.Document, api RoutableAPI) Router {
builder := newDefaultRouteBuilder(spec, api)
if spec != nil {
for method, paths := range builder.analyzer.Operations() {
for path, operation := range paths {
fp := fpath.Join(spec.BasePath(), path)
debugLog("adding route %s %s %q", method, fp, operation.ID)
builder.AddRoute(method, fp, operation)
}
}
}
return builder.Build()
} | [
"func",
"DefaultRouter",
"(",
"spec",
"*",
"loads",
".",
"Document",
",",
"api",
"RoutableAPI",
")",
"Router",
"{",
"builder",
":=",
"newDefaultRouteBuilder",
"(",
"spec",
",",
"api",
")",
"\n",
"if",
"spec",
"!=",
"nil",
"{",
"for",
"method",
",",
"paths",
":=",
"range",
"builder",
".",
"analyzer",
".",
"Operations",
"(",
")",
"{",
"for",
"path",
",",
"operation",
":=",
"range",
"paths",
"{",
"fp",
":=",
"fpath",
".",
"Join",
"(",
"spec",
".",
"BasePath",
"(",
")",
",",
"path",
")",
"\n",
"debugLog",
"(",
"\"",
"\"",
",",
"method",
",",
"fp",
",",
"operation",
".",
"ID",
")",
"\n",
"builder",
".",
"AddRoute",
"(",
"method",
",",
"fp",
",",
"operation",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"builder",
".",
"Build",
"(",
")",
"\n",
"}"
]
| // DefaultRouter creates a default implemenation of the router | [
"DefaultRouter",
"creates",
"a",
"default",
"implemenation",
"of",
"the",
"router"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/router.go#L132-L144 |
10,263 | go-openapi/runtime | middleware/router.go | Authenticate | func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
if ra.allowAnonymous {
route.Authenticator = ra
return true, nil, nil
}
// iterate in proper order
var lastResult interface{}
for _, scheme := range ra.Schemes {
if authenticator, ok := ra.Authenticator[scheme]; ok {
applies, princ, err := authenticator.Authenticate(&security.ScopedAuthRequest{
Request: req,
RequiredScopes: ra.Scopes[scheme],
})
if !applies {
return false, nil, nil
}
if err != nil {
route.Authenticator = ra
return true, nil, err
}
lastResult = princ
}
}
route.Authenticator = ra
return true, lastResult, nil
} | go | func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
if ra.allowAnonymous {
route.Authenticator = ra
return true, nil, nil
}
// iterate in proper order
var lastResult interface{}
for _, scheme := range ra.Schemes {
if authenticator, ok := ra.Authenticator[scheme]; ok {
applies, princ, err := authenticator.Authenticate(&security.ScopedAuthRequest{
Request: req,
RequiredScopes: ra.Scopes[scheme],
})
if !applies {
return false, nil, nil
}
if err != nil {
route.Authenticator = ra
return true, nil, err
}
lastResult = princ
}
}
route.Authenticator = ra
return true, lastResult, nil
} | [
"func",
"(",
"ra",
"*",
"RouteAuthenticator",
")",
"Authenticate",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"route",
"*",
"MatchedRoute",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"ra",
".",
"allowAnonymous",
"{",
"route",
".",
"Authenticator",
"=",
"ra",
"\n",
"return",
"true",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"// iterate in proper order",
"var",
"lastResult",
"interface",
"{",
"}",
"\n",
"for",
"_",
",",
"scheme",
":=",
"range",
"ra",
".",
"Schemes",
"{",
"if",
"authenticator",
",",
"ok",
":=",
"ra",
".",
"Authenticator",
"[",
"scheme",
"]",
";",
"ok",
"{",
"applies",
",",
"princ",
",",
"err",
":=",
"authenticator",
".",
"Authenticate",
"(",
"&",
"security",
".",
"ScopedAuthRequest",
"{",
"Request",
":",
"req",
",",
"RequiredScopes",
":",
"ra",
".",
"Scopes",
"[",
"scheme",
"]",
",",
"}",
")",
"\n",
"if",
"!",
"applies",
"{",
"return",
"false",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"route",
".",
"Authenticator",
"=",
"ra",
"\n",
"return",
"true",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"lastResult",
"=",
"princ",
"\n",
"}",
"\n",
"}",
"\n",
"route",
".",
"Authenticator",
"=",
"ra",
"\n",
"return",
"true",
",",
"lastResult",
",",
"nil",
"\n",
"}"
]
| // Authenticate Authenticator interface implementation | [
"Authenticate",
"Authenticator",
"interface",
"implementation"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/router.go#L175-L200 |
10,264 | go-openapi/runtime | middleware/router.go | AllowsAnonymous | func (ras RouteAuthenticators) AllowsAnonymous() bool {
for _, ra := range ras {
if ra.AllowsAnonymous() {
return true
}
}
return false
} | go | func (ras RouteAuthenticators) AllowsAnonymous() bool {
for _, ra := range ras {
if ra.AllowsAnonymous() {
return true
}
}
return false
} | [
"func",
"(",
"ras",
"RouteAuthenticators",
")",
"AllowsAnonymous",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"ra",
":=",
"range",
"ras",
"{",
"if",
"ra",
".",
"AllowsAnonymous",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
]
| // AllowsAnonymous returns true when there is an authenticator that means optional auth | [
"AllowsAnonymous",
"returns",
"true",
"when",
"there",
"is",
"an",
"authenticator",
"that",
"means",
"optional",
"auth"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/router.go#L244-L251 |
10,265 | go-openapi/runtime | middleware/router.go | Authenticate | func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
var lastError error
var allowsAnon bool
var anonAuth RouteAuthenticator
for _, ra := range ras {
if ra.AllowsAnonymous() {
anonAuth = ra
allowsAnon = true
continue
}
applies, usr, err := ra.Authenticate(req, route)
if !applies || err != nil || usr == nil {
if err != nil {
lastError = err
}
continue
}
return applies, usr, nil
}
if allowsAnon && lastError == nil {
route.Authenticator = &anonAuth
return true, nil, lastError
}
return lastError != nil, nil, lastError
} | go | func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
var lastError error
var allowsAnon bool
var anonAuth RouteAuthenticator
for _, ra := range ras {
if ra.AllowsAnonymous() {
anonAuth = ra
allowsAnon = true
continue
}
applies, usr, err := ra.Authenticate(req, route)
if !applies || err != nil || usr == nil {
if err != nil {
lastError = err
}
continue
}
return applies, usr, nil
}
if allowsAnon && lastError == nil {
route.Authenticator = &anonAuth
return true, nil, lastError
}
return lastError != nil, nil, lastError
} | [
"func",
"(",
"ras",
"RouteAuthenticators",
")",
"Authenticate",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"route",
"*",
"MatchedRoute",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"lastError",
"error",
"\n",
"var",
"allowsAnon",
"bool",
"\n",
"var",
"anonAuth",
"RouteAuthenticator",
"\n\n",
"for",
"_",
",",
"ra",
":=",
"range",
"ras",
"{",
"if",
"ra",
".",
"AllowsAnonymous",
"(",
")",
"{",
"anonAuth",
"=",
"ra",
"\n",
"allowsAnon",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"applies",
",",
"usr",
",",
"err",
":=",
"ra",
".",
"Authenticate",
"(",
"req",
",",
"route",
")",
"\n",
"if",
"!",
"applies",
"||",
"err",
"!=",
"nil",
"||",
"usr",
"==",
"nil",
"{",
"if",
"err",
"!=",
"nil",
"{",
"lastError",
"=",
"err",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"applies",
",",
"usr",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"allowsAnon",
"&&",
"lastError",
"==",
"nil",
"{",
"route",
".",
"Authenticator",
"=",
"&",
"anonAuth",
"\n",
"return",
"true",
",",
"nil",
",",
"lastError",
"\n",
"}",
"\n",
"return",
"lastError",
"!=",
"nil",
",",
"nil",
",",
"lastError",
"\n",
"}"
]
| // Authenticate method implemention so this collection can be used as authenticator | [
"Authenticate",
"method",
"implemention",
"so",
"this",
"collection",
"can",
"be",
"used",
"as",
"authenticator"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/router.go#L254-L280 |
10,266 | go-openapi/runtime | flagext/byte_size.go | MarshalFlag | func (b ByteSize) MarshalFlag() (string, error) {
return units.HumanSize(float64(b)), nil
} | go | func (b ByteSize) MarshalFlag() (string, error) {
return units.HumanSize(float64(b)), nil
} | [
"func",
"(",
"b",
"ByteSize",
")",
"MarshalFlag",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"units",
".",
"HumanSize",
"(",
"float64",
"(",
"b",
")",
")",
",",
"nil",
"\n",
"}"
]
| // MarshalFlag implements go-flags Marshaller interface | [
"MarshalFlag",
"implements",
"go",
"-",
"flags",
"Marshaller",
"interface"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/flagext/byte_size.go#L11-L13 |
10,267 | go-openapi/runtime | flagext/byte_size.go | UnmarshalFlag | func (b *ByteSize) UnmarshalFlag(value string) error {
sz, err := units.FromHumanSize(value)
if err != nil {
return err
}
*b = ByteSize(int(sz))
return nil
} | go | func (b *ByteSize) UnmarshalFlag(value string) error {
sz, err := units.FromHumanSize(value)
if err != nil {
return err
}
*b = ByteSize(int(sz))
return nil
} | [
"func",
"(",
"b",
"*",
"ByteSize",
")",
"UnmarshalFlag",
"(",
"value",
"string",
")",
"error",
"{",
"sz",
",",
"err",
":=",
"units",
".",
"FromHumanSize",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"b",
"=",
"ByteSize",
"(",
"int",
"(",
"sz",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
]
| // UnmarshalFlag implements go-flags Unmarshaller interface | [
"UnmarshalFlag",
"implements",
"go",
"-",
"flags",
"Unmarshaller",
"interface"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/flagext/byte_size.go#L16-L23 |
10,268 | go-openapi/runtime | client_auth_info.go | AuthenticateRequest | func (fn ClientAuthInfoWriterFunc) AuthenticateRequest(req ClientRequest, reg strfmt.Registry) error {
return fn(req, reg)
} | go | func (fn ClientAuthInfoWriterFunc) AuthenticateRequest(req ClientRequest, reg strfmt.Registry) error {
return fn(req, reg)
} | [
"func",
"(",
"fn",
"ClientAuthInfoWriterFunc",
")",
"AuthenticateRequest",
"(",
"req",
"ClientRequest",
",",
"reg",
"strfmt",
".",
"Registry",
")",
"error",
"{",
"return",
"fn",
"(",
"req",
",",
"reg",
")",
"\n",
"}"
]
| // AuthenticateRequest adds authentication data to the request | [
"AuthenticateRequest",
"adds",
"authentication",
"data",
"to",
"the",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client_auth_info.go#L23-L25 |
10,269 | go-openapi/runtime | middleware/operation.go | NewOperationExecutor | func NewOperationExecutor(ctx *Context) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// use context to lookup routes
route, rCtx, _ := ctx.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
route.Handler.ServeHTTP(rw, r)
})
} | go | func NewOperationExecutor(ctx *Context) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// use context to lookup routes
route, rCtx, _ := ctx.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
route.Handler.ServeHTTP(rw, r)
})
} | [
"func",
"NewOperationExecutor",
"(",
"ctx",
"*",
"Context",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"// use context to lookup routes",
"route",
",",
"rCtx",
",",
"_",
":=",
"ctx",
".",
"RouteInfo",
"(",
"r",
")",
"\n",
"if",
"rCtx",
"!=",
"nil",
"{",
"r",
"=",
"rCtx",
"\n",
"}",
"\n\n",
"route",
".",
"Handler",
".",
"ServeHTTP",
"(",
"rw",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // NewOperationExecutor creates a context aware middleware that handles the operations after routing | [
"NewOperationExecutor",
"creates",
"a",
"context",
"aware",
"middleware",
"that",
"handles",
"the",
"operations",
"after",
"routing"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/operation.go#L20-L30 |
10,270 | go-openapi/runtime | yamlpc/yaml.go | YAMLConsumer | func YAMLConsumer() runtime.Consumer {
return runtime.ConsumerFunc(func(r io.Reader, v interface{}) error {
buf, err := ioutil.ReadAll(r)
if err != nil {
return err
}
return yaml.Unmarshal(buf, v)
})
} | go | func YAMLConsumer() runtime.Consumer {
return runtime.ConsumerFunc(func(r io.Reader, v interface{}) error {
buf, err := ioutil.ReadAll(r)
if err != nil {
return err
}
return yaml.Unmarshal(buf, v)
})
} | [
"func",
"YAMLConsumer",
"(",
")",
"runtime",
".",
"Consumer",
"{",
"return",
"runtime",
".",
"ConsumerFunc",
"(",
"func",
"(",
"r",
"io",
".",
"Reader",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"yaml",
".",
"Unmarshal",
"(",
"buf",
",",
"v",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // YAMLConsumer creates a consumer for yaml data | [
"YAMLConsumer",
"creates",
"a",
"consumer",
"for",
"yaml",
"data"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/yamlpc/yaml.go#L27-L35 |
10,271 | go-openapi/runtime | yamlpc/yaml.go | YAMLProducer | func YAMLProducer() runtime.Producer {
return runtime.ProducerFunc(func(w io.Writer, v interface{}) error {
b, _ := yaml.Marshal(v) // can't make this error come up
_, err := w.Write(b)
return err
})
} | go | func YAMLProducer() runtime.Producer {
return runtime.ProducerFunc(func(w io.Writer, v interface{}) error {
b, _ := yaml.Marshal(v) // can't make this error come up
_, err := w.Write(b)
return err
})
} | [
"func",
"YAMLProducer",
"(",
")",
"runtime",
".",
"Producer",
"{",
"return",
"runtime",
".",
"ProducerFunc",
"(",
"func",
"(",
"w",
"io",
".",
"Writer",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"b",
",",
"_",
":=",
"yaml",
".",
"Marshal",
"(",
"v",
")",
"// can't make this error come up",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"b",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
]
| // YAMLProducer creates a producer for yaml data | [
"YAMLProducer",
"creates",
"a",
"producer",
"for",
"yaml",
"data"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/yamlpc/yaml.go#L38-L44 |
10,272 | go-openapi/runtime | security/authenticator.go | HttpAuthenticator | func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator {
return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
if request, ok := params.(*http.Request); ok {
return handler(request)
}
if scoped, ok := params.(*ScopedAuthRequest); ok {
return handler(scoped.Request)
}
return false, nil, nil
})
} | go | func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator {
return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
if request, ok := params.(*http.Request); ok {
return handler(request)
}
if scoped, ok := params.(*ScopedAuthRequest); ok {
return handler(scoped.Request)
}
return false, nil, nil
})
} | [
"func",
"HttpAuthenticator",
"(",
"handler",
"func",
"(",
"*",
"http",
".",
"Request",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
")",
"runtime",
".",
"Authenticator",
"{",
"return",
"runtime",
".",
"AuthenticatorFunc",
"(",
"func",
"(",
"params",
"interface",
"{",
"}",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"request",
",",
"ok",
":=",
"params",
".",
"(",
"*",
"http",
".",
"Request",
")",
";",
"ok",
"{",
"return",
"handler",
"(",
"request",
")",
"\n",
"}",
"\n",
"if",
"scoped",
",",
"ok",
":=",
"params",
".",
"(",
"*",
"ScopedAuthRequest",
")",
";",
"ok",
"{",
"return",
"handler",
"(",
"scoped",
".",
"Request",
")",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
",",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // HttpAuthenticator is a function that authenticates a HTTP request | [
"HttpAuthenticator",
"is",
"a",
"function",
"that",
"authenticates",
"a",
"HTTP",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/security/authenticator.go#L32-L42 |
10,273 | go-openapi/runtime | security/authenticator.go | ScopedAuthenticator | func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, error)) runtime.Authenticator {
return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
if request, ok := params.(*ScopedAuthRequest); ok {
return handler(request)
}
return false, nil, nil
})
} | go | func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, error)) runtime.Authenticator {
return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
if request, ok := params.(*ScopedAuthRequest); ok {
return handler(request)
}
return false, nil, nil
})
} | [
"func",
"ScopedAuthenticator",
"(",
"handler",
"func",
"(",
"*",
"ScopedAuthRequest",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
")",
"runtime",
".",
"Authenticator",
"{",
"return",
"runtime",
".",
"AuthenticatorFunc",
"(",
"func",
"(",
"params",
"interface",
"{",
"}",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"request",
",",
"ok",
":=",
"params",
".",
"(",
"*",
"ScopedAuthRequest",
")",
";",
"ok",
"{",
"return",
"handler",
"(",
"request",
")",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
",",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // ScopedAuthenticator is a function that authenticates a HTTP request against a list of valid scopes | [
"ScopedAuthenticator",
"is",
"a",
"function",
"that",
"authenticates",
"a",
"HTTP",
"request",
"against",
"a",
"list",
"of",
"valid",
"scopes"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/security/authenticator.go#L45-L52 |
10,274 | go-openapi/runtime | security/authenticator.go | BasicAuthRealmCtx | func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) runtime.Authenticator {
if realm == "" {
realm = DefaultRealmName
}
return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
if usr, pass, ok := r.BasicAuth(); ok {
ctx, p, err := authenticate(r.Context(), usr, pass)
if err != nil {
ctx = context.WithValue(ctx, failedBasicAuth, realm)
}
*r = *r.WithContext(ctx)
return true, p, err
}
*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
return false, nil, nil
})
} | go | func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) runtime.Authenticator {
if realm == "" {
realm = DefaultRealmName
}
return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
if usr, pass, ok := r.BasicAuth(); ok {
ctx, p, err := authenticate(r.Context(), usr, pass)
if err != nil {
ctx = context.WithValue(ctx, failedBasicAuth, realm)
}
*r = *r.WithContext(ctx)
return true, p, err
}
*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
return false, nil, nil
})
} | [
"func",
"BasicAuthRealmCtx",
"(",
"realm",
"string",
",",
"authenticate",
"UserPassAuthenticationCtx",
")",
"runtime",
".",
"Authenticator",
"{",
"if",
"realm",
"==",
"\"",
"\"",
"{",
"realm",
"=",
"DefaultRealmName",
"\n",
"}",
"\n\n",
"return",
"HttpAuthenticator",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"usr",
",",
"pass",
",",
"ok",
":=",
"r",
".",
"BasicAuth",
"(",
")",
";",
"ok",
"{",
"ctx",
",",
"p",
",",
"err",
":=",
"authenticate",
"(",
"r",
".",
"Context",
"(",
")",
",",
"usr",
",",
"pass",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
"=",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"failedBasicAuth",
",",
"realm",
")",
"\n",
"}",
"\n",
"*",
"r",
"=",
"*",
"r",
".",
"WithContext",
"(",
"ctx",
")",
"\n",
"return",
"true",
",",
"p",
",",
"err",
"\n",
"}",
"\n",
"*",
"r",
"=",
"*",
"r",
".",
"WithContext",
"(",
"context",
".",
"WithValue",
"(",
"r",
".",
"Context",
"(",
")",
",",
"failedBasicAuth",
",",
"realm",
")",
")",
"\n",
"return",
"false",
",",
"nil",
",",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // BasicAuthCtx creates a basic auth authenticator with the provided authentication function and realm name with support for context.Context | [
"BasicAuthCtx",
"creates",
"a",
"basic",
"auth",
"authenticator",
"with",
"the",
"provided",
"authentication",
"function",
"and",
"realm",
"name",
"with",
"support",
"for",
"context",
".",
"Context"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/security/authenticator.go#L122-L139 |
10,275 | go-openapi/runtime | security/authenticator.go | APIKeyAuth | func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authenticator {
inl := strings.ToLower(in)
if inl != query && inl != header {
// panic because this is most likely a typo
panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\"."))
}
var getToken func(*http.Request) string
switch inl {
case header:
getToken = func(r *http.Request) string { return r.Header.Get(name) }
case query:
getToken = func(r *http.Request) string { return r.URL.Query().Get(name) }
}
return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
token := getToken(r)
if token == "" {
return false, nil, nil
}
p, err := authenticate(token)
return true, p, err
})
} | go | func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authenticator {
inl := strings.ToLower(in)
if inl != query && inl != header {
// panic because this is most likely a typo
panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\"."))
}
var getToken func(*http.Request) string
switch inl {
case header:
getToken = func(r *http.Request) string { return r.Header.Get(name) }
case query:
getToken = func(r *http.Request) string { return r.URL.Query().Get(name) }
}
return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
token := getToken(r)
if token == "" {
return false, nil, nil
}
p, err := authenticate(token)
return true, p, err
})
} | [
"func",
"APIKeyAuth",
"(",
"name",
",",
"in",
"string",
",",
"authenticate",
"TokenAuthentication",
")",
"runtime",
".",
"Authenticator",
"{",
"inl",
":=",
"strings",
".",
"ToLower",
"(",
"in",
")",
"\n",
"if",
"inl",
"!=",
"query",
"&&",
"inl",
"!=",
"header",
"{",
"// panic because this is most likely a typo",
"panic",
"(",
"errors",
".",
"New",
"(",
"500",
",",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"var",
"getToken",
"func",
"(",
"*",
"http",
".",
"Request",
")",
"string",
"\n",
"switch",
"inl",
"{",
"case",
"header",
":",
"getToken",
"=",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"return",
"r",
".",
"Header",
".",
"Get",
"(",
"name",
")",
"}",
"\n",
"case",
"query",
":",
"getToken",
"=",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"return",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"name",
")",
"}",
"\n",
"}",
"\n\n",
"return",
"HttpAuthenticator",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"token",
":=",
"getToken",
"(",
"r",
")",
"\n",
"if",
"token",
"==",
"\"",
"\"",
"{",
"return",
"false",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"p",
",",
"err",
":=",
"authenticate",
"(",
"token",
")",
"\n",
"return",
"true",
",",
"p",
",",
"err",
"\n",
"}",
")",
"\n",
"}"
]
| // APIKeyAuth creates an authenticator that uses a token for authorization.
// This token can be obtained from either a header or a query string | [
"APIKeyAuth",
"creates",
"an",
"authenticator",
"that",
"uses",
"a",
"token",
"for",
"authorization",
".",
"This",
"token",
"can",
"be",
"obtained",
"from",
"either",
"a",
"header",
"or",
"a",
"query",
"string"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/security/authenticator.go#L143-L167 |
10,276 | go-openapi/runtime | security/authenticator.go | BearerAuth | func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Authenticator {
const prefix = "Bearer "
return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) {
var token string
hdr := r.Request.Header.Get("Authorization")
if strings.HasPrefix(hdr, prefix) {
token = strings.TrimPrefix(hdr, prefix)
}
if token == "" {
qs := r.Request.URL.Query()
token = qs.Get("access_token")
}
//#nosec
ct, _, _ := runtime.ContentType(r.Request.Header)
if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") {
token = r.Request.FormValue("access_token")
}
if token == "" {
return false, nil, nil
}
p, err := authenticate(token, r.RequiredScopes)
return true, p, err
})
} | go | func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Authenticator {
const prefix = "Bearer "
return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) {
var token string
hdr := r.Request.Header.Get("Authorization")
if strings.HasPrefix(hdr, prefix) {
token = strings.TrimPrefix(hdr, prefix)
}
if token == "" {
qs := r.Request.URL.Query()
token = qs.Get("access_token")
}
//#nosec
ct, _, _ := runtime.ContentType(r.Request.Header)
if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") {
token = r.Request.FormValue("access_token")
}
if token == "" {
return false, nil, nil
}
p, err := authenticate(token, r.RequiredScopes)
return true, p, err
})
} | [
"func",
"BearerAuth",
"(",
"name",
"string",
",",
"authenticate",
"ScopedTokenAuthentication",
")",
"runtime",
".",
"Authenticator",
"{",
"const",
"prefix",
"=",
"\"",
"\"",
"\n",
"return",
"ScopedAuthenticator",
"(",
"func",
"(",
"r",
"*",
"ScopedAuthRequest",
")",
"(",
"bool",
",",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"token",
"string",
"\n",
"hdr",
":=",
"r",
".",
"Request",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"hdr",
",",
"prefix",
")",
"{",
"token",
"=",
"strings",
".",
"TrimPrefix",
"(",
"hdr",
",",
"prefix",
")",
"\n",
"}",
"\n",
"if",
"token",
"==",
"\"",
"\"",
"{",
"qs",
":=",
"r",
".",
"Request",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"token",
"=",
"qs",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"//#nosec",
"ct",
",",
"_",
",",
"_",
":=",
"runtime",
".",
"ContentType",
"(",
"r",
".",
"Request",
".",
"Header",
")",
"\n",
"if",
"token",
"==",
"\"",
"\"",
"&&",
"(",
"ct",
"==",
"\"",
"\"",
"||",
"ct",
"==",
"\"",
"\"",
")",
"{",
"token",
"=",
"r",
".",
"Request",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"token",
"==",
"\"",
"\"",
"{",
"return",
"false",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"p",
",",
"err",
":=",
"authenticate",
"(",
"token",
",",
"r",
".",
"RequiredScopes",
")",
"\n",
"return",
"true",
",",
"p",
",",
"err",
"\n",
"}",
")",
"\n",
"}"
]
| // BearerAuth for use with oauth2 flows | [
"BearerAuth",
"for",
"use",
"with",
"oauth2",
"flows"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/security/authenticator.go#L205-L230 |
10,277 | go-openapi/runtime | headers.go | ContentType | func ContentType(headers http.Header) (string, string, error) {
ct := headers.Get(HeaderContentType)
orig := ct
if ct == "" {
ct = DefaultMime
}
if ct == "" {
return "", "", nil
}
mt, opts, err := mime.ParseMediaType(ct)
if err != nil {
return "", "", errors.NewParseError(HeaderContentType, "header", orig, err)
}
if cs, ok := opts[charsetKey]; ok {
return mt, cs, nil
}
return mt, "", nil
} | go | func ContentType(headers http.Header) (string, string, error) {
ct := headers.Get(HeaderContentType)
orig := ct
if ct == "" {
ct = DefaultMime
}
if ct == "" {
return "", "", nil
}
mt, opts, err := mime.ParseMediaType(ct)
if err != nil {
return "", "", errors.NewParseError(HeaderContentType, "header", orig, err)
}
if cs, ok := opts[charsetKey]; ok {
return mt, cs, nil
}
return mt, "", nil
} | [
"func",
"ContentType",
"(",
"headers",
"http",
".",
"Header",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"ct",
":=",
"headers",
".",
"Get",
"(",
"HeaderContentType",
")",
"\n",
"orig",
":=",
"ct",
"\n",
"if",
"ct",
"==",
"\"",
"\"",
"{",
"ct",
"=",
"DefaultMime",
"\n",
"}",
"\n",
"if",
"ct",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n\n",
"mt",
",",
"opts",
",",
"err",
":=",
"mime",
".",
"ParseMediaType",
"(",
"ct",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"NewParseError",
"(",
"HeaderContentType",
",",
"\"",
"\"",
",",
"orig",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"cs",
",",
"ok",
":=",
"opts",
"[",
"charsetKey",
"]",
";",
"ok",
"{",
"return",
"mt",
",",
"cs",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"mt",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}"
]
| // ContentType parses a content type header | [
"ContentType",
"parses",
"a",
"content",
"type",
"header"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/headers.go#L25-L45 |
10,278 | go-openapi/runtime | json.go | JSONConsumer | func JSONConsumer() Consumer {
return ConsumerFunc(func(reader io.Reader, data interface{}) error {
dec := json.NewDecoder(reader)
dec.UseNumber() // preserve number formats
return dec.Decode(data)
})
} | go | func JSONConsumer() Consumer {
return ConsumerFunc(func(reader io.Reader, data interface{}) error {
dec := json.NewDecoder(reader)
dec.UseNumber() // preserve number formats
return dec.Decode(data)
})
} | [
"func",
"JSONConsumer",
"(",
")",
"Consumer",
"{",
"return",
"ConsumerFunc",
"(",
"func",
"(",
"reader",
"io",
".",
"Reader",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"reader",
")",
"\n",
"dec",
".",
"UseNumber",
"(",
")",
"// preserve number formats",
"\n",
"return",
"dec",
".",
"Decode",
"(",
"data",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // JSONConsumer creates a new JSON consumer | [
"JSONConsumer",
"creates",
"a",
"new",
"JSON",
"consumer"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/json.go#L23-L29 |
10,279 | go-openapi/runtime | json.go | JSONProducer | func JSONProducer() Producer {
return ProducerFunc(func(writer io.Writer, data interface{}) error {
enc := json.NewEncoder(writer)
enc.SetEscapeHTML(false)
return enc.Encode(data)
})
} | go | func JSONProducer() Producer {
return ProducerFunc(func(writer io.Writer, data interface{}) error {
enc := json.NewEncoder(writer)
enc.SetEscapeHTML(false)
return enc.Encode(data)
})
} | [
"func",
"JSONProducer",
"(",
")",
"Producer",
"{",
"return",
"ProducerFunc",
"(",
"func",
"(",
"writer",
"io",
".",
"Writer",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"enc",
":=",
"json",
".",
"NewEncoder",
"(",
"writer",
")",
"\n",
"enc",
".",
"SetEscapeHTML",
"(",
"false",
")",
"\n",
"return",
"enc",
".",
"Encode",
"(",
"data",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // JSONProducer creates a new JSON producer | [
"JSONProducer",
"creates",
"a",
"new",
"JSON",
"producer"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/json.go#L32-L38 |
10,280 | go-openapi/runtime | middleware/validation.go | validateContentType | func validateContentType(allowed []string, actual string) error {
debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", "))
if len(allowed) == 0 {
return nil
}
mt, _, err := mime.ParseMediaType(actual)
if err != nil {
return errors.InvalidContentType(actual, allowed)
}
if swag.ContainsStringsCI(allowed, mt) {
return nil
}
if swag.ContainsStringsCI(allowed, "*/*") {
return nil
}
parts := strings.Split(actual, "/")
if len(parts) == 2 && swag.ContainsStringsCI(allowed, parts[0]+"/*") {
return nil
}
return errors.InvalidContentType(actual, allowed)
} | go | func validateContentType(allowed []string, actual string) error {
debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", "))
if len(allowed) == 0 {
return nil
}
mt, _, err := mime.ParseMediaType(actual)
if err != nil {
return errors.InvalidContentType(actual, allowed)
}
if swag.ContainsStringsCI(allowed, mt) {
return nil
}
if swag.ContainsStringsCI(allowed, "*/*") {
return nil
}
parts := strings.Split(actual, "/")
if len(parts) == 2 && swag.ContainsStringsCI(allowed, parts[0]+"/*") {
return nil
}
return errors.InvalidContentType(actual, allowed)
} | [
"func",
"validateContentType",
"(",
"allowed",
"[",
"]",
"string",
",",
"actual",
"string",
")",
"error",
"{",
"debugLog",
"(",
"\"",
"\"",
",",
"actual",
",",
"strings",
".",
"Join",
"(",
"allowed",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"len",
"(",
"allowed",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"mt",
",",
"_",
",",
"err",
":=",
"mime",
".",
"ParseMediaType",
"(",
"actual",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"InvalidContentType",
"(",
"actual",
",",
"allowed",
")",
"\n",
"}",
"\n",
"if",
"swag",
".",
"ContainsStringsCI",
"(",
"allowed",
",",
"mt",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"swag",
".",
"ContainsStringsCI",
"(",
"allowed",
",",
"\"",
"\"",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"parts",
":=",
"strings",
".",
"Split",
"(",
"actual",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
"&&",
"swag",
".",
"ContainsStringsCI",
"(",
"allowed",
",",
"parts",
"[",
"0",
"]",
"+",
"\"",
"\"",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"InvalidContentType",
"(",
"actual",
",",
"allowed",
")",
"\n",
"}"
]
| // ContentType validates the content type of a request | [
"ContentType",
"validates",
"the",
"content",
"type",
"of",
"a",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/validation.go#L36-L56 |
10,281 | go-openapi/runtime | middleware/redoc.go | EnsureDefaults | func (r *RedocOpts) EnsureDefaults() {
if r.BasePath == "" {
r.BasePath = "/"
}
if r.Path == "" {
r.Path = "docs"
}
if r.SpecURL == "" {
r.SpecURL = "/swagger.json"
}
if r.RedocURL == "" {
r.RedocURL = redocLatest
}
if r.Title == "" {
r.Title = "API documentation"
}
} | go | func (r *RedocOpts) EnsureDefaults() {
if r.BasePath == "" {
r.BasePath = "/"
}
if r.Path == "" {
r.Path = "docs"
}
if r.SpecURL == "" {
r.SpecURL = "/swagger.json"
}
if r.RedocURL == "" {
r.RedocURL = redocLatest
}
if r.Title == "" {
r.Title = "API documentation"
}
} | [
"func",
"(",
"r",
"*",
"RedocOpts",
")",
"EnsureDefaults",
"(",
")",
"{",
"if",
"r",
".",
"BasePath",
"==",
"\"",
"\"",
"{",
"r",
".",
"BasePath",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"r",
".",
"Path",
"==",
"\"",
"\"",
"{",
"r",
".",
"Path",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"r",
".",
"SpecURL",
"==",
"\"",
"\"",
"{",
"r",
".",
"SpecURL",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"r",
".",
"RedocURL",
"==",
"\"",
"\"",
"{",
"r",
".",
"RedocURL",
"=",
"redocLatest",
"\n",
"}",
"\n",
"if",
"r",
".",
"Title",
"==",
"\"",
"\"",
"{",
"r",
".",
"Title",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}"
]
| // EnsureDefaults in case some options are missing | [
"EnsureDefaults",
"in",
"case",
"some",
"options",
"are",
"missing"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/redoc.go#L26-L42 |
10,282 | go-openapi/runtime | middleware/redoc.go | Redoc | func Redoc(opts RedocOpts, next http.Handler) http.Handler {
opts.EnsureDefaults()
pth := path.Join(opts.BasePath, opts.Path)
tmpl := template.Must(template.New("redoc").Parse(redocTemplate))
buf := bytes.NewBuffer(nil)
_ = tmpl.Execute(buf, opts)
b := buf.Bytes()
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.URL.Path == pth {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.WriteHeader(http.StatusOK)
_, _ = rw.Write(b)
return
}
if next == nil {
rw.Header().Set("Content-Type", "text/plain")
rw.WriteHeader(http.StatusNotFound)
_, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
return
}
next.ServeHTTP(rw, r)
})
} | go | func Redoc(opts RedocOpts, next http.Handler) http.Handler {
opts.EnsureDefaults()
pth := path.Join(opts.BasePath, opts.Path)
tmpl := template.Must(template.New("redoc").Parse(redocTemplate))
buf := bytes.NewBuffer(nil)
_ = tmpl.Execute(buf, opts)
b := buf.Bytes()
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.URL.Path == pth {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.WriteHeader(http.StatusOK)
_, _ = rw.Write(b)
return
}
if next == nil {
rw.Header().Set("Content-Type", "text/plain")
rw.WriteHeader(http.StatusNotFound)
_, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
return
}
next.ServeHTTP(rw, r)
})
} | [
"func",
"Redoc",
"(",
"opts",
"RedocOpts",
",",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"opts",
".",
"EnsureDefaults",
"(",
")",
"\n\n",
"pth",
":=",
"path",
".",
"Join",
"(",
"opts",
".",
"BasePath",
",",
"opts",
".",
"Path",
")",
"\n",
"tmpl",
":=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"redocTemplate",
")",
")",
"\n\n",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"_",
"=",
"tmpl",
".",
"Execute",
"(",
"buf",
",",
"opts",
")",
"\n",
"b",
":=",
"buf",
".",
"Bytes",
"(",
")",
"\n\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"URL",
".",
"Path",
"==",
"pth",
"{",
"rw",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n\n",
"_",
",",
"_",
"=",
"rw",
".",
"Write",
"(",
"b",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"next",
"==",
"nil",
"{",
"rw",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"_",
",",
"_",
"=",
"rw",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pth",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"next",
".",
"ServeHTTP",
"(",
"rw",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
]
| // Redoc creates a middleware to serve a documentation site for a swagger spec.
// This allows for altering the spec before starting the http listener.
// | [
"Redoc",
"creates",
"a",
"middleware",
"to",
"serve",
"a",
"documentation",
"site",
"for",
"a",
"swagger",
"spec",
".",
"This",
"allows",
"for",
"altering",
"the",
"spec",
"before",
"starting",
"the",
"http",
"listener",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/middleware/redoc.go#L47-L74 |
10,283 | go-openapi/runtime | request.go | CanHaveBody | func CanHaveBody(method string) bool {
mn := strings.ToUpper(method)
return mn == "POST" || mn == "PUT" || mn == "PATCH" || mn == "DELETE"
} | go | func CanHaveBody(method string) bool {
mn := strings.ToUpper(method)
return mn == "POST" || mn == "PUT" || mn == "PATCH" || mn == "DELETE"
} | [
"func",
"CanHaveBody",
"(",
"method",
"string",
")",
"bool",
"{",
"mn",
":=",
"strings",
".",
"ToUpper",
"(",
"method",
")",
"\n",
"return",
"mn",
"==",
"\"",
"\"",
"||",
"mn",
"==",
"\"",
"\"",
"||",
"mn",
"==",
"\"",
"\"",
"||",
"mn",
"==",
"\"",
"\"",
"\n",
"}"
]
| // CanHaveBody returns true if this method can have a body | [
"CanHaveBody",
"returns",
"true",
"if",
"this",
"method",
"can",
"have",
"a",
"body"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/request.go#L26-L29 |
10,284 | go-openapi/runtime | request.go | IsSafe | func IsSafe(r *http.Request) bool {
mn := strings.ToUpper(r.Method)
return mn == "GET" || mn == "HEAD"
} | go | func IsSafe(r *http.Request) bool {
mn := strings.ToUpper(r.Method)
return mn == "GET" || mn == "HEAD"
} | [
"func",
"IsSafe",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"mn",
":=",
"strings",
".",
"ToUpper",
"(",
"r",
".",
"Method",
")",
"\n",
"return",
"mn",
"==",
"\"",
"\"",
"||",
"mn",
"==",
"\"",
"\"",
"\n",
"}"
]
| // IsSafe returns true if this is a request with a safe method | [
"IsSafe",
"returns",
"true",
"if",
"this",
"is",
"a",
"request",
"with",
"a",
"safe",
"method"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/request.go#L32-L35 |
10,285 | go-openapi/runtime | request.go | HasBody | func HasBody(r *http.Request) bool {
return len(r.TransferEncoding) > 0 || r.ContentLength > 0
} | go | func HasBody(r *http.Request) bool {
return len(r.TransferEncoding) > 0 || r.ContentLength > 0
} | [
"func",
"HasBody",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"return",
"len",
"(",
"r",
".",
"TransferEncoding",
")",
">",
"0",
"||",
"r",
".",
"ContentLength",
">",
"0",
"\n",
"}"
]
| // HasBody returns true if this method needs a content-type | [
"HasBody",
"returns",
"true",
"if",
"this",
"method",
"needs",
"a",
"content",
"-",
"type"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/request.go#L44-L46 |
10,286 | go-openapi/runtime | request.go | JSONRequest | func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return nil, err
}
req.Header.Add(HeaderContentType, JSONMime)
req.Header.Add(HeaderAccept, JSONMime)
return req, nil
} | go | func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return nil, err
}
req.Header.Add(HeaderContentType, JSONMime)
req.Header.Add(HeaderAccept, JSONMime)
return req, nil
} | [
"func",
"JSONRequest",
"(",
"method",
",",
"urlStr",
"string",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"urlStr",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Add",
"(",
"HeaderContentType",
",",
"JSONMime",
")",
"\n",
"req",
".",
"Header",
".",
"Add",
"(",
"HeaderAccept",
",",
"JSONMime",
")",
"\n",
"return",
"req",
",",
"nil",
"\n",
"}"
]
| // JSONRequest creates a new http request with json headers set | [
"JSONRequest",
"creates",
"a",
"new",
"http",
"request",
"with",
"json",
"headers",
"set"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/request.go#L49-L57 |
10,287 | go-openapi/runtime | request.go | ReadSingleValue | func ReadSingleValue(values Gettable, name string) string {
vv, _, hv := values.GetOK(name)
if hv {
return vv[len(vv)-1]
}
return ""
} | go | func ReadSingleValue(values Gettable, name string) string {
vv, _, hv := values.GetOK(name)
if hv {
return vv[len(vv)-1]
}
return ""
} | [
"func",
"ReadSingleValue",
"(",
"values",
"Gettable",
",",
"name",
"string",
")",
"string",
"{",
"vv",
",",
"_",
",",
"hv",
":=",
"values",
".",
"GetOK",
"(",
"name",
")",
"\n",
"if",
"hv",
"{",
"return",
"vv",
"[",
"len",
"(",
"vv",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
]
| // ReadSingleValue reads a single value from the source | [
"ReadSingleValue",
"reads",
"a",
"single",
"value",
"from",
"the",
"source"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/request.go#L65-L71 |
10,288 | go-openapi/runtime | request.go | ReadCollectionValue | func ReadCollectionValue(values Gettable, name, collectionFormat string) []string {
v := ReadSingleValue(values, name)
return swag.SplitByFormat(v, collectionFormat)
} | go | func ReadCollectionValue(values Gettable, name, collectionFormat string) []string {
v := ReadSingleValue(values, name)
return swag.SplitByFormat(v, collectionFormat)
} | [
"func",
"ReadCollectionValue",
"(",
"values",
"Gettable",
",",
"name",
",",
"collectionFormat",
"string",
")",
"[",
"]",
"string",
"{",
"v",
":=",
"ReadSingleValue",
"(",
"values",
",",
"name",
")",
"\n",
"return",
"swag",
".",
"SplitByFormat",
"(",
"v",
",",
"collectionFormat",
")",
"\n",
"}"
]
| // ReadCollectionValue reads a collection value from a string data source | [
"ReadCollectionValue",
"reads",
"a",
"collection",
"value",
"from",
"a",
"string",
"data",
"source"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/request.go#L74-L77 |
10,289 | go-openapi/runtime | values.go | GetOK | func (v Values) GetOK(key string) (value []string, hasKey bool, hasValue bool) {
value, hasKey = v[key]
if !hasKey {
return
}
if len(value) == 0 {
return
}
hasValue = true
return
} | go | func (v Values) GetOK(key string) (value []string, hasKey bool, hasValue bool) {
value, hasKey = v[key]
if !hasKey {
return
}
if len(value) == 0 {
return
}
hasValue = true
return
} | [
"func",
"(",
"v",
"Values",
")",
"GetOK",
"(",
"key",
"string",
")",
"(",
"value",
"[",
"]",
"string",
",",
"hasKey",
"bool",
",",
"hasValue",
"bool",
")",
"{",
"value",
",",
"hasKey",
"=",
"v",
"[",
"key",
"]",
"\n",
"if",
"!",
"hasKey",
"{",
"return",
"\n",
"}",
"\n",
"if",
"len",
"(",
"value",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"hasValue",
"=",
"true",
"\n",
"return",
"\n",
"}"
]
| // GetOK returns the values collection for the given key.
// When the key is present in the map it will return true for hasKey.
// When the value is not empty it will return true for hasValue. | [
"GetOK",
"returns",
"the",
"values",
"collection",
"for",
"the",
"given",
"key",
".",
"When",
"the",
"key",
"is",
"present",
"in",
"the",
"map",
"it",
"will",
"return",
"true",
"for",
"hasKey",
".",
"When",
"the",
"value",
"is",
"not",
"empty",
"it",
"will",
"return",
"true",
"for",
"hasValue",
"."
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/values.go#L9-L19 |
10,290 | go-openapi/runtime | client/request.go | newRequest | func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) (*request, error) {
return &request{
pathPattern: pathPattern,
method: method,
writer: writer,
header: make(http.Header),
query: make(url.Values),
timeout: DefaultTimeout,
}, nil
} | go | func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) (*request, error) {
return &request{
pathPattern: pathPattern,
method: method,
writer: writer,
header: make(http.Header),
query: make(url.Values),
timeout: DefaultTimeout,
}, nil
} | [
"func",
"newRequest",
"(",
"method",
",",
"pathPattern",
"string",
",",
"writer",
"runtime",
".",
"ClientRequestWriter",
")",
"(",
"*",
"request",
",",
"error",
")",
"{",
"return",
"&",
"request",
"{",
"pathPattern",
":",
"pathPattern",
",",
"method",
":",
"method",
",",
"writer",
":",
"writer",
",",
"header",
":",
"make",
"(",
"http",
".",
"Header",
")",
",",
"query",
":",
"make",
"(",
"url",
".",
"Values",
")",
",",
"timeout",
":",
"DefaultTimeout",
",",
"}",
",",
"nil",
"\n",
"}"
]
| // NewRequest creates a new swagger http client request | [
"NewRequest",
"creates",
"a",
"new",
"swagger",
"http",
"client",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/request.go#L37-L46 |
10,291 | go-openapi/runtime | client/request.go | BuildHTTP | func (r *request) BuildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry) (*http.Request, error) {
return r.buildHTTP(mediaType, basePath, producers, registry, nil)
} | go | func (r *request) BuildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry) (*http.Request, error) {
return r.buildHTTP(mediaType, basePath, producers, registry, nil)
} | [
"func",
"(",
"r",
"*",
"request",
")",
"BuildHTTP",
"(",
"mediaType",
",",
"basePath",
"string",
",",
"producers",
"map",
"[",
"string",
"]",
"runtime",
".",
"Producer",
",",
"registry",
"strfmt",
".",
"Registry",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"return",
"r",
".",
"buildHTTP",
"(",
"mediaType",
",",
"basePath",
",",
"producers",
",",
"registry",
",",
"nil",
")",
"\n",
"}"
]
| // BuildHTTP creates a new http request based on the data from the params | [
"BuildHTTP",
"creates",
"a",
"new",
"http",
"request",
"based",
"on",
"the",
"data",
"from",
"the",
"params"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/request.go#L86-L88 |
10,292 | go-openapi/runtime | client/request.go | GetQueryParams | func (r *request) GetQueryParams() url.Values {
var result = make(url.Values)
for key, value := range r.query {
result[key] = append([]string{}, value...)
}
return result
} | go | func (r *request) GetQueryParams() url.Values {
var result = make(url.Values)
for key, value := range r.query {
result[key] = append([]string{}, value...)
}
return result
} | [
"func",
"(",
"r",
"*",
"request",
")",
"GetQueryParams",
"(",
")",
"url",
".",
"Values",
"{",
"var",
"result",
"=",
"make",
"(",
"url",
".",
"Values",
")",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"r",
".",
"query",
"{",
"result",
"[",
"key",
"]",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"}",
",",
"value",
"...",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
]
| // GetQueryParams returns a copy of all query params currently set for the request | [
"GetQueryParams",
"returns",
"a",
"copy",
"of",
"all",
"query",
"params",
"currently",
"set",
"for",
"the",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/request.go#L303-L309 |
10,293 | go-openapi/runtime | client/request.go | SetPathParam | func (r *request) SetPathParam(name string, value string) error {
if r.pathParams == nil {
r.pathParams = make(map[string]string)
}
r.pathParams[name] = value
return nil
} | go | func (r *request) SetPathParam(name string, value string) error {
if r.pathParams == nil {
r.pathParams = make(map[string]string)
}
r.pathParams[name] = value
return nil
} | [
"func",
"(",
"r",
"*",
"request",
")",
"SetPathParam",
"(",
"name",
"string",
",",
"value",
"string",
")",
"error",
"{",
"if",
"r",
".",
"pathParams",
"==",
"nil",
"{",
"r",
".",
"pathParams",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"}",
"\n\n",
"r",
".",
"pathParams",
"[",
"name",
"]",
"=",
"value",
"\n",
"return",
"nil",
"\n",
"}"
]
| // SetPathParam adds a path param to the request | [
"SetPathParam",
"adds",
"a",
"path",
"param",
"to",
"the",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/request.go#L323-L330 |
10,294 | go-openapi/runtime | client/request.go | SetFileParam | func (r *request) SetFileParam(name string, files ...runtime.NamedReadCloser) error {
for _, file := range files {
if actualFile, ok := file.(*os.File); ok {
fi, err := os.Stat(actualFile.Name())
if err != nil {
return err
}
if fi.IsDir() {
return fmt.Errorf("%q is a directory, only files are supported", file.Name())
}
}
}
if r.fileFields == nil {
r.fileFields = make(map[string][]runtime.NamedReadCloser)
}
if r.formFields == nil {
r.formFields = make(url.Values)
}
r.fileFields[name] = files
return nil
} | go | func (r *request) SetFileParam(name string, files ...runtime.NamedReadCloser) error {
for _, file := range files {
if actualFile, ok := file.(*os.File); ok {
fi, err := os.Stat(actualFile.Name())
if err != nil {
return err
}
if fi.IsDir() {
return fmt.Errorf("%q is a directory, only files are supported", file.Name())
}
}
}
if r.fileFields == nil {
r.fileFields = make(map[string][]runtime.NamedReadCloser)
}
if r.formFields == nil {
r.formFields = make(url.Values)
}
r.fileFields[name] = files
return nil
} | [
"func",
"(",
"r",
"*",
"request",
")",
"SetFileParam",
"(",
"name",
"string",
",",
"files",
"...",
"runtime",
".",
"NamedReadCloser",
")",
"error",
"{",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"if",
"actualFile",
",",
"ok",
":=",
"file",
".",
"(",
"*",
"os",
".",
"File",
")",
";",
"ok",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"actualFile",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"fi",
".",
"IsDir",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"fileFields",
"==",
"nil",
"{",
"r",
".",
"fileFields",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"runtime",
".",
"NamedReadCloser",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"formFields",
"==",
"nil",
"{",
"r",
".",
"formFields",
"=",
"make",
"(",
"url",
".",
"Values",
")",
"\n",
"}",
"\n\n",
"r",
".",
"fileFields",
"[",
"name",
"]",
"=",
"files",
"\n",
"return",
"nil",
"\n",
"}"
]
| // SetFileParam adds a file param to the request | [
"SetFileParam",
"adds",
"a",
"file",
"param",
"to",
"the",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/request.go#L333-L355 |
10,295 | go-openapi/runtime | client/request.go | SetTimeout | func (r *request) SetTimeout(timeout time.Duration) error {
r.timeout = timeout
return nil
} | go | func (r *request) SetTimeout(timeout time.Duration) error {
r.timeout = timeout
return nil
} | [
"func",
"(",
"r",
"*",
"request",
")",
"SetTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"r",
".",
"timeout",
"=",
"timeout",
"\n",
"return",
"nil",
"\n",
"}"
]
| // SetTimeout sets the timeout for a request | [
"SetTimeout",
"sets",
"the",
"timeout",
"for",
"a",
"request"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/request.go#L373-L376 |
10,296 | go-openapi/runtime | interfaces.go | Consume | func (fn ConsumerFunc) Consume(reader io.Reader, data interface{}) error {
return fn(reader, data)
} | go | func (fn ConsumerFunc) Consume(reader io.Reader, data interface{}) error {
return fn(reader, data)
} | [
"func",
"(",
"fn",
"ConsumerFunc",
")",
"Consume",
"(",
"reader",
"io",
".",
"Reader",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"fn",
"(",
"reader",
",",
"data",
")",
"\n",
"}"
]
| // Consume consumes the reader into the data parameter | [
"Consume",
"consumes",
"the",
"reader",
"into",
"the",
"data",
"parameter"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/interfaces.go#L41-L43 |
10,297 | go-openapi/runtime | interfaces.go | Produce | func (f ProducerFunc) Produce(writer io.Writer, data interface{}) error {
return f(writer, data)
} | go | func (f ProducerFunc) Produce(writer io.Writer, data interface{}) error {
return f(writer, data)
} | [
"func",
"(",
"f",
"ProducerFunc",
")",
"Produce",
"(",
"writer",
"io",
".",
"Writer",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"f",
"(",
"writer",
",",
"data",
")",
"\n",
"}"
]
| // Produce produces the response for the provided data | [
"Produce",
"produces",
"the",
"response",
"for",
"the",
"provided",
"data"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/interfaces.go#L56-L58 |
10,298 | go-openapi/runtime | interfaces.go | Authorize | func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error {
return f(r, principal)
} | go | func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error {
return f(r, principal)
} | [
"func",
"(",
"f",
"AuthorizerFunc",
")",
"Authorize",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"principal",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"f",
"(",
"r",
",",
"principal",
")",
"\n",
"}"
]
| // Authorize authorizes the processing of the request for the principal | [
"Authorize",
"authorizes",
"the",
"processing",
"of",
"the",
"request",
"for",
"the",
"principal"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/interfaces.go#L86-L88 |
10,299 | go-openapi/runtime | client/runtime.go | TLSClientAuth | func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
// create client tls config
cfg := &tls.Config{}
// load client cert if specified
if opts.Certificate != "" {
cert, err := tls.LoadX509KeyPair(opts.Certificate, opts.Key)
if err != nil {
return nil, fmt.Errorf("tls client cert: %v", err)
}
cfg.Certificates = []tls.Certificate{cert}
} else if opts.LoadedCertificate != nil {
block := pem.Block{Type: "CERTIFICATE", Bytes: opts.LoadedCertificate.Raw}
certPem := pem.EncodeToMemory(&block)
var keyBytes []byte
switch k := opts.LoadedKey.(type) {
case *rsa.PrivateKey:
keyBytes = x509.MarshalPKCS1PrivateKey(k)
case *ecdsa.PrivateKey:
var err error
keyBytes, err = x509.MarshalECPrivateKey(k)
if err != nil {
return nil, fmt.Errorf("tls client priv key: %v", err)
}
default:
return nil, fmt.Errorf("tls client priv key: unsupported key type")
}
block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes}
keyPem := pem.EncodeToMemory(&block)
cert, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
return nil, fmt.Errorf("tls client cert: %v", err)
}
cfg.Certificates = []tls.Certificate{cert}
}
cfg.InsecureSkipVerify = opts.InsecureSkipVerify
// When no CA certificate is provided, default to the system cert pool
// that way when a request is made to a server known by the system trust store,
// the name is still verified
if opts.LoadedCA != nil {
caCertPool := x509.NewCertPool()
caCertPool.AddCert(opts.LoadedCA)
cfg.RootCAs = caCertPool
} else if opts.CA != "" {
// load ca cert
caCert, err := ioutil.ReadFile(opts.CA)
if err != nil {
return nil, fmt.Errorf("tls client ca: %v", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
cfg.RootCAs = caCertPool
}
// apply servername overrride
if opts.ServerName != "" {
cfg.InsecureSkipVerify = false
cfg.ServerName = opts.ServerName
}
cfg.BuildNameToCertificate()
return cfg, nil
} | go | func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
// create client tls config
cfg := &tls.Config{}
// load client cert if specified
if opts.Certificate != "" {
cert, err := tls.LoadX509KeyPair(opts.Certificate, opts.Key)
if err != nil {
return nil, fmt.Errorf("tls client cert: %v", err)
}
cfg.Certificates = []tls.Certificate{cert}
} else if opts.LoadedCertificate != nil {
block := pem.Block{Type: "CERTIFICATE", Bytes: opts.LoadedCertificate.Raw}
certPem := pem.EncodeToMemory(&block)
var keyBytes []byte
switch k := opts.LoadedKey.(type) {
case *rsa.PrivateKey:
keyBytes = x509.MarshalPKCS1PrivateKey(k)
case *ecdsa.PrivateKey:
var err error
keyBytes, err = x509.MarshalECPrivateKey(k)
if err != nil {
return nil, fmt.Errorf("tls client priv key: %v", err)
}
default:
return nil, fmt.Errorf("tls client priv key: unsupported key type")
}
block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes}
keyPem := pem.EncodeToMemory(&block)
cert, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
return nil, fmt.Errorf("tls client cert: %v", err)
}
cfg.Certificates = []tls.Certificate{cert}
}
cfg.InsecureSkipVerify = opts.InsecureSkipVerify
// When no CA certificate is provided, default to the system cert pool
// that way when a request is made to a server known by the system trust store,
// the name is still verified
if opts.LoadedCA != nil {
caCertPool := x509.NewCertPool()
caCertPool.AddCert(opts.LoadedCA)
cfg.RootCAs = caCertPool
} else if opts.CA != "" {
// load ca cert
caCert, err := ioutil.ReadFile(opts.CA)
if err != nil {
return nil, fmt.Errorf("tls client ca: %v", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
cfg.RootCAs = caCertPool
}
// apply servername overrride
if opts.ServerName != "" {
cfg.InsecureSkipVerify = false
cfg.ServerName = opts.ServerName
}
cfg.BuildNameToCertificate()
return cfg, nil
} | [
"func",
"TLSClientAuth",
"(",
"opts",
"TLSClientOptions",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"// create client tls config",
"cfg",
":=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n\n",
"// load client cert if specified",
"if",
"opts",
".",
"Certificate",
"!=",
"\"",
"\"",
"{",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"opts",
".",
"Certificate",
",",
"opts",
".",
"Key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cfg",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
"\n",
"}",
"else",
"if",
"opts",
".",
"LoadedCertificate",
"!=",
"nil",
"{",
"block",
":=",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"opts",
".",
"LoadedCertificate",
".",
"Raw",
"}",
"\n",
"certPem",
":=",
"pem",
".",
"EncodeToMemory",
"(",
"&",
"block",
")",
"\n\n",
"var",
"keyBytes",
"[",
"]",
"byte",
"\n",
"switch",
"k",
":=",
"opts",
".",
"LoadedKey",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rsa",
".",
"PrivateKey",
":",
"keyBytes",
"=",
"x509",
".",
"MarshalPKCS1PrivateKey",
"(",
"k",
")",
"\n",
"case",
"*",
"ecdsa",
".",
"PrivateKey",
":",
"var",
"err",
"error",
"\n",
"keyBytes",
",",
"err",
"=",
"x509",
".",
"MarshalECPrivateKey",
"(",
"k",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"block",
"=",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"keyBytes",
"}",
"\n",
"keyPem",
":=",
"pem",
".",
"EncodeToMemory",
"(",
"&",
"block",
")",
"\n\n",
"cert",
",",
"err",
":=",
"tls",
".",
"X509KeyPair",
"(",
"certPem",
",",
"keyPem",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cfg",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
"\n",
"}",
"\n\n",
"cfg",
".",
"InsecureSkipVerify",
"=",
"opts",
".",
"InsecureSkipVerify",
"\n\n",
"// When no CA certificate is provided, default to the system cert pool",
"// that way when a request is made to a server known by the system trust store,",
"// the name is still verified",
"if",
"opts",
".",
"LoadedCA",
"!=",
"nil",
"{",
"caCertPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"caCertPool",
".",
"AddCert",
"(",
"opts",
".",
"LoadedCA",
")",
"\n",
"cfg",
".",
"RootCAs",
"=",
"caCertPool",
"\n",
"}",
"else",
"if",
"opts",
".",
"CA",
"!=",
"\"",
"\"",
"{",
"// load ca cert",
"caCert",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"opts",
".",
"CA",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"caCertPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"caCertPool",
".",
"AppendCertsFromPEM",
"(",
"caCert",
")",
"\n",
"cfg",
".",
"RootCAs",
"=",
"caCertPool",
"\n",
"}",
"\n\n",
"// apply servername overrride",
"if",
"opts",
".",
"ServerName",
"!=",
"\"",
"\"",
"{",
"cfg",
".",
"InsecureSkipVerify",
"=",
"false",
"\n",
"cfg",
".",
"ServerName",
"=",
"opts",
".",
"ServerName",
"\n",
"}",
"\n\n",
"cfg",
".",
"BuildNameToCertificate",
"(",
")",
"\n\n",
"return",
"cfg",
",",
"nil",
"\n",
"}"
]
| // TLSClientAuth creates a tls.Config for mutual auth | [
"TLSClientAuth",
"creates",
"a",
"tls",
".",
"Config",
"for",
"mutual",
"auth"
]
| a790424692bbda30f61bc3b21754972de1803b91 | https://github.com/go-openapi/runtime/blob/a790424692bbda30f61bc3b21754972de1803b91/client/runtime.go#L83-L151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.