repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
Azure/go-autorest
autorest/mocks/helpers.go
NewRequestWithParams
func NewRequestWithParams(method, u string, body io.Reader) *http.Request { r, err := http.NewRequest(method, u, body) if err != nil { panic(fmt.Sprintf("mocks: ERROR (%v) parsing testing URL %s", err, u)) } return r }
go
func NewRequestWithParams(method, u string, body io.Reader) *http.Request { r, err := http.NewRequest(method, u, body) if err != nil { panic(fmt.Sprintf("mocks: ERROR (%v) parsing testing URL %s", err, u)) } return r }
[ "func", "NewRequestWithParams", "(", "method", ",", "u", "string", ",", "body", "io", ".", "Reader", ")", "*", "http", ".", "Request", "{", "r", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "u", ",", "body", ")", "\n", "if", "er...
// NewRequestWithParams instantiates a new request using the provided parameters.
[ "NewRequestWithParams", "instantiates", "a", "new", "request", "using", "the", "provided", "parameters", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L80-L86
train
Azure/go-autorest
autorest/mocks/helpers.go
NewResponseWithContent
func NewResponseWithContent(c string) *http.Response { return &http.Response{ Status: "200 OK", StatusCode: 200, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Body: NewBody(c), Request: NewRequest(), } }
go
func NewResponseWithContent(c string) *http.Response { return &http.Response{ Status: "200 OK", StatusCode: 200, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Body: NewBody(c), Request: NewRequest(), } }
[ "func", "NewResponseWithContent", "(", "c", "string", ")", "*", "http", ".", "Response", "{", "return", "&", "http", ".", "Response", "{", "Status", ":", "\"", "\"", ",", "StatusCode", ":", "200", ",", "Proto", ":", "\"", "\"", ",", "ProtoMajor", ":", ...
// NewResponseWithContent instantiates a new response with the passed string as the body content.
[ "NewResponseWithContent", "instantiates", "a", "new", "response", "with", "the", "passed", "string", "as", "the", "body", "content", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L94-L104
train
Azure/go-autorest
autorest/mocks/helpers.go
NewResponseWithStatus
func NewResponseWithStatus(s string, c int) *http.Response { resp := NewResponse() resp.Status = s resp.StatusCode = c return resp }
go
func NewResponseWithStatus(s string, c int) *http.Response { resp := NewResponse() resp.Status = s resp.StatusCode = c return resp }
[ "func", "NewResponseWithStatus", "(", "s", "string", ",", "c", "int", ")", "*", "http", ".", "Response", "{", "resp", ":=", "NewResponse", "(", ")", "\n", "resp", ".", "Status", "=", "s", "\n", "resp", ".", "StatusCode", "=", "c", "\n", "return", "re...
// NewResponseWithStatus instantiates a new response using the passed string and integer as the // status and status code.
[ "NewResponseWithStatus", "instantiates", "a", "new", "response", "using", "the", "passed", "string", "and", "integer", "as", "the", "status", "and", "status", "code", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L108-L113
train
Azure/go-autorest
autorest/mocks/helpers.go
NewResponseWithBodyAndStatus
func NewResponseWithBodyAndStatus(body *Body, c int, s string) *http.Response { resp := NewResponse() resp.Body = body resp.ContentLength = body.Length() resp.Status = s resp.StatusCode = c return resp }
go
func NewResponseWithBodyAndStatus(body *Body, c int, s string) *http.Response { resp := NewResponse() resp.Body = body resp.ContentLength = body.Length() resp.Status = s resp.StatusCode = c return resp }
[ "func", "NewResponseWithBodyAndStatus", "(", "body", "*", "Body", ",", "c", "int", ",", "s", "string", ")", "*", "http", ".", "Response", "{", "resp", ":=", "NewResponse", "(", ")", "\n", "resp", ".", "Body", "=", "body", "\n", "resp", ".", "ContentLen...
// NewResponseWithBodyAndStatus instantiates a new response using the specified mock body, // status and status code
[ "NewResponseWithBodyAndStatus", "instantiates", "a", "new", "response", "using", "the", "specified", "mock", "body", "status", "and", "status", "code" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L117-L124
train
Azure/go-autorest
autorest/mocks/helpers.go
SetResponseHeader
func SetResponseHeader(resp *http.Response, h string, v string) { if resp.Header == nil { resp.Header = make(http.Header) } resp.Header.Set(h, v) }
go
func SetResponseHeader(resp *http.Response, h string, v string) { if resp.Header == nil { resp.Header = make(http.Header) } resp.Header.Set(h, v) }
[ "func", "SetResponseHeader", "(", "resp", "*", "http", ".", "Response", ",", "h", "string", ",", "v", "string", ")", "{", "if", "resp", ".", "Header", "==", "nil", "{", "resp", ".", "Header", "=", "make", "(", "http", ".", "Header", ")", "\n", "}",...
// SetResponseHeader adds a header to the passed response.
[ "SetResponseHeader", "adds", "a", "header", "to", "the", "passed", "response", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L127-L132
train
Azure/go-autorest
autorest/mocks/helpers.go
SetResponseHeaderValues
func SetResponseHeaderValues(resp *http.Response, h string, values []string) { if resp.Header == nil { resp.Header = make(http.Header) } for _, v := range values { resp.Header.Add(h, v) } }
go
func SetResponseHeaderValues(resp *http.Response, h string, values []string) { if resp.Header == nil { resp.Header = make(http.Header) } for _, v := range values { resp.Header.Add(h, v) } }
[ "func", "SetResponseHeaderValues", "(", "resp", "*", "http", ".", "Response", ",", "h", "string", ",", "values", "[", "]", "string", ")", "{", "if", "resp", ".", "Header", "==", "nil", "{", "resp", ".", "Header", "=", "make", "(", "http", ".", "Heade...
// SetResponseHeaderValues adds a header containing all the passed string values.
[ "SetResponseHeaderValues", "adds", "a", "header", "containing", "all", "the", "passed", "string", "values", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L135-L142
train
Azure/go-autorest
autorest/mocks/helpers.go
SetAcceptedHeaders
func SetAcceptedHeaders(resp *http.Response) { SetLocationHeader(resp, TestURL) SetRetryHeader(resp, TestDelay) }
go
func SetAcceptedHeaders(resp *http.Response) { SetLocationHeader(resp, TestURL) SetRetryHeader(resp, TestDelay) }
[ "func", "SetAcceptedHeaders", "(", "resp", "*", "http", ".", "Response", ")", "{", "SetLocationHeader", "(", "resp", ",", "TestURL", ")", "\n", "SetRetryHeader", "(", "resp", ",", "TestDelay", ")", "\n", "}" ]
// SetAcceptedHeaders adds the headers usually associated with a 202 Accepted response.
[ "SetAcceptedHeaders", "adds", "the", "headers", "usually", "associated", "with", "a", "202", "Accepted", "response", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L145-L148
train
Azure/go-autorest
autorest/mocks/helpers.go
SetLocationHeader
func SetLocationHeader(resp *http.Response, location string) { SetResponseHeader(resp, http.CanonicalHeaderKey(headerLocation), location) }
go
func SetLocationHeader(resp *http.Response, location string) { SetResponseHeader(resp, http.CanonicalHeaderKey(headerLocation), location) }
[ "func", "SetLocationHeader", "(", "resp", "*", "http", ".", "Response", ",", "location", "string", ")", "{", "SetResponseHeader", "(", "resp", ",", "http", ".", "CanonicalHeaderKey", "(", "headerLocation", ")", ",", "location", ")", "\n", "}" ]
// SetLocationHeader adds the Location header.
[ "SetLocationHeader", "adds", "the", "Location", "header", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L151-L153
train
Azure/go-autorest
autorest/mocks/helpers.go
SetRetryHeader
func SetRetryHeader(resp *http.Response, delay time.Duration) { SetResponseHeader(resp, http.CanonicalHeaderKey(headerRetryAfter), fmt.Sprintf("%v", delay.Seconds())) }
go
func SetRetryHeader(resp *http.Response, delay time.Duration) { SetResponseHeader(resp, http.CanonicalHeaderKey(headerRetryAfter), fmt.Sprintf("%v", delay.Seconds())) }
[ "func", "SetRetryHeader", "(", "resp", "*", "http", ".", "Response", ",", "delay", "time", ".", "Duration", ")", "{", "SetResponseHeader", "(", "resp", ",", "http", ".", "CanonicalHeaderKey", "(", "headerRetryAfter", ")", ",", "fmt", ".", "Sprintf", "(", "...
// SetRetryHeader adds the Retry-After header.
[ "SetRetryHeader", "adds", "the", "Retry", "-", "After", "header", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/helpers.go#L156-L158
train
Azure/go-autorest
autorest/utility.go
NewDecoder
func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { if encodedAs == EncodedAsJSON { return json.NewDecoder(r) } else if encodedAs == EncodedAsXML { return xml.NewDecoder(r) } return nil }
go
func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { if encodedAs == EncodedAsJSON { return json.NewDecoder(r) } else if encodedAs == EncodedAsXML { return xml.NewDecoder(r) } return nil }
[ "func", "NewDecoder", "(", "encodedAs", "EncodedAs", ",", "r", "io", ".", "Reader", ")", "Decoder", "{", "if", "encodedAs", "==", "EncodedAsJSON", "{", "return", "json", ".", "NewDecoder", "(", "r", ")", "\n", "}", "else", "if", "encodedAs", "==", "Encod...
// NewDecoder creates a new decoder appropriate to the passed encoding. // encodedAs specifies the type of encoding and r supplies the io.Reader containing the // encoded data.
[ "NewDecoder", "creates", "a", "new", "decoder", "appropriate", "to", "the", "passed", "encoding", ".", "encodedAs", "specifies", "the", "type", "of", "encoding", "and", "r", "supplies", "the", "io", ".", "Reader", "containing", "the", "encoded", "data", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/utility.go#L51-L58
train
Azure/go-autorest
autorest/utility.go
CopyAndDecode
func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { b := bytes.Buffer{} return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) }
go
func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { b := bytes.Buffer{} return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) }
[ "func", "CopyAndDecode", "(", "encodedAs", "EncodedAs", ",", "r", "io", ".", "Reader", ",", "v", "interface", "{", "}", ")", "(", "bytes", ".", "Buffer", ",", "error", ")", "{", "b", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "return", "b", ",",...
// CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy // is especially useful if there is a chance the data will fail to decode. // encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v // is the decoding destination.
[ "CopyAndDecode", "decodes", "the", "data", "from", "the", "passed", "io", ".", "Reader", "while", "making", "a", "copy", ".", "Having", "a", "copy", "is", "especially", "useful", "if", "there", "is", "a", "chance", "the", "data", "will", "fail", "to", "d...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/utility.go#L64-L67
train
Azure/go-autorest
autorest/utility.go
TeeReadCloser
func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { return &teeReadCloser{rc, io.TeeReader(rc, w)} }
go
func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { return &teeReadCloser{rc, io.TeeReader(rc, w)} }
[ "func", "TeeReadCloser", "(", "rc", "io", ".", "ReadCloser", ",", "w", "io", ".", "Writer", ")", "io", ".", "ReadCloser", "{", "return", "&", "teeReadCloser", "{", "rc", ",", "io", ".", "TeeReader", "(", "rc", ",", "w", ")", "}", "\n", "}" ]
// TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. // It utilizes io.TeeReader to copy the data read and has the same behavior when reading. // Further, when it is closed, it ensures that rc is closed as well.
[ "TeeReadCloser", "returns", "a", "ReadCloser", "that", "writes", "to", "w", "what", "it", "reads", "from", "rc", ".", "It", "utilizes", "io", ".", "TeeReader", "to", "copy", "the", "data", "read", "and", "has", "the", "same", "behavior", "when", "reading",...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/utility.go#L72-L74
train
Azure/go-autorest
autorest/utility.go
Encode
func Encode(location string, v interface{}, sep ...string) string { s := String(v, sep...) switch strings.ToLower(location) { case "path": return pathEscape(s) case "query": return queryEscape(s) default: return s } }
go
func Encode(location string, v interface{}, sep ...string) string { s := String(v, sep...) switch strings.ToLower(location) { case "path": return pathEscape(s) case "query": return queryEscape(s) default: return s } }
[ "func", "Encode", "(", "location", "string", ",", "v", "interface", "{", "}", ",", "sep", "...", "string", ")", "string", "{", "s", ":=", "String", "(", "v", ",", "sep", "...", ")", "\n", "switch", "strings", ".", "ToLower", "(", "location", ")", "...
// Encode method encodes url path and query parameters.
[ "Encode", "method", "encodes", "url", "path", "and", "query", "parameters", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/utility.go#L178-L188
train
Azure/go-autorest
autorest/utility.go
IsTokenRefreshError
func IsTokenRefreshError(err error) bool { if _, ok := err.(adal.TokenRefreshError); ok { return true } if de, ok := err.(DetailedError); ok { return IsTokenRefreshError(de.Original) } return false }
go
func IsTokenRefreshError(err error) bool { if _, ok := err.(adal.TokenRefreshError); ok { return true } if de, ok := err.(DetailedError); ok { return IsTokenRefreshError(de.Original) } return false }
[ "func", "IsTokenRefreshError", "(", "err", "error", ")", "bool", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "adal", ".", "TokenRefreshError", ")", ";", "ok", "{", "return", "true", "\n", "}", "\n", "if", "de", ",", "ok", ":=", "err", ".", ...
// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError // interface. If err is a DetailedError it will walk the chain of Original errors.
[ "IsTokenRefreshError", "returns", "true", "if", "the", "specified", "error", "implements", "the", "TokenRefreshError", "interface", ".", "If", "err", "is", "a", "DetailedError", "it", "will", "walk", "the", "chain", "of", "Original", "errors", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/utility.go#L211-L219
train
Azure/go-autorest
autorest/adal/token.go
Expires
func (t Token) Expires() time.Time { s, err := t.ExpiresOn.Float64() if err != nil { s = -3600 } expiration := date.NewUnixTimeFromSeconds(s) return time.Time(expiration).UTC() }
go
func (t Token) Expires() time.Time { s, err := t.ExpiresOn.Float64() if err != nil { s = -3600 } expiration := date.NewUnixTimeFromSeconds(s) return time.Time(expiration).UTC() }
[ "func", "(", "t", "Token", ")", "Expires", "(", ")", "time", ".", "Time", "{", "s", ",", "err", ":=", "t", ".", "ExpiresOn", ".", "Float64", "(", ")", "\n", "if", "err", "!=", "nil", "{", "s", "=", "-", "3600", "\n", "}", "\n\n", "expiration", ...
// Expires returns the time.Time when the Token expires.
[ "Expires", "returns", "the", "time", ".", "Time", "when", "the", "Token", "expires", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L126-L135
train
Azure/go-autorest
autorest/adal/token.go
WillExpireIn
func (t Token) WillExpireIn(d time.Duration) bool { return !t.Expires().After(time.Now().Add(d)) }
go
func (t Token) WillExpireIn(d time.Duration) bool { return !t.Expires().After(time.Now().Add(d)) }
[ "func", "(", "t", "Token", ")", "WillExpireIn", "(", "d", "time", ".", "Duration", ")", "bool", "{", "return", "!", "t", ".", "Expires", "(", ")", ".", "After", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "d", ")", ")", "\n", "}" ]
// WillExpireIn returns true if the Token will expire after the passed time.Duration interval // from now, false otherwise.
[ "WillExpireIn", "returns", "true", "if", "the", "Token", "will", "expire", "after", "the", "passed", "time", ".", "Duration", "interval", "from", "now", "false", "otherwise", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L144-L146
train
Azure/go-autorest
autorest/adal/token.go
SetAuthenticationValues
func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token") }
go
func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token") }
[ "func", "(", "noSecret", "*", "ServicePrincipalNoSecret", ")", "SetAuthenticationValues", "(", "spt", "*", "ServicePrincipalToken", ",", "v", "*", "url", ".", "Values", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret // It only returns an error for the ServicePrincipalNoSecret type
[ "SetAuthenticationValues", "is", "a", "method", "of", "the", "interface", "ServicePrincipalSecret", "It", "only", "returns", "an", "error", "for", "the", "ServicePrincipalNoSecret", "type" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L166-L168
train
Azure/go-autorest
autorest/adal/token.go
SetAuthenticationValues
func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { v.Set("client_secret", tokenSecret.ClientSecret) return nil }
go
func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { v.Set("client_secret", tokenSecret.ClientSecret) return nil }
[ "func", "(", "tokenSecret", "*", "ServicePrincipalTokenSecret", ")", "SetAuthenticationValues", "(", "spt", "*", "ServicePrincipalToken", ",", "v", "*", "url", ".", "Values", ")", "error", "{", "v", ".", "Set", "(", "\"", "\"", ",", "tokenSecret", ".", "Clie...
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. // It will populate the form submitted during oAuth Token Acquisition using the client_secret.
[ "SetAuthenticationValues", "is", "a", "method", "of", "the", "interface", "ServicePrincipalSecret", ".", "It", "will", "populate", "the", "form", "submitted", "during", "oAuth", "Token", "Acquisition", "using", "the", "client_secret", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L187-L190
train
Azure/go-autorest
autorest/adal/token.go
SignJwt
func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { hasher := sha1.New() _, err := hasher.Write(secret.Certificate.Raw) if err != nil { return "", err } thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) // The jti (JWT ID) claim provides a unique identifier for the JWT. jti := make([]byte, 20) _, err = rand.Read(jti) if err != nil { return "", err } token := jwt.New(jwt.SigningMethodRS256) token.Header["x5t"] = thumbprint x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)} token.Header["x5c"] = x5c token.Claims = jwt.MapClaims{ "aud": spt.inner.OauthConfig.TokenEndpoint.String(), "iss": spt.inner.ClientID, "sub": spt.inner.ClientID, "jti": base64.URLEncoding.EncodeToString(jti), "nbf": time.Now().Unix(), "exp": time.Now().Add(time.Hour * 24).Unix(), } signedString, err := token.SignedString(secret.PrivateKey) return signedString, err }
go
func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { hasher := sha1.New() _, err := hasher.Write(secret.Certificate.Raw) if err != nil { return "", err } thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) // The jti (JWT ID) claim provides a unique identifier for the JWT. jti := make([]byte, 20) _, err = rand.Read(jti) if err != nil { return "", err } token := jwt.New(jwt.SigningMethodRS256) token.Header["x5t"] = thumbprint x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)} token.Header["x5c"] = x5c token.Claims = jwt.MapClaims{ "aud": spt.inner.OauthConfig.TokenEndpoint.String(), "iss": spt.inner.ClientID, "sub": spt.inner.ClientID, "jti": base64.URLEncoding.EncodeToString(jti), "nbf": time.Now().Unix(), "exp": time.Now().Add(time.Hour * 24).Unix(), } signedString, err := token.SignedString(secret.PrivateKey) return signedString, err }
[ "func", "(", "secret", "*", "ServicePrincipalCertificateSecret", ")", "SignJwt", "(", "spt", "*", "ServicePrincipalToken", ")", "(", "string", ",", "error", ")", "{", "hasher", ":=", "sha1", ".", "New", "(", ")", "\n", "_", ",", "err", ":=", "hasher", "....
// SignJwt returns the JWT signed with the certificate's private key.
[ "SignJwt", "returns", "the", "JWT", "signed", "with", "the", "certificate", "s", "private", "key", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L211-L242
train
Azure/go-autorest
autorest/adal/token.go
SetAuthenticationValues
func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { jwt, err := secret.SignJwt(spt) if err != nil { return err } v.Set("client_assertion", jwt) v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") return nil }
go
func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { jwt, err := secret.SignJwt(spt) if err != nil { return err } v.Set("client_assertion", jwt) v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") return nil }
[ "func", "(", "secret", "*", "ServicePrincipalCertificateSecret", ")", "SetAuthenticationValues", "(", "spt", "*", "ServicePrincipalToken", ",", "v", "*", "url", ".", "Values", ")", "error", "{", "jwt", ",", "err", ":=", "secret", ".", "SignJwt", "(", "spt", ...
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. // It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate.
[ "SetAuthenticationValues", "is", "a", "method", "of", "the", "interface", "ServicePrincipalSecret", ".", "It", "will", "populate", "the", "form", "submitted", "during", "oAuth", "Token", "Acquisition", "using", "a", "JWT", "signed", "with", "a", "certificate", "."...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L246-L255
train
Azure/go-autorest
autorest/adal/token.go
MarshalTokenJSON
func (spt ServicePrincipalToken) MarshalTokenJSON() ([]byte, error) { return json.Marshal(spt.inner.Token) }
go
func (spt ServicePrincipalToken) MarshalTokenJSON() ([]byte, error) { return json.Marshal(spt.inner.Token) }
[ "func", "(", "spt", "ServicePrincipalToken", ")", "MarshalTokenJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "spt", ".", "inner", ".", "Token", ")", "\n", "}" ]
// MarshalTokenJSON returns the marshalled inner token.
[ "MarshalTokenJSON", "returns", "the", "marshalled", "inner", "token", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L345-L347
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalTokenWithSecret
func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(id, "id"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } if secret == nil { return nil, fmt.Errorf("parameter 'secret' cannot be nil") } spt := &ServicePrincipalToken{ inner: servicePrincipalToken{ Token: newToken(), OauthConfig: oauthConfig, Secret: secret, ClientID: id, Resource: resource, AutoRefresh: true, RefreshWithin: defaultRefresh, }, refreshLock: &sync.RWMutex{}, sender: &http.Client{Transport: tracing.Transport}, refreshCallbacks: callbacks, } return spt, nil }
go
func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(id, "id"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } if secret == nil { return nil, fmt.Errorf("parameter 'secret' cannot be nil") } spt := &ServicePrincipalToken{ inner: servicePrincipalToken{ Token: newToken(), OauthConfig: oauthConfig, Secret: secret, ClientID: id, Resource: resource, AutoRefresh: true, RefreshWithin: defaultRefresh, }, refreshLock: &sync.RWMutex{}, sender: &http.Client{Transport: tracing.Transport}, refreshCallbacks: callbacks, } return spt, nil }
[ "func", "NewServicePrincipalTokenWithSecret", "(", "oauthConfig", "OAuthConfig", ",", "id", "string", ",", "resource", "string", ",", "secret", "ServicePrincipalSecret", ",", "callbacks", "...", "TokenRefreshCallback", ")", "(", "*", "ServicePrincipalToken", ",", "error...
// NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation.
[ "NewServicePrincipalTokenWithSecret", "create", "a", "ServicePrincipalToken", "using", "the", "supplied", "ServicePrincipalSecret", "implementation", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L417-L445
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalTokenFromManualToken
func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } if token.IsZero() { return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") } spt, err := NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalNoSecret{}, callbacks...) if err != nil { return nil, err } spt.inner.Token = token return spt, nil }
go
func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } if token.IsZero() { return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") } spt, err := NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalNoSecret{}, callbacks...) if err != nil { return nil, err } spt.inner.Token = token return spt, nil }
[ "func", "NewServicePrincipalTokenFromManualToken", "(", "oauthConfig", "OAuthConfig", ",", "clientID", "string", ",", "resource", "string", ",", "token", "Token", ",", "callbacks", "...", "TokenRefreshCallback", ")", "(", "*", "ServicePrincipalToken", ",", "error", ")...
// NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token
[ "NewServicePrincipalTokenFromManualToken", "creates", "a", "ServicePrincipalToken", "using", "the", "supplied", "token" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L448-L474
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalToken
func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(secret, "secret"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalTokenSecret{ ClientSecret: secret, }, callbacks..., ) }
go
func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(secret, "secret"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalTokenSecret{ ClientSecret: secret, }, callbacks..., ) }
[ "func", "NewServicePrincipalToken", "(", "oauthConfig", "OAuthConfig", ",", "clientID", "string", ",", "secret", "string", ",", "resource", "string", ",", "callbacks", "...", "TokenRefreshCallback", ")", "(", "*", "ServicePrincipalToken", ",", "error", ")", "{", "...
// NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal // credentials scoped to the named resource.
[ "NewServicePrincipalToken", "creates", "a", "ServicePrincipalToken", "from", "the", "supplied", "Service", "Principal", "credentials", "scoped", "to", "the", "named", "resource", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L510-L532
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalTokenFromCertificate
func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } if certificate == nil { return nil, fmt.Errorf("parameter 'certificate' cannot be nil") } if privateKey == nil { return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalCertificateSecret{ PrivateKey: privateKey, Certificate: certificate, }, callbacks..., ) }
go
func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } if certificate == nil { return nil, fmt.Errorf("parameter 'certificate' cannot be nil") } if privateKey == nil { return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalCertificateSecret{ PrivateKey: privateKey, Certificate: certificate, }, callbacks..., ) }
[ "func", "NewServicePrincipalTokenFromCertificate", "(", "oauthConfig", "OAuthConfig", ",", "clientID", "string", ",", "certificate", "*", "x509", ".", "Certificate", ",", "privateKey", "*", "rsa", ".", "PrivateKey", ",", "resource", "string", ",", "callbacks", "..."...
// NewServicePrincipalTokenFromCertificate creates a ServicePrincipalToken from the supplied pkcs12 bytes.
[ "NewServicePrincipalTokenFromCertificate", "creates", "a", "ServicePrincipalToken", "from", "the", "supplied", "pkcs12", "bytes", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L535-L561
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalTokenFromUsernamePassword
func NewServicePrincipalTokenFromUsernamePassword(oauthConfig OAuthConfig, clientID string, username string, password string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(username, "username"); err != nil { return nil, err } if err := validateStringParam(password, "password"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalUsernamePasswordSecret{ Username: username, Password: password, }, callbacks..., ) }
go
func NewServicePrincipalTokenFromUsernamePassword(oauthConfig OAuthConfig, clientID string, username string, password string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(username, "username"); err != nil { return nil, err } if err := validateStringParam(password, "password"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalUsernamePasswordSecret{ Username: username, Password: password, }, callbacks..., ) }
[ "func", "NewServicePrincipalTokenFromUsernamePassword", "(", "oauthConfig", "OAuthConfig", ",", "clientID", "string", ",", "username", "string", ",", "password", "string", ",", "resource", "string", ",", "callbacks", "...", "TokenRefreshCallback", ")", "(", "*", "Serv...
// NewServicePrincipalTokenFromUsernamePassword creates a ServicePrincipalToken from the username and password.
[ "NewServicePrincipalTokenFromUsernamePassword", "creates", "a", "ServicePrincipalToken", "from", "the", "username", "and", "password", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L564-L590
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalTokenFromAuthorizationCode
func NewServicePrincipalTokenFromAuthorizationCode(oauthConfig OAuthConfig, clientID string, clientSecret string, authorizationCode string, redirectURI string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(clientSecret, "clientSecret"); err != nil { return nil, err } if err := validateStringParam(authorizationCode, "authorizationCode"); err != nil { return nil, err } if err := validateStringParam(redirectURI, "redirectURI"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalAuthorizationCodeSecret{ ClientSecret: clientSecret, AuthorizationCode: authorizationCode, RedirectURI: redirectURI, }, callbacks..., ) }
go
func NewServicePrincipalTokenFromAuthorizationCode(oauthConfig OAuthConfig, clientID string, clientSecret string, authorizationCode string, redirectURI string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { if err := validateOAuthConfig(oauthConfig); err != nil { return nil, err } if err := validateStringParam(clientID, "clientID"); err != nil { return nil, err } if err := validateStringParam(clientSecret, "clientSecret"); err != nil { return nil, err } if err := validateStringParam(authorizationCode, "authorizationCode"); err != nil { return nil, err } if err := validateStringParam(redirectURI, "redirectURI"); err != nil { return nil, err } if err := validateStringParam(resource, "resource"); err != nil { return nil, err } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, resource, &ServicePrincipalAuthorizationCodeSecret{ ClientSecret: clientSecret, AuthorizationCode: authorizationCode, RedirectURI: redirectURI, }, callbacks..., ) }
[ "func", "NewServicePrincipalTokenFromAuthorizationCode", "(", "oauthConfig", "OAuthConfig", ",", "clientID", "string", ",", "clientSecret", "string", ",", "authorizationCode", "string", ",", "redirectURI", "string", ",", "resource", "string", ",", "callbacks", "...", "T...
// NewServicePrincipalTokenFromAuthorizationCode creates a ServicePrincipalToken from the
[ "NewServicePrincipalTokenFromAuthorizationCode", "creates", "a", "ServicePrincipalToken", "from", "the" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L593-L625
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalTokenFromMSI
func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...) }
go
func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...) }
[ "func", "NewServicePrincipalTokenFromMSI", "(", "msiEndpoint", ",", "resource", "string", ",", "callbacks", "...", "TokenRefreshCallback", ")", "(", "*", "ServicePrincipalToken", ",", "error", ")", "{", "return", "newServicePrincipalTokenFromMSI", "(", "msiEndpoint", ",...
// NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. // It will use the system assigned identity when creating the token.
[ "NewServicePrincipalTokenFromMSI", "creates", "a", "ServicePrincipalToken", "via", "the", "MSI", "VM", "Extension", ".", "It", "will", "use", "the", "system", "assigned", "identity", "when", "creating", "the", "token", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L634-L636
train
Azure/go-autorest
autorest/adal/token.go
NewServicePrincipalTokenFromMSIWithUserAssignedID
func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { return newServicePrincipalTokenFromMSI(msiEndpoint, resource, &userAssignedID, callbacks...) }
go
func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { return newServicePrincipalTokenFromMSI(msiEndpoint, resource, &userAssignedID, callbacks...) }
[ "func", "NewServicePrincipalTokenFromMSIWithUserAssignedID", "(", "msiEndpoint", ",", "resource", "string", ",", "userAssignedID", "string", ",", "callbacks", "...", "TokenRefreshCallback", ")", "(", "*", "ServicePrincipalToken", ",", "error", ")", "{", "return", "newSe...
// NewServicePrincipalTokenFromMSIWithUserAssignedID creates a ServicePrincipalToken via the MSI VM Extension. // It will use the specified user assigned identity when creating the token.
[ "NewServicePrincipalTokenFromMSIWithUserAssignedID", "creates", "a", "ServicePrincipalToken", "via", "the", "MSI", "VM", "Extension", ".", "It", "will", "use", "the", "specified", "user", "assigned", "identity", "when", "creating", "the", "token", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L640-L642
train
Azure/go-autorest
autorest/adal/token.go
InvokeRefreshCallbacks
func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { if spt.refreshCallbacks != nil { for _, callback := range spt.refreshCallbacks { err := callback(spt.inner.Token) if err != nil { return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err) } } } return nil }
go
func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { if spt.refreshCallbacks != nil { for _, callback := range spt.refreshCallbacks { err := callback(spt.inner.Token) if err != nil { return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err) } } } return nil }
[ "func", "(", "spt", "*", "ServicePrincipalToken", ")", "InvokeRefreshCallbacks", "(", "token", "Token", ")", "error", "{", "if", "spt", ".", "refreshCallbacks", "!=", "nil", "{", "for", "_", ",", "callback", ":=", "range", "spt", ".", "refreshCallbacks", "{"...
// InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization
[ "InvokeRefreshCallbacks", "calls", "any", "TokenRefreshCallbacks", "that", "were", "added", "to", "the", "SPT", "during", "initialization" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L735-L745
train
Azure/go-autorest
autorest/adal/token.go
RefreshWithContext
func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error { spt.refreshLock.Lock() defer spt.refreshLock.Unlock() return spt.refreshInternal(ctx, spt.inner.Resource) }
go
func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error { spt.refreshLock.Lock() defer spt.refreshLock.Unlock() return spt.refreshInternal(ctx, spt.inner.Resource) }
[ "func", "(", "spt", "*", "ServicePrincipalToken", ")", "RefreshWithContext", "(", "ctx", "context", ".", "Context", ")", "error", "{", "spt", ".", "refreshLock", ".", "Lock", "(", ")", "\n", "defer", "spt", ".", "refreshLock", ".", "Unlock", "(", ")", "\...
// RefreshWithContext obtains a fresh token for the Service Principal. // This method is not safe for concurrent use and should be syncrhonized.
[ "RefreshWithContext", "obtains", "a", "fresh", "token", "for", "the", "Service", "Principal", ".", "This", "method", "is", "not", "safe", "for", "concurrent", "use", "and", "should", "be", "syncrhonized", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L755-L759
train
Azure/go-autorest
autorest/adal/token.go
RefreshExchange
func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { return spt.RefreshExchangeWithContext(context.Background(), resource) }
go
func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { return spt.RefreshExchangeWithContext(context.Background(), resource) }
[ "func", "(", "spt", "*", "ServicePrincipalToken", ")", "RefreshExchange", "(", "resource", "string", ")", "error", "{", "return", "spt", ".", "RefreshExchangeWithContext", "(", "context", ".", "Background", "(", ")", ",", "resource", ")", "\n", "}" ]
// RefreshExchange refreshes the token, but for a different resource. // This method is not safe for concurrent use and should be syncrhonized.
[ "RefreshExchange", "refreshes", "the", "token", "but", "for", "a", "different", "resource", ".", "This", "method", "is", "not", "safe", "for", "concurrent", "use", "and", "should", "be", "syncrhonized", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L763-L765
train
Azure/go-autorest
autorest/adal/token.go
RefreshExchangeWithContext
func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { spt.refreshLock.Lock() defer spt.refreshLock.Unlock() return spt.refreshInternal(ctx, resource) }
go
func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { spt.refreshLock.Lock() defer spt.refreshLock.Unlock() return spt.refreshInternal(ctx, resource) }
[ "func", "(", "spt", "*", "ServicePrincipalToken", ")", "RefreshExchangeWithContext", "(", "ctx", "context", ".", "Context", ",", "resource", "string", ")", "error", "{", "spt", ".", "refreshLock", ".", "Lock", "(", ")", "\n", "defer", "spt", ".", "refreshLoc...
// RefreshExchangeWithContext refreshes the token, but for a different resource. // This method is not safe for concurrent use and should be syncrhonized.
[ "RefreshExchangeWithContext", "refreshes", "the", "token", "but", "for", "a", "different", "resource", ".", "This", "method", "is", "not", "safe", "for", "concurrent", "use", "and", "should", "be", "syncrhonized", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L769-L773
train
Azure/go-autorest
autorest/adal/token.go
retryForIMDS
func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) { // copied from client.go due to circular dependency retries := []int{ http.StatusRequestTimeout, // 408 http.StatusTooManyRequests, // 429 http.StatusInternalServerError, // 500 http.StatusBadGateway, // 502 http.StatusServiceUnavailable, // 503 http.StatusGatewayTimeout, // 504 } // extra retry status codes specific to IMDS retries = append(retries, http.StatusNotFound, http.StatusGone, // all remaining 5xx http.StatusNotImplemented, http.StatusHTTPVersionNotSupported, http.StatusVariantAlsoNegotiates, http.StatusInsufficientStorage, http.StatusLoopDetected, http.StatusNotExtended, http.StatusNetworkAuthenticationRequired) // see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance const maxDelay time.Duration = 60 * time.Second attempt := 0 delay := time.Duration(0) for attempt < maxAttempts { resp, err = sender.Do(req) // retry on temporary network errors, e.g. transient network failures. // if we don't receive a response then assume we can't connect to the // endpoint so we're likely not running on an Azure VM so don't retry. if (err != nil && !isTemporaryNetworkError(err)) || resp == nil || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) { return } // perform exponential backoff with a cap. // must increment attempt before calculating delay. attempt++ // the base value of 2 is the "delta backoff" as specified in the guidance doc delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second) if delay > maxDelay { delay = maxDelay } select { case <-time.After(delay): // intentionally left blank case <-req.Context().Done(): err = req.Context().Err() return } } return }
go
func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) { // copied from client.go due to circular dependency retries := []int{ http.StatusRequestTimeout, // 408 http.StatusTooManyRequests, // 429 http.StatusInternalServerError, // 500 http.StatusBadGateway, // 502 http.StatusServiceUnavailable, // 503 http.StatusGatewayTimeout, // 504 } // extra retry status codes specific to IMDS retries = append(retries, http.StatusNotFound, http.StatusGone, // all remaining 5xx http.StatusNotImplemented, http.StatusHTTPVersionNotSupported, http.StatusVariantAlsoNegotiates, http.StatusInsufficientStorage, http.StatusLoopDetected, http.StatusNotExtended, http.StatusNetworkAuthenticationRequired) // see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance const maxDelay time.Duration = 60 * time.Second attempt := 0 delay := time.Duration(0) for attempt < maxAttempts { resp, err = sender.Do(req) // retry on temporary network errors, e.g. transient network failures. // if we don't receive a response then assume we can't connect to the // endpoint so we're likely not running on an Azure VM so don't retry. if (err != nil && !isTemporaryNetworkError(err)) || resp == nil || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) { return } // perform exponential backoff with a cap. // must increment attempt before calculating delay. attempt++ // the base value of 2 is the "delta backoff" as specified in the guidance doc delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second) if delay > maxDelay { delay = maxDelay } select { case <-time.After(delay): // intentionally left blank case <-req.Context().Done(): err = req.Context().Err() return } } return }
[ "func", "retryForIMDS", "(", "sender", "Sender", ",", "req", "*", "http", ".", "Request", ",", "maxAttempts", "int", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "// copied from client.go due to circular dependency", "retries", ...
// retry logic specific to retrieving a token from the IMDS endpoint
[ "retry", "logic", "specific", "to", "retrieving", "a", "token", "from", "the", "IMDS", "endpoint" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L879-L936
train
Azure/go-autorest
autorest/adal/token.go
isTemporaryNetworkError
func isTemporaryNetworkError(err error) bool { if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) { return true } return false }
go
func isTemporaryNetworkError(err error) bool { if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) { return true } return false }
[ "func", "isTemporaryNetworkError", "(", "err", "error", ")", "bool", "{", "if", "netErr", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "!", "ok", "||", "(", "ok", "&&", "netErr", ".", "Temporary", "(", ")", ")", "{", "return", ...
// returns true if the specified error is a temporary network error or false if it's not. // if the error doesn't implement the net.Error interface the return value is true.
[ "returns", "true", "if", "the", "specified", "error", "is", "a", "temporary", "network", "error", "or", "false", "if", "it", "s", "not", ".", "if", "the", "error", "doesn", "t", "implement", "the", "net", ".", "Error", "interface", "the", "return", "valu...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L940-L945
train
Azure/go-autorest
autorest/adal/token.go
SetRefreshWithin
func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { spt.inner.RefreshWithin = d return }
go
func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { spt.inner.RefreshWithin = d return }
[ "func", "(", "spt", "*", "ServicePrincipalToken", ")", "SetRefreshWithin", "(", "d", "time", ".", "Duration", ")", "{", "spt", ".", "inner", ".", "RefreshWithin", "=", "d", "\n", "return", "\n", "}" ]
// SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will // refresh the token.
[ "SetRefreshWithin", "sets", "the", "interval", "within", "which", "if", "the", "token", "will", "expire", "EnsureFresh", "will", "refresh", "the", "token", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L964-L967
train
Azure/go-autorest
autorest/adal/token.go
OAuthToken
func (spt *ServicePrincipalToken) OAuthToken() string { spt.refreshLock.RLock() defer spt.refreshLock.RUnlock() return spt.inner.Token.OAuthToken() }
go
func (spt *ServicePrincipalToken) OAuthToken() string { spt.refreshLock.RLock() defer spt.refreshLock.RUnlock() return spt.inner.Token.OAuthToken() }
[ "func", "(", "spt", "*", "ServicePrincipalToken", ")", "OAuthToken", "(", ")", "string", "{", "spt", ".", "refreshLock", ".", "RLock", "(", ")", "\n", "defer", "spt", ".", "refreshLock", ".", "RUnlock", "(", ")", "\n", "return", "spt", ".", "inner", "....
// OAuthToken implements the OAuthTokenProvider interface. It returns the current access token.
[ "OAuthToken", "implements", "the", "OAuthTokenProvider", "interface", ".", "It", "returns", "the", "current", "access", "token", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L974-L978
train
Azure/go-autorest
autorest/adal/token.go
Token
func (spt *ServicePrincipalToken) Token() Token { spt.refreshLock.RLock() defer spt.refreshLock.RUnlock() return spt.inner.Token }
go
func (spt *ServicePrincipalToken) Token() Token { spt.refreshLock.RLock() defer spt.refreshLock.RUnlock() return spt.inner.Token }
[ "func", "(", "spt", "*", "ServicePrincipalToken", ")", "Token", "(", ")", "Token", "{", "spt", ".", "refreshLock", ".", "RLock", "(", ")", "\n", "defer", "spt", ".", "refreshLock", ".", "RUnlock", "(", ")", "\n", "return", "spt", ".", "inner", ".", "...
// Token returns a copy of the current token.
[ "Token", "returns", "a", "copy", "of", "the", "current", "token", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L981-L985
train
Azure/go-autorest
autorest/mocks/mocks.go
Read
func (body *Body) Read(b []byte) (n int, err error) { if !body.IsOpen() { return 0, fmt.Errorf("ERROR: Body has been closed") } if len(body.b) == 0 { return 0, io.EOF } n = copy(b, body.b) body.b = body.b[n:] return n, nil }
go
func (body *Body) Read(b []byte) (n int, err error) { if !body.IsOpen() { return 0, fmt.Errorf("ERROR: Body has been closed") } if len(body.b) == 0 { return 0, io.EOF } n = copy(b, body.b) body.b = body.b[n:] return n, nil }
[ "func", "(", "body", "*", "Body", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "!", "body", ".", "IsOpen", "(", ")", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")",...
// Read reads into the passed byte slice and returns the bytes read.
[ "Read", "reads", "into", "the", "passed", "byte", "slice", "and", "returns", "the", "bytes", "read", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L46-L56
train
Azure/go-autorest
autorest/mocks/mocks.go
Close
func (body *Body) Close() error { if body.isOpen { body.isOpen = false body.closeAttempts++ } return nil }
go
func (body *Body) Close() error { if body.isOpen { body.isOpen = false body.closeAttempts++ } return nil }
[ "func", "(", "body", "*", "Body", ")", "Close", "(", ")", "error", "{", "if", "body", ".", "isOpen", "{", "body", ".", "isOpen", "=", "false", "\n", "body", ".", "closeAttempts", "++", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes the body.
[ "Close", "closes", "the", "body", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L59-L65
train
Azure/go-autorest
autorest/mocks/mocks.go
Length
func (body *Body) Length() int64 { if body == nil { return 0 } return int64(len(body.b)) }
go
func (body *Body) Length() int64 { if body == nil { return 0 } return int64(len(body.b)) }
[ "func", "(", "body", "*", "Body", ")", "Length", "(", ")", "int64", "{", "if", "body", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "int64", "(", "len", "(", "body", ".", "b", ")", ")", "\n", "}" ]
// Length returns the number of bytes in the body.
[ "Length", "returns", "the", "number", "of", "bytes", "in", "the", "body", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L84-L89
train
Azure/go-autorest
autorest/mocks/mocks.go
Do
func (c *Sender) Do(r *http.Request) (resp *http.Response, err error) { c.attempts++ if len(c.responses) > 0 { resp = c.responses[0].r if resp != nil { if b, ok := resp.Body.(*Body); ok { b.reset() } } else { err = c.responses[0].e } time.Sleep(c.responses[0].d) c.repeatResponse[0]-- if c.repeatResponse[0] == 0 { c.responses = c.responses[1:] c.repeatResponse = c.repeatResponse[1:] } } else { resp = NewResponse() } if resp != nil { resp.Request = r } if c.emitErrorAfter > 0 { c.emitErrorAfter-- } else if c.err != nil { err = c.err c.repeatError-- if c.repeatError == 0 { c.err = nil } } return }
go
func (c *Sender) Do(r *http.Request) (resp *http.Response, err error) { c.attempts++ if len(c.responses) > 0 { resp = c.responses[0].r if resp != nil { if b, ok := resp.Body.(*Body); ok { b.reset() } } else { err = c.responses[0].e } time.Sleep(c.responses[0].d) c.repeatResponse[0]-- if c.repeatResponse[0] == 0 { c.responses = c.responses[1:] c.repeatResponse = c.repeatResponse[1:] } } else { resp = NewResponse() } if resp != nil { resp.Request = r } if c.emitErrorAfter > 0 { c.emitErrorAfter-- } else if c.err != nil { err = c.err c.repeatError-- if c.repeatError == 0 { c.err = nil } } return }
[ "func", "(", "c", "*", "Sender", ")", "Do", "(", "r", "*", "http", ".", "Request", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "c", ".", "attempts", "++", "\n\n", "if", "len", "(", "c", ".", "responses", ")", ...
// Do accepts the passed request and, based on settings, emits a response and possible error.
[ "Do", "accepts", "the", "passed", "request", "and", "based", "on", "settings", "emits", "a", "response", "and", "possible", "error", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L114-L150
train
Azure/go-autorest
autorest/mocks/mocks.go
AppendResponseWithDelay
func (c *Sender) AppendResponseWithDelay(resp *http.Response, delay time.Duration) { c.AppendAndRepeatResponseWithDelay(resp, delay, 1) }
go
func (c *Sender) AppendResponseWithDelay(resp *http.Response, delay time.Duration) { c.AppendAndRepeatResponseWithDelay(resp, delay, 1) }
[ "func", "(", "c", "*", "Sender", ")", "AppendResponseWithDelay", "(", "resp", "*", "http", ".", "Response", ",", "delay", "time", ".", "Duration", ")", "{", "c", ".", "AppendAndRepeatResponseWithDelay", "(", "resp", ",", "delay", ",", "1", ")", "\n", "}"...
// AppendResponseWithDelay adds the passed http.Response to the response stack with the specified delay.
[ "AppendResponseWithDelay", "adds", "the", "passed", "http", ".", "Response", "to", "the", "response", "stack", "with", "the", "specified", "delay", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L158-L160
train
Azure/go-autorest
autorest/mocks/mocks.go
AppendAndRepeatResponse
func (c *Sender) AppendAndRepeatResponse(resp *http.Response, repeat int) { c.appendAndRepeat(response{r: resp}, repeat) }
go
func (c *Sender) AppendAndRepeatResponse(resp *http.Response, repeat int) { c.appendAndRepeat(response{r: resp}, repeat) }
[ "func", "(", "c", "*", "Sender", ")", "AppendAndRepeatResponse", "(", "resp", "*", "http", ".", "Response", ",", "repeat", "int", ")", "{", "c", ".", "appendAndRepeat", "(", "response", "{", "r", ":", "resp", "}", ",", "repeat", ")", "\n", "}" ]
// AppendAndRepeatResponse adds the passed http.Response to the response stack along with a // repeat count. A negative repeat count will return the response for all remaining calls to Do.
[ "AppendAndRepeatResponse", "adds", "the", "passed", "http", ".", "Response", "to", "the", "response", "stack", "along", "with", "a", "repeat", "count", ".", "A", "negative", "repeat", "count", "will", "return", "the", "response", "for", "all", "remaining", "ca...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L164-L166
train
Azure/go-autorest
autorest/mocks/mocks.go
AppendAndRepeatResponseWithDelay
func (c *Sender) AppendAndRepeatResponseWithDelay(resp *http.Response, delay time.Duration, repeat int) { c.appendAndRepeat(response{r: resp, d: delay}, repeat) }
go
func (c *Sender) AppendAndRepeatResponseWithDelay(resp *http.Response, delay time.Duration, repeat int) { c.appendAndRepeat(response{r: resp, d: delay}, repeat) }
[ "func", "(", "c", "*", "Sender", ")", "AppendAndRepeatResponseWithDelay", "(", "resp", "*", "http", ".", "Response", ",", "delay", "time", ".", "Duration", ",", "repeat", "int", ")", "{", "c", ".", "appendAndRepeat", "(", "response", "{", "r", ":", "resp...
// AppendAndRepeatResponseWithDelay adds the passed http.Response to the response stack with the specified // delay along with a repeat count. A negative repeat count will return the response for all remaining calls to Do.
[ "AppendAndRepeatResponseWithDelay", "adds", "the", "passed", "http", ".", "Response", "to", "the", "response", "stack", "with", "the", "specified", "delay", "along", "with", "a", "repeat", "count", ".", "A", "negative", "repeat", "count", "will", "return", "the"...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L170-L172
train
Azure/go-autorest
autorest/mocks/mocks.go
AppendAndRepeatError
func (c *Sender) AppendAndRepeatError(err error, repeat int) { c.appendAndRepeat(response{e: err}, repeat) }
go
func (c *Sender) AppendAndRepeatError(err error, repeat int) { c.appendAndRepeat(response{e: err}, repeat) }
[ "func", "(", "c", "*", "Sender", ")", "AppendAndRepeatError", "(", "err", "error", ",", "repeat", "int", ")", "{", "c", ".", "appendAndRepeat", "(", "response", "{", "e", ":", "err", "}", ",", "repeat", ")", "\n", "}" ]
// AppendAndRepeatError adds the passed error to the response stack along with a repeat // count. A negative repeat count will return the response for all remaining calls to Do.
[ "AppendAndRepeatError", "adds", "the", "passed", "error", "to", "the", "response", "stack", "along", "with", "a", "repeat", "count", ".", "A", "negative", "repeat", "count", "will", "return", "the", "response", "for", "all", "remaining", "calls", "to", "Do", ...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L181-L183
train
Azure/go-autorest
autorest/mocks/mocks.go
SetAndRepeatError
func (c *Sender) SetAndRepeatError(err error, repeat int) { c.err = err c.repeatError = repeat }
go
func (c *Sender) SetAndRepeatError(err error, repeat int) { c.err = err c.repeatError = repeat }
[ "func", "(", "c", "*", "Sender", ")", "SetAndRepeatError", "(", "err", "error", ",", "repeat", "int", ")", "{", "c", ".", "err", "=", "err", "\n", "c", ".", "repeatError", "=", "repeat", "\n", "}" ]
// SetAndRepeatError sets the error Do should return and how many calls to Do will return the error. // A negative repeat value will return the error for all remaining calls to Do.
[ "SetAndRepeatError", "sets", "the", "error", "Do", "should", "return", "and", "how", "many", "calls", "to", "Do", "will", "return", "the", "error", ".", "A", "negative", "repeat", "value", "will", "return", "the", "error", "for", "all", "remaining", "calls",...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L208-L211
train
Azure/go-autorest
autorest/azure/cli/profile.go
ProfilePath
func ProfilePath() (string, error) { if cfgDir := os.Getenv("AZURE_CONFIG_DIR"); cfgDir != "" { return filepath.Join(cfgDir, azureProfileJSON), nil } return homedir.Expand("~/.azure/" + azureProfileJSON) }
go
func ProfilePath() (string, error) { if cfgDir := os.Getenv("AZURE_CONFIG_DIR"); cfgDir != "" { return filepath.Join(cfgDir, azureProfileJSON), nil } return homedir.Expand("~/.azure/" + azureProfileJSON) }
[ "func", "ProfilePath", "(", ")", "(", "string", ",", "error", ")", "{", "if", "cfgDir", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "cfgDir", "!=", "\"", "\"", "{", "return", "filepath", ".", "Join", "(", "cfgDir", ",", "azureProfileJSON", ...
// ProfilePath returns the path where the Azure Profile is stored from the Azure CLI
[ "ProfilePath", "returns", "the", "path", "where", "the", "Azure", "Profile", "is", "stored", "from", "the", "Azure", "CLI" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/profile.go#L55-L60
train
Azure/go-autorest
autorest/azure/cli/profile.go
LoadProfile
func LoadProfile(path string) (result Profile, err error) { var contents []byte contents, err = ioutil.ReadFile(path) if err != nil { err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) return } reader := utfbom.SkipOnly(bytes.NewReader(contents)) dec := json.NewDecoder(reader) if err = dec.Decode(&result); err != nil { err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err) return } return }
go
func LoadProfile(path string) (result Profile, err error) { var contents []byte contents, err = ioutil.ReadFile(path) if err != nil { err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) return } reader := utfbom.SkipOnly(bytes.NewReader(contents)) dec := json.NewDecoder(reader) if err = dec.Decode(&result); err != nil { err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err) return } return }
[ "func", "LoadProfile", "(", "path", "string", ")", "(", "result", "Profile", ",", "err", "error", ")", "{", "var", "contents", "[", "]", "byte", "\n", "contents", ",", "err", "=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", ...
// LoadProfile restores a Profile object from a file located at 'path'.
[ "LoadProfile", "restores", "a", "Profile", "object", "from", "a", "file", "located", "at", "path", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/profile.go#L63-L79
train
Azure/go-autorest
autorest/autorest.go
ResponseHasStatusCode
func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { if resp == nil { return false } return containsInt(codes, resp.StatusCode) }
go
func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { if resp == nil { return false } return containsInt(codes, resp.StatusCode) }
[ "func", "ResponseHasStatusCode", "(", "resp", "*", "http", ".", "Response", ",", "codes", "...", "int", ")", "bool", "{", "if", "resp", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "containsInt", "(", "codes", ",", "resp", ".", "Stat...
// ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set // and false otherwise.
[ "ResponseHasStatusCode", "returns", "true", "if", "the", "status", "code", "in", "the", "HTTP", "Response", "is", "in", "the", "passed", "set", "and", "false", "otherwise", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L90-L95
train
Azure/go-autorest
autorest/autorest.go
GetRetryAfter
func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { retry := resp.Header.Get(HeaderRetryAfter) if retry == "" { return defaultDelay } d, err := time.ParseDuration(retry + "s") if err != nil { return defaultDelay } return d }
go
func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { retry := resp.Header.Get(HeaderRetryAfter) if retry == "" { return defaultDelay } d, err := time.ParseDuration(retry + "s") if err != nil { return defaultDelay } return d }
[ "func", "GetRetryAfter", "(", "resp", "*", "http", ".", "Response", ",", "defaultDelay", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "retry", ":=", "resp", ".", "Header", ".", "Get", "(", "HeaderRetryAfter", ")", "\n", "if", "retry", "=="...
// GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If // the header is absent or is malformed, it will return the supplied default delay time.Duration.
[ "GetRetryAfter", "extracts", "the", "retry", "delay", "from", "the", "Retry", "-", "After", "header", "of", "the", "passed", "response", ".", "If", "the", "header", "is", "absent", "or", "is", "malformed", "it", "will", "return", "the", "supplied", "default"...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L104-L116
train
Azure/go-autorest
autorest/autorest.go
NewPollingRequest
func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { location := GetLocation(resp) if location == "" { return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") } req, err := Prepare(&http.Request{Cancel: cancel}, AsGet(), WithBaseURL(location)) if err != nil { return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) } return req, nil }
go
func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { location := GetLocation(resp) if location == "" { return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") } req, err := Prepare(&http.Request{Cancel: cancel}, AsGet(), WithBaseURL(location)) if err != nil { return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) } return req, nil }
[ "func", "NewPollingRequest", "(", "resp", "*", "http", ".", "Response", ",", "cancel", "<-", "chan", "struct", "{", "}", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "location", ":=", "GetLocation", "(", "resp", ")", "\n", "if", "lo...
// NewPollingRequest allocates and returns a new http.Request to poll for the passed response.
[ "NewPollingRequest", "allocates", "and", "returns", "a", "new", "http", ".", "Request", "to", "poll", "for", "the", "passed", "response", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L119-L133
train
Azure/go-autorest
autorest/autorest.go
NewPollingRequestWithContext
func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) { location := GetLocation(resp) if location == "" { return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling") } req, err := Prepare((&http.Request{}).WithContext(ctx), AsGet(), WithBaseURL(location)) if err != nil { return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location) } return req, nil }
go
func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) { location := GetLocation(resp) if location == "" { return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling") } req, err := Prepare((&http.Request{}).WithContext(ctx), AsGet(), WithBaseURL(location)) if err != nil { return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location) } return req, nil }
[ "func", "NewPollingRequestWithContext", "(", "ctx", "context", ".", "Context", ",", "resp", "*", "http", ".", "Response", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "location", ":=", "GetLocation", "(", "resp", ")", "\n", "if", "locat...
// NewPollingRequestWithContext allocates and returns a new http.Request with the specified context to poll for the passed response.
[ "NewPollingRequestWithContext", "allocates", "and", "returns", "a", "new", "http", ".", "Request", "with", "the", "specified", "context", "to", "poll", "for", "the", "passed", "response", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L136-L150
train
Azure/go-autorest
autorest/error.go
NewError
func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { return NewErrorWithError(nil, packageType, method, nil, message, args...) }
go
func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { return NewErrorWithError(nil, packageType, method, nil, message, args...) }
[ "func", "NewError", "(", "packageType", "string", ",", "method", "string", ",", "message", "string", ",", "args", "...", "interface", "{", "}", ")", "DetailedError", "{", "return", "NewErrorWithError", "(", "nil", ",", "packageType", ",", "method", ",", "nil...
// NewError creates a new Error conforming object from the passed packageType, method, and // message. message is treated as a format string to which the optional args apply.
[ "NewError", "creates", "a", "new", "Error", "conforming", "object", "from", "the", "passed", "packageType", "method", "and", "message", ".", "message", "is", "treated", "as", "a", "format", "string", "to", "which", "the", "optional", "args", "apply", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/error.go#L55-L57
train
Azure/go-autorest
autorest/date/utility.go
ParseTime
func ParseTime(format string, t string) (d time.Time, err error) { return time.Parse(format, strings.ToUpper(t)) }
go
func ParseTime(format string, t string) (d time.Time, err error) { return time.Parse(format, strings.ToUpper(t)) }
[ "func", "ParseTime", "(", "format", "string", ",", "t", "string", ")", "(", "d", "time", ".", "Time", ",", "err", "error", ")", "{", "return", "time", ".", "Parse", "(", "format", ",", "strings", ".", "ToUpper", "(", "t", ")", ")", "\n", "}" ]
// ParseTime to parse Time string to specified format.
[ "ParseTime", "to", "parse", "Time", "string", "to", "specified", "format", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/utility.go#L23-L25
train
Azure/go-autorest
autorest/adal/config.go
NewOAuthConfig
func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { apiVer := "1.0" return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer) }
go
func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { apiVer := "1.0" return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer) }
[ "func", "NewOAuthConfig", "(", "activeDirectoryEndpoint", ",", "tenantID", "string", ")", "(", "*", "OAuthConfig", ",", "error", ")", "{", "apiVer", ":=", "\"", "\"", "\n", "return", "NewOAuthConfigWithAPIVersion", "(", "activeDirectoryEndpoint", ",", "tenantID", ...
// NewOAuthConfig returns an OAuthConfig with tenant specific urls
[ "NewOAuthConfig", "returns", "an", "OAuthConfig", "with", "tenant", "specific", "urls" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/config.go#L44-L47
train
Azure/go-autorest
autorest/adal/config.go
NewOAuthConfigWithAPIVersion
func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) { if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { return nil, err } api := "" // it's legal for tenantID to be empty so don't validate it if apiVersion != nil { if err := validateStringParam(*apiVersion, "apiVersion"); err != nil { return nil, err } api = fmt.Sprintf("?api-version=%s", *apiVersion) } const activeDirectoryEndpointTemplate = "%s/oauth2/%s%s" u, err := url.Parse(activeDirectoryEndpoint) if err != nil { return nil, err } authorityURL, err := u.Parse(tenantID) if err != nil { return nil, err } authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api)) if err != nil { return nil, err } tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api)) if err != nil { return nil, err } deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api)) if err != nil { return nil, err } return &OAuthConfig{ AuthorityEndpoint: *authorityURL, AuthorizeEndpoint: *authorizeURL, TokenEndpoint: *tokenURL, DeviceCodeEndpoint: *deviceCodeURL, }, nil }
go
func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) { if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { return nil, err } api := "" // it's legal for tenantID to be empty so don't validate it if apiVersion != nil { if err := validateStringParam(*apiVersion, "apiVersion"); err != nil { return nil, err } api = fmt.Sprintf("?api-version=%s", *apiVersion) } const activeDirectoryEndpointTemplate = "%s/oauth2/%s%s" u, err := url.Parse(activeDirectoryEndpoint) if err != nil { return nil, err } authorityURL, err := u.Parse(tenantID) if err != nil { return nil, err } authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api)) if err != nil { return nil, err } tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api)) if err != nil { return nil, err } deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api)) if err != nil { return nil, err } return &OAuthConfig{ AuthorityEndpoint: *authorityURL, AuthorizeEndpoint: *authorizeURL, TokenEndpoint: *tokenURL, DeviceCodeEndpoint: *deviceCodeURL, }, nil }
[ "func", "NewOAuthConfigWithAPIVersion", "(", "activeDirectoryEndpoint", ",", "tenantID", "string", ",", "apiVersion", "*", "string", ")", "(", "*", "OAuthConfig", ",", "error", ")", "{", "if", "err", ":=", "validateStringParam", "(", "activeDirectoryEndpoint", ",", ...
// NewOAuthConfigWithAPIVersion returns an OAuthConfig with tenant specific urls. // If apiVersion is not nil the "api-version" query parameter will be appended to the endpoint URLs with the specified value.
[ "NewOAuthConfigWithAPIVersion", "returns", "an", "OAuthConfig", "with", "tenant", "specific", "urls", ".", "If", "apiVersion", "is", "not", "nil", "the", "api", "-", "version", "query", "parameter", "will", "be", "appended", "to", "the", "endpoint", "URLs", "wit...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/config.go#L51-L91
train
Azure/go-autorest
autorest/adal/devicetoken.go
InitiateDeviceAuth
func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { v := url.Values{ "client_id": []string{clientID}, "resource": []string{resource}, } s := v.Encode() body := ioutil.NopCloser(strings.NewReader(s)) req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) } req.ContentLength = int64(len(s)) req.Header.Set(contentType, mimeTypeFormPost) resp, err := sender.Do(req) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) } defer resp.Body.Close() rb, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK) } if len(strings.Trim(string(rb), " ")) == 0 { return nil, ErrDeviceCodeEmpty } var code DeviceCode err = json.Unmarshal(rb, &code) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) } code.ClientID = clientID code.Resource = resource code.OAuthConfig = oauthConfig return &code, nil }
go
func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { v := url.Values{ "client_id": []string{clientID}, "resource": []string{resource}, } s := v.Encode() body := ioutil.NopCloser(strings.NewReader(s)) req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) } req.ContentLength = int64(len(s)) req.Header.Set(contentType, mimeTypeFormPost) resp, err := sender.Do(req) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) } defer resp.Body.Close() rb, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK) } if len(strings.Trim(string(rb), " ")) == 0 { return nil, ErrDeviceCodeEmpty } var code DeviceCode err = json.Unmarshal(rb, &code) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) } code.ClientID = clientID code.Resource = resource code.OAuthConfig = oauthConfig return &code, nil }
[ "func", "InitiateDeviceAuth", "(", "sender", "Sender", ",", "oauthConfig", "OAuthConfig", ",", "clientID", ",", "resource", "string", ")", "(", "*", "DeviceCode", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "[", "]", ...
// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode // that can be used with CheckForUserCompletion or WaitForUserCompletion.
[ "InitiateDeviceAuth", "initiates", "a", "device", "auth", "flow", ".", "It", "returns", "a", "DeviceCode", "that", "can", "be", "used", "with", "CheckForUserCompletion", "or", "WaitForUserCompletion", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/devicetoken.go#L104-L150
train
Azure/go-autorest
autorest/adal/devicetoken.go
WaitForUserCompletion
func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { intervalDuration := time.Duration(*code.Interval) * time.Second waitDuration := intervalDuration for { token, err := CheckForUserCompletion(sender, code) if err == nil { return token, nil } switch err { case ErrDeviceSlowDown: waitDuration += waitDuration case ErrDeviceAuthorizationPending: // noop default: // everything else is "fatal" to us return nil, err } if waitDuration > (intervalDuration * 3) { return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) } time.Sleep(waitDuration) } }
go
func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { intervalDuration := time.Duration(*code.Interval) * time.Second waitDuration := intervalDuration for { token, err := CheckForUserCompletion(sender, code) if err == nil { return token, nil } switch err { case ErrDeviceSlowDown: waitDuration += waitDuration case ErrDeviceAuthorizationPending: // noop default: // everything else is "fatal" to us return nil, err } if waitDuration > (intervalDuration * 3) { return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) } time.Sleep(waitDuration) } }
[ "func", "WaitForUserCompletion", "(", "sender", "Sender", ",", "code", "*", "DeviceCode", ")", "(", "*", "Token", ",", "error", ")", "{", "intervalDuration", ":=", "time", ".", "Duration", "(", "*", "code", ".", "Interval", ")", "*", "time", ".", "Second...
// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. // This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'.
[ "WaitForUserCompletion", "calls", "CheckForUserCompletion", "repeatedly", "until", "a", "token", "is", "granted", "or", "an", "error", "state", "occurs", ".", "This", "prevents", "the", "user", "from", "looping", "and", "checking", "against", "ErrDeviceAuthorizationPe...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/devicetoken.go#L216-L242
train
Azure/go-autorest
autorest/date/unixtime.go
Duration
func (t UnixTime) Duration() time.Duration { return time.Time(t).Sub(unixEpoch) }
go
func (t UnixTime) Duration() time.Duration { return time.Time(t).Sub(unixEpoch) }
[ "func", "(", "t", "UnixTime", ")", "Duration", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Time", "(", "t", ")", ".", "Sub", "(", "unixEpoch", ")", "\n", "}" ]
// Duration returns the time as a Duration since the UnixEpoch.
[ "Duration", "returns", "the", "time", "as", "a", "Duration", "since", "the", "UnixEpoch", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L32-L34
train
Azure/go-autorest
autorest/date/unixtime.go
NewUnixTimeFromSeconds
func NewUnixTimeFromSeconds(seconds float64) UnixTime { return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second))) }
go
func NewUnixTimeFromSeconds(seconds float64) UnixTime { return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second))) }
[ "func", "NewUnixTimeFromSeconds", "(", "seconds", "float64", ")", "UnixTime", "{", "return", "NewUnixTimeFromDuration", "(", "time", ".", "Duration", "(", "seconds", "*", "float64", "(", "time", ".", "Second", ")", ")", ")", "\n", "}" ]
// NewUnixTimeFromSeconds creates a UnixTime as a number of seconds from the UnixEpoch.
[ "NewUnixTimeFromSeconds", "creates", "a", "UnixTime", "as", "a", "number", "of", "seconds", "from", "the", "UnixEpoch", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L37-L39
train
Azure/go-autorest
autorest/date/unixtime.go
UnmarshalJSON
func (t *UnixTime) UnmarshalJSON(text []byte) error { dec := json.NewDecoder(bytes.NewReader(text)) var secondsSinceEpoch float64 if err := dec.Decode(&secondsSinceEpoch); err != nil { return err } *t = NewUnixTimeFromSeconds(secondsSinceEpoch) return nil }
go
func (t *UnixTime) UnmarshalJSON(text []byte) error { dec := json.NewDecoder(bytes.NewReader(text)) var secondsSinceEpoch float64 if err := dec.Decode(&secondsSinceEpoch); err != nil { return err } *t = NewUnixTimeFromSeconds(secondsSinceEpoch) return nil }
[ "func", "(", "t", "*", "UnixTime", ")", "UnmarshalJSON", "(", "text", "[", "]", "byte", ")", "error", "{", "dec", ":=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "text", ")", ")", "\n\n", "var", "secondsSinceEpoch", "float64", "\n...
// UnmarshalJSON reconstitures a UnixTime saved as a JSON number of the number of seconds since // midnight January 1st, 1970.
[ "UnmarshalJSON", "reconstitures", "a", "UnixTime", "saved", "as", "a", "JSON", "number", "of", "the", "number", "of", "seconds", "since", "midnight", "January", "1st", "1970", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L70-L81
train
Azure/go-autorest
autorest/date/unixtime.go
MarshalText
func (t UnixTime) MarshalText() ([]byte, error) { cast := time.Time(t) return cast.MarshalText() }
go
func (t UnixTime) MarshalText() ([]byte, error) { cast := time.Time(t) return cast.MarshalText() }
[ "func", "(", "t", "UnixTime", ")", "MarshalText", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cast", ":=", "time", ".", "Time", "(", "t", ")", "\n", "return", "cast", ".", "MarshalText", "(", ")", "\n", "}" ]
// MarshalText stores the number of seconds since the Unix Epoch as a textual floating point number.
[ "MarshalText", "stores", "the", "number", "of", "seconds", "since", "the", "Unix", "Epoch", "as", "a", "textual", "floating", "point", "number", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L84-L87
train
Azure/go-autorest
autorest/date/unixtime.go
UnmarshalText
func (t *UnixTime) UnmarshalText(raw []byte) error { var unmarshaled time.Time if err := unmarshaled.UnmarshalText(raw); err != nil { return err } *t = UnixTime(unmarshaled) return nil }
go
func (t *UnixTime) UnmarshalText(raw []byte) error { var unmarshaled time.Time if err := unmarshaled.UnmarshalText(raw); err != nil { return err } *t = UnixTime(unmarshaled) return nil }
[ "func", "(", "t", "*", "UnixTime", ")", "UnmarshalText", "(", "raw", "[", "]", "byte", ")", "error", "{", "var", "unmarshaled", "time", ".", "Time", "\n\n", "if", "err", ":=", "unmarshaled", ".", "UnmarshalText", "(", "raw", ")", ";", "err", "!=", "n...
// UnmarshalText populates a UnixTime with a value stored textually as a floating point number of seconds since the Unix Epoch.
[ "UnmarshalText", "populates", "a", "UnixTime", "with", "a", "value", "stored", "textually", "as", "a", "floating", "point", "number", "of", "seconds", "since", "the", "Unix", "Epoch", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L90-L99
train
Azure/go-autorest
autorest/date/unixtime.go
MarshalBinary
func (t UnixTime) MarshalBinary() ([]byte, error) { buf := &bytes.Buffer{} payload := int64(t.Duration()) if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil { return nil, err } return buf.Bytes(), nil }
go
func (t UnixTime) MarshalBinary() ([]byte, error) { buf := &bytes.Buffer{} payload := int64(t.Duration()) if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "t", "UnixTime", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n\n", "payload", ":=", "int64", "(", "t", ".", "Duration", "(", ")", ")", "\n\n", ...
// MarshalBinary converts a UnixTime into a binary.LittleEndian float64 of nanoseconds since the epoch.
[ "MarshalBinary", "converts", "a", "UnixTime", "into", "a", "binary", ".", "LittleEndian", "float64", "of", "nanoseconds", "since", "the", "epoch", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L102-L112
train
Azure/go-autorest
autorest/date/unixtime.go
UnmarshalBinary
func (t *UnixTime) UnmarshalBinary(raw []byte) error { var nanosecondsSinceEpoch int64 if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil { return err } *t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch) return nil }
go
func (t *UnixTime) UnmarshalBinary(raw []byte) error { var nanosecondsSinceEpoch int64 if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil { return err } *t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch) return nil }
[ "func", "(", "t", "*", "UnixTime", ")", "UnmarshalBinary", "(", "raw", "[", "]", "byte", ")", "error", "{", "var", "nanosecondsSinceEpoch", "int64", "\n\n", "if", "err", ":=", "binary", ".", "Read", "(", "bytes", ".", "NewReader", "(", "raw", ")", ",",...
// UnmarshalBinary converts a from a binary.LittleEndian float64 of nanoseconds since the epoch into a UnixTime.
[ "UnmarshalBinary", "converts", "a", "from", "a", "binary", ".", "LittleEndian", "float64", "of", "nanoseconds", "since", "the", "epoch", "into", "a", "UnixTime", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L115-L123
train
Azure/go-autorest
autorest/to/convert.go
StringMap
func StringMap(msp map[string]*string) map[string]string { ms := make(map[string]string, len(msp)) for k, sp := range msp { if sp != nil { ms[k] = *sp } else { ms[k] = "" } } return ms }
go
func StringMap(msp map[string]*string) map[string]string { ms := make(map[string]string, len(msp)) for k, sp := range msp { if sp != nil { ms[k] = *sp } else { ms[k] = "" } } return ms }
[ "func", "StringMap", "(", "msp", "map", "[", "string", "]", "*", "string", ")", "map", "[", "string", "]", "string", "{", "ms", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "msp", ")", ")", "\n", "for", "k", ",", "sp...
// StringMap returns a map of strings built from the map of string pointers. The empty string is // used for nil pointers.
[ "StringMap", "returns", "a", "map", "of", "strings", "built", "from", "the", "map", "of", "string", "pointers", ".", "The", "empty", "string", "is", "used", "for", "nil", "pointers", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/to/convert.go#L50-L60
train
Azure/go-autorest
autorest/to/convert.go
StringMapPtr
func StringMapPtr(ms map[string]string) *map[string]*string { msp := make(map[string]*string, len(ms)) for k, s := range ms { msp[k] = StringPtr(s) } return &msp }
go
func StringMapPtr(ms map[string]string) *map[string]*string { msp := make(map[string]*string, len(ms)) for k, s := range ms { msp[k] = StringPtr(s) } return &msp }
[ "func", "StringMapPtr", "(", "ms", "map", "[", "string", "]", "string", ")", "*", "map", "[", "string", "]", "*", "string", "{", "msp", ":=", "make", "(", "map", "[", "string", "]", "*", "string", ",", "len", "(", "ms", ")", ")", "\n", "for", "...
// StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings.
[ "StringMapPtr", "returns", "a", "pointer", "to", "a", "map", "of", "string", "pointers", "built", "from", "the", "passed", "map", "of", "strings", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/to/convert.go#L63-L69
train
Azure/go-autorest
autorest/azure/cli/token.go
ToADALToken
func (t Token) ToADALToken() (converted adal.Token, err error) { tokenExpirationDate, err := ParseExpirationDate(t.ExpiresOn) if err != nil { err = fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err) return } difference := tokenExpirationDate.Sub(date.UnixEpoch()) converted = adal.Token{ AccessToken: t.AccessToken, Type: t.TokenType, ExpiresIn: "3600", ExpiresOn: json.Number(strconv.Itoa(int(difference.Seconds()))), RefreshToken: t.RefreshToken, Resource: t.Resource, } return }
go
func (t Token) ToADALToken() (converted adal.Token, err error) { tokenExpirationDate, err := ParseExpirationDate(t.ExpiresOn) if err != nil { err = fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err) return } difference := tokenExpirationDate.Sub(date.UnixEpoch()) converted = adal.Token{ AccessToken: t.AccessToken, Type: t.TokenType, ExpiresIn: "3600", ExpiresOn: json.Number(strconv.Itoa(int(difference.Seconds()))), RefreshToken: t.RefreshToken, Resource: t.Resource, } return }
[ "func", "(", "t", "Token", ")", "ToADALToken", "(", ")", "(", "converted", "adal", ".", "Token", ",", "err", "error", ")", "{", "tokenExpirationDate", ",", "err", ":=", "ParseExpirationDate", "(", "t", ".", "ExpiresOn", ")", "\n", "if", "err", "!=", "n...
// ToADALToken converts an Azure CLI `Token`` to an `adal.Token``
[ "ToADALToken", "converts", "an", "Azure", "CLI", "Token", "to", "an", "adal", ".", "Token" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L48-L66
train
Azure/go-autorest
autorest/azure/cli/token.go
ParseExpirationDate
func ParseExpirationDate(input string) (*time.Time, error) { // CloudShell (and potentially the Azure CLI in future) expirationDate, cloudShellErr := time.Parse(time.RFC3339, input) if cloudShellErr != nil { // Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone) const cliFormat = "2006-01-02 15:04:05.999999" expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local) if cliErr == nil { return &expirationDate, nil } return nil, fmt.Errorf("Error parsing expiration date %q.\n\nCloudShell Error: \n%+v\n\nCLI Error:\n%+v", input, cloudShellErr, cliErr) } return &expirationDate, nil }
go
func ParseExpirationDate(input string) (*time.Time, error) { // CloudShell (and potentially the Azure CLI in future) expirationDate, cloudShellErr := time.Parse(time.RFC3339, input) if cloudShellErr != nil { // Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone) const cliFormat = "2006-01-02 15:04:05.999999" expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local) if cliErr == nil { return &expirationDate, nil } return nil, fmt.Errorf("Error parsing expiration date %q.\n\nCloudShell Error: \n%+v\n\nCLI Error:\n%+v", input, cloudShellErr, cliErr) } return &expirationDate, nil }
[ "func", "ParseExpirationDate", "(", "input", "string", ")", "(", "*", "time", ".", "Time", ",", "error", ")", "{", "// CloudShell (and potentially the Azure CLI in future)", "expirationDate", ",", "cloudShellErr", ":=", "time", ".", "Parse", "(", "time", ".", "RFC...
// ParseExpirationDate parses either a Azure CLI or CloudShell date into a time object
[ "ParseExpirationDate", "parses", "either", "a", "Azure", "CLI", "or", "CloudShell", "date", "into", "a", "time", "object" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L85-L100
train
Azure/go-autorest
autorest/azure/cli/token.go
LoadTokens
func LoadTokens(path string) ([]Token, error) { file, err := os.Open(path) if err != nil { return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) } defer file.Close() var tokens []Token dec := json.NewDecoder(file) if err = dec.Decode(&tokens); err != nil { return nil, fmt.Errorf("failed to decode contents of file (%s) into a `cli.Token` representation: %v", path, err) } return tokens, nil }
go
func LoadTokens(path string) ([]Token, error) { file, err := os.Open(path) if err != nil { return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) } defer file.Close() var tokens []Token dec := json.NewDecoder(file) if err = dec.Decode(&tokens); err != nil { return nil, fmt.Errorf("failed to decode contents of file (%s) into a `cli.Token` representation: %v", path, err) } return tokens, nil }
[ "func", "LoadTokens", "(", "path", "string", ")", "(", "[", "]", "Token", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(...
// LoadTokens restores a set of Token objects from a file located at 'path'.
[ "LoadTokens", "restores", "a", "set", "of", "Token", "objects", "from", "a", "file", "located", "at", "path", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L103-L118
train
Azure/go-autorest
autorest/azure/cli/token.go
GetTokenFromCLI
func GetTokenFromCLI(resource string) (*Token, error) { // This is the path that a developer can set to tell this class what the install path for Azure CLI is. const azureCLIPath = "AzureCLIPath" // The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI. azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles")) // Default path for non-Windows. const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin" // Validate resource, since it gets sent as a command line argument to Azure CLI const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed." match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource) if err != nil { return nil, err } if !match { return nil, fmt.Errorf(invalidResourceErrorTemplate, resource) } // Execute Azure CLI to get token var cliCmd *exec.Cmd if runtime.GOOS == "windows" { cliCmd = exec.Command(fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir"))) cliCmd.Env = os.Environ() cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows)) cliCmd.Args = append(cliCmd.Args, "/c", "az") } else { cliCmd = exec.Command("az") cliCmd.Env = os.Environ() cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath)) } cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource) var stderr bytes.Buffer cliCmd.Stderr = &stderr output, err := cliCmd.Output() if err != nil { return nil, fmt.Errorf("Invoking Azure CLI failed with the following error: %s", stderr.String()) } tokenResponse := Token{} err = json.Unmarshal(output, &tokenResponse) if err != nil { return nil, err } return &tokenResponse, err }
go
func GetTokenFromCLI(resource string) (*Token, error) { // This is the path that a developer can set to tell this class what the install path for Azure CLI is. const azureCLIPath = "AzureCLIPath" // The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI. azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles")) // Default path for non-Windows. const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin" // Validate resource, since it gets sent as a command line argument to Azure CLI const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed." match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource) if err != nil { return nil, err } if !match { return nil, fmt.Errorf(invalidResourceErrorTemplate, resource) } // Execute Azure CLI to get token var cliCmd *exec.Cmd if runtime.GOOS == "windows" { cliCmd = exec.Command(fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir"))) cliCmd.Env = os.Environ() cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows)) cliCmd.Args = append(cliCmd.Args, "/c", "az") } else { cliCmd = exec.Command("az") cliCmd.Env = os.Environ() cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath)) } cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource) var stderr bytes.Buffer cliCmd.Stderr = &stderr output, err := cliCmd.Output() if err != nil { return nil, fmt.Errorf("Invoking Azure CLI failed with the following error: %s", stderr.String()) } tokenResponse := Token{} err = json.Unmarshal(output, &tokenResponse) if err != nil { return nil, err } return &tokenResponse, err }
[ "func", "GetTokenFromCLI", "(", "resource", "string", ")", "(", "*", "Token", ",", "error", ")", "{", "// This is the path that a developer can set to tell this class what the install path for Azure CLI is.", "const", "azureCLIPath", "=", "\"", "\"", "\n\n", "// The default i...
// GetTokenFromCLI gets a token using Azure CLI 2.0 for local development scenarios.
[ "GetTokenFromCLI", "gets", "a", "token", "using", "Azure", "CLI", "2", ".", "0", "for", "local", "development", "scenarios", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L121-L170
train
Azure/go-autorest
autorest/date/date.go
ParseDate
func ParseDate(date string) (d Date, err error) { return parseDate(date, fullDate) }
go
func ParseDate(date string) (d Date, err error) { return parseDate(date, fullDate) }
[ "func", "ParseDate", "(", "date", "string", ")", "(", "d", "Date", ",", "err", "error", ")", "{", "return", "parseDate", "(", "date", ",", "fullDate", ")", "\n", "}" ]
// ParseDate create a new Date from the passed string.
[ "ParseDate", "create", "a", "new", "Date", "from", "the", "passed", "string", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/date.go#L41-L43
train
Azure/go-autorest
autorest/azure/metadata_environment.go
EnvironmentFromURL
func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) { var metadataEnvProperties environmentMetadataInfo if resourceManagerEndpoint == "" { return environment, fmt.Errorf("Metadata resource manager endpoint is empty") } if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil { return environment, err } // Give priority to user's override values overrideProperties(&environment, properties) if environment.Name == "" { environment.Name = "HybridEnvironment" } stampDNSSuffix := environment.StorageEndpointSuffix if stampDNSSuffix == "" { stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/") environment.StorageEndpointSuffix = stampDNSSuffix } if environment.KeyVaultDNSSuffix == "" { environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix) } if environment.KeyVaultEndpoint == "" { environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix) } if environment.TokenAudience == "" { environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0] } if environment.ActiveDirectoryEndpoint == "" { environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint } if environment.ResourceManagerEndpoint == "" { environment.ResourceManagerEndpoint = resourceManagerEndpoint } if environment.GalleryEndpoint == "" { environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint } if environment.GraphEndpoint == "" { environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint } return environment, nil }
go
func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) { var metadataEnvProperties environmentMetadataInfo if resourceManagerEndpoint == "" { return environment, fmt.Errorf("Metadata resource manager endpoint is empty") } if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil { return environment, err } // Give priority to user's override values overrideProperties(&environment, properties) if environment.Name == "" { environment.Name = "HybridEnvironment" } stampDNSSuffix := environment.StorageEndpointSuffix if stampDNSSuffix == "" { stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/") environment.StorageEndpointSuffix = stampDNSSuffix } if environment.KeyVaultDNSSuffix == "" { environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix) } if environment.KeyVaultEndpoint == "" { environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix) } if environment.TokenAudience == "" { environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0] } if environment.ActiveDirectoryEndpoint == "" { environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint } if environment.ResourceManagerEndpoint == "" { environment.ResourceManagerEndpoint = resourceManagerEndpoint } if environment.GalleryEndpoint == "" { environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint } if environment.GraphEndpoint == "" { environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint } return environment, nil }
[ "func", "EnvironmentFromURL", "(", "resourceManagerEndpoint", "string", ",", "properties", "...", "OverrideProperty", ")", "(", "environment", "Environment", ",", "err", "error", ")", "{", "var", "metadataEnvProperties", "environmentMetadataInfo", "\n\n", "if", "resourc...
// EnvironmentFromURL loads an Environment from a URL // This function is particularly useful in the Hybrid Cloud model, where one may define their own // endpoints.
[ "EnvironmentFromURL", "loads", "an", "Environment", "from", "a", "URL", "This", "function", "is", "particularly", "useful", "in", "the", "Hybrid", "Cloud", "model", "where", "one", "may", "define", "their", "own", "endpoints", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/metadata_environment.go#L96-L141
train
Azure/go-autorest
autorest/azure/async.go
NewFutureFromResponse
func NewFutureFromResponse(resp *http.Response) (Future, error) { pt, err := createPollingTracker(resp) return Future{pt: pt}, err }
go
func NewFutureFromResponse(resp *http.Response) (Future, error) { pt, err := createPollingTracker(resp) return Future{pt: pt}, err }
[ "func", "NewFutureFromResponse", "(", "resp", "*", "http", ".", "Response", ")", "(", "Future", ",", "error", ")", "{", "pt", ",", "err", ":=", "createPollingTracker", "(", "resp", ")", "\n", "return", "Future", "{", "pt", ":", "pt", "}", ",", "err", ...
// NewFutureFromResponse returns a new Future object initialized // with the initial response from an asynchronous operation.
[ "NewFutureFromResponse", "returns", "a", "new", "Future", "object", "initialized", "with", "the", "initial", "response", "from", "an", "asynchronous", "operation", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L53-L56
train
Azure/go-autorest
autorest/azure/async.go
Response
func (f Future) Response() *http.Response { if f.pt == nil { return nil } return f.pt.latestResponse() }
go
func (f Future) Response() *http.Response { if f.pt == nil { return nil } return f.pt.latestResponse() }
[ "func", "(", "f", "Future", ")", "Response", "(", ")", "*", "http", ".", "Response", "{", "if", "f", ".", "pt", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "f", ".", "pt", ".", "latestResponse", "(", ")", "\n", "}" ]
// Response returns the last HTTP response.
[ "Response", "returns", "the", "last", "HTTP", "response", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L59-L64
train
Azure/go-autorest
autorest/azure/async.go
Status
func (f Future) Status() string { if f.pt == nil { return "" } return f.pt.pollingStatus() }
go
func (f Future) Status() string { if f.pt == nil { return "" } return f.pt.pollingStatus() }
[ "func", "(", "f", "Future", ")", "Status", "(", ")", "string", "{", "if", "f", ".", "pt", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "f", ".", "pt", ".", "pollingStatus", "(", ")", "\n", "}" ]
// Status returns the last status message of the operation.
[ "Status", "returns", "the", "last", "status", "message", "of", "the", "operation", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L67-L72
train
Azure/go-autorest
autorest/azure/async.go
PollingMethod
func (f Future) PollingMethod() PollingMethodType { if f.pt == nil { return PollingUnknown } return f.pt.pollingMethod() }
go
func (f Future) PollingMethod() PollingMethodType { if f.pt == nil { return PollingUnknown } return f.pt.pollingMethod() }
[ "func", "(", "f", "Future", ")", "PollingMethod", "(", ")", "PollingMethodType", "{", "if", "f", ".", "pt", "==", "nil", "{", "return", "PollingUnknown", "\n", "}", "\n", "return", "f", ".", "pt", ".", "pollingMethod", "(", ")", "\n", "}" ]
// PollingMethod returns the method used to monitor the status of the asynchronous operation.
[ "PollingMethod", "returns", "the", "method", "used", "to", "monitor", "the", "status", "of", "the", "asynchronous", "operation", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L75-L80
train
Azure/go-autorest
autorest/azure/async.go
DoneWithContext
func (f *Future) DoneWithContext(ctx context.Context, sender autorest.Sender) (done bool, err error) { ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.DoneWithContext") defer func() { sc := -1 resp := f.Response() if resp != nil { sc = resp.StatusCode } tracing.EndSpan(ctx, sc, err) }() if f.pt == nil { return false, autorest.NewError("Future", "Done", "future is not initialized") } if f.pt.hasTerminated() { return true, f.pt.pollingError() } if err := f.pt.pollForStatus(ctx, sender); err != nil { return false, err } if err := f.pt.checkForErrors(); err != nil { return f.pt.hasTerminated(), err } if err := f.pt.updatePollingState(f.pt.provisioningStateApplicable()); err != nil { return false, err } if err := f.pt.initPollingMethod(); err != nil { return false, err } if err := f.pt.updatePollingMethod(); err != nil { return false, err } return f.pt.hasTerminated(), f.pt.pollingError() }
go
func (f *Future) DoneWithContext(ctx context.Context, sender autorest.Sender) (done bool, err error) { ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.DoneWithContext") defer func() { sc := -1 resp := f.Response() if resp != nil { sc = resp.StatusCode } tracing.EndSpan(ctx, sc, err) }() if f.pt == nil { return false, autorest.NewError("Future", "Done", "future is not initialized") } if f.pt.hasTerminated() { return true, f.pt.pollingError() } if err := f.pt.pollForStatus(ctx, sender); err != nil { return false, err } if err := f.pt.checkForErrors(); err != nil { return f.pt.hasTerminated(), err } if err := f.pt.updatePollingState(f.pt.provisioningStateApplicable()); err != nil { return false, err } if err := f.pt.initPollingMethod(); err != nil { return false, err } if err := f.pt.updatePollingMethod(); err != nil { return false, err } return f.pt.hasTerminated(), f.pt.pollingError() }
[ "func", "(", "f", "*", "Future", ")", "DoneWithContext", "(", "ctx", "context", ".", "Context", ",", "sender", "autorest", ".", "Sender", ")", "(", "done", "bool", ",", "err", "error", ")", "{", "ctx", "=", "tracing", ".", "StartSpan", "(", "ctx", ",...
// DoneWithContext queries the service to see if the operation has completed.
[ "DoneWithContext", "queries", "the", "service", "to", "see", "if", "the", "operation", "has", "completed", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L83-L116
train
Azure/go-autorest
autorest/azure/async.go
GetPollingDelay
func (f Future) GetPollingDelay() (time.Duration, bool) { if f.pt == nil { return 0, false } resp := f.pt.latestResponse() if resp == nil { return 0, false } retry := resp.Header.Get(autorest.HeaderRetryAfter) if retry == "" { return 0, false } d, err := time.ParseDuration(retry + "s") if err != nil { panic(err) } return d, true }
go
func (f Future) GetPollingDelay() (time.Duration, bool) { if f.pt == nil { return 0, false } resp := f.pt.latestResponse() if resp == nil { return 0, false } retry := resp.Header.Get(autorest.HeaderRetryAfter) if retry == "" { return 0, false } d, err := time.ParseDuration(retry + "s") if err != nil { panic(err) } return d, true }
[ "func", "(", "f", "Future", ")", "GetPollingDelay", "(", ")", "(", "time", ".", "Duration", ",", "bool", ")", "{", "if", "f", ".", "pt", "==", "nil", "{", "return", "0", ",", "false", "\n", "}", "\n", "resp", ":=", "f", ".", "pt", ".", "latestR...
// GetPollingDelay returns a duration the application should wait before checking // the status of the asynchronous request and true; this value is returned from // the service via the Retry-After response header. If the header wasn't returned // then the function returns the zero-value time.Duration and false.
[ "GetPollingDelay", "returns", "a", "duration", "the", "application", "should", "wait", "before", "checking", "the", "status", "of", "the", "asynchronous", "request", "and", "true", ";", "this", "value", "is", "returned", "from", "the", "service", "via", "the", ...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L122-L142
train
Azure/go-autorest
autorest/azure/async.go
PollingURL
func (f Future) PollingURL() string { if f.pt == nil { return "" } return f.pt.pollingURL() }
go
func (f Future) PollingURL() string { if f.pt == nil { return "" } return f.pt.pollingURL() }
[ "func", "(", "f", "Future", ")", "PollingURL", "(", ")", "string", "{", "if", "f", ".", "pt", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "f", ".", "pt", ".", "pollingURL", "(", ")", "\n", "}" ]
// PollingURL returns the URL used for retrieving the status of the long-running operation.
[ "PollingURL", "returns", "the", "URL", "used", "for", "retrieving", "the", "status", "of", "the", "long", "-", "running", "operation", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L238-L243
train
Azure/go-autorest
autorest/azure/async.go
GetResult
func (f Future) GetResult(sender autorest.Sender) (*http.Response, error) { if f.pt.finalGetURL() == "" { // we can end up in this situation if the async operation returns a 200 // with no polling URLs. in that case return the response which should // contain the JSON payload (only do this for successful terminal cases). if lr := f.pt.latestResponse(); lr != nil && f.pt.hasSucceeded() { return lr, nil } return nil, autorest.NewError("Future", "GetResult", "missing URL for retrieving result") } req, err := http.NewRequest(http.MethodGet, f.pt.finalGetURL(), nil) if err != nil { return nil, err } return sender.Do(req) }
go
func (f Future) GetResult(sender autorest.Sender) (*http.Response, error) { if f.pt.finalGetURL() == "" { // we can end up in this situation if the async operation returns a 200 // with no polling URLs. in that case return the response which should // contain the JSON payload (only do this for successful terminal cases). if lr := f.pt.latestResponse(); lr != nil && f.pt.hasSucceeded() { return lr, nil } return nil, autorest.NewError("Future", "GetResult", "missing URL for retrieving result") } req, err := http.NewRequest(http.MethodGet, f.pt.finalGetURL(), nil) if err != nil { return nil, err } return sender.Do(req) }
[ "func", "(", "f", "Future", ")", "GetResult", "(", "sender", "autorest", ".", "Sender", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "if", "f", ".", "pt", ".", "finalGetURL", "(", ")", "==", "\"", "\"", "{", "// we can end up in th...
// GetResult should be called once polling has completed successfully. // It makes the final GET call to retrieve the resultant payload.
[ "GetResult", "should", "be", "called", "once", "polling", "has", "completed", "successfully", ".", "It", "makes", "the", "final", "GET", "call", "to", "retrieve", "the", "resultant", "payload", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L247-L262
train
Azure/go-autorest
autorest/azure/async.go
baseCheckForErrors
func (pt pollingTrackerBase) baseCheckForErrors() error { // for Azure-AsyncOperations the response body cannot be nil or empty if pt.Pm == PollingAsyncOperation { if pt.resp.Body == nil || pt.resp.ContentLength == 0 { return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "for Azure-AsyncOperation response body cannot be nil") } if pt.rawBody["status"] == nil { return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "missing status property in Azure-AsyncOperation response body") } } return nil }
go
func (pt pollingTrackerBase) baseCheckForErrors() error { // for Azure-AsyncOperations the response body cannot be nil or empty if pt.Pm == PollingAsyncOperation { if pt.resp.Body == nil || pt.resp.ContentLength == 0 { return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "for Azure-AsyncOperation response body cannot be nil") } if pt.rawBody["status"] == nil { return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "missing status property in Azure-AsyncOperation response body") } } return nil }
[ "func", "(", "pt", "pollingTrackerBase", ")", "baseCheckForErrors", "(", ")", "error", "{", "// for Azure-AsyncOperations the response body cannot be nil or empty", "if", "pt", ".", "Pm", "==", "PollingAsyncOperation", "{", "if", "pt", ".", "resp", ".", "Body", "==", ...
// error checking common to all trackers
[ "error", "checking", "common", "to", "all", "trackers" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L550-L561
train
Azure/go-autorest
autorest/azure/async.go
createPollingTracker
func createPollingTracker(resp *http.Response) (pollingTracker, error) { var pt pollingTracker switch strings.ToUpper(resp.Request.Method) { case http.MethodDelete: pt = &pollingTrackerDelete{pollingTrackerBase: pollingTrackerBase{resp: resp}} case http.MethodPatch: pt = &pollingTrackerPatch{pollingTrackerBase: pollingTrackerBase{resp: resp}} case http.MethodPost: pt = &pollingTrackerPost{pollingTrackerBase: pollingTrackerBase{resp: resp}} case http.MethodPut: pt = &pollingTrackerPut{pollingTrackerBase: pollingTrackerBase{resp: resp}} default: return nil, autorest.NewError("azure", "createPollingTracker", "unsupported HTTP method %s", resp.Request.Method) } if err := pt.initializeState(); err != nil { return pt, err } // this initializes the polling header values, we do this during creation in case the // initial response send us invalid values; this way the API call will return a non-nil // error (not doing this means the error shows up in Future.Done) return pt, pt.updatePollingMethod() }
go
func createPollingTracker(resp *http.Response) (pollingTracker, error) { var pt pollingTracker switch strings.ToUpper(resp.Request.Method) { case http.MethodDelete: pt = &pollingTrackerDelete{pollingTrackerBase: pollingTrackerBase{resp: resp}} case http.MethodPatch: pt = &pollingTrackerPatch{pollingTrackerBase: pollingTrackerBase{resp: resp}} case http.MethodPost: pt = &pollingTrackerPost{pollingTrackerBase: pollingTrackerBase{resp: resp}} case http.MethodPut: pt = &pollingTrackerPut{pollingTrackerBase: pollingTrackerBase{resp: resp}} default: return nil, autorest.NewError("azure", "createPollingTracker", "unsupported HTTP method %s", resp.Request.Method) } if err := pt.initializeState(); err != nil { return pt, err } // this initializes the polling header values, we do this during creation in case the // initial response send us invalid values; this way the API call will return a non-nil // error (not doing this means the error shows up in Future.Done) return pt, pt.updatePollingMethod() }
[ "func", "createPollingTracker", "(", "resp", "*", "http", ".", "Response", ")", "(", "pollingTracker", ",", "error", ")", "{", "var", "pt", "pollingTracker", "\n", "switch", "strings", ".", "ToUpper", "(", "resp", ".", "Request", ".", "Method", ")", "{", ...
// creates a polling tracker based on the verb of the original request
[ "creates", "a", "polling", "tracker", "based", "on", "the", "verb", "of", "the", "original", "request" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L831-L852
train
Azure/go-autorest
autorest/azure/async.go
getURLFromAsyncOpHeader
func getURLFromAsyncOpHeader(resp *http.Response) (string, error) { s := resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) if s == "" { return "", nil } if !isValidURL(s) { return "", autorest.NewError("azure", "getURLFromAsyncOpHeader", "invalid polling URL '%s'", s) } return s, nil }
go
func getURLFromAsyncOpHeader(resp *http.Response) (string, error) { s := resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) if s == "" { return "", nil } if !isValidURL(s) { return "", autorest.NewError("azure", "getURLFromAsyncOpHeader", "invalid polling URL '%s'", s) } return s, nil }
[ "func", "getURLFromAsyncOpHeader", "(", "resp", "*", "http", ".", "Response", ")", "(", "string", ",", "error", ")", "{", "s", ":=", "resp", ".", "Header", ".", "Get", "(", "http", ".", "CanonicalHeaderKey", "(", "headerAsyncOperation", ")", ")", "\n", "...
// gets the polling URL from the Azure-AsyncOperation header. // ensures the URL is well-formed and absolute.
[ "gets", "the", "polling", "URL", "from", "the", "Azure", "-", "AsyncOperation", "header", ".", "ensures", "the", "URL", "is", "well", "-", "formed", "and", "absolute", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L856-L865
train
Azure/go-autorest
autorest/azure/async.go
getURLFromLocationHeader
func getURLFromLocationHeader(resp *http.Response) (string, error) { s := resp.Header.Get(http.CanonicalHeaderKey(autorest.HeaderLocation)) if s == "" { return "", nil } if !isValidURL(s) { return "", autorest.NewError("azure", "getURLFromLocationHeader", "invalid polling URL '%s'", s) } return s, nil }
go
func getURLFromLocationHeader(resp *http.Response) (string, error) { s := resp.Header.Get(http.CanonicalHeaderKey(autorest.HeaderLocation)) if s == "" { return "", nil } if !isValidURL(s) { return "", autorest.NewError("azure", "getURLFromLocationHeader", "invalid polling URL '%s'", s) } return s, nil }
[ "func", "getURLFromLocationHeader", "(", "resp", "*", "http", ".", "Response", ")", "(", "string", ",", "error", ")", "{", "s", ":=", "resp", ".", "Header", ".", "Get", "(", "http", ".", "CanonicalHeaderKey", "(", "autorest", ".", "HeaderLocation", ")", ...
// gets the polling URL from the Location header. // ensures the URL is well-formed and absolute.
[ "gets", "the", "polling", "URL", "from", "the", "Location", "header", ".", "ensures", "the", "URL", "is", "well", "-", "formed", "and", "absolute", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L869-L878
train
Azure/go-autorest
autorest/azure/async.go
isValidURL
func isValidURL(s string) bool { u, err := url.Parse(s) return err == nil && u.IsAbs() }
go
func isValidURL(s string) bool { u, err := url.Parse(s) return err == nil && u.IsAbs() }
[ "func", "isValidURL", "(", "s", "string", ")", "bool", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "s", ")", "\n", "return", "err", "==", "nil", "&&", "u", ".", "IsAbs", "(", ")", "\n", "}" ]
// verify that the URL is valid and absolute
[ "verify", "that", "the", "URL", "is", "valid", "and", "absolute" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L881-L884
train
Azure/go-autorest
autorest/sender.go
Do
func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { return sf(r) }
go
func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { return sf(r) }
[ "func", "(", "sf", "SenderFunc", ")", "Do", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "sf", "(", "r", ")", "\n", "}" ]
// Do implements the Sender interface on SenderFunc.
[ "Do", "implements", "the", "Sender", "interface", "on", "SenderFunc", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L39-L41
train
Azure/go-autorest
autorest/sender.go
SendWithSender
func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) { return DecorateSender(s, decorators...).Do(r) }
go
func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) { return DecorateSender(s, decorators...).Do(r) }
[ "func", "SendWithSender", "(", "s", "Sender", ",", "r", "*", "http", ".", "Request", ",", "decorators", "...", "SendDecorator", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "DecorateSender", "(", "s", ",", "decorators", "..."...
// SendWithSender sends the passed http.Request, through the provided Sender, returning the // http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which // it will apply the http.Client before invoking the Do method. // // SendWithSender will not poll or retry requests.
[ "SendWithSender", "sends", "the", "passed", "http", ".", "Request", "through", "the", "provided", "Sender", "returning", "the", "http", ".", "Response", "and", "possible", "error", ".", "It", "also", "accepts", "a", "possibly", "empty", "set", "of", "SendDecor...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L81-L83
train
Azure/go-autorest
autorest/sender.go
AfterDelay
func AfterDelay(d time.Duration) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { if !DelayForBackoff(d, 0, r.Context().Done()) { return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") } return s.Do(r) }) } }
go
func AfterDelay(d time.Duration) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { if !DelayForBackoff(d, 0, r.Context().Done()) { return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") } return s.Do(r) }) } }
[ "func", "AfterDelay", "(", "d", "time", ".", "Duration", ")", "SendDecorator", "{", "return", "func", "(", "s", "Sender", ")", "Sender", "{", "return", "SenderFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Res...
// AfterDelay returns a SendDecorator that delays for the passed time.Duration before // invoking the Sender. The delay may be terminated by closing the optional channel on the // http.Request. If canceled, no further Senders are invoked.
[ "AfterDelay", "returns", "a", "SendDecorator", "that", "delays", "for", "the", "passed", "time", ".", "Duration", "before", "invoking", "the", "Sender", ".", "The", "delay", "may", "be", "terminated", "by", "closing", "the", "optional", "channel", "on", "the",...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L88-L97
train
Azure/go-autorest
autorest/sender.go
AsIs
func AsIs() SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { return s.Do(r) }) } }
go
func AsIs() SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { return s.Do(r) }) } }
[ "func", "AsIs", "(", ")", "SendDecorator", "{", "return", "func", "(", "s", "Sender", ")", "Sender", "{", "return", "SenderFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "r...
// AsIs returns a SendDecorator that invokes the passed Sender without modifying the http.Request.
[ "AsIs", "returns", "a", "SendDecorator", "that", "invokes", "the", "passed", "Sender", "without", "modifying", "the", "http", ".", "Request", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L100-L106
train
Azure/go-autorest
autorest/sender.go
DoCloseIfError
func DoCloseIfError() SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err != nil { Respond(resp, ByDiscardingBody(), ByClosing()) } return resp, err }) } }
go
func DoCloseIfError() SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err != nil { Respond(resp, ByDiscardingBody(), ByClosing()) } return resp, err }) } }
[ "func", "DoCloseIfError", "(", ")", "SendDecorator", "{", "return", "func", "(", "s", "Sender", ")", "Sender", "{", "return", "SenderFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", ...
// DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which // it closes the response if the passed Sender returns an error and the response body exists.
[ "DoCloseIfError", "returns", "a", "SendDecorator", "that", "first", "invokes", "the", "passed", "Sender", "after", "which", "it", "closes", "the", "response", "if", "the", "passed", "Sender", "returns", "an", "error", "and", "the", "response", "body", "exists", ...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L110-L120
train
Azure/go-autorest
autorest/sender.go
DoErrorUnlessStatusCode
func DoErrorUnlessStatusCode(codes ...int) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err == nil && !ResponseHasStatusCode(resp, codes...) { err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", resp.Request.Method, resp.Request.URL, resp.Status) } return resp, err }) } }
go
func DoErrorUnlessStatusCode(codes ...int) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err == nil && !ResponseHasStatusCode(resp, codes...) { err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", resp.Request.Method, resp.Request.URL, resp.Status) } return resp, err }) } }
[ "func", "DoErrorUnlessStatusCode", "(", "codes", "...", "int", ")", "SendDecorator", "{", "return", "func", "(", "s", "Sender", ")", "Sender", "{", "return", "SenderFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", ...
// DoErrorUnlessStatusCode returns a SendDecorator that emits an error unless the response // StatusCode is among the set passed. Since these are artificial errors, the response body // may still require closing.
[ "DoErrorUnlessStatusCode", "returns", "a", "SendDecorator", "that", "emits", "an", "error", "unless", "the", "response", "StatusCode", "is", "among", "the", "set", "passed", ".", "Since", "these", "are", "artificial", "errors", "the", "response", "body", "may", ...
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L143-L156
train
Azure/go-autorest
autorest/sender.go
DelayWithRetryAfter
func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool { if resp == nil { return false } retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After")) if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 { select { case <-time.After(time.Duration(retryAfter) * time.Second): return true case <-cancel: return false } } return false }
go
func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool { if resp == nil { return false } retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After")) if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 { select { case <-time.After(time.Duration(retryAfter) * time.Second): return true case <-cancel: return false } } return false }
[ "func", "DelayWithRetryAfter", "(", "resp", "*", "http", ".", "Response", ",", "cancel", "<-", "chan", "struct", "{", "}", ")", "bool", "{", "if", "resp", "==", "nil", "{", "return", "false", "\n", "}", "\n", "retryAfter", ",", "_", ":=", "strconv", ...
// DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header in // responses with status code 429
[ "DelayWithRetryAfter", "invokes", "time", ".", "After", "for", "the", "duration", "specified", "in", "the", "Retry", "-", "After", "header", "in", "responses", "with", "status", "code", "429" ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L253-L267
train
Azure/go-autorest
autorest/sender.go
WithLogging
func WithLogging(logger *log.Logger) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { logger.Printf("Sending %s %s", r.Method, r.URL) resp, err := s.Do(r) if err != nil { logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) } else { logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) } return resp, err }) } }
go
func WithLogging(logger *log.Logger) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { logger.Printf("Sending %s %s", r.Method, r.URL) resp, err := s.Do(r) if err != nil { logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) } else { logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) } return resp, err }) } }
[ "func", "WithLogging", "(", "logger", "*", "log", ".", "Logger", ")", "SendDecorator", "{", "return", "func", "(", "s", "Sender", ")", "Sender", "{", "return", "SenderFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", "...
// WithLogging returns a SendDecorator that implements simple before and after logging of the // request.
[ "WithLogging", "returns", "a", "SendDecorator", "that", "implements", "simple", "before", "and", "after", "logging", "of", "the", "request", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L298-L311
train
Azure/go-autorest
autorest/validation/error.go
Error
func (e Error) Error() string { return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message) }
go
func (e Error) Error() string { return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message) }
[ "func", "(", "e", "Error", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "PackageType", ",", "e", ".", "Method", ",", "e", ".", "Message", ")", "\n", "}" ]
// Error returns a string containing the details of the validation failure.
[ "Error", "returns", "a", "string", "containing", "the", "details", "of", "the", "validation", "failure", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/validation/error.go#L36-L38
train
Azure/go-autorest
autorest/validation/error.go
NewError
func NewError(packageType string, method string, message string, args ...interface{}) Error { return Error{ PackageType: packageType, Method: method, Message: fmt.Sprintf(message, args...), } }
go
func NewError(packageType string, method string, message string, args ...interface{}) Error { return Error{ PackageType: packageType, Method: method, Message: fmt.Sprintf(message, args...), } }
[ "func", "NewError", "(", "packageType", "string", ",", "method", "string", ",", "message", "string", ",", "args", "...", "interface", "{", "}", ")", "Error", "{", "return", "Error", "{", "PackageType", ":", "packageType", ",", "Method", ":", "method", ",",...
// NewError creates a new Error object with the specified parameters. // message is treated as a format string to which the optional args apply.
[ "NewError", "creates", "a", "new", "Error", "object", "with", "the", "specified", "parameters", ".", "message", "is", "treated", "as", "a", "format", "string", "to", "which", "the", "optional", "args", "apply", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/validation/error.go#L42-L48
train
Azure/go-autorest
autorest/validation/validation.go
Validate
func Validate(m []Validation) error { for _, item := range m { v := reflect.ValueOf(item.TargetValue) for _, constraint := range item.Constraints { var err error switch v.Kind() { case reflect.Ptr: err = validatePtr(v, constraint) case reflect.String: err = validateString(v, constraint) case reflect.Struct: err = validateStruct(v, constraint) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: err = validateInt(v, constraint) case reflect.Float32, reflect.Float64: err = validateFloat(v, constraint) case reflect.Array, reflect.Slice, reflect.Map: err = validateArrayMap(v, constraint) default: err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) } if err != nil { return err } } } return nil }
go
func Validate(m []Validation) error { for _, item := range m { v := reflect.ValueOf(item.TargetValue) for _, constraint := range item.Constraints { var err error switch v.Kind() { case reflect.Ptr: err = validatePtr(v, constraint) case reflect.String: err = validateString(v, constraint) case reflect.Struct: err = validateStruct(v, constraint) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: err = validateInt(v, constraint) case reflect.Float32, reflect.Float64: err = validateFloat(v, constraint) case reflect.Array, reflect.Slice, reflect.Map: err = validateArrayMap(v, constraint) default: err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) } if err != nil { return err } } } return nil }
[ "func", "Validate", "(", "m", "[", "]", "Validation", ")", "error", "{", "for", "_", ",", "item", ":=", "range", "m", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "item", ".", "TargetValue", ")", "\n", "for", "_", ",", "constraint", ":=", "range...
// Validate method validates constraints on parameter // passed in validation array.
[ "Validate", "method", "validates", "constraints", "on", "parameter", "passed", "in", "validation", "array", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/validation/validation.go#L70-L98
train
alexedwards/scs
postgresstore/postgresstore.go
Find
func (p *PostgresStore) Find(token string) (b []byte, exists bool, err error) { row := p.db.QueryRow("SELECT data FROM sessions WHERE token = $1 AND current_timestamp < expiry", token) err = row.Scan(&b) if err == sql.ErrNoRows { return nil, false, nil } else if err != nil { return nil, false, err } return b, true, nil }
go
func (p *PostgresStore) Find(token string) (b []byte, exists bool, err error) { row := p.db.QueryRow("SELECT data FROM sessions WHERE token = $1 AND current_timestamp < expiry", token) err = row.Scan(&b) if err == sql.ErrNoRows { return nil, false, nil } else if err != nil { return nil, false, err } return b, true, nil }
[ "func", "(", "p", "*", "PostgresStore", ")", "Find", "(", "token", "string", ")", "(", "b", "[", "]", "byte", ",", "exists", "bool", ",", "err", "error", ")", "{", "row", ":=", "p", ".", "db", ".", "QueryRow", "(", "\"", "\"", ",", "token", ")"...
// Find returns the data for a given session token from the PostgresStore instance. // If the session token is not found or is expired, the returned exists flag will // be set to false.
[ "Find", "returns", "the", "data", "for", "a", "given", "session", "token", "from", "the", "PostgresStore", "instance", ".", "If", "the", "session", "token", "is", "not", "found", "or", "is", "expired", "the", "returned", "exists", "flag", "will", "be", "se...
7591275b1edfd53a361e4bdbe42148cbd1b00ac1
https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/postgresstore/postgresstore.go#L36-L45
train
alexedwards/scs
postgresstore/postgresstore.go
Commit
func (p *PostgresStore) Commit(token string, b []byte, expiry time.Time) error { _, err := p.db.Exec("INSERT INTO sessions (token, data, expiry) VALUES ($1, $2, $3) ON CONFLICT (token) DO UPDATE SET data = EXCLUDED.data, expiry = EXCLUDED.expiry", token, b, expiry) if err != nil { return err } return nil }
go
func (p *PostgresStore) Commit(token string, b []byte, expiry time.Time) error { _, err := p.db.Exec("INSERT INTO sessions (token, data, expiry) VALUES ($1, $2, $3) ON CONFLICT (token) DO UPDATE SET data = EXCLUDED.data, expiry = EXCLUDED.expiry", token, b, expiry) if err != nil { return err } return nil }
[ "func", "(", "p", "*", "PostgresStore", ")", "Commit", "(", "token", "string", ",", "b", "[", "]", "byte", ",", "expiry", "time", ".", "Time", ")", "error", "{", "_", ",", "err", ":=", "p", ".", "db", ".", "Exec", "(", "\"", "\"", ",", "token",...
// Commit adds a session token and data to the PostgresStore instance with the // given expiry time. If the session token already exists, then the data and expiry // time are updated.
[ "Commit", "adds", "a", "session", "token", "and", "data", "to", "the", "PostgresStore", "instance", "with", "the", "given", "expiry", "time", ".", "If", "the", "session", "token", "already", "exists", "then", "the", "data", "and", "expiry", "time", "are", ...
7591275b1edfd53a361e4bdbe42148cbd1b00ac1
https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/postgresstore/postgresstore.go#L50-L56
train