repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
rightscale/rsc
cm16/codegen_client.go
NetworkInterfaceLocator
func (api *API) NetworkInterfaceLocator(href string) *NetworkInterfaceLocator { return &NetworkInterfaceLocator{Href(href), api} }
go
func (api *API) NetworkInterfaceLocator(href string) *NetworkInterfaceLocator { return &NetworkInterfaceLocator{Href(href), api} }
[ "func", "(", "api", "*", "API", ")", "NetworkInterfaceLocator", "(", "href", "string", ")", "*", "NetworkInterfaceLocator", "{", "return", "&", "NetworkInterfaceLocator", "{", "Href", "(", "href", ")", ",", "api", "}", "\n", "}" ]
// NetworkInterfaceLocator builds a locator from the given href.
[ "NetworkInterfaceLocator", "builds", "a", "locator", "from", "the", "given", "href", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1336-L1338
test
rightscale/rsc
cm16/codegen_client.go
NetworkInterfaceAttachmentLocator
func (api *API) NetworkInterfaceAttachmentLocator(href string) *NetworkInterfaceAttachmentLocator { return &NetworkInterfaceAttachmentLocator{Href(href), api} }
go
func (api *API) NetworkInterfaceAttachmentLocator(href string) *NetworkInterfaceAttachmentLocator { return &NetworkInterfaceAttachmentLocator{Href(href), api} }
[ "func", "(", "api", "*", "API", ")", "NetworkInterfaceAttachmentLocator", "(", "href", "string", ")", "*", "NetworkInterfaceAttachmentLocator", "{", "return", "&", "NetworkInterfaceAttachmentLocator", "{", "Href", "(", "href", ")", ",", "api", "}", "\n", "}" ]
// NetworkInterfaceAttachmentLocator builds a locator from the given href.
[ "NetworkInterfaceAttachmentLocator", "builds", "a", "locator", "from", "the", "given", "href", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1437-L1439
test
rightscale/rsc
cm15/ruby_time.go
UnmarshalJSON
func (r *RubyTime) UnmarshalJSON(b []byte) (err error) { s := string(b) t, err := time.Parse("2006/01/02 15:04:05 -0700", s[1:len(s)-1]) if err != nil { return err } r.Time = t return nil }
go
func (r *RubyTime) UnmarshalJSON(b []byte) (err error) { s := string(b) t, err := time.Parse("2006/01/02 15:04:05 -0700", s[1:len(s)-1]) if err != nil { return err } r.Time = t return nil }
[ "func", "(", "r", "*", "RubyTime", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "s", ":=", "string", "(", "b", ")", "\n", "t", ",", "err", ":=", "time", ".", "Parse", "(", "\"2006/01/02 15:04:05 -0700\"", ",", "s", "[", "1", ":", "len", "(", "s", ")", "-", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "r", ".", "Time", "=", "t", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements the unmarshaller interface.
[ "UnmarshalJSON", "implements", "the", "unmarshaller", "interface", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/ruby_time.go#L20-L28
test
rightscale/rsc
ss/ssm/codegen_client.go
ExecutionLocator
func (api *API) ExecutionLocator(href string) *ExecutionLocator { return &ExecutionLocator{Href(href), api} }
go
func (api *API) ExecutionLocator(href string) *ExecutionLocator { return &ExecutionLocator{Href(href), api} }
[ "func", "(", "api", "*", "API", ")", "ExecutionLocator", "(", "href", "string", ")", "*", "ExecutionLocator", "{", "return", "&", "ExecutionLocator", "{", "Href", "(", "href", ")", ",", "api", "}", "\n", "}" ]
// ExecutionLocator builds a locator from the given href.
[ "ExecutionLocator", "builds", "a", "locator", "from", "the", "given", "href", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L120-L122
test
rightscale/rsc
ss/ssm/codegen_client.go
NotificationLocator
func (api *API) NotificationLocator(href string) *NotificationLocator { return &NotificationLocator{Href(href), api} }
go
func (api *API) NotificationLocator(href string) *NotificationLocator { return &NotificationLocator{Href(href), api} }
[ "func", "(", "api", "*", "API", ")", "NotificationLocator", "(", "href", "string", ")", "*", "NotificationLocator", "{", "return", "&", "NotificationLocator", "{", "Href", "(", "href", ")", ",", "api", "}", "\n", "}" ]
// NotificationLocator builds a locator from the given href.
[ "NotificationLocator", "builds", "a", "locator", "from", "the", "given", "href", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L842-L844
test
rightscale/rsc
ss/ssm/codegen_client.go
OperationLocator
func (api *API) OperationLocator(href string) *OperationLocator { return &OperationLocator{Href(href), api} }
go
func (api *API) OperationLocator(href string) *OperationLocator { return &OperationLocator{Href(href), api} }
[ "func", "(", "api", "*", "API", ")", "OperationLocator", "(", "href", "string", ")", "*", "OperationLocator", "{", "return", "&", "OperationLocator", "{", "Href", "(", "href", ")", ",", "api", "}", "\n", "}" ]
// OperationLocator builds a locator from the given href.
[ "OperationLocator", "builds", "a", "locator", "from", "the", "given", "href", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L965-L967
test
rightscale/rsc
ss/ssm/codegen_client.go
ScheduledActionLocator
func (api *API) ScheduledActionLocator(href string) *ScheduledActionLocator { return &ScheduledActionLocator{Href(href), api} }
go
func (api *API) ScheduledActionLocator(href string) *ScheduledActionLocator { return &ScheduledActionLocator{Href(href), api} }
[ "func", "(", "api", "*", "API", ")", "ScheduledActionLocator", "(", "href", "string", ")", "*", "ScheduledActionLocator", "{", "return", "&", "ScheduledActionLocator", "{", "Href", "(", "href", ")", ",", "api", "}", "\n", "}" ]
// ScheduledActionLocator builds a locator from the given href.
[ "ScheduledActionLocator", "builds", "a", "locator", "from", "the", "given", "href", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L1155-L1157
test
rightscale/rsc
rsapi/auth.go
NewBasicAuthenticator
func NewBasicAuthenticator(username, password string, accountID int) Authenticator { builder := basicLoginRequestBuilder{username: username, password: password, accountID: accountID} return newCookieSigner(&builder, accountID) }
go
func NewBasicAuthenticator(username, password string, accountID int) Authenticator { builder := basicLoginRequestBuilder{username: username, password: password, accountID: accountID} return newCookieSigner(&builder, accountID) }
[ "func", "NewBasicAuthenticator", "(", "username", ",", "password", "string", ",", "accountID", "int", ")", "Authenticator", "{", "builder", ":=", "basicLoginRequestBuilder", "{", "username", ":", "username", ",", "password", ":", "password", ",", "accountID", ":", "accountID", "}", "\n", "return", "newCookieSigner", "(", "&", "builder", ",", "accountID", ")", "\n", "}" ]
// NewBasicAuthenticator returns a authenticator that uses email and password to create sessions. // The returned authenticator takes care of refreshing the RightScale session as needed.
[ "NewBasicAuthenticator", "returns", "a", "authenticator", "that", "uses", "email", "and", "password", "to", "create", "sessions", ".", "The", "returned", "authenticator", "takes", "care", "of", "refreshing", "the", "RightScale", "session", "as", "needed", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L32-L35
test
rightscale/rsc
rsapi/auth.go
NewSSAuthenticator
func NewSSAuthenticator(auther Authenticator, accountID int) Authenticator { if _, ok := auther.(*ssAuthenticator); ok { // Only wrap if not wrapped already return auther } return &ssAuthenticator{ auther: auther, accountID: accountID, refreshAt: time.Now().Add(-2 * time.Minute), client: httpclient.NewNoRedirect(), } }
go
func NewSSAuthenticator(auther Authenticator, accountID int) Authenticator { if _, ok := auther.(*ssAuthenticator); ok { // Only wrap if not wrapped already return auther } return &ssAuthenticator{ auther: auther, accountID: accountID, refreshAt: time.Now().Add(-2 * time.Minute), client: httpclient.NewNoRedirect(), } }
[ "func", "NewSSAuthenticator", "(", "auther", "Authenticator", ",", "accountID", "int", ")", "Authenticator", "{", "if", "_", ",", "ok", ":=", "auther", ".", "(", "*", "ssAuthenticator", ")", ";", "ok", "{", "return", "auther", "\n", "}", "\n", "return", "&", "ssAuthenticator", "{", "auther", ":", "auther", ",", "accountID", ":", "accountID", ",", "refreshAt", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "2", "*", "time", ".", "Minute", ")", ",", "client", ":", "httpclient", ".", "NewNoRedirect", "(", ")", ",", "}", "\n", "}" ]
// NewSSAuthenticator returns an authenticator that wraps another one and adds the logic needed to // create sessions in Self-Service.
[ "NewSSAuthenticator", "returns", "an", "authenticator", "that", "wraps", "another", "one", "and", "adds", "the", "logic", "needed", "to", "create", "sessions", "in", "Self", "-", "Service", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L72-L83
test
rightscale/rsc
rsapi/auth.go
newCookieSigner
func newCookieSigner(builder loginRequestBuilder, accountID int) Authenticator { return &cookieSigner{ builder: builder, accountID: accountID, refreshAt: time.Now().Add(-2 * time.Minute), client: httpclient.NewNoRedirect(), } }
go
func newCookieSigner(builder loginRequestBuilder, accountID int) Authenticator { return &cookieSigner{ builder: builder, accountID: accountID, refreshAt: time.Now().Add(-2 * time.Minute), client: httpclient.NewNoRedirect(), } }
[ "func", "newCookieSigner", "(", "builder", "loginRequestBuilder", ",", "accountID", "int", ")", "Authenticator", "{", "return", "&", "cookieSigner", "{", "builder", ":", "builder", ",", "accountID", ":", "accountID", ",", "refreshAt", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "2", "*", "time", ".", "Minute", ")", ",", "client", ":", "httpclient", ".", "NewNoRedirect", "(", ")", ",", "}", "\n", "}" ]
// newCookieSigner returns a cookie signer that uses the given builder to build login requests.
[ "newCookieSigner", "returns", "a", "cookie", "signer", "that", "uses", "the", "given", "builder", "to", "build", "login", "requests", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L108-L115
test
rightscale/rsc
rsapi/auth.go
Sign
func (s *cookieSigner) Sign(req *http.Request) error { if time.Now().After(s.refreshAt) { authReq, authErr := s.builder.BuildLoginRequest(s.host) if authErr != nil { return authErr } resp, err := s.client.DoHidden(authReq) if err != nil { return err } url, err := extractRedirectURL(resp) if err != nil { return err } if url != nil { authReq, authErr = s.builder.BuildLoginRequest(url.Host) if authErr != nil { return authErr } s.host = url.Host req.Host = url.Host req.URL.Host = url.Host resp, err = s.client.DoHidden(authReq) } if err != nil { return fmt.Errorf("Authentication failed: %s", err) } if err := s.refresh(resp); err != nil { return err } } for _, c := range s.cookies { req.AddCookie(c) } req.Header.Set("X-Account", strconv.Itoa(s.accountID)) return nil }
go
func (s *cookieSigner) Sign(req *http.Request) error { if time.Now().After(s.refreshAt) { authReq, authErr := s.builder.BuildLoginRequest(s.host) if authErr != nil { return authErr } resp, err := s.client.DoHidden(authReq) if err != nil { return err } url, err := extractRedirectURL(resp) if err != nil { return err } if url != nil { authReq, authErr = s.builder.BuildLoginRequest(url.Host) if authErr != nil { return authErr } s.host = url.Host req.Host = url.Host req.URL.Host = url.Host resp, err = s.client.DoHidden(authReq) } if err != nil { return fmt.Errorf("Authentication failed: %s", err) } if err := s.refresh(resp); err != nil { return err } } for _, c := range s.cookies { req.AddCookie(c) } req.Header.Set("X-Account", strconv.Itoa(s.accountID)) return nil }
[ "func", "(", "s", "*", "cookieSigner", ")", "Sign", "(", "req", "*", "http", ".", "Request", ")", "error", "{", "if", "time", ".", "Now", "(", ")", ".", "After", "(", "s", ".", "refreshAt", ")", "{", "authReq", ",", "authErr", ":=", "s", ".", "builder", ".", "BuildLoginRequest", "(", "s", ".", "host", ")", "\n", "if", "authErr", "!=", "nil", "{", "return", "authErr", "\n", "}", "\n", "resp", ",", "err", ":=", "s", ".", "client", ".", "DoHidden", "(", "authReq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "url", ",", "err", ":=", "extractRedirectURL", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "url", "!=", "nil", "{", "authReq", ",", "authErr", "=", "s", ".", "builder", ".", "BuildLoginRequest", "(", "url", ".", "Host", ")", "\n", "if", "authErr", "!=", "nil", "{", "return", "authErr", "\n", "}", "\n", "s", ".", "host", "=", "url", ".", "Host", "\n", "req", ".", "Host", "=", "url", ".", "Host", "\n", "req", ".", "URL", ".", "Host", "=", "url", ".", "Host", "\n", "resp", ",", "err", "=", "s", ".", "client", ".", "DoHidden", "(", "authReq", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Authentication failed: %s\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "s", ".", "refresh", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "s", ".", "cookies", "{", "req", ".", "AddCookie", "(", "c", ")", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"X-Account\"", ",", "strconv", ".", "Itoa", "(", "s", ".", "accountID", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Sign adds the username and password authorization cookies to the request. // Checks the freshness of the session and creates a new one if needed.
[ "Sign", "adds", "the", "username", "and", "password", "authorization", "cookies", "to", "the", "request", ".", "Checks", "the", "freshness", "of", "the", "session", "and", "creates", "a", "new", "one", "if", "needed", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L119-L155
test
rightscale/rsc
rsapi/auth.go
CanAuthenticate
func (s *cookieSigner) CanAuthenticate(host string) error { _, instance := s.builder.(*instanceLoginRequestBuilder) return testAuth(s, s.client, host, instance) }
go
func (s *cookieSigner) CanAuthenticate(host string) error { _, instance := s.builder.(*instanceLoginRequestBuilder) return testAuth(s, s.client, host, instance) }
[ "func", "(", "s", "*", "cookieSigner", ")", "CanAuthenticate", "(", "host", "string", ")", "error", "{", "_", ",", "instance", ":=", "s", ".", "builder", ".", "(", "*", "instanceLoginRequestBuilder", ")", "\n", "return", "testAuth", "(", "s", ",", "s", ".", "client", ",", "host", ",", "instance", ")", "\n", "}" ]
// CanAuthenticate makes a test request to CM 1.5 and returns true if it is successful.
[ "CanAuthenticate", "makes", "a", "test", "request", "to", "CM", "1", ".", "5", "and", "returns", "true", "if", "it", "is", "successful", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L163-L166
test
rightscale/rsc
rsapi/auth.go
refresh
func (s *cookieSigner) refresh(resp *http.Response) error { if resp.StatusCode != 204 { return fmt.Errorf("Authentication failed: %s", resp.Status) } s.cookies = resp.Cookies() s.refreshAt = time.Now().Add(time.Duration(2) * time.Hour) return nil }
go
func (s *cookieSigner) refresh(resp *http.Response) error { if resp.StatusCode != 204 { return fmt.Errorf("Authentication failed: %s", resp.Status) } s.cookies = resp.Cookies() s.refreshAt = time.Now().Add(time.Duration(2) * time.Hour) return nil }
[ "func", "(", "s", "*", "cookieSigner", ")", "refresh", "(", "resp", "*", "http", ".", "Response", ")", "error", "{", "if", "resp", ".", "StatusCode", "!=", "204", "{", "return", "fmt", ".", "Errorf", "(", "\"Authentication failed: %s\"", ",", "resp", ".", "Status", ")", "\n", "}", "\n", "s", ".", "cookies", "=", "resp", ".", "Cookies", "(", ")", "\n", "s", ".", "refreshAt", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Duration", "(", "2", ")", "*", "time", ".", "Hour", ")", "\n", "return", "nil", "\n", "}" ]
// refresh updates the cookie and expiration used to sign requests from a successful session // creation API response.
[ "refresh", "updates", "the", "cookie", "and", "expiration", "used", "to", "sign", "requests", "from", "a", "successful", "session", "creation", "API", "response", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L170-L177
test
rightscale/rsc
rsapi/auth.go
Sign
func (t *tokenAuthenticator) Sign(r *http.Request) error { r.Header.Set("Authorization", "Bearer "+t.token) if t.accountID != 0 { r.Header.Set("X-Account", strconv.Itoa(t.accountID)) } return nil }
go
func (t *tokenAuthenticator) Sign(r *http.Request) error { r.Header.Set("Authorization", "Bearer "+t.token) if t.accountID != 0 { r.Header.Set("X-Account", strconv.Itoa(t.accountID)) } return nil }
[ "func", "(", "t", "*", "tokenAuthenticator", ")", "Sign", "(", "r", "*", "http", ".", "Request", ")", "error", "{", "r", ".", "Header", ".", "Set", "(", "\"Authorization\"", ",", "\"Bearer \"", "+", "t", ".", "token", ")", "\n", "if", "t", ".", "accountID", "!=", "0", "{", "r", ".", "Header", ".", "Set", "(", "\"X-Account\"", ",", "strconv", ".", "Itoa", "(", "t", ".", "accountID", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Sign sets the OAuth authorization header
[ "Sign", "sets", "the", "OAuth", "authorization", "header" ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L261-L267
test
rightscale/rsc
rsapi/auth.go
Sign
func (a *rl10Authenticator) Sign(r *http.Request) error { r.Header.Set("X-RLL-Secret", a.secret) return nil }
go
func (a *rl10Authenticator) Sign(r *http.Request) error { r.Header.Set("X-RLL-Secret", a.secret) return nil }
[ "func", "(", "a", "*", "rl10Authenticator", ")", "Sign", "(", "r", "*", "http", ".", "Request", ")", "error", "{", "r", ".", "Header", ".", "Set", "(", "\"X-RLL-Secret\"", ",", "a", ".", "secret", ")", "\n", "return", "nil", "\n", "}" ]
// RL10 authenticator uses special header
[ "RL10", "authenticator", "uses", "special", "header" ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L287-L290
test
rightscale/rsc
rsapi/auth.go
Sign
func (a *ssAuthenticator) Sign(r *http.Request) error { if time.Now().After(a.refreshAt) { u := buildURL(a.host, "api/catalog/new_session") u += "?account_id=" + strconv.Itoa(a.accountID) authReq, err := http.NewRequest("GET", u, nil) if err != nil { return err } if err := a.auther.Sign(authReq); err != nil { return err } // A bit tricky: if the auther is the cookie signer it could have updated the // host after being redirected. if ca, ok := a.auther.(*cookieSigner); ok { a.SetHost(ca.host) authReq.Host = a.host authReq.URL.Host = a.host } authReq.Header.Set("Content-Type", "application/json") resp, err := a.client.DoHidden(authReq) if err != nil { return fmt.Errorf("Authentication failed: %s", err) } if resp.StatusCode != 303 { body, err := ioutil.ReadAll(resp.Body) var msg string if err != nil { msg = " - <failed to read body>" } if len(body) > 0 { msg = " - " + string(body) } return fmt.Errorf("Authentication failed: %s%s", resp.Status, msg) } a.refreshAt = time.Now().Add(2 * time.Hour) } a.auther.Sign(r) r.Header.Set("X-Api-Version", "1.0") r.Host = a.host r.URL.Host = a.host return nil }
go
func (a *ssAuthenticator) Sign(r *http.Request) error { if time.Now().After(a.refreshAt) { u := buildURL(a.host, "api/catalog/new_session") u += "?account_id=" + strconv.Itoa(a.accountID) authReq, err := http.NewRequest("GET", u, nil) if err != nil { return err } if err := a.auther.Sign(authReq); err != nil { return err } // A bit tricky: if the auther is the cookie signer it could have updated the // host after being redirected. if ca, ok := a.auther.(*cookieSigner); ok { a.SetHost(ca.host) authReq.Host = a.host authReq.URL.Host = a.host } authReq.Header.Set("Content-Type", "application/json") resp, err := a.client.DoHidden(authReq) if err != nil { return fmt.Errorf("Authentication failed: %s", err) } if resp.StatusCode != 303 { body, err := ioutil.ReadAll(resp.Body) var msg string if err != nil { msg = " - <failed to read body>" } if len(body) > 0 { msg = " - " + string(body) } return fmt.Errorf("Authentication failed: %s%s", resp.Status, msg) } a.refreshAt = time.Now().Add(2 * time.Hour) } a.auther.Sign(r) r.Header.Set("X-Api-Version", "1.0") r.Host = a.host r.URL.Host = a.host return nil }
[ "func", "(", "a", "*", "ssAuthenticator", ")", "Sign", "(", "r", "*", "http", ".", "Request", ")", "error", "{", "if", "time", ".", "Now", "(", ")", ".", "After", "(", "a", ".", "refreshAt", ")", "{", "u", ":=", "buildURL", "(", "a", ".", "host", ",", "\"api/catalog/new_session\"", ")", "\n", "u", "+=", "\"?account_id=\"", "+", "strconv", ".", "Itoa", "(", "a", ".", "accountID", ")", "\n", "authReq", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"GET\"", ",", "u", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "a", ".", "auther", ".", "Sign", "(", "authReq", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "ca", ",", "ok", ":=", "a", ".", "auther", ".", "(", "*", "cookieSigner", ")", ";", "ok", "{", "a", ".", "SetHost", "(", "ca", ".", "host", ")", "\n", "authReq", ".", "Host", "=", "a", ".", "host", "\n", "authReq", ".", "URL", ".", "Host", "=", "a", ".", "host", "\n", "}", "\n", "authReq", ".", "Header", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "resp", ",", "err", ":=", "a", ".", "client", ".", "DoHidden", "(", "authReq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Authentication failed: %s\"", ",", "err", ")", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "303", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "var", "msg", "string", "\n", "if", "err", "!=", "nil", "{", "msg", "=", "\" - <failed to read body>\"", "\n", "}", "\n", "if", "len", "(", "body", ")", ">", "0", "{", "msg", "=", "\" - \"", "+", "string", "(", "body", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"Authentication failed: %s%s\"", ",", "resp", ".", "Status", ",", "msg", ")", "\n", "}", "\n", "a", ".", "refreshAt", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "2", "*", "time", ".", "Hour", ")", "\n", "}", "\n", "a", ".", "auther", ".", "Sign", "(", "r", ")", "\n", "r", ".", "Header", ".", "Set", "(", "\"X-Api-Version\"", ",", "\"1.0\"", ")", "\n", "r", ".", "Host", "=", "a", ".", "host", "\n", "r", ".", "URL", ".", "Host", "=", "a", ".", "host", "\n", "return", "nil", "\n", "}" ]
// Self-Service authenticator first creates a global session with the core then creates a local // session with self-service.
[ "Self", "-", "Service", "authenticator", "first", "creates", "a", "global", "session", "with", "the", "core", "then", "creates", "a", "local", "session", "with", "self", "-", "service", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L314-L358
test
rightscale/rsc
rsapi/auth.go
SetHost
func (a *ssAuthenticator) SetHost(host string) { a.auther.SetHost(host) urlElems := strings.Split(host, ".") hostPrefix := urlElems[0] elems := strings.Split(hostPrefix, "-") if len(elems) == 1 && elems[0] == "cm" { // accommodates micromoo host inference, such as "cm.rightscale.local" => "selfservice.rightscale.local" elems[0] = "selfservice" } else if len(elems) < 2 { // don't know how to compute this ss host; use the cm host a.host = host return } else { elems[len(elems)-2] = "selfservice" } ssLoginHostPrefix := strings.Join(elems, "-") a.host = strings.Join(append([]string{ssLoginHostPrefix}, urlElems[1:]...), ".") }
go
func (a *ssAuthenticator) SetHost(host string) { a.auther.SetHost(host) urlElems := strings.Split(host, ".") hostPrefix := urlElems[0] elems := strings.Split(hostPrefix, "-") if len(elems) == 1 && elems[0] == "cm" { // accommodates micromoo host inference, such as "cm.rightscale.local" => "selfservice.rightscale.local" elems[0] = "selfservice" } else if len(elems) < 2 { // don't know how to compute this ss host; use the cm host a.host = host return } else { elems[len(elems)-2] = "selfservice" } ssLoginHostPrefix := strings.Join(elems, "-") a.host = strings.Join(append([]string{ssLoginHostPrefix}, urlElems[1:]...), ".") }
[ "func", "(", "a", "*", "ssAuthenticator", ")", "SetHost", "(", "host", "string", ")", "{", "a", ".", "auther", ".", "SetHost", "(", "host", ")", "\n", "urlElems", ":=", "strings", ".", "Split", "(", "host", ",", "\".\"", ")", "\n", "hostPrefix", ":=", "urlElems", "[", "0", "]", "\n", "elems", ":=", "strings", ".", "Split", "(", "hostPrefix", ",", "\"-\"", ")", "\n", "if", "len", "(", "elems", ")", "==", "1", "&&", "elems", "[", "0", "]", "==", "\"cm\"", "{", "elems", "[", "0", "]", "=", "\"selfservice\"", "\n", "}", "else", "if", "len", "(", "elems", ")", "<", "2", "{", "a", ".", "host", "=", "host", "\n", "return", "\n", "}", "else", "{", "elems", "[", "len", "(", "elems", ")", "-", "2", "]", "=", "\"selfservice\"", "\n", "}", "\n", "ssLoginHostPrefix", ":=", "strings", ".", "Join", "(", "elems", ",", "\"-\"", ")", "\n", "a", ".", "host", "=", "strings", ".", "Join", "(", "append", "(", "[", "]", "string", "{", "ssLoginHostPrefix", "}", ",", "urlElems", "[", "1", ":", "]", "...", ")", ",", "\".\"", ")", "\n", "}" ]
// SetHost sets the host used to create Self-Service session. // Pass in the CM 1.5 host, this method computes the Self-Service host from it.
[ "SetHost", "sets", "the", "host", "used", "to", "create", "Self", "-", "Service", "session", ".", "Pass", "in", "the", "CM", "1", ".", "5", "host", "this", "method", "computes", "the", "Self", "-", "Service", "host", "from", "it", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L362-L380
test
rightscale/rsc
rsapi/auth.go
CanAuthenticate
func (a *ssAuthenticator) CanAuthenticate(host string) error { url := fmt.Sprintf("api/catalog/accounts/%d/user_preferences", a.accountID) req, err := http.NewRequest("GET", buildURL(host, url), nil) if err != nil { return err } req.Header.Set("X-Api-Version", "1.0") if err := a.Sign(req); err != nil { return err } resp, err := a.client.DoHidden(req) if err != nil { return err } if resp.StatusCode != 200 { var body string if b, err := ioutil.ReadAll(resp.Body); err != nil { body = ": " + string(b) } return fmt.Errorf("%s%s", resp.Status, body) } return nil }
go
func (a *ssAuthenticator) CanAuthenticate(host string) error { url := fmt.Sprintf("api/catalog/accounts/%d/user_preferences", a.accountID) req, err := http.NewRequest("GET", buildURL(host, url), nil) if err != nil { return err } req.Header.Set("X-Api-Version", "1.0") if err := a.Sign(req); err != nil { return err } resp, err := a.client.DoHidden(req) if err != nil { return err } if resp.StatusCode != 200 { var body string if b, err := ioutil.ReadAll(resp.Body); err != nil { body = ": " + string(b) } return fmt.Errorf("%s%s", resp.Status, body) } return nil }
[ "func", "(", "a", "*", "ssAuthenticator", ")", "CanAuthenticate", "(", "host", "string", ")", "error", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"api/catalog/accounts/%d/user_preferences\"", ",", "a", ".", "accountID", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"GET\"", ",", "buildURL", "(", "host", ",", "url", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"X-Api-Version\"", ",", "\"1.0\"", ")", "\n", "if", "err", ":=", "a", ".", "Sign", "(", "req", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "a", ".", "client", ".", "DoHidden", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "200", "{", "var", "body", "string", "\n", "if", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", ";", "err", "!=", "nil", "{", "body", "=", "\": \"", "+", "string", "(", "b", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"%s%s\"", ",", "resp", ".", "Status", ",", "body", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CanAuthenticate makes a test request to SS and returns true if it is successful.
[ "CanAuthenticate", "makes", "a", "test", "request", "to", "SS", "and", "returns", "true", "if", "it", "is", "successful", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L383-L405
test
rightscale/rsc
rsapi/auth.go
extractRedirectURL
func extractRedirectURL(resp *http.Response) (*url.URL, error) { var u *url.URL if resp.StatusCode > 299 && resp.StatusCode < 399 { loc := resp.Header.Get("Location") if loc != "" { var err error u, err = url.Parse(loc) if err != nil { return nil, fmt.Errorf("invalid Location header '%s': %s", loc, err) } } } return u, nil }
go
func extractRedirectURL(resp *http.Response) (*url.URL, error) { var u *url.URL if resp.StatusCode > 299 && resp.StatusCode < 399 { loc := resp.Header.Get("Location") if loc != "" { var err error u, err = url.Parse(loc) if err != nil { return nil, fmt.Errorf("invalid Location header '%s': %s", loc, err) } } } return u, nil }
[ "func", "extractRedirectURL", "(", "resp", "*", "http", ".", "Response", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "var", "u", "*", "url", ".", "URL", "\n", "if", "resp", ".", "StatusCode", ">", "299", "&&", "resp", ".", "StatusCode", "<", "399", "{", "loc", ":=", "resp", ".", "Header", ".", "Get", "(", "\"Location\"", ")", "\n", "if", "loc", "!=", "\"\"", "{", "var", "err", "error", "\n", "u", ",", "err", "=", "url", ".", "Parse", "(", "loc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid Location header '%s': %s\"", ",", "loc", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "u", ",", "nil", "\n", "}" ]
// extractRedirectURL is a helper function that extracts the Location header from a redirect // response. It returns nil if the header is missing, an error if it's malformed.
[ "extractRedirectURL", "is", "a", "helper", "function", "that", "extracts", "the", "Location", "header", "from", "a", "redirect", "response", ".", "It", "returns", "nil", "if", "the", "header", "is", "missing", "an", "error", "if", "it", "s", "malformed", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L456-L469
test
rightscale/rsc
rsapi/auth.go
buildURL
func buildURL(host, path string) string { scheme := "https" if httpclient.Insecure { scheme = "http" } u := url.URL{ Scheme: scheme, Host: host, Path: path, } return u.String() }
go
func buildURL(host, path string) string { scheme := "https" if httpclient.Insecure { scheme = "http" } u := url.URL{ Scheme: scheme, Host: host, Path: path, } return u.String() }
[ "func", "buildURL", "(", "host", ",", "path", "string", ")", "string", "{", "scheme", ":=", "\"https\"", "\n", "if", "httpclient", ".", "Insecure", "{", "scheme", "=", "\"http\"", "\n", "}", "\n", "u", ":=", "url", ".", "URL", "{", "Scheme", ":", "scheme", ",", "Host", ":", "host", ",", "Path", ":", "path", ",", "}", "\n", "return", "u", ".", "String", "(", ")", "\n", "}" ]
// Compute API URL given a scheme, hostname and a path
[ "Compute", "API", "URL", "given", "a", "scheme", "hostname", "and", "a", "path" ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L472-L483
test
rightscale/rsc
metadata/resource.go
GetAction
func (r *Resource) GetAction(name string) *Action { for _, a := range r.Actions { if a.Name == name { return a } } return nil }
go
func (r *Resource) GetAction(name string) *Action { for _, a := range r.Actions { if a.Name == name { return a } } return nil }
[ "func", "(", "r", "*", "Resource", ")", "GetAction", "(", "name", "string", ")", "*", "Action", "{", "for", "_", ",", "a", ":=", "range", "r", ".", "Actions", "{", "if", "a", ".", "Name", "==", "name", "{", "return", "a", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetAction returns the action with the given name, returns nil if none is found.
[ "GetAction", "returns", "the", "action", "with", "the", "given", "name", "returns", "nil", "if", "none", "is", "found", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/resource.go#L51-L58
test
rightscale/rsc
metadata/resource.go
HasLink
func (r *Resource) HasLink(name string) bool { for n, _ := range r.Links { if n == name { return true } } return false }
go
func (r *Resource) HasLink(name string) bool { for n, _ := range r.Links { if n == name { return true } } return false }
[ "func", "(", "r", "*", "Resource", ")", "HasLink", "(", "name", "string", ")", "bool", "{", "for", "n", ",", "_", ":=", "range", "r", ".", "Links", "{", "if", "n", "==", "name", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasLink returns whether the resource has a link with the given name.
[ "HasLink", "returns", "whether", "the", "resource", "has", "a", "link", "with", "the", "given", "name", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/resource.go#L61-L68
test
rightscale/rsc
metadata/resource.go
findMatches
func (r *Resource) findMatches(href string) []*PathPattern { var matches []*PathPattern for _, action := range r.Actions { for _, pattern := range action.PathPatterns { if pattern.Regexp.MatchString(href) || pattern.Regexp.MatchString(href+"/") { matches = append(matches, pattern) } } } return matches }
go
func (r *Resource) findMatches(href string) []*PathPattern { var matches []*PathPattern for _, action := range r.Actions { for _, pattern := range action.PathPatterns { if pattern.Regexp.MatchString(href) || pattern.Regexp.MatchString(href+"/") { matches = append(matches, pattern) } } } return matches }
[ "func", "(", "r", "*", "Resource", ")", "findMatches", "(", "href", "string", ")", "[", "]", "*", "PathPattern", "{", "var", "matches", "[", "]", "*", "PathPattern", "\n", "for", "_", ",", "action", ":=", "range", "r", ".", "Actions", "{", "for", "_", ",", "pattern", ":=", "range", "action", ".", "PathPatterns", "{", "if", "pattern", ".", "Regexp", ".", "MatchString", "(", "href", ")", "||", "pattern", ".", "Regexp", ".", "MatchString", "(", "href", "+", "\"/\"", ")", "{", "matches", "=", "append", "(", "matches", ",", "pattern", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "matches", "\n", "}" ]
// Find paths that match given href
[ "Find", "paths", "that", "match", "given", "href" ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/resource.go#L71-L81
test
rightscale/rsc
httpclient/http.go
NewPB
func NewPB(pb *ParamBlock) HTTPClient { responseHeaderTimeout := pb.ResponseHeaderTimeout if responseHeaderTimeout == 0 { responseHeaderTimeout = defaultResponseHeaderTimeout } dumpFormat := pb.DumpFormat if dumpFormat == 0 { dumpFormat = NoDump } hiddenHeaders := pb.HiddenHeaders if hiddenHeaders == nil { hiddenHeaders = defaultHiddenHeaders // immutable } else { hiddenHeaders = copyHiddenHeaders(hiddenHeaders) // copy to avoid side-effects } dc := &dumpClient{Client: newRawClient(pb.NoRedirect, pb.NoCertCheck, pb.DisableKeepAlives, responseHeaderTimeout)} dc.isInsecure = func() bool { return pb.Insecure } dc.dumpFormat = func() Format { return dumpFormat } dc.hiddenHeaders = func() map[string]bool { return hiddenHeaders } return dc }
go
func NewPB(pb *ParamBlock) HTTPClient { responseHeaderTimeout := pb.ResponseHeaderTimeout if responseHeaderTimeout == 0 { responseHeaderTimeout = defaultResponseHeaderTimeout } dumpFormat := pb.DumpFormat if dumpFormat == 0 { dumpFormat = NoDump } hiddenHeaders := pb.HiddenHeaders if hiddenHeaders == nil { hiddenHeaders = defaultHiddenHeaders // immutable } else { hiddenHeaders = copyHiddenHeaders(hiddenHeaders) // copy to avoid side-effects } dc := &dumpClient{Client: newRawClient(pb.NoRedirect, pb.NoCertCheck, pb.DisableKeepAlives, responseHeaderTimeout)} dc.isInsecure = func() bool { return pb.Insecure } dc.dumpFormat = func() Format { return dumpFormat } dc.hiddenHeaders = func() map[string]bool { return hiddenHeaders } return dc }
[ "func", "NewPB", "(", "pb", "*", "ParamBlock", ")", "HTTPClient", "{", "responseHeaderTimeout", ":=", "pb", ".", "ResponseHeaderTimeout", "\n", "if", "responseHeaderTimeout", "==", "0", "{", "responseHeaderTimeout", "=", "defaultResponseHeaderTimeout", "\n", "}", "\n", "dumpFormat", ":=", "pb", ".", "DumpFormat", "\n", "if", "dumpFormat", "==", "0", "{", "dumpFormat", "=", "NoDump", "\n", "}", "\n", "hiddenHeaders", ":=", "pb", ".", "HiddenHeaders", "\n", "if", "hiddenHeaders", "==", "nil", "{", "hiddenHeaders", "=", "defaultHiddenHeaders", "\n", "}", "else", "{", "hiddenHeaders", "=", "copyHiddenHeaders", "(", "hiddenHeaders", ")", "\n", "}", "\n", "dc", ":=", "&", "dumpClient", "{", "Client", ":", "newRawClient", "(", "pb", ".", "NoRedirect", ",", "pb", ".", "NoCertCheck", ",", "pb", ".", "DisableKeepAlives", ",", "responseHeaderTimeout", ")", "}", "\n", "dc", ".", "isInsecure", "=", "func", "(", ")", "bool", "{", "return", "pb", ".", "Insecure", "\n", "}", "\n", "dc", ".", "dumpFormat", "=", "func", "(", ")", "Format", "{", "return", "dumpFormat", "\n", "}", "\n", "dc", ".", "hiddenHeaders", "=", "func", "(", ")", "map", "[", "string", "]", "bool", "{", "return", "hiddenHeaders", "\n", "}", "\n", "return", "dc", "\n", "}" ]
// NewPB returns an HTTP client using only the parameter block and ignoring // the current values of the package variables, which are not go-routine safe.
[ "NewPB", "returns", "an", "HTTP", "client", "using", "only", "the", "parameter", "block", "and", "ignoring", "the", "current", "values", "of", "the", "package", "variables", "which", "are", "not", "go", "-", "routine", "safe", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L158-L184
test
rightscale/rsc
httpclient/http.go
newVariableDumpClient
func newVariableDumpClient(c *http.Client) HTTPClient { dc := &dumpClient{Client: c} dc.isInsecure = func() bool { return Insecure } dc.dumpFormat = func() Format { return DumpFormat } dc.hiddenHeaders = func() map[string]bool { return HiddenHeaders } return dc }
go
func newVariableDumpClient(c *http.Client) HTTPClient { dc := &dumpClient{Client: c} dc.isInsecure = func() bool { return Insecure } dc.dumpFormat = func() Format { return DumpFormat } dc.hiddenHeaders = func() map[string]bool { return HiddenHeaders } return dc }
[ "func", "newVariableDumpClient", "(", "c", "*", "http", ".", "Client", ")", "HTTPClient", "{", "dc", ":=", "&", "dumpClient", "{", "Client", ":", "c", "}", "\n", "dc", ".", "isInsecure", "=", "func", "(", ")", "bool", "{", "return", "Insecure", "\n", "}", "\n", "dc", ".", "dumpFormat", "=", "func", "(", ")", "Format", "{", "return", "DumpFormat", "\n", "}", "\n", "dc", ".", "hiddenHeaders", "=", "func", "(", ")", "map", "[", "string", "]", "bool", "{", "return", "HiddenHeaders", "\n", "}", "\n", "return", "dc", "\n", "}" ]
// newVariableDumpClient defines accessors for package variables, which are not // go-routine safe so can theoretically change value while the client is in use. // this emulates the legacy behavior.
[ "newVariableDumpClient", "defines", "accessors", "for", "package", "variables", "which", "are", "not", "go", "-", "routine", "safe", "so", "can", "theoretically", "change", "value", "while", "the", "client", "is", "in", "use", ".", "this", "emulates", "the", "legacy", "behavior", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L189-L201
test
rightscale/rsc
httpclient/http.go
newRawClient
func newRawClient( noRedirect, noCertCheck, disableKeepAlives bool, responseHeaderTimeout time.Duration) *http.Client { tr := http.Transport{ DisableKeepAlives: disableKeepAlives, ResponseHeaderTimeout: responseHeaderTimeout, Proxy: http.ProxyFromEnvironment, } tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: noCertCheck} c := http.Client{Transport: &tr} if noRedirect { c.CheckRedirect = func(*http.Request, []*http.Request) error { return fmt.Errorf(noRedirectError) } } return &c }
go
func newRawClient( noRedirect, noCertCheck, disableKeepAlives bool, responseHeaderTimeout time.Duration) *http.Client { tr := http.Transport{ DisableKeepAlives: disableKeepAlives, ResponseHeaderTimeout: responseHeaderTimeout, Proxy: http.ProxyFromEnvironment, } tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: noCertCheck} c := http.Client{Transport: &tr} if noRedirect { c.CheckRedirect = func(*http.Request, []*http.Request) error { return fmt.Errorf(noRedirectError) } } return &c }
[ "func", "newRawClient", "(", "noRedirect", ",", "noCertCheck", ",", "disableKeepAlives", "bool", ",", "responseHeaderTimeout", "time", ".", "Duration", ")", "*", "http", ".", "Client", "{", "tr", ":=", "http", ".", "Transport", "{", "DisableKeepAlives", ":", "disableKeepAlives", ",", "ResponseHeaderTimeout", ":", "responseHeaderTimeout", ",", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "}", "\n", "tr", ".", "TLSClientConfig", "=", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "noCertCheck", "}", "\n", "c", ":=", "http", ".", "Client", "{", "Transport", ":", "&", "tr", "}", "\n", "if", "noRedirect", "{", "c", ".", "CheckRedirect", "=", "func", "(", "*", "http", ".", "Request", ",", "[", "]", "*", "http", ".", "Request", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "noRedirectError", ")", "\n", "}", "\n", "}", "\n", "return", "&", "c", "\n", "}" ]
// newRawClient creates an http package Client taking into account both the parameters and package // variables.
[ "newRawClient", "creates", "an", "http", "package", "Client", "taking", "into", "account", "both", "the", "parameters", "and", "package", "variables", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L213-L230
test
rightscale/rsc
httpclient/http.go
DoHidden
func (d *dumpClient) DoHidden(req *http.Request) (*http.Response, error) { return d.doImp(req, true, nil) }
go
func (d *dumpClient) DoHidden(req *http.Request) (*http.Response, error) { return d.doImp(req, true, nil) }
[ "func", "(", "d", "*", "dumpClient", ")", "DoHidden", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "d", ".", "doImp", "(", "req", ",", "true", ",", "nil", ")", "\n", "}" ]
// DoHidden is equivalent to Do with the exception that nothing gets logged unless DumpFormat is // set to Verbose.
[ "DoHidden", "is", "equivalent", "to", "Do", "with", "the", "exception", "that", "nothing", "gets", "logged", "unless", "DumpFormat", "is", "set", "to", "Verbose", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L254-L256
test
rightscale/rsc
httpclient/http.go
Do
func (d *dumpClient) Do(req *http.Request) (*http.Response, error) { return d.doImp(req, false, nil) }
go
func (d *dumpClient) Do(req *http.Request) (*http.Response, error) { return d.doImp(req, false, nil) }
[ "func", "(", "d", "*", "dumpClient", ")", "Do", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "d", ".", "doImp", "(", "req", ",", "false", ",", "nil", ")", "\n", "}" ]
// Do dumps the request, makes the request and dumps the response as specified by DumpFormat.
[ "Do", "dumps", "the", "request", "makes", "the", "request", "and", "dumps", "the", "response", "as", "specified", "by", "DumpFormat", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L259-L261
test
rightscale/rsc
httpclient/http.go
doImp
func (d *dumpClient) doImp(req *http.Request, hidden bool, ctx context.Context) (*http.Response, error) { if req.URL.Scheme == "" { if d.isInsecure() { req.URL.Scheme = "http" } else { req.URL.Scheme = "https" } } //set user-agent if one is not provided. ua := req.Header.Get("User-Agent") if ua == "" { req.Header.Set("User-Agent", UA) } var reqBody []byte startedAt := time.Now() // prefer the X-Request-Id header as request token for logging, if present. id := req.Header.Get(requestIdHeader) if id == "" { id = ShortToken() } log.Info("started", "id", id, req.Method, req.URL.String()) df := d.dumpFormat() hide := (df == NoDump) || (hidden && !df.IsVerbose()) if !hide { startedAt = time.Now() reqBody = d.dumpRequest(req) } var resp *http.Response var err error if ctx == nil { resp, err = d.Client.Do(req) } else { resp, err = ctxhttpDo(ctx, d.getClientWithoutTimeout(), req) } if urlError, ok := err.(*url.Error); ok { if urlError.Err.Error() == noRedirectError { err = nil } } if err != nil { return nil, err } if !hide { d.dumpResponse(resp, req, reqBody) } log.Info("completed", "id", id, "status", resp.Status, "time", time.Since(startedAt).String()) return resp, nil }
go
func (d *dumpClient) doImp(req *http.Request, hidden bool, ctx context.Context) (*http.Response, error) { if req.URL.Scheme == "" { if d.isInsecure() { req.URL.Scheme = "http" } else { req.URL.Scheme = "https" } } //set user-agent if one is not provided. ua := req.Header.Get("User-Agent") if ua == "" { req.Header.Set("User-Agent", UA) } var reqBody []byte startedAt := time.Now() // prefer the X-Request-Id header as request token for logging, if present. id := req.Header.Get(requestIdHeader) if id == "" { id = ShortToken() } log.Info("started", "id", id, req.Method, req.URL.String()) df := d.dumpFormat() hide := (df == NoDump) || (hidden && !df.IsVerbose()) if !hide { startedAt = time.Now() reqBody = d.dumpRequest(req) } var resp *http.Response var err error if ctx == nil { resp, err = d.Client.Do(req) } else { resp, err = ctxhttpDo(ctx, d.getClientWithoutTimeout(), req) } if urlError, ok := err.(*url.Error); ok { if urlError.Err.Error() == noRedirectError { err = nil } } if err != nil { return nil, err } if !hide { d.dumpResponse(resp, req, reqBody) } log.Info("completed", "id", id, "status", resp.Status, "time", time.Since(startedAt).String()) return resp, nil }
[ "func", "(", "d", "*", "dumpClient", ")", "doImp", "(", "req", "*", "http", ".", "Request", ",", "hidden", "bool", ",", "ctx", "context", ".", "Context", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "if", "req", ".", "URL", ".", "Scheme", "==", "\"\"", "{", "if", "d", ".", "isInsecure", "(", ")", "{", "req", ".", "URL", ".", "Scheme", "=", "\"http\"", "\n", "}", "else", "{", "req", ".", "URL", ".", "Scheme", "=", "\"https\"", "\n", "}", "\n", "}", "\n", "ua", ":=", "req", ".", "Header", ".", "Get", "(", "\"User-Agent\"", ")", "\n", "if", "ua", "==", "\"\"", "{", "req", ".", "Header", ".", "Set", "(", "\"User-Agent\"", ",", "UA", ")", "\n", "}", "\n", "var", "reqBody", "[", "]", "byte", "\n", "startedAt", ":=", "time", ".", "Now", "(", ")", "\n", "id", ":=", "req", ".", "Header", ".", "Get", "(", "requestIdHeader", ")", "\n", "if", "id", "==", "\"\"", "{", "id", "=", "ShortToken", "(", ")", "\n", "}", "\n", "log", ".", "Info", "(", "\"started\"", ",", "\"id\"", ",", "id", ",", "req", ".", "Method", ",", "req", ".", "URL", ".", "String", "(", ")", ")", "\n", "df", ":=", "d", ".", "dumpFormat", "(", ")", "\n", "hide", ":=", "(", "df", "==", "NoDump", ")", "||", "(", "hidden", "&&", "!", "df", ".", "IsVerbose", "(", ")", ")", "\n", "if", "!", "hide", "{", "startedAt", "=", "time", ".", "Now", "(", ")", "\n", "reqBody", "=", "d", ".", "dumpRequest", "(", "req", ")", "\n", "}", "\n", "var", "resp", "*", "http", ".", "Response", "\n", "var", "err", "error", "\n", "if", "ctx", "==", "nil", "{", "resp", ",", "err", "=", "d", ".", "Client", ".", "Do", "(", "req", ")", "\n", "}", "else", "{", "resp", ",", "err", "=", "ctxhttpDo", "(", "ctx", ",", "d", ".", "getClientWithoutTimeout", "(", ")", ",", "req", ")", "\n", "}", "\n", "if", "urlError", ",", "ok", ":=", "err", ".", "(", "*", "url", ".", "Error", ")", ";", "ok", "{", "if", "urlError", ".", "Err", ".", "Error", "(", ")", "==", "noRedirectError", "{", "err", "=", "nil", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "hide", "{", "d", ".", "dumpResponse", "(", "resp", ",", "req", ",", "reqBody", ")", "\n", "}", "\n", "log", ".", "Info", "(", "\"completed\"", ",", "\"id\"", ",", "id", ",", "\"status\"", ",", "resp", ".", "Status", ",", "\"time\"", ",", "time", ".", "Since", "(", "startedAt", ")", ".", "String", "(", ")", ")", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// doImp actually performs the HTTP request logging according to the various settings.
[ "doImp", "actually", "performs", "the", "HTTP", "request", "logging", "according", "to", "the", "various", "settings", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L272-L323
test
rightscale/rsc
httpclient/http.go
getClientWithoutTimeout
func (d *dumpClient) getClientWithoutTimeout() *http.Client { // Get a copy of the client and modify as multiple concurrent go routines can be using this client. client := *d.Client tr, ok := client.Transport.(*http.Transport) if ok { // note that the http.Transport struct has internal mutex fields that are // not safe to copy. we have to be selective in copying fields. trCopy := &http.Transport{ Proxy: tr.Proxy, DialContext: tr.DialContext, Dial: tr.Dial, DialTLS: tr.DialTLS, TLSClientConfig: tr.TLSClientConfig, TLSHandshakeTimeout: tr.TLSHandshakeTimeout, DisableKeepAlives: tr.DisableKeepAlives, DisableCompression: tr.DisableCompression, MaxIdleConns: tr.MaxIdleConns, MaxIdleConnsPerHost: tr.MaxIdleConnsPerHost, IdleConnTimeout: tr.IdleConnTimeout, ResponseHeaderTimeout: 0, // explicitly zeroed-out ExpectContinueTimeout: tr.ExpectContinueTimeout, TLSNextProto: tr.TLSNextProto, MaxResponseHeaderBytes: tr.MaxResponseHeaderBytes, } tr = trCopy } else { // note that the following code has a known issue in that it depends on the // current value of the NoCertCheck global. if that global changes after // creation of this client then the behavior is undefined. tr = &http.Transport{Proxy: http.ProxyFromEnvironment} tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: NoCertCheck} } client.Transport = tr return &client }
go
func (d *dumpClient) getClientWithoutTimeout() *http.Client { // Get a copy of the client and modify as multiple concurrent go routines can be using this client. client := *d.Client tr, ok := client.Transport.(*http.Transport) if ok { // note that the http.Transport struct has internal mutex fields that are // not safe to copy. we have to be selective in copying fields. trCopy := &http.Transport{ Proxy: tr.Proxy, DialContext: tr.DialContext, Dial: tr.Dial, DialTLS: tr.DialTLS, TLSClientConfig: tr.TLSClientConfig, TLSHandshakeTimeout: tr.TLSHandshakeTimeout, DisableKeepAlives: tr.DisableKeepAlives, DisableCompression: tr.DisableCompression, MaxIdleConns: tr.MaxIdleConns, MaxIdleConnsPerHost: tr.MaxIdleConnsPerHost, IdleConnTimeout: tr.IdleConnTimeout, ResponseHeaderTimeout: 0, // explicitly zeroed-out ExpectContinueTimeout: tr.ExpectContinueTimeout, TLSNextProto: tr.TLSNextProto, MaxResponseHeaderBytes: tr.MaxResponseHeaderBytes, } tr = trCopy } else { // note that the following code has a known issue in that it depends on the // current value of the NoCertCheck global. if that global changes after // creation of this client then the behavior is undefined. tr = &http.Transport{Proxy: http.ProxyFromEnvironment} tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: NoCertCheck} } client.Transport = tr return &client }
[ "func", "(", "d", "*", "dumpClient", ")", "getClientWithoutTimeout", "(", ")", "*", "http", ".", "Client", "{", "client", ":=", "*", "d", ".", "Client", "\n", "tr", ",", "ok", ":=", "client", ".", "Transport", ".", "(", "*", "http", ".", "Transport", ")", "\n", "if", "ok", "{", "trCopy", ":=", "&", "http", ".", "Transport", "{", "Proxy", ":", "tr", ".", "Proxy", ",", "DialContext", ":", "tr", ".", "DialContext", ",", "Dial", ":", "tr", ".", "Dial", ",", "DialTLS", ":", "tr", ".", "DialTLS", ",", "TLSClientConfig", ":", "tr", ".", "TLSClientConfig", ",", "TLSHandshakeTimeout", ":", "tr", ".", "TLSHandshakeTimeout", ",", "DisableKeepAlives", ":", "tr", ".", "DisableKeepAlives", ",", "DisableCompression", ":", "tr", ".", "DisableCompression", ",", "MaxIdleConns", ":", "tr", ".", "MaxIdleConns", ",", "MaxIdleConnsPerHost", ":", "tr", ".", "MaxIdleConnsPerHost", ",", "IdleConnTimeout", ":", "tr", ".", "IdleConnTimeout", ",", "ResponseHeaderTimeout", ":", "0", ",", "ExpectContinueTimeout", ":", "tr", ".", "ExpectContinueTimeout", ",", "TLSNextProto", ":", "tr", ".", "TLSNextProto", ",", "MaxResponseHeaderBytes", ":", "tr", ".", "MaxResponseHeaderBytes", ",", "}", "\n", "tr", "=", "trCopy", "\n", "}", "else", "{", "tr", "=", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", "}", "\n", "tr", ".", "TLSClientConfig", "=", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "NoCertCheck", "}", "\n", "}", "\n", "client", ".", "Transport", "=", "tr", "\n", "return", "&", "client", "\n", "}" ]
// getClientWithoutTimeout returns a modified client that doesn't have the ResponseHeaderTimeout field set // in its Transport.
[ "getClientWithoutTimeout", "returns", "a", "modified", "client", "that", "doesn", "t", "have", "the", "ResponseHeaderTimeout", "field", "set", "in", "its", "Transport", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L327-L361
test
rightscale/rsc
httpclient/http.go
dumpRequest
func (d *dumpClient) dumpRequest(req *http.Request) []byte { df := d.dumpFormat() if df == NoDump { return nil } reqBody, err := dumpReqBody(req) if err != nil { log.Error("Failed to load request body for dump", "error", err.Error()) } if df.IsDebug() { var buffer bytes.Buffer buffer.WriteString(req.Method + " " + req.URL.String() + "\n") d.writeHeaders(&buffer, req.Header) if reqBody != nil { buffer.WriteString("\n") buffer.Write(reqBody) buffer.WriteString("\n") } fmt.Fprint(OsStderr, buffer.String()) } else if df.IsJSON() { return reqBody } return nil }
go
func (d *dumpClient) dumpRequest(req *http.Request) []byte { df := d.dumpFormat() if df == NoDump { return nil } reqBody, err := dumpReqBody(req) if err != nil { log.Error("Failed to load request body for dump", "error", err.Error()) } if df.IsDebug() { var buffer bytes.Buffer buffer.WriteString(req.Method + " " + req.URL.String() + "\n") d.writeHeaders(&buffer, req.Header) if reqBody != nil { buffer.WriteString("\n") buffer.Write(reqBody) buffer.WriteString("\n") } fmt.Fprint(OsStderr, buffer.String()) } else if df.IsJSON() { return reqBody } return nil }
[ "func", "(", "d", "*", "dumpClient", ")", "dumpRequest", "(", "req", "*", "http", ".", "Request", ")", "[", "]", "byte", "{", "df", ":=", "d", ".", "dumpFormat", "(", ")", "\n", "if", "df", "==", "NoDump", "{", "return", "nil", "\n", "}", "\n", "reqBody", ",", "err", ":=", "dumpReqBody", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "\"Failed to load request body for dump\"", ",", "\"error\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "df", ".", "IsDebug", "(", ")", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "buffer", ".", "WriteString", "(", "req", ".", "Method", "+", "\" \"", "+", "req", ".", "URL", ".", "String", "(", ")", "+", "\"\\n\"", ")", "\n", "\\n", "\n", "d", ".", "writeHeaders", "(", "&", "buffer", ",", "req", ".", "Header", ")", "\n", "if", "reqBody", "!=", "nil", "{", "buffer", ".", "WriteString", "(", "\"\\n\"", ")", "\n", "\\n", "\n", "buffer", ".", "Write", "(", "reqBody", ")", "\n", "}", "\n", "}", "else", "buffer", ".", "WriteString", "(", "\"\\n\"", ")", "\n", "\\n", "\n", "}" ]
// Dump request if needed. // Return request serialized as JSON if DumpFormat is JSON, nil otherwise.
[ "Dump", "request", "if", "needed", ".", "Return", "request", "serialized", "as", "JSON", "if", "DumpFormat", "is", "JSON", "nil", "otherwise", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L365-L388
test
rightscale/rsc
httpclient/http.go
writeHeaders
func (d *dumpClient) writeHeaders(buffer *bytes.Buffer, headers http.Header) { filterHeaders( d.dumpFormat(), d.hiddenHeaders(), headers, func(name string, value []string) { buffer.WriteString(name) buffer.WriteString(": ") buffer.WriteString(strings.Join(value, ", ")) buffer.WriteString("\n") }) }
go
func (d *dumpClient) writeHeaders(buffer *bytes.Buffer, headers http.Header) { filterHeaders( d.dumpFormat(), d.hiddenHeaders(), headers, func(name string, value []string) { buffer.WriteString(name) buffer.WriteString(": ") buffer.WriteString(strings.Join(value, ", ")) buffer.WriteString("\n") }) }
[ "func", "(", "d", "*", "dumpClient", ")", "writeHeaders", "(", "buffer", "*", "bytes", ".", "Buffer", ",", "headers", "http", ".", "Header", ")", "{", "filterHeaders", "(", "d", ".", "dumpFormat", "(", ")", ",", "d", ".", "hiddenHeaders", "(", ")", ",", "headers", ",", "func", "(", "name", "string", ",", "value", "[", "]", "string", ")", "{", "buffer", ".", "WriteString", "(", "name", ")", "\n", "buffer", ".", "WriteString", "(", "\": \"", ")", "\n", "buffer", ".", "WriteString", "(", "strings", ".", "Join", "(", "value", ",", "\", \"", ")", ")", "\n", "buffer", ".", "WriteString", "(", "\"\\n\"", ")", "\n", "}", ")", "\n", "}" ]
// writeHeaders is a helper function that writes the given HTTP headers to the given buffer as // human readable strings. If DumpFormat is not Verbose then writeHeaders filters out headers whose // names are keys of HiddenHeaders.
[ "writeHeaders", "is", "a", "helper", "function", "that", "writes", "the", "given", "HTTP", "headers", "to", "the", "given", "buffer", "as", "human", "readable", "strings", ".", "If", "DumpFormat", "is", "not", "Verbose", "then", "writeHeaders", "filters", "out", "headers", "whose", "names", "are", "keys", "of", "HiddenHeaders", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L448-L459
test
rightscale/rsc
httpclient/http.go
copyHiddenHeaders
func copyHiddenHeaders(from map[string]bool) (to map[string]bool) { to = make(map[string]bool) for k, v := range from { to[k] = v } return }
go
func copyHiddenHeaders(from map[string]bool) (to map[string]bool) { to = make(map[string]bool) for k, v := range from { to[k] = v } return }
[ "func", "copyHiddenHeaders", "(", "from", "map", "[", "string", "]", "bool", ")", "(", "to", "map", "[", "string", "]", "bool", ")", "{", "to", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "k", ",", "v", ":=", "range", "from", "{", "to", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "\n", "}" ]
// copyHiddenHeaders copies the given map
[ "copyHiddenHeaders", "copies", "the", "given", "map" ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L550-L556
test
rightscale/rsc
command_line.go
validateCommandLine
func validateCommandLine(cmdLine *cmd.CommandLine) { if cmdLine.Command == "setup" || cmdLine.Command == "actions" || cmdLine.Command == "json" || cmdLine.ShowHelp || cmdLine.RL10 { return } if cmdLine.Account == 0 && cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && !cmdLine.NoAuth { kingpin.Fatalf("missing --account option") } if cmdLine.Host == "" { kingpin.Fatalf("missing --host option") } if cmdLine.Password == "" && cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && !cmdLine.NoAuth { kingpin.Fatalf("missing login info, use --email and --pwd or use --key, --apiToken or --rl10") } }
go
func validateCommandLine(cmdLine *cmd.CommandLine) { if cmdLine.Command == "setup" || cmdLine.Command == "actions" || cmdLine.Command == "json" || cmdLine.ShowHelp || cmdLine.RL10 { return } if cmdLine.Account == 0 && cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && !cmdLine.NoAuth { kingpin.Fatalf("missing --account option") } if cmdLine.Host == "" { kingpin.Fatalf("missing --host option") } if cmdLine.Password == "" && cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && !cmdLine.NoAuth { kingpin.Fatalf("missing login info, use --email and --pwd or use --key, --apiToken or --rl10") } }
[ "func", "validateCommandLine", "(", "cmdLine", "*", "cmd", ".", "CommandLine", ")", "{", "if", "cmdLine", ".", "Command", "==", "\"setup\"", "||", "cmdLine", ".", "Command", "==", "\"actions\"", "||", "cmdLine", ".", "Command", "==", "\"json\"", "||", "cmdLine", ".", "ShowHelp", "||", "cmdLine", ".", "RL10", "{", "return", "\n", "}", "\n", "if", "cmdLine", ".", "Account", "==", "0", "&&", "cmdLine", ".", "OAuthToken", "==", "\"\"", "&&", "cmdLine", ".", "OAuthAccessToken", "==", "\"\"", "&&", "cmdLine", ".", "APIToken", "==", "\"\"", "&&", "!", "cmdLine", ".", "NoAuth", "{", "kingpin", ".", "Fatalf", "(", "\"missing --account option\"", ")", "\n", "}", "\n", "if", "cmdLine", ".", "Host", "==", "\"\"", "{", "kingpin", ".", "Fatalf", "(", "\"missing --host option\"", ")", "\n", "}", "\n", "if", "cmdLine", ".", "Password", "==", "\"\"", "&&", "cmdLine", ".", "OAuthToken", "==", "\"\"", "&&", "cmdLine", ".", "OAuthAccessToken", "==", "\"\"", "&&", "cmdLine", ".", "APIToken", "==", "\"\"", "&&", "!", "cmdLine", ".", "NoAuth", "{", "kingpin", ".", "Fatalf", "(", "\"missing login info, use --email and --pwd or use --key, --apiToken or --rl10\"", ")", "\n", "}", "\n", "}" ]
// Make sure all the required information is there
[ "Make", "sure", "all", "the", "required", "information", "is", "there" ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/command_line.go#L112-L129
test
rightscale/rsc
command_line.go
APIClient
func APIClient(name string, cmdLine *cmd.CommandLine) (cmd.CommandClient, error) { switch name { case Cm15Command: return cm15.FromCommandLine(cmdLine) case Cm16Command: return cm16.FromCommandLine(cmdLine) case SsCommand: return ss.FromCommandLine(cmdLine) case Rl10Command: return rl10.FromCommandLine(cmdLine) case CaCommand: return ca.FromCommandLine(cmdLine) case PolicyCommand: return policy.FromCommandLine(cmdLine) default: return nil, fmt.Errorf("No client for '%s'", name) } }
go
func APIClient(name string, cmdLine *cmd.CommandLine) (cmd.CommandClient, error) { switch name { case Cm15Command: return cm15.FromCommandLine(cmdLine) case Cm16Command: return cm16.FromCommandLine(cmdLine) case SsCommand: return ss.FromCommandLine(cmdLine) case Rl10Command: return rl10.FromCommandLine(cmdLine) case CaCommand: return ca.FromCommandLine(cmdLine) case PolicyCommand: return policy.FromCommandLine(cmdLine) default: return nil, fmt.Errorf("No client for '%s'", name) } }
[ "func", "APIClient", "(", "name", "string", ",", "cmdLine", "*", "cmd", ".", "CommandLine", ")", "(", "cmd", ".", "CommandClient", ",", "error", ")", "{", "switch", "name", "{", "case", "Cm15Command", ":", "return", "cm15", ".", "FromCommandLine", "(", "cmdLine", ")", "\n", "case", "Cm16Command", ":", "return", "cm16", ".", "FromCommandLine", "(", "cmdLine", ")", "\n", "case", "SsCommand", ":", "return", "ss", ".", "FromCommandLine", "(", "cmdLine", ")", "\n", "case", "Rl10Command", ":", "return", "rl10", ".", "FromCommandLine", "(", "cmdLine", ")", "\n", "case", "CaCommand", ":", "return", "ca", ".", "FromCommandLine", "(", "cmdLine", ")", "\n", "case", "PolicyCommand", ":", "return", "policy", ".", "FromCommandLine", "(", "cmdLine", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"No client for '%s'\"", ",", "name", ")", "\n", "}", "\n", "}" ]
// APIClient instantiates a client with the given name from command line arguments.
[ "APIClient", "instantiates", "a", "client", "with", "the", "given", "name", "from", "command", "line", "arguments", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/command_line.go#L155-L172
test
rightscale/rsc
command_line.go
RegisterClientCommands
func RegisterClientCommands(app *kingpin.Application) { cm15Cmd := app.Command(Cm15Command, cm15.APIName) registrar := rsapi.Registrar{APICmd: cm15Cmd} cm15.RegisterCommands(&registrar) cm16Cmd := app.Command(Cm16Command, cm16.APIName) registrar = rsapi.Registrar{APICmd: cm16Cmd} cm16.RegisterCommands(&registrar) ssCmd := app.Command(SsCommand, ss.APIName) registrar = rsapi.Registrar{APICmd: ssCmd} ss.RegisterCommands(&registrar) rl10Cmd := app.Command(Rl10Command, rl10.APIName) registrar = rsapi.Registrar{APICmd: rl10Cmd} rl10.RegisterCommands(&registrar) caCmd := app.Command(CaCommand, ca.APIName) registrar = rsapi.Registrar{APICmd: caCmd} ca.RegisterCommands(&registrar) policyCmd := app.Command(PolicyCommand, policy.APIName) registrar = rsapi.Registrar{APICmd: policyCmd} policy.RegisterCommands(&registrar) }
go
func RegisterClientCommands(app *kingpin.Application) { cm15Cmd := app.Command(Cm15Command, cm15.APIName) registrar := rsapi.Registrar{APICmd: cm15Cmd} cm15.RegisterCommands(&registrar) cm16Cmd := app.Command(Cm16Command, cm16.APIName) registrar = rsapi.Registrar{APICmd: cm16Cmd} cm16.RegisterCommands(&registrar) ssCmd := app.Command(SsCommand, ss.APIName) registrar = rsapi.Registrar{APICmd: ssCmd} ss.RegisterCommands(&registrar) rl10Cmd := app.Command(Rl10Command, rl10.APIName) registrar = rsapi.Registrar{APICmd: rl10Cmd} rl10.RegisterCommands(&registrar) caCmd := app.Command(CaCommand, ca.APIName) registrar = rsapi.Registrar{APICmd: caCmd} ca.RegisterCommands(&registrar) policyCmd := app.Command(PolicyCommand, policy.APIName) registrar = rsapi.Registrar{APICmd: policyCmd} policy.RegisterCommands(&registrar) }
[ "func", "RegisterClientCommands", "(", "app", "*", "kingpin", ".", "Application", ")", "{", "cm15Cmd", ":=", "app", ".", "Command", "(", "Cm15Command", ",", "cm15", ".", "APIName", ")", "\n", "registrar", ":=", "rsapi", ".", "Registrar", "{", "APICmd", ":", "cm15Cmd", "}", "\n", "cm15", ".", "RegisterCommands", "(", "&", "registrar", ")", "\n", "cm16Cmd", ":=", "app", ".", "Command", "(", "Cm16Command", ",", "cm16", ".", "APIName", ")", "\n", "registrar", "=", "rsapi", ".", "Registrar", "{", "APICmd", ":", "cm16Cmd", "}", "\n", "cm16", ".", "RegisterCommands", "(", "&", "registrar", ")", "\n", "ssCmd", ":=", "app", ".", "Command", "(", "SsCommand", ",", "ss", ".", "APIName", ")", "\n", "registrar", "=", "rsapi", ".", "Registrar", "{", "APICmd", ":", "ssCmd", "}", "\n", "ss", ".", "RegisterCommands", "(", "&", "registrar", ")", "\n", "rl10Cmd", ":=", "app", ".", "Command", "(", "Rl10Command", ",", "rl10", ".", "APIName", ")", "\n", "registrar", "=", "rsapi", ".", "Registrar", "{", "APICmd", ":", "rl10Cmd", "}", "\n", "rl10", ".", "RegisterCommands", "(", "&", "registrar", ")", "\n", "caCmd", ":=", "app", ".", "Command", "(", "CaCommand", ",", "ca", ".", "APIName", ")", "\n", "registrar", "=", "rsapi", ".", "Registrar", "{", "APICmd", ":", "caCmd", "}", "\n", "ca", ".", "RegisterCommands", "(", "&", "registrar", ")", "\n", "policyCmd", ":=", "app", ".", "Command", "(", "PolicyCommand", ",", "policy", ".", "APIName", ")", "\n", "registrar", "=", "rsapi", ".", "Registrar", "{", "APICmd", ":", "policyCmd", "}", "\n", "policy", ".", "RegisterCommands", "(", "&", "registrar", ")", "\n", "}" ]
// RegisterClientCommands registers all API client commands.
[ "RegisterClientCommands", "registers", "all", "API", "client", "commands", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/command_line.go#L175-L199
test
rightscale/rsc
log/log.go
Interactive
func Interactive() { Logger.SetHandler(log15.MultiHandler( log15.LvlFilterHandler( log15.LvlError, log15.StderrHandler))) }
go
func Interactive() { Logger.SetHandler(log15.MultiHandler( log15.LvlFilterHandler( log15.LvlError, log15.StderrHandler))) }
[ "func", "Interactive", "(", ")", "{", "Logger", ".", "SetHandler", "(", "log15", ".", "MultiHandler", "(", "log15", ".", "LvlFilterHandler", "(", "log15", ".", "LvlError", ",", "log15", ".", "StderrHandler", ")", ")", ")", "\n", "}" ]
// Interactive configures the logger to log messages of level Info or higher to Stdout and messages // of level Error or lesser to Stderr.
[ "Interactive", "configures", "the", "logger", "to", "log", "messages", "of", "level", "Info", "or", "higher", "to", "Stdout", "and", "messages", "of", "level", "Error", "or", "lesser", "to", "Stderr", "." ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/log/log.go#L17-L22
test
rightscale/rsc
gen/praxisgen/action_analysis.go
toPattern
func toPattern(verb, path string) *gen.PathPattern { pattern := gen.PathPattern{ HTTPMethod: verb, Path: path, Pattern: pathVariablesRegexp.ReplaceAllLiteralString(path, "/%s"), Regexp: pathVariablesRegexp.ReplaceAllLiteralString(regexp.QuoteMeta(path), `/([^/]+)`), } matches := pathVariablesRegexp.FindAllStringSubmatch(path, -1) if len(matches) > 0 { pattern.Variables = make([]string, len(matches)) for i, m := range matches { pattern.Variables[i] = m[1] } } return &pattern }
go
func toPattern(verb, path string) *gen.PathPattern { pattern := gen.PathPattern{ HTTPMethod: verb, Path: path, Pattern: pathVariablesRegexp.ReplaceAllLiteralString(path, "/%s"), Regexp: pathVariablesRegexp.ReplaceAllLiteralString(regexp.QuoteMeta(path), `/([^/]+)`), } matches := pathVariablesRegexp.FindAllStringSubmatch(path, -1) if len(matches) > 0 { pattern.Variables = make([]string, len(matches)) for i, m := range matches { pattern.Variables[i] = m[1] } } return &pattern }
[ "func", "toPattern", "(", "verb", ",", "path", "string", ")", "*", "gen", ".", "PathPattern", "{", "pattern", ":=", "gen", ".", "PathPattern", "{", "HTTPMethod", ":", "verb", ",", "Path", ":", "path", ",", "Pattern", ":", "pathVariablesRegexp", ".", "ReplaceAllLiteralString", "(", "path", ",", "\"/%s\"", ")", ",", "Regexp", ":", "pathVariablesRegexp", ".", "ReplaceAllLiteralString", "(", "regexp", ".", "QuoteMeta", "(", "path", ")", ",", "`/([^/]+)`", ")", ",", "}", "\n", "matches", ":=", "pathVariablesRegexp", ".", "FindAllStringSubmatch", "(", "path", ",", "-", "1", ")", "\n", "if", "len", "(", "matches", ")", ">", "0", "{", "pattern", ".", "Variables", "=", "make", "(", "[", "]", "string", ",", "len", "(", "matches", ")", ")", "\n", "for", "i", ",", "m", ":=", "range", "matches", "{", "pattern", ".", "Variables", "[", "i", "]", "=", "m", "[", "1", "]", "\n", "}", "\n", "}", "\n", "return", "&", "pattern", "\n", "}" ]
// Create path pattern from HTTP verb and request path
[ "Create", "path", "pattern", "from", "HTTP", "verb", "and", "request", "path" ]
96079a1ee7238dae9cbb7efa77dd94a479d217bd
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/action_analysis.go#L275-L291
test
segmentio/nsq-go
nsqlookup/topology.go
WithClientIP
func WithClientIP(ctx context.Context, ip net.IP) context.Context { if ip == nil { return ctx } return context.WithValue(ctx, clientIPKey{}, ip) }
go
func WithClientIP(ctx context.Context, ip net.IP) context.Context { if ip == nil { return ctx } return context.WithValue(ctx, clientIPKey{}, ip) }
[ "func", "WithClientIP", "(", "ctx", "context", ".", "Context", ",", "ip", "net", ".", "IP", ")", "context", ".", "Context", "{", "if", "ip", "==", "nil", "{", "return", "ctx", "\n", "}", "\n", "return", "context", ".", "WithValue", "(", "ctx", ",", "clientIPKey", "{", "}", ",", "ip", ")", "\n", "}" ]
// WithClientIP returns a context which carries the given client IP.
[ "WithClientIP", "returns", "a", "context", "which", "carries", "the", "given", "client", "IP", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/topology.go#L36-L41
test
segmentio/nsq-go
nsqlookup/topology.go
ClientIP
func ClientIP(ctx context.Context) net.IP { ip, _ := ctx.Value(clientIPKey{}).(net.IP) return ip }
go
func ClientIP(ctx context.Context) net.IP { ip, _ := ctx.Value(clientIPKey{}).(net.IP) return ip }
[ "func", "ClientIP", "(", "ctx", "context", ".", "Context", ")", "net", ".", "IP", "{", "ip", ",", "_", ":=", "ctx", ".", "Value", "(", "clientIPKey", "{", "}", ")", ".", "(", "net", ".", "IP", ")", "\n", "return", "ip", "\n", "}" ]
// ClientIP returns the client IP embedded in the context, or nil if none were // found.
[ "ClientIP", "returns", "the", "client", "IP", "embedded", "in", "the", "context", "or", "nil", "if", "none", "were", "found", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/topology.go#L45-L48
test
segmentio/nsq-go
producer.go
NewProducer
func NewProducer(config ProducerConfig) (p *Producer, err error) { config.defaults() p = &Producer{ reqs: make(chan ProducerRequest, config.MaxConcurrency), done: make(chan struct{}), address: config.Address, topic: config.Topic, dialTimeout: config.DialTimeout, readTimeout: config.ReadTimeout, writeTimeout: config.WriteTimeout, } return }
go
func NewProducer(config ProducerConfig) (p *Producer, err error) { config.defaults() p = &Producer{ reqs: make(chan ProducerRequest, config.MaxConcurrency), done: make(chan struct{}), address: config.Address, topic: config.Topic, dialTimeout: config.DialTimeout, readTimeout: config.ReadTimeout, writeTimeout: config.WriteTimeout, } return }
[ "func", "NewProducer", "(", "config", "ProducerConfig", ")", "(", "p", "*", "Producer", ",", "err", "error", ")", "{", "config", ".", "defaults", "(", ")", "\n", "p", "=", "&", "Producer", "{", "reqs", ":", "make", "(", "chan", "ProducerRequest", ",", "config", ".", "MaxConcurrency", ")", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "address", ":", "config", ".", "Address", ",", "topic", ":", "config", ".", "Topic", ",", "dialTimeout", ":", "config", ".", "DialTimeout", ",", "readTimeout", ":", "config", ".", "ReadTimeout", ",", "writeTimeout", ":", "config", ".", "WriteTimeout", ",", "}", "\n", "return", "\n", "}" ]
// NewProducer configures a new producer instance.
[ "NewProducer", "configures", "a", "new", "producer", "instance", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/producer.go#L74-L88
test
segmentio/nsq-go
producer.go
StartProducer
func StartProducer(config ProducerConfig) (p *Producer, err error) { p, err = NewProducer(config) if err != nil { return } p.Start() return }
go
func StartProducer(config ProducerConfig) (p *Producer, err error) { p, err = NewProducer(config) if err != nil { return } p.Start() return }
[ "func", "StartProducer", "(", "config", "ProducerConfig", ")", "(", "p", "*", "Producer", ",", "err", "error", ")", "{", "p", ",", "err", "=", "NewProducer", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "p", ".", "Start", "(", ")", "\n", "return", "\n", "}" ]
// StartProducer starts and returns a new producer p, configured with the // variables from the config parameter, or returning an non-nil error if // some of the configuration variables were invalid.
[ "StartProducer", "starts", "and", "returns", "a", "new", "producer", "p", "configured", "with", "the", "variables", "from", "the", "config", "parameter", "or", "returning", "an", "non", "-", "nil", "error", "if", "some", "of", "the", "configuration", "variables", "were", "invalid", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/producer.go#L93-L101
test
segmentio/nsq-go
producer.go
Start
func (p *Producer) Start() { if p.started { panic("(*Producer).Start has already been called") } concurrency := cap(p.reqs) p.join.Add(concurrency) for i := 0; i != concurrency; i++ { go p.run() } p.started = true }
go
func (p *Producer) Start() { if p.started { panic("(*Producer).Start has already been called") } concurrency := cap(p.reqs) p.join.Add(concurrency) for i := 0; i != concurrency; i++ { go p.run() } p.started = true }
[ "func", "(", "p", "*", "Producer", ")", "Start", "(", ")", "{", "if", "p", ".", "started", "{", "panic", "(", "\"(*Producer).Start has already been called\"", ")", "\n", "}", "\n", "concurrency", ":=", "cap", "(", "p", ".", "reqs", ")", "\n", "p", ".", "join", ".", "Add", "(", "concurrency", ")", "\n", "for", "i", ":=", "0", ";", "i", "!=", "concurrency", ";", "i", "++", "{", "go", "p", ".", "run", "(", ")", "\n", "}", "\n", "p", ".", "started", "=", "true", "\n", "}" ]
// Start explicitly begins the producer in case it was initialized with // NewProducer instead of StartProducer.
[ "Start", "explicitly", "begins", "the", "producer", "in", "case", "it", "was", "initialized", "with", "NewProducer", "instead", "of", "StartProducer", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/producer.go#L105-L117
test
segmentio/nsq-go
producer.go
Stop
func (p *Producer) Stop() { p.once.Do(p.stop) err := errors.New("publishing to a producer that was already stopped") for req := range p.reqs { req.complete(err) } p.join.Wait() }
go
func (p *Producer) Stop() { p.once.Do(p.stop) err := errors.New("publishing to a producer that was already stopped") for req := range p.reqs { req.complete(err) } p.join.Wait() }
[ "func", "(", "p", "*", "Producer", ")", "Stop", "(", ")", "{", "p", ".", "once", ".", "Do", "(", "p", ".", "stop", ")", "\n", "err", ":=", "errors", ".", "New", "(", "\"publishing to a producer that was already stopped\"", ")", "\n", "for", "req", ":=", "range", "p", ".", "reqs", "{", "req", ".", "complete", "(", "err", ")", "\n", "}", "\n", "p", ".", "join", ".", "Wait", "(", ")", "\n", "}" ]
// Stop gracefully shutsdown the producer, cancelling all inflight requests and // waiting for all backend connections to be closed. // // It is safe to call the method multiple times and from multiple goroutines, // they will all block until the producer has been completely shutdown.
[ "Stop", "gracefully", "shutsdown", "the", "producer", "cancelling", "all", "inflight", "requests", "and", "waiting", "for", "all", "backend", "connections", "to", "be", "closed", ".", "It", "is", "safe", "to", "call", "the", "method", "multiple", "times", "and", "from", "multiple", "goroutines", "they", "will", "all", "block", "until", "the", "producer", "has", "been", "completely", "shutdown", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/producer.go#L124-L133
test
segmentio/nsq-go
producer.go
Publish
func (p *Producer) Publish(message []byte) (err error) { return p.PublishTo(p.topic, message) }
go
func (p *Producer) Publish(message []byte) (err error) { return p.PublishTo(p.topic, message) }
[ "func", "(", "p", "*", "Producer", ")", "Publish", "(", "message", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "return", "p", ".", "PublishTo", "(", "p", ".", "topic", ",", "message", ")", "\n", "}" ]
// Publish sends a message using the producer p, returning an error if it was // already closed or if an error occurred while publishing the message. // // Note that no retry is done internally, the producer will fail after the // first unsuccessful attempt to publish the message. It is the responsibility // of the caller to retry if necessary.
[ "Publish", "sends", "a", "message", "using", "the", "producer", "p", "returning", "an", "error", "if", "it", "was", "already", "closed", "or", "if", "an", "error", "occurred", "while", "publishing", "the", "message", ".", "Note", "that", "no", "retry", "is", "done", "internally", "the", "producer", "will", "fail", "after", "the", "first", "unsuccessful", "attempt", "to", "publish", "the", "message", ".", "It", "is", "the", "responsibility", "of", "the", "caller", "to", "retry", "if", "necessary", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/producer.go#L141-L143
test
segmentio/nsq-go
producer.go
PublishTo
func (p *Producer) PublishTo(topic string, message []byte) (err error) { defer func() { if recover() != nil { err = errors.New("publishing to a producer that was already stopped") } }() if len(topic) == 0 { return errors.New("no topic set for publishing message") } response := make(chan error, 1) deadline := time.Now().Add(p.dialTimeout + p.readTimeout + p.writeTimeout) // Attempts to queue the request so one of the active connections can pick // it up. p.reqs <- ProducerRequest{ Topic: topic, Message: message, Response: response, Deadline: deadline, } // This will always trigger, either if the connection was lost or if a // response was successfully sent. err = <-response return }
go
func (p *Producer) PublishTo(topic string, message []byte) (err error) { defer func() { if recover() != nil { err = errors.New("publishing to a producer that was already stopped") } }() if len(topic) == 0 { return errors.New("no topic set for publishing message") } response := make(chan error, 1) deadline := time.Now().Add(p.dialTimeout + p.readTimeout + p.writeTimeout) // Attempts to queue the request so one of the active connections can pick // it up. p.reqs <- ProducerRequest{ Topic: topic, Message: message, Response: response, Deadline: deadline, } // This will always trigger, either if the connection was lost or if a // response was successfully sent. err = <-response return }
[ "func", "(", "p", "*", "Producer", ")", "PublishTo", "(", "topic", "string", ",", "message", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "recover", "(", ")", "!=", "nil", "{", "err", "=", "errors", ".", "New", "(", "\"publishing to a producer that was already stopped\"", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "len", "(", "topic", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"no topic set for publishing message\"", ")", "\n", "}", "\n", "response", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "deadline", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "p", ".", "dialTimeout", "+", "p", ".", "readTimeout", "+", "p", ".", "writeTimeout", ")", "\n", "p", ".", "reqs", "<-", "ProducerRequest", "{", "Topic", ":", "topic", ",", "Message", ":", "message", ",", "Response", ":", "response", ",", "Deadline", ":", "deadline", ",", "}", "\n", "err", "=", "<-", "response", "\n", "return", "\n", "}" ]
// PublishTo sends a message to a specific topic using the producer p, returning // an error if it was already closed or if an error occurred while publishing the // message. // // Note that no retry is done internally, the producer will fail after the // first unsuccessful attempt to publish the message. It is the responsibility // of the caller to retry if necessary.
[ "PublishTo", "sends", "a", "message", "to", "a", "specific", "topic", "using", "the", "producer", "p", "returning", "an", "error", "if", "it", "was", "already", "closed", "or", "if", "an", "error", "occurred", "while", "publishing", "the", "message", ".", "Note", "that", "no", "retry", "is", "done", "internally", "the", "producer", "will", "fail", "after", "the", "first", "unsuccessful", "attempt", "to", "publish", "the", "message", ".", "It", "is", "the", "responsibility", "of", "the", "caller", "to", "retry", "if", "necessary", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/producer.go#L152-L179
test
segmentio/nsq-go
nsqlookup/local.go
NewLocalEngine
func NewLocalEngine(config LocalConfig) *LocalEngine { if config.NodeTimeout == 0 { config.NodeTimeout = DefaultLocalEngineNodeTimeout } if config.TombstoneTimeout == 0 { config.TombstoneTimeout = DefaultLocalEngineTombstoneTimeout } e := &LocalEngine{ nodeTimeout: config.NodeTimeout, tombTimeout: config.TombstoneTimeout, done: make(chan struct{}), join: make(chan struct{}), nodes: make(map[string]*LocalNode), } go e.run() return e }
go
func NewLocalEngine(config LocalConfig) *LocalEngine { if config.NodeTimeout == 0 { config.NodeTimeout = DefaultLocalEngineNodeTimeout } if config.TombstoneTimeout == 0 { config.TombstoneTimeout = DefaultLocalEngineTombstoneTimeout } e := &LocalEngine{ nodeTimeout: config.NodeTimeout, tombTimeout: config.TombstoneTimeout, done: make(chan struct{}), join: make(chan struct{}), nodes: make(map[string]*LocalNode), } go e.run() return e }
[ "func", "NewLocalEngine", "(", "config", "LocalConfig", ")", "*", "LocalEngine", "{", "if", "config", ".", "NodeTimeout", "==", "0", "{", "config", ".", "NodeTimeout", "=", "DefaultLocalEngineNodeTimeout", "\n", "}", "\n", "if", "config", ".", "TombstoneTimeout", "==", "0", "{", "config", ".", "TombstoneTimeout", "=", "DefaultLocalEngineTombstoneTimeout", "\n", "}", "\n", "e", ":=", "&", "LocalEngine", "{", "nodeTimeout", ":", "config", ".", "NodeTimeout", ",", "tombTimeout", ":", "config", ".", "TombstoneTimeout", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "join", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "nodes", ":", "make", "(", "map", "[", "string", "]", "*", "LocalNode", ")", ",", "}", "\n", "go", "e", ".", "run", "(", ")", "\n", "return", "e", "\n", "}" ]
// NewLocalEngine creates and returns an instance of LocalEngine configured with // config.
[ "NewLocalEngine", "creates", "and", "returns", "an", "instance", "of", "LocalEngine", "configured", "with", "config", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/local.go#L52-L73
test
segmentio/nsq-go
consumer.go
validate
func (c *ConsumerConfig) validate() error { if len(c.Topic) == 0 { return errors.New("creating a new consumer requires a non-empty topic") } if len(c.Channel) == 0 { return errors.New("creating a new consumer requires a non-empty channel") } return nil }
go
func (c *ConsumerConfig) validate() error { if len(c.Topic) == 0 { return errors.New("creating a new consumer requires a non-empty topic") } if len(c.Channel) == 0 { return errors.New("creating a new consumer requires a non-empty channel") } return nil }
[ "func", "(", "c", "*", "ConsumerConfig", ")", "validate", "(", ")", "error", "{", "if", "len", "(", "c", ".", "Topic", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"creating a new consumer requires a non-empty topic\"", ")", "\n", "}", "\n", "if", "len", "(", "c", ".", "Channel", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"creating a new consumer requires a non-empty channel\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validate ensures that this configuration is well-formed.
[ "validate", "ensures", "that", "this", "configuration", "is", "well", "-", "formed", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L52-L62
test
segmentio/nsq-go
consumer.go
defaults
func (c *ConsumerConfig) defaults() { if c.MaxInFlight == 0 { c.MaxInFlight = DefaultMaxInFlight } if c.DialTimeout == 0 { c.DialTimeout = DefaultDialTimeout } if c.ReadTimeout == 0 { c.ReadTimeout = DefaultReadTimeout } if c.WriteTimeout == 0 { c.WriteTimeout = DefaultWriteTimeout } }
go
func (c *ConsumerConfig) defaults() { if c.MaxInFlight == 0 { c.MaxInFlight = DefaultMaxInFlight } if c.DialTimeout == 0 { c.DialTimeout = DefaultDialTimeout } if c.ReadTimeout == 0 { c.ReadTimeout = DefaultReadTimeout } if c.WriteTimeout == 0 { c.WriteTimeout = DefaultWriteTimeout } }
[ "func", "(", "c", "*", "ConsumerConfig", ")", "defaults", "(", ")", "{", "if", "c", ".", "MaxInFlight", "==", "0", "{", "c", ".", "MaxInFlight", "=", "DefaultMaxInFlight", "\n", "}", "\n", "if", "c", ".", "DialTimeout", "==", "0", "{", "c", ".", "DialTimeout", "=", "DefaultDialTimeout", "\n", "}", "\n", "if", "c", ".", "ReadTimeout", "==", "0", "{", "c", ".", "ReadTimeout", "=", "DefaultReadTimeout", "\n", "}", "\n", "if", "c", ".", "WriteTimeout", "==", "0", "{", "c", ".", "WriteTimeout", "=", "DefaultWriteTimeout", "\n", "}", "\n", "}" ]
// defaults will set up this configuration with the global defaults where they // were not already set.
[ "defaults", "will", "set", "up", "this", "configuration", "with", "the", "global", "defaults", "where", "they", "were", "not", "already", "set", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L66-L82
test
segmentio/nsq-go
consumer.go
NewConsumer
func NewConsumer(config ConsumerConfig) (c *Consumer, err error) { if err = config.validate(); err != nil { return } config.defaults() c = &Consumer{ msgs: make(chan Message, config.MaxInFlight), done: make(chan struct{}), topic: config.Topic, channel: config.Channel, address: config.Address, lookup: append([]string{}, config.Lookup...), maxInFlight: config.MaxInFlight, identify: setIdentifyDefaults(config.Identify), dialTimeout: config.DialTimeout, readTimeout: config.ReadTimeout, writeTimeout: config.WriteTimeout, conns: make(map[string](chan<- Command)), } return }
go
func NewConsumer(config ConsumerConfig) (c *Consumer, err error) { if err = config.validate(); err != nil { return } config.defaults() c = &Consumer{ msgs: make(chan Message, config.MaxInFlight), done: make(chan struct{}), topic: config.Topic, channel: config.Channel, address: config.Address, lookup: append([]string{}, config.Lookup...), maxInFlight: config.MaxInFlight, identify: setIdentifyDefaults(config.Identify), dialTimeout: config.DialTimeout, readTimeout: config.ReadTimeout, writeTimeout: config.WriteTimeout, conns: make(map[string](chan<- Command)), } return }
[ "func", "NewConsumer", "(", "config", "ConsumerConfig", ")", "(", "c", "*", "Consumer", ",", "err", "error", ")", "{", "if", "err", "=", "config", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "config", ".", "defaults", "(", ")", "\n", "c", "=", "&", "Consumer", "{", "msgs", ":", "make", "(", "chan", "Message", ",", "config", ".", "MaxInFlight", ")", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "topic", ":", "config", ".", "Topic", ",", "channel", ":", "config", ".", "Channel", ",", "address", ":", "config", ".", "Address", ",", "lookup", ":", "append", "(", "[", "]", "string", "{", "}", ",", "config", ".", "Lookup", "...", ")", ",", "maxInFlight", ":", "config", ".", "MaxInFlight", ",", "identify", ":", "setIdentifyDefaults", "(", "config", ".", "Identify", ")", ",", "dialTimeout", ":", "config", ".", "DialTimeout", ",", "readTimeout", ":", "config", ".", "ReadTimeout", ",", "writeTimeout", ":", "config", ".", "WriteTimeout", ",", "conns", ":", "make", "(", "map", "[", "string", "]", "(", "chan", "<-", "Command", ")", ")", ",", "}", "\n", "return", "\n", "}" ]
// NewConsumer configures a new consumer instance.
[ "NewConsumer", "configures", "a", "new", "consumer", "instance", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L85-L110
test
segmentio/nsq-go
consumer.go
StartConsumer
func StartConsumer(config ConsumerConfig) (c *Consumer, err error) { c, err = NewConsumer(config) if err != nil { return } c.Start() return }
go
func StartConsumer(config ConsumerConfig) (c *Consumer, err error) { c, err = NewConsumer(config) if err != nil { return } c.Start() return }
[ "func", "StartConsumer", "(", "config", "ConsumerConfig", ")", "(", "c", "*", "Consumer", ",", "err", "error", ")", "{", "c", ",", "err", "=", "NewConsumer", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "c", ".", "Start", "(", ")", "\n", "return", "\n", "}" ]
// StartConsumer creates and starts consuming from NSQ right away. This is the // fastest way to get up and running.
[ "StartConsumer", "creates", "and", "starts", "consuming", "from", "NSQ", "right", "away", ".", "This", "is", "the", "fastest", "way", "to", "get", "up", "and", "running", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L114-L122
test
segmentio/nsq-go
consumer.go
Start
func (c *Consumer) Start() { if c.started { panic("(*Consumer).Start has already been called") } go c.run() c.started = true }
go
func (c *Consumer) Start() { if c.started { panic("(*Consumer).Start has already been called") } go c.run() c.started = true }
[ "func", "(", "c", "*", "Consumer", ")", "Start", "(", ")", "{", "if", "c", ".", "started", "{", "panic", "(", "\"(*Consumer).Start has already been called\"", ")", "\n", "}", "\n", "go", "c", ".", "run", "(", ")", "\n", "c", ".", "started", "=", "true", "\n", "}" ]
// Start explicitly begins consumption in case the consumer was initialized // with NewConsumer instead of StartConsumer.
[ "Start", "explicitly", "begins", "consumption", "in", "case", "the", "consumer", "was", "initialized", "with", "NewConsumer", "instead", "of", "StartConsumer", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L126-L134
test
segmentio/nsq-go
consumer.go
RateLimit
func RateLimit(limit int, messages <-chan Message) <-chan Message { if limit <= 0 { return messages } output := make(chan Message) go func() { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() defer close(output) input := messages count := 0 for { select { case <-ticker.C: count = 0 input = messages case msg, ok := <-input: if !ok { return } output <- msg if count++; count >= limit { input = nil } } } }() return output }
go
func RateLimit(limit int, messages <-chan Message) <-chan Message { if limit <= 0 { return messages } output := make(chan Message) go func() { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() defer close(output) input := messages count := 0 for { select { case <-ticker.C: count = 0 input = messages case msg, ok := <-input: if !ok { return } output <- msg if count++; count >= limit { input = nil } } } }() return output }
[ "func", "RateLimit", "(", "limit", "int", ",", "messages", "<-", "chan", "Message", ")", "<-", "chan", "Message", "{", "if", "limit", "<=", "0", "{", "return", "messages", "\n", "}", "\n", "output", ":=", "make", "(", "chan", "Message", ")", "\n", "go", "func", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "1", "*", "time", ".", "Second", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "defer", "close", "(", "output", ")", "\n", "input", ":=", "messages", "\n", "count", ":=", "0", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "count", "=", "0", "\n", "input", "=", "messages", "\n", "case", "msg", ",", "ok", ":=", "<-", "input", ":", "if", "!", "ok", "{", "return", "\n", "}", "\n", "output", "<-", "msg", "\n", "if", "count", "++", ";", "count", ">=", "limit", "{", "input", "=", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "output", "\n", "}" ]
// RateLimit consumes messages from the messages channel and limits the rate at // which they are produced to the channel returned by this function. // // The limit is the maximum number of messages per second that are produced. // No rate limit is applied if limit is negative or zero. // // The returned channel is closed when the messages channel is closed.
[ "RateLimit", "consumes", "messages", "from", "the", "messages", "channel", "and", "limits", "the", "rate", "at", "which", "they", "are", "produced", "to", "the", "channel", "returned", "by", "this", "function", ".", "The", "limit", "is", "the", "maximum", "number", "of", "messages", "per", "second", "that", "are", "produced", ".", "No", "rate", "limit", "is", "applied", "if", "limit", "is", "negative", "or", "zero", ".", "The", "returned", "channel", "is", "closed", "when", "the", "messages", "channel", "is", "closed", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L347-L383
test
segmentio/nsq-go
nsqlookup/response.go
Write
func (r RawResponse) Write(w *bufio.Writer) error { return writeResponse(w, []byte(r)) }
go
func (r RawResponse) Write(w *bufio.Writer) error { return writeResponse(w, []byte(r)) }
[ "func", "(", "r", "RawResponse", ")", "Write", "(", "w", "*", "bufio", ".", "Writer", ")", "error", "{", "return", "writeResponse", "(", "w", ",", "[", "]", "byte", "(", "r", ")", ")", "\n", "}" ]
// Write outputs the response to w.
[ "Write", "outputs", "the", "response", "to", "w", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/response.go#L30-L32
test
segmentio/nsq-go
nsqlookup/response.go
ReadResponse
func ReadResponse(r *bufio.Reader) (res Response, err error) { var data []byte var size int32 if err = binary.Read(r, binary.BigEndian, &size); err != nil { return } data = make([]byte, int(size)) if _, err = io.ReadFull(r, data); err != nil { return } switch { case bytes.Equal(data, []byte("OK")): res = OK{} case bytes.HasPrefix(data, []byte("E_")): res = readError(data) default: res = RawResponse(data) } return }
go
func ReadResponse(r *bufio.Reader) (res Response, err error) { var data []byte var size int32 if err = binary.Read(r, binary.BigEndian, &size); err != nil { return } data = make([]byte, int(size)) if _, err = io.ReadFull(r, data); err != nil { return } switch { case bytes.Equal(data, []byte("OK")): res = OK{} case bytes.HasPrefix(data, []byte("E_")): res = readError(data) default: res = RawResponse(data) } return }
[ "func", "ReadResponse", "(", "r", "*", "bufio", ".", "Reader", ")", "(", "res", "Response", ",", "err", "error", ")", "{", "var", "data", "[", "]", "byte", "\n", "var", "size", "int32", "\n", "if", "err", "=", "binary", ".", "Read", "(", "r", ",", "binary", ".", "BigEndian", ",", "&", "size", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "data", "=", "make", "(", "[", "]", "byte", ",", "int", "(", "size", ")", ")", "\n", "if", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "switch", "{", "case", "bytes", ".", "Equal", "(", "data", ",", "[", "]", "byte", "(", "\"OK\"", ")", ")", ":", "res", "=", "OK", "{", "}", "\n", "case", "bytes", ".", "HasPrefix", "(", "data", ",", "[", "]", "byte", "(", "\"E_\"", ")", ")", ":", "res", "=", "readError", "(", "data", ")", "\n", "default", ":", "res", "=", "RawResponse", "(", "data", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ReadResponse reads res from r, or returns an error if no responses could be // read.
[ "ReadResponse", "reads", "res", "from", "r", "or", "returns", "an", "error", "if", "no", "responses", "could", "be", "read", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/response.go#L36-L62
test
segmentio/nsq-go
cmd/nsq-to-http/main.go
backoff
func backoff(rand *rand.Rand, attempt int, min, max time.Duration) time.Duration { if attempt <= 0 { panic("tube.Backoff: attempt <= 0") } if min > max { panic("tube.Backoff: min > max") } // Hardcoded backoff coefficient, maybe we'll make it configuration in the // future? const coeff = 2.0 return jitteredBackoff(rand, attempt, min, max, coeff) }
go
func backoff(rand *rand.Rand, attempt int, min, max time.Duration) time.Duration { if attempt <= 0 { panic("tube.Backoff: attempt <= 0") } if min > max { panic("tube.Backoff: min > max") } // Hardcoded backoff coefficient, maybe we'll make it configuration in the // future? const coeff = 2.0 return jitteredBackoff(rand, attempt, min, max, coeff) }
[ "func", "backoff", "(", "rand", "*", "rand", ".", "Rand", ",", "attempt", "int", ",", "min", ",", "max", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "if", "attempt", "<=", "0", "{", "panic", "(", "\"tube.Backoff: attempt <= 0\"", ")", "\n", "}", "\n", "if", "min", ">", "max", "{", "panic", "(", "\"tube.Backoff: min > max\"", ")", "\n", "}", "\n", "const", "coeff", "=", "2.0", "\n", "return", "jitteredBackoff", "(", "rand", ",", "attempt", ",", "min", ",", "max", ",", "coeff", ")", "\n", "}" ]
// backoff computes a random exponential backoff value for a given number of // attempts, and boundaries of min and max backoff durations.
[ "backoff", "computes", "a", "random", "exponential", "backoff", "value", "for", "a", "given", "number", "of", "attempts", "and", "boundaries", "of", "min", "and", "max", "backoff", "durations", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/cmd/nsq-to-http/main.go#L143-L156
test
segmentio/nsq-go
frame.go
String
func (t FrameType) String() string { switch t { case FrameTypeResponse: return "response" case FrameTypeError: return "error" case FrameTypeMessage: return "message" default: return "frame <" + strconv.Itoa(int(t)) + ">" } }
go
func (t FrameType) String() string { switch t { case FrameTypeResponse: return "response" case FrameTypeError: return "error" case FrameTypeMessage: return "message" default: return "frame <" + strconv.Itoa(int(t)) + ">" } }
[ "func", "(", "t", "FrameType", ")", "String", "(", ")", "string", "{", "switch", "t", "{", "case", "FrameTypeResponse", ":", "return", "\"response\"", "\n", "case", "FrameTypeError", ":", "return", "\"error\"", "\n", "case", "FrameTypeMessage", ":", "return", "\"message\"", "\n", "default", ":", "return", "\"frame <\"", "+", "strconv", ".", "Itoa", "(", "int", "(", "t", ")", ")", "+", "\">\"", "\n", "}", "\n", "}" ]
// String returns a human-readable representation of the frame type.
[ "String", "returns", "a", "human", "-", "readable", "representation", "of", "the", "frame", "type", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/frame.go#L30-L44
test
segmentio/nsq-go
nsqlookup/consul.go
NewConsulEngine
func NewConsulEngine(config ConsulConfig) *ConsulEngine { if len(config.Address) == 0 { config.Address = DefaultConsulAddress } if len(config.Namespace) == 0 { config.Namespace = DefaultConsulNamespace } if config.NodeTimeout == 0 { config.NodeTimeout = DefaultLocalEngineNodeTimeout } if config.TombstoneTimeout == 0 { config.TombstoneTimeout = DefaultLocalEngineTombstoneTimeout } if !strings.Contains(config.Address, "://") { config.Address = "http://" + config.Address } return &ConsulEngine{ client: http.Client{Transport: config.Transport}, address: config.Address, namespace: config.Namespace, nodeTimeout: config.NodeTimeout, tombTimeout: config.TombstoneTimeout, } }
go
func NewConsulEngine(config ConsulConfig) *ConsulEngine { if len(config.Address) == 0 { config.Address = DefaultConsulAddress } if len(config.Namespace) == 0 { config.Namespace = DefaultConsulNamespace } if config.NodeTimeout == 0 { config.NodeTimeout = DefaultLocalEngineNodeTimeout } if config.TombstoneTimeout == 0 { config.TombstoneTimeout = DefaultLocalEngineTombstoneTimeout } if !strings.Contains(config.Address, "://") { config.Address = "http://" + config.Address } return &ConsulEngine{ client: http.Client{Transport: config.Transport}, address: config.Address, namespace: config.Namespace, nodeTimeout: config.NodeTimeout, tombTimeout: config.TombstoneTimeout, } }
[ "func", "NewConsulEngine", "(", "config", "ConsulConfig", ")", "*", "ConsulEngine", "{", "if", "len", "(", "config", ".", "Address", ")", "==", "0", "{", "config", ".", "Address", "=", "DefaultConsulAddress", "\n", "}", "\n", "if", "len", "(", "config", ".", "Namespace", ")", "==", "0", "{", "config", ".", "Namespace", "=", "DefaultConsulNamespace", "\n", "}", "\n", "if", "config", ".", "NodeTimeout", "==", "0", "{", "config", ".", "NodeTimeout", "=", "DefaultLocalEngineNodeTimeout", "\n", "}", "\n", "if", "config", ".", "TombstoneTimeout", "==", "0", "{", "config", ".", "TombstoneTimeout", "=", "DefaultLocalEngineTombstoneTimeout", "\n", "}", "\n", "if", "!", "strings", ".", "Contains", "(", "config", ".", "Address", ",", "\"://\"", ")", "{", "config", ".", "Address", "=", "\"http://\"", "+", "config", ".", "Address", "\n", "}", "\n", "return", "&", "ConsulEngine", "{", "client", ":", "http", ".", "Client", "{", "Transport", ":", "config", ".", "Transport", "}", ",", "address", ":", "config", ".", "Address", ",", "namespace", ":", "config", ".", "Namespace", ",", "nodeTimeout", ":", "config", ".", "NodeTimeout", ",", "tombTimeout", ":", "config", ".", "TombstoneTimeout", ",", "}", "\n", "}" ]
// NewConsulEngine creates and return a new engine configured with config.
[ "NewConsulEngine", "creates", "and", "return", "a", "new", "engine", "configured", "with", "config", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/consul.go#L61-L89
test
segmentio/nsq-go
message.go
ParseMessageID
func ParseMessageID(s string) (id MessageID, err error) { var v uint64 v, err = strconv.ParseUint(s, 16, 64) id = MessageID(v) return }
go
func ParseMessageID(s string) (id MessageID, err error) { var v uint64 v, err = strconv.ParseUint(s, 16, 64) id = MessageID(v) return }
[ "func", "ParseMessageID", "(", "s", "string", ")", "(", "id", "MessageID", ",", "err", "error", ")", "{", "var", "v", "uint64", "\n", "v", ",", "err", "=", "strconv", ".", "ParseUint", "(", "s", ",", "16", ",", "64", ")", "\n", "id", "=", "MessageID", "(", "v", ")", "\n", "return", "\n", "}" ]
// ParseMessageID attempts to parse s, which should be an hexadecimal // representation of an 8 byte message ID.
[ "ParseMessageID", "attempts", "to", "parse", "s", "which", "should", "be", "an", "hexadecimal", "representation", "of", "an", "8", "byte", "message", "ID", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L18-L23
test
segmentio/nsq-go
message.go
WriteTo
func (id MessageID) WriteTo(w io.Writer) (int64, error) { a := [16]byte{} b := strconv.AppendUint(a[:0], uint64(id), 16) n := len(a) - len(b) copy(a[n:], b) for i := 0; i != n; i++ { a[i] = '0' } c, e := w.Write(a[:]) return int64(c), e }
go
func (id MessageID) WriteTo(w io.Writer) (int64, error) { a := [16]byte{} b := strconv.AppendUint(a[:0], uint64(id), 16) n := len(a) - len(b) copy(a[n:], b) for i := 0; i != n; i++ { a[i] = '0' } c, e := w.Write(a[:]) return int64(c), e }
[ "func", "(", "id", "MessageID", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "a", ":=", "[", "16", "]", "byte", "{", "}", "\n", "b", ":=", "strconv", ".", "AppendUint", "(", "a", "[", ":", "0", "]", ",", "uint64", "(", "id", ")", ",", "16", ")", "\n", "n", ":=", "len", "(", "a", ")", "-", "len", "(", "b", ")", "\n", "copy", "(", "a", "[", "n", ":", "]", ",", "b", ")", "\n", "for", "i", ":=", "0", ";", "i", "!=", "n", ";", "i", "++", "{", "a", "[", "i", "]", "=", "'0'", "\n", "}", "\n", "c", ",", "e", ":=", "w", ".", "Write", "(", "a", "[", ":", "]", ")", "\n", "return", "int64", "(", "c", ")", ",", "e", "\n", "}" ]
// WriteTo writes the message ID to w. // // This method satisfies the io.WriterTo interface.
[ "WriteTo", "writes", "the", "message", "ID", "to", "w", ".", "This", "method", "satisfies", "the", "io", ".", "WriterTo", "interface", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L33-L45
test
segmentio/nsq-go
message.go
NewMessage
func NewMessage(id MessageID, body []byte, cmdChan chan<- Command) *Message { return &Message{ ID: id, Body: body, cmdChan: cmdChan, } }
go
func NewMessage(id MessageID, body []byte, cmdChan chan<- Command) *Message { return &Message{ ID: id, Body: body, cmdChan: cmdChan, } }
[ "func", "NewMessage", "(", "id", "MessageID", ",", "body", "[", "]", "byte", ",", "cmdChan", "chan", "<-", "Command", ")", "*", "Message", "{", "return", "&", "Message", "{", "ID", ":", "id", ",", "Body", ":", "body", ",", "cmdChan", ":", "cmdChan", ",", "}", "\n", "}" ]
// NewMessage is a helper for creating Message instances directly. A common // use-case is for writing tests, generally you won't use this directly. // // If you do use this, the Command channel is used internally to communicate // message commands, such as "Finish" or "Requeue". When using this for testing, // you can make a channel and inspect any message sent along it for assertions.
[ "NewMessage", "is", "a", "helper", "for", "creating", "Message", "instances", "directly", ".", "A", "common", "use", "-", "case", "is", "for", "writing", "tests", "generally", "you", "won", "t", "use", "this", "directly", ".", "If", "you", "do", "use", "this", "the", "Command", "channel", "is", "used", "internally", "to", "communicate", "message", "commands", "such", "as", "Finish", "or", "Requeue", ".", "When", "using", "this", "for", "testing", "you", "can", "make", "a", "channel", "and", "inspect", "any", "message", "sent", "along", "it", "for", "assertions", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L71-L77
test
segmentio/nsq-go
message.go
Finish
func (m *Message) Finish() { if m.Complete() { panic("(*Message).Finish or (*Message).Requeue has already been called") } defer func() { recover() }() // the connection may have been closed asynchronously m.cmdChan <- Fin{MessageID: m.ID} m.cmdChan = nil }
go
func (m *Message) Finish() { if m.Complete() { panic("(*Message).Finish or (*Message).Requeue has already been called") } defer func() { recover() }() // the connection may have been closed asynchronously m.cmdChan <- Fin{MessageID: m.ID} m.cmdChan = nil }
[ "func", "(", "m", "*", "Message", ")", "Finish", "(", ")", "{", "if", "m", ".", "Complete", "(", ")", "{", "panic", "(", "\"(*Message).Finish or (*Message).Requeue has already been called\"", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "recover", "(", ")", "}", "(", ")", "\n", "m", ".", "cmdChan", "<-", "Fin", "{", "MessageID", ":", "m", ".", "ID", "}", "\n", "m", ".", "cmdChan", "=", "nil", "\n", "}" ]
// Finish must be called on every message received from a consumer to let the // NSQ server know that the message was successfully processed. // // One of Finish or Requeue should be called on every message, and the methods // will panic if they are called more than once.
[ "Finish", "must", "be", "called", "on", "every", "message", "received", "from", "a", "consumer", "to", "let", "the", "NSQ", "server", "know", "that", "the", "message", "was", "successfully", "processed", ".", "One", "of", "Finish", "or", "Requeue", "should", "be", "called", "on", "every", "message", "and", "the", "methods", "will", "panic", "if", "they", "are", "called", "more", "than", "once", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L84-L91
test
segmentio/nsq-go
message.go
Requeue
func (m *Message) Requeue(timeout time.Duration) { if m.Complete() { panic("(*Message).Finish or (*Message).Requeue has already been called") } defer func() { recover() }() // the connection may have been closed asynchronously m.cmdChan <- Req{MessageID: m.ID, Timeout: timeout} m.cmdChan = nil }
go
func (m *Message) Requeue(timeout time.Duration) { if m.Complete() { panic("(*Message).Finish or (*Message).Requeue has already been called") } defer func() { recover() }() // the connection may have been closed asynchronously m.cmdChan <- Req{MessageID: m.ID, Timeout: timeout} m.cmdChan = nil }
[ "func", "(", "m", "*", "Message", ")", "Requeue", "(", "timeout", "time", ".", "Duration", ")", "{", "if", "m", ".", "Complete", "(", ")", "{", "panic", "(", "\"(*Message).Finish or (*Message).Requeue has already been called\"", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "recover", "(", ")", "}", "(", ")", "\n", "m", ".", "cmdChan", "<-", "Req", "{", "MessageID", ":", "m", ".", "ID", ",", "Timeout", ":", "timeout", "}", "\n", "m", ".", "cmdChan", "=", "nil", "\n", "}" ]
// Requeue must be called on messages received from a consumer to let the NSQ // server know that the message could not be proessed and should be retried. // The timeout is the amount of time the NSQ server waits before offering this // message again to its consumers. // // One of Finish or Requeue should be called on every message, and the methods // will panic if they are called more than once.
[ "Requeue", "must", "be", "called", "on", "messages", "received", "from", "a", "consumer", "to", "let", "the", "NSQ", "server", "know", "that", "the", "message", "could", "not", "be", "proessed", "and", "should", "be", "retried", ".", "The", "timeout", "is", "the", "amount", "of", "time", "the", "NSQ", "server", "waits", "before", "offering", "this", "message", "again", "to", "its", "consumers", ".", "One", "of", "Finish", "or", "Requeue", "should", "be", "called", "on", "every", "message", "and", "the", "methods", "will", "panic", "if", "they", "are", "called", "more", "than", "once", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L100-L107
test
segmentio/nsq-go
nsqlookup/command.go
ReadCommand
func ReadCommand(r *bufio.Reader) (cmd Command, err error) { var line string if line, err = r.ReadString('\n'); err != nil { return } parts := strings.Split(strings.TrimSpace(line), " ") if len(parts) == 0 { err = makeErrInvalid("invalid empty command") return } switch name, args := parts[0], parts[1:]; name { case "PING": return readPing(args...) case "IDENTIFY": return readIdentify(r, args...) case "REGISTER": return readRegister(args...) case "UNREGISTER": return readUnregister(args...) default: err = makeErrInvalid("invalid command %s", name) return } }
go
func ReadCommand(r *bufio.Reader) (cmd Command, err error) { var line string if line, err = r.ReadString('\n'); err != nil { return } parts := strings.Split(strings.TrimSpace(line), " ") if len(parts) == 0 { err = makeErrInvalid("invalid empty command") return } switch name, args := parts[0], parts[1:]; name { case "PING": return readPing(args...) case "IDENTIFY": return readIdentify(r, args...) case "REGISTER": return readRegister(args...) case "UNREGISTER": return readUnregister(args...) default: err = makeErrInvalid("invalid command %s", name) return } }
[ "func", "ReadCommand", "(", "r", "*", "bufio", ".", "Reader", ")", "(", "cmd", "Command", ",", "err", "error", ")", "{", "var", "line", "string", "\n", "if", "line", ",", "err", "=", "r", ".", "ReadString", "(", "'\\n'", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "parts", ":=", "strings", ".", "Split", "(", "strings", ".", "TrimSpace", "(", "line", ")", ",", "\" \"", ")", "\n", "if", "len", "(", "parts", ")", "==", "0", "{", "err", "=", "makeErrInvalid", "(", "\"invalid empty command\"", ")", "\n", "return", "\n", "}", "\n", "switch", "name", ",", "args", ":=", "parts", "[", "0", "]", ",", "parts", "[", "1", ":", "]", ";", "name", "{", "case", "\"PING\"", ":", "return", "readPing", "(", "args", "...", ")", "\n", "case", "\"IDENTIFY\"", ":", "return", "readIdentify", "(", "r", ",", "args", "...", ")", "\n", "case", "\"REGISTER\"", ":", "return", "readRegister", "(", "args", "...", ")", "\n", "case", "\"UNREGISTER\"", ":", "return", "readUnregister", "(", "args", "...", ")", "\n", "default", ":", "err", "=", "makeErrInvalid", "(", "\"invalid command %s\"", ",", "name", ")", "\n", "return", "\n", "}", "\n", "}" ]
// ReadCommand reads cmd from r, or returns an error if no commands could be // read.
[ "ReadCommand", "reads", "cmd", "from", "r", "or", "returns", "an", "error", "if", "no", "commands", "could", "be", "read", "." ]
ff4eef968f46eb580d9dba4f637c5dfb1e5b2208
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/command.go#L22-L53
test
qor/render
template.go
funcMapMaker
func (tmpl *Template) funcMapMaker(req *http.Request, writer http.ResponseWriter) template.FuncMap { var funcMap = template.FuncMap{} for key, fc := range tmpl.render.funcMaps { funcMap[key] = fc } if tmpl.render.Config.FuncMapMaker != nil { for key, fc := range tmpl.render.Config.FuncMapMaker(tmpl.render, req, writer) { funcMap[key] = fc } } for key, fc := range tmpl.funcMap { funcMap[key] = fc } return funcMap }
go
func (tmpl *Template) funcMapMaker(req *http.Request, writer http.ResponseWriter) template.FuncMap { var funcMap = template.FuncMap{} for key, fc := range tmpl.render.funcMaps { funcMap[key] = fc } if tmpl.render.Config.FuncMapMaker != nil { for key, fc := range tmpl.render.Config.FuncMapMaker(tmpl.render, req, writer) { funcMap[key] = fc } } for key, fc := range tmpl.funcMap { funcMap[key] = fc } return funcMap }
[ "func", "(", "tmpl", "*", "Template", ")", "funcMapMaker", "(", "req", "*", "http", ".", "Request", ",", "writer", "http", ".", "ResponseWriter", ")", "template", ".", "FuncMap", "{", "var", "funcMap", "=", "template", ".", "FuncMap", "{", "}", "\n", "for", "key", ",", "fc", ":=", "range", "tmpl", ".", "render", ".", "funcMaps", "{", "funcMap", "[", "key", "]", "=", "fc", "\n", "}", "\n", "if", "tmpl", ".", "render", ".", "Config", ".", "FuncMapMaker", "!=", "nil", "{", "for", "key", ",", "fc", ":=", "range", "tmpl", ".", "render", ".", "Config", ".", "FuncMapMaker", "(", "tmpl", ".", "render", ",", "req", ",", "writer", ")", "{", "funcMap", "[", "key", "]", "=", "fc", "\n", "}", "\n", "}", "\n", "for", "key", ",", "fc", ":=", "range", "tmpl", ".", "funcMap", "{", "funcMap", "[", "key", "]", "=", "fc", "\n", "}", "\n", "return", "funcMap", "\n", "}" ]
// FuncMap get func maps from tmpl
[ "FuncMap", "get", "func", "maps", "from", "tmpl" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/template.go#L21-L38
test
qor/render
template.go
Funcs
func (tmpl *Template) Funcs(funcMap template.FuncMap) *Template { tmpl.funcMap = funcMap return tmpl }
go
func (tmpl *Template) Funcs(funcMap template.FuncMap) *Template { tmpl.funcMap = funcMap return tmpl }
[ "func", "(", "tmpl", "*", "Template", ")", "Funcs", "(", "funcMap", "template", ".", "FuncMap", ")", "*", "Template", "{", "tmpl", ".", "funcMap", "=", "funcMap", "\n", "return", "tmpl", "\n", "}" ]
// Funcs register Funcs for tmpl
[ "Funcs", "register", "Funcs", "for", "tmpl" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/template.go#L41-L44
test
qor/render
template.go
Execute
func (tmpl *Template) Execute(templateName string, obj interface{}, req *http.Request, w http.ResponseWriter) error { result, err := tmpl.Render(templateName, obj, req, w) if err == nil { if w.Header().Get("Content-Type") == "" { w.Header().Set("Content-Type", "text/html") } _, err = w.Write([]byte(result)) } return err }
go
func (tmpl *Template) Execute(templateName string, obj interface{}, req *http.Request, w http.ResponseWriter) error { result, err := tmpl.Render(templateName, obj, req, w) if err == nil { if w.Header().Get("Content-Type") == "" { w.Header().Set("Content-Type", "text/html") } _, err = w.Write([]byte(result)) } return err }
[ "func", "(", "tmpl", "*", "Template", ")", "Execute", "(", "templateName", "string", ",", "obj", "interface", "{", "}", ",", "req", "*", "http", ".", "Request", ",", "w", "http", ".", "ResponseWriter", ")", "error", "{", "result", ",", "err", ":=", "tmpl", ".", "Render", "(", "templateName", ",", "obj", ",", "req", ",", "w", ")", "\n", "if", "err", "==", "nil", "{", "if", "w", ".", "Header", "(", ")", ".", "Get", "(", "\"Content-Type\"", ")", "==", "\"\"", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"text/html\"", ")", "\n", "}", "\n", "_", ",", "err", "=", "w", ".", "Write", "(", "[", "]", "byte", "(", "result", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Execute execute tmpl
[ "Execute", "execute", "tmpl" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/template.go#L137-L147
test
qor/render
assetfs/filesystem.go
RegisterPath
func (fs *AssetFileSystem) RegisterPath(pth string) error { if _, err := os.Stat(pth); !os.IsNotExist(err) { var existing bool for _, p := range fs.paths { if p == pth { existing = true break } } if !existing { fs.paths = append(fs.paths, pth) } return nil } return errors.New("not found") }
go
func (fs *AssetFileSystem) RegisterPath(pth string) error { if _, err := os.Stat(pth); !os.IsNotExist(err) { var existing bool for _, p := range fs.paths { if p == pth { existing = true break } } if !existing { fs.paths = append(fs.paths, pth) } return nil } return errors.New("not found") }
[ "func", "(", "fs", "*", "AssetFileSystem", ")", "RegisterPath", "(", "pth", "string", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "pth", ")", ";", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "var", "existing", "bool", "\n", "for", "_", ",", "p", ":=", "range", "fs", ".", "paths", "{", "if", "p", "==", "pth", "{", "existing", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "existing", "{", "fs", ".", "paths", "=", "append", "(", "fs", ".", "paths", ",", "pth", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"not found\"", ")", "\n", "}" ]
// RegisterPath register view paths
[ "RegisterPath", "register", "view", "paths" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L19-L34
test
qor/render
assetfs/filesystem.go
Asset
func (fs *AssetFileSystem) Asset(name string) ([]byte, error) { for _, pth := range fs.paths { if _, err := os.Stat(filepath.Join(pth, name)); err == nil { return ioutil.ReadFile(filepath.Join(pth, name)) } } return []byte{}, fmt.Errorf("%v not found", name) }
go
func (fs *AssetFileSystem) Asset(name string) ([]byte, error) { for _, pth := range fs.paths { if _, err := os.Stat(filepath.Join(pth, name)); err == nil { return ioutil.ReadFile(filepath.Join(pth, name)) } } return []byte{}, fmt.Errorf("%v not found", name) }
[ "func", "(", "fs", "*", "AssetFileSystem", ")", "Asset", "(", "name", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "for", "_", ",", "pth", ":=", "range", "fs", ".", "paths", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "pth", ",", "name", ")", ")", ";", "err", "==", "nil", "{", "return", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "pth", ",", "name", ")", ")", "\n", "}", "\n", "}", "\n", "return", "[", "]", "byte", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"%v not found\"", ",", "name", ")", "\n", "}" ]
// Asset get content with name from assetfs
[ "Asset", "get", "content", "with", "name", "from", "assetfs" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L55-L62
test
qor/render
assetfs/filesystem.go
Glob
func (fs *AssetFileSystem) Glob(pattern string) (matches []string, err error) { for _, pth := range fs.paths { if results, err := filepath.Glob(filepath.Join(pth, pattern)); err == nil { for _, result := range results { matches = append(matches, strings.TrimPrefix(result, pth)) } } } return }
go
func (fs *AssetFileSystem) Glob(pattern string) (matches []string, err error) { for _, pth := range fs.paths { if results, err := filepath.Glob(filepath.Join(pth, pattern)); err == nil { for _, result := range results { matches = append(matches, strings.TrimPrefix(result, pth)) } } } return }
[ "func", "(", "fs", "*", "AssetFileSystem", ")", "Glob", "(", "pattern", "string", ")", "(", "matches", "[", "]", "string", ",", "err", "error", ")", "{", "for", "_", ",", "pth", ":=", "range", "fs", ".", "paths", "{", "if", "results", ",", "err", ":=", "filepath", ".", "Glob", "(", "filepath", ".", "Join", "(", "pth", ",", "pattern", ")", ")", ";", "err", "==", "nil", "{", "for", "_", ",", "result", ":=", "range", "results", "{", "matches", "=", "append", "(", "matches", ",", "strings", ".", "TrimPrefix", "(", "result", ",", "pth", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Glob list matched files from assetfs
[ "Glob", "list", "matched", "files", "from", "assetfs" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L65-L74
test
qor/render
assetfs/filesystem.go
NameSpace
func (fs *AssetFileSystem) NameSpace(nameSpace string) Interface { if fs.nameSpacedFS == nil { fs.nameSpacedFS = map[string]Interface{} } fs.nameSpacedFS[nameSpace] = &AssetFileSystem{} return fs.nameSpacedFS[nameSpace] }
go
func (fs *AssetFileSystem) NameSpace(nameSpace string) Interface { if fs.nameSpacedFS == nil { fs.nameSpacedFS = map[string]Interface{} } fs.nameSpacedFS[nameSpace] = &AssetFileSystem{} return fs.nameSpacedFS[nameSpace] }
[ "func", "(", "fs", "*", "AssetFileSystem", ")", "NameSpace", "(", "nameSpace", "string", ")", "Interface", "{", "if", "fs", ".", "nameSpacedFS", "==", "nil", "{", "fs", ".", "nameSpacedFS", "=", "map", "[", "string", "]", "Interface", "{", "}", "\n", "}", "\n", "fs", ".", "nameSpacedFS", "[", "nameSpace", "]", "=", "&", "AssetFileSystem", "{", "}", "\n", "return", "fs", ".", "nameSpacedFS", "[", "nameSpace", "]", "\n", "}" ]
// NameSpace return namespaced filesystem
[ "NameSpace", "return", "namespaced", "filesystem" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L82-L88
test
qor/render
render.go
New
func New(config *Config, viewPaths ...string) *Render { if config == nil { config = &Config{} } if config.DefaultLayout == "" { config.DefaultLayout = DefaultLayout } if config.AssetFileSystem == nil { config.AssetFileSystem = assetfs.AssetFS().NameSpace("views") } config.ViewPaths = append(append(config.ViewPaths, viewPaths...), DefaultViewPath) render := &Render{funcMaps: map[string]interface{}{}, Config: config} for _, viewPath := range config.ViewPaths { render.RegisterViewPath(viewPath) } return render }
go
func New(config *Config, viewPaths ...string) *Render { if config == nil { config = &Config{} } if config.DefaultLayout == "" { config.DefaultLayout = DefaultLayout } if config.AssetFileSystem == nil { config.AssetFileSystem = assetfs.AssetFS().NameSpace("views") } config.ViewPaths = append(append(config.ViewPaths, viewPaths...), DefaultViewPath) render := &Render{funcMaps: map[string]interface{}{}, Config: config} for _, viewPath := range config.ViewPaths { render.RegisterViewPath(viewPath) } return render }
[ "func", "New", "(", "config", "*", "Config", ",", "viewPaths", "...", "string", ")", "*", "Render", "{", "if", "config", "==", "nil", "{", "config", "=", "&", "Config", "{", "}", "\n", "}", "\n", "if", "config", ".", "DefaultLayout", "==", "\"\"", "{", "config", ".", "DefaultLayout", "=", "DefaultLayout", "\n", "}", "\n", "if", "config", ".", "AssetFileSystem", "==", "nil", "{", "config", ".", "AssetFileSystem", "=", "assetfs", ".", "AssetFS", "(", ")", ".", "NameSpace", "(", "\"views\"", ")", "\n", "}", "\n", "config", ".", "ViewPaths", "=", "append", "(", "append", "(", "config", ".", "ViewPaths", ",", "viewPaths", "...", ")", ",", "DefaultViewPath", ")", "\n", "render", ":=", "&", "Render", "{", "funcMaps", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "Config", ":", "config", "}", "\n", "for", "_", ",", "viewPath", ":=", "range", "config", ".", "ViewPaths", "{", "render", ".", "RegisterViewPath", "(", "viewPath", ")", "\n", "}", "\n", "return", "render", "\n", "}" ]
// New initalize the render struct.
[ "New", "initalize", "the", "render", "struct", "." ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L35-L57
test
qor/render
render.go
RegisterViewPath
func (render *Render) RegisterViewPath(paths ...string) { for _, pth := range paths { if filepath.IsAbs(pth) { render.ViewPaths = append(render.ViewPaths, pth) render.AssetFileSystem.RegisterPath(pth) } else { if absPath, err := filepath.Abs(pth); err == nil && isExistingDir(absPath) { render.ViewPaths = append(render.ViewPaths, absPath) render.AssetFileSystem.RegisterPath(absPath) } else if isExistingDir(filepath.Join(utils.AppRoot, "vendor", pth)) { render.AssetFileSystem.RegisterPath(filepath.Join(utils.AppRoot, "vendor", pth)) } else { for _, gopath := range utils.GOPATH() { if p := filepath.Join(gopath, "src", pth); isExistingDir(p) { render.ViewPaths = append(render.ViewPaths, p) render.AssetFileSystem.RegisterPath(p) } } } } } }
go
func (render *Render) RegisterViewPath(paths ...string) { for _, pth := range paths { if filepath.IsAbs(pth) { render.ViewPaths = append(render.ViewPaths, pth) render.AssetFileSystem.RegisterPath(pth) } else { if absPath, err := filepath.Abs(pth); err == nil && isExistingDir(absPath) { render.ViewPaths = append(render.ViewPaths, absPath) render.AssetFileSystem.RegisterPath(absPath) } else if isExistingDir(filepath.Join(utils.AppRoot, "vendor", pth)) { render.AssetFileSystem.RegisterPath(filepath.Join(utils.AppRoot, "vendor", pth)) } else { for _, gopath := range utils.GOPATH() { if p := filepath.Join(gopath, "src", pth); isExistingDir(p) { render.ViewPaths = append(render.ViewPaths, p) render.AssetFileSystem.RegisterPath(p) } } } } } }
[ "func", "(", "render", "*", "Render", ")", "RegisterViewPath", "(", "paths", "...", "string", ")", "{", "for", "_", ",", "pth", ":=", "range", "paths", "{", "if", "filepath", ".", "IsAbs", "(", "pth", ")", "{", "render", ".", "ViewPaths", "=", "append", "(", "render", ".", "ViewPaths", ",", "pth", ")", "\n", "render", ".", "AssetFileSystem", ".", "RegisterPath", "(", "pth", ")", "\n", "}", "else", "{", "if", "absPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "pth", ")", ";", "err", "==", "nil", "&&", "isExistingDir", "(", "absPath", ")", "{", "render", ".", "ViewPaths", "=", "append", "(", "render", ".", "ViewPaths", ",", "absPath", ")", "\n", "render", ".", "AssetFileSystem", ".", "RegisterPath", "(", "absPath", ")", "\n", "}", "else", "if", "isExistingDir", "(", "filepath", ".", "Join", "(", "utils", ".", "AppRoot", ",", "\"vendor\"", ",", "pth", ")", ")", "{", "render", ".", "AssetFileSystem", ".", "RegisterPath", "(", "filepath", ".", "Join", "(", "utils", ".", "AppRoot", ",", "\"vendor\"", ",", "pth", ")", ")", "\n", "}", "else", "{", "for", "_", ",", "gopath", ":=", "range", "utils", ".", "GOPATH", "(", ")", "{", "if", "p", ":=", "filepath", ".", "Join", "(", "gopath", ",", "\"src\"", ",", "pth", ")", ";", "isExistingDir", "(", "p", ")", "{", "render", ".", "ViewPaths", "=", "append", "(", "render", ".", "ViewPaths", ",", "p", ")", "\n", "render", ".", "AssetFileSystem", ".", "RegisterPath", "(", "p", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// RegisterViewPath register view path
[ "RegisterViewPath", "register", "view", "path" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L60-L81
test
qor/render
render.go
SetAssetFS
func (render *Render) SetAssetFS(assetFS assetfs.Interface) { for _, viewPath := range render.ViewPaths { assetFS.RegisterPath(viewPath) } render.AssetFileSystem = assetFS }
go
func (render *Render) SetAssetFS(assetFS assetfs.Interface) { for _, viewPath := range render.ViewPaths { assetFS.RegisterPath(viewPath) } render.AssetFileSystem = assetFS }
[ "func", "(", "render", "*", "Render", ")", "SetAssetFS", "(", "assetFS", "assetfs", ".", "Interface", ")", "{", "for", "_", ",", "viewPath", ":=", "range", "render", ".", "ViewPaths", "{", "assetFS", ".", "RegisterPath", "(", "viewPath", ")", "\n", "}", "\n", "render", ".", "AssetFileSystem", "=", "assetFS", "\n", "}" ]
// SetAssetFS set asset fs for render
[ "SetAssetFS", "set", "asset", "fs", "for", "render" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L108-L114
test
qor/render
render.go
Layout
func (render *Render) Layout(name string) *Template { return &Template{render: render, layout: name} }
go
func (render *Render) Layout(name string) *Template { return &Template{render: render, layout: name} }
[ "func", "(", "render", "*", "Render", ")", "Layout", "(", "name", "string", ")", "*", "Template", "{", "return", "&", "Template", "{", "render", ":", "render", ",", "layout", ":", "name", "}", "\n", "}" ]
// Layout set layout for template.
[ "Layout", "set", "layout", "for", "template", "." ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L117-L119
test
qor/render
render.go
Funcs
func (render *Render) Funcs(funcMap template.FuncMap) *Template { tmpl := &Template{render: render, usingDefaultLayout: true} return tmpl.Funcs(funcMap) }
go
func (render *Render) Funcs(funcMap template.FuncMap) *Template { tmpl := &Template{render: render, usingDefaultLayout: true} return tmpl.Funcs(funcMap) }
[ "func", "(", "render", "*", "Render", ")", "Funcs", "(", "funcMap", "template", ".", "FuncMap", ")", "*", "Template", "{", "tmpl", ":=", "&", "Template", "{", "render", ":", "render", ",", "usingDefaultLayout", ":", "true", "}", "\n", "return", "tmpl", ".", "Funcs", "(", "funcMap", ")", "\n", "}" ]
// Funcs set helper functions for template with default "application" layout.
[ "Funcs", "set", "helper", "functions", "for", "template", "with", "default", "application", "layout", "." ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L122-L125
test
qor/render
render.go
Execute
func (render *Render) Execute(name string, context interface{}, request *http.Request, writer http.ResponseWriter) error { tmpl := &Template{render: render, usingDefaultLayout: true} return tmpl.Execute(name, context, request, writer) }
go
func (render *Render) Execute(name string, context interface{}, request *http.Request, writer http.ResponseWriter) error { tmpl := &Template{render: render, usingDefaultLayout: true} return tmpl.Execute(name, context, request, writer) }
[ "func", "(", "render", "*", "Render", ")", "Execute", "(", "name", "string", ",", "context", "interface", "{", "}", ",", "request", "*", "http", ".", "Request", ",", "writer", "http", ".", "ResponseWriter", ")", "error", "{", "tmpl", ":=", "&", "Template", "{", "render", ":", "render", ",", "usingDefaultLayout", ":", "true", "}", "\n", "return", "tmpl", ".", "Execute", "(", "name", ",", "context", ",", "request", ",", "writer", ")", "\n", "}" ]
// Execute render template with default "application" layout.
[ "Execute", "render", "template", "with", "default", "application", "layout", "." ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L128-L131
test
qor/render
render.go
RegisterFuncMap
func (render *Render) RegisterFuncMap(name string, fc interface{}) { if render.funcMaps == nil { render.funcMaps = template.FuncMap{} } render.funcMaps[name] = fc }
go
func (render *Render) RegisterFuncMap(name string, fc interface{}) { if render.funcMaps == nil { render.funcMaps = template.FuncMap{} } render.funcMaps[name] = fc }
[ "func", "(", "render", "*", "Render", ")", "RegisterFuncMap", "(", "name", "string", ",", "fc", "interface", "{", "}", ")", "{", "if", "render", ".", "funcMaps", "==", "nil", "{", "render", ".", "funcMaps", "=", "template", ".", "FuncMap", "{", "}", "\n", "}", "\n", "render", ".", "funcMaps", "[", "name", "]", "=", "fc", "\n", "}" ]
// RegisterFuncMap register FuncMap for render.
[ "RegisterFuncMap", "register", "FuncMap", "for", "render", "." ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L134-L139
test
qor/render
render.go
Asset
func (render *Render) Asset(name string) ([]byte, error) { return render.AssetFileSystem.Asset(name) }
go
func (render *Render) Asset(name string) ([]byte, error) { return render.AssetFileSystem.Asset(name) }
[ "func", "(", "render", "*", "Render", ")", "Asset", "(", "name", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "render", ".", "AssetFileSystem", ".", "Asset", "(", "name", ")", "\n", "}" ]
// Asset get content from AssetFS by name
[ "Asset", "get", "content", "from", "AssetFS", "by", "name" ]
63566e46f01b134ae9882a59a06518e82a903231
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L142-L144
test
emersion/go-sasl
plain.go
NewPlainClient
func NewPlainClient(identity, username, password string) Client { return &plainClient{identity, username, password} }
go
func NewPlainClient(identity, username, password string) Client { return &plainClient{identity, username, password} }
[ "func", "NewPlainClient", "(", "identity", ",", "username", ",", "password", "string", ")", "Client", "{", "return", "&", "plainClient", "{", "identity", ",", "username", ",", "password", "}", "\n", "}" ]
// A client implementation of the PLAIN authentication mechanism, as described // in RFC 4616. Authorization identity may be left blank to indicate that it is // the same as the username.
[ "A", "client", "implementation", "of", "the", "PLAIN", "authentication", "mechanism", "as", "described", "in", "RFC", "4616", ".", "Authorization", "identity", "may", "be", "left", "blank", "to", "indicate", "that", "it", "is", "the", "same", "as", "the", "username", "." ]
7e096a0a6197b89989e8cc31016daa67c8c62051
https://github.com/emersion/go-sasl/blob/7e096a0a6197b89989e8cc31016daa67c8c62051/plain.go#L30-L32
test
kr/s3
s3util/uploader.go
Create
func Create(url string, h http.Header, c *Config) (io.WriteCloser, error) { if c == nil { c = DefaultConfig } return newUploader(url, h, c) }
go
func Create(url string, h http.Header, c *Config) (io.WriteCloser, error) { if c == nil { c = DefaultConfig } return newUploader(url, h, c) }
[ "func", "Create", "(", "url", "string", ",", "h", "http", ".", "Header", ",", "c", "*", "Config", ")", "(", "io", ".", "WriteCloser", ",", "error", ")", "{", "if", "c", "==", "nil", "{", "c", "=", "DefaultConfig", "\n", "}", "\n", "return", "newUploader", "(", "url", ",", "h", ",", "c", ")", "\n", "}" ]
// Create creates an S3 object at url and sends multipart upload requests as // data is written. // // If h is not nil, each of its entries is added to the HTTP request header. // If c is nil, Create uses DefaultConfig.
[ "Create", "creates", "an", "S3", "object", "at", "url", "and", "sends", "multipart", "upload", "requests", "as", "data", "is", "written", ".", "If", "h", "is", "not", "nil", "each", "of", "its", "entries", "is", "added", "to", "the", "HTTP", "request", "header", ".", "If", "c", "is", "nil", "Create", "uses", "DefaultConfig", "." ]
c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/s3util/uploader.go#L66-L71
test
kr/s3
s3util/open.go
Open
func Open(url string, c *Config) (io.ReadCloser, error) { if c == nil { c = DefaultConfig } // TODO(kr): maybe parallel range fetching r, _ := http.NewRequest("GET", url, nil) r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat)) c.Sign(r, *c.Keys) client := c.Client if client == nil { client = http.DefaultClient } resp, err := client.Do(r) if err != nil { return nil, err } if resp.StatusCode != 200 { return nil, newRespError(resp) } return resp.Body, nil }
go
func Open(url string, c *Config) (io.ReadCloser, error) { if c == nil { c = DefaultConfig } // TODO(kr): maybe parallel range fetching r, _ := http.NewRequest("GET", url, nil) r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat)) c.Sign(r, *c.Keys) client := c.Client if client == nil { client = http.DefaultClient } resp, err := client.Do(r) if err != nil { return nil, err } if resp.StatusCode != 200 { return nil, newRespError(resp) } return resp.Body, nil }
[ "func", "Open", "(", "url", "string", ",", "c", "*", "Config", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "if", "c", "==", "nil", "{", "c", "=", "DefaultConfig", "\n", "}", "\n", "r", ",", "_", ":=", "http", ".", "NewRequest", "(", "\"GET\"", ",", "url", ",", "nil", ")", "\n", "r", ".", "Header", ".", "Set", "(", "\"Date\"", ",", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Format", "(", "http", ".", "TimeFormat", ")", ")", "\n", "c", ".", "Sign", "(", "r", ",", "*", "c", ".", "Keys", ")", "\n", "client", ":=", "c", ".", "Client", "\n", "if", "client", "==", "nil", "{", "client", "=", "http", ".", "DefaultClient", "\n", "}", "\n", "resp", ",", "err", ":=", "client", ".", "Do", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "200", "{", "return", "nil", ",", "newRespError", "(", "resp", ")", "\n", "}", "\n", "return", "resp", ".", "Body", ",", "nil", "\n", "}" ]
// Open requests the S3 object at url. An HTTP status other than 200 is // considered an error. // // If c is nil, Open uses DefaultConfig.
[ "Open", "requests", "the", "S3", "object", "at", "url", ".", "An", "HTTP", "status", "other", "than", "200", "is", "considered", "an", "error", ".", "If", "c", "is", "nil", "Open", "uses", "DefaultConfig", "." ]
c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/s3util/open.go#L13-L33
test
kr/s3
sign.go
Sign
func Sign(r *http.Request, k Keys) { DefaultService.Sign(r, k) }
go
func Sign(r *http.Request, k Keys) { DefaultService.Sign(r, k) }
[ "func", "Sign", "(", "r", "*", "http", ".", "Request", ",", "k", "Keys", ")", "{", "DefaultService", ".", "Sign", "(", "r", ",", "k", ")", "\n", "}" ]
// Sign signs an HTTP request with the given S3 keys. // // This function is a wrapper around DefaultService.Sign.
[ "Sign", "signs", "an", "HTTP", "request", "with", "the", "given", "S3", "keys", ".", "This", "function", "is", "a", "wrapper", "around", "DefaultService", ".", "Sign", "." ]
c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/sign.go#L81-L83
test
kr/s3
sign.go
Sign
func (s *Service) Sign(r *http.Request, k Keys) { if k.SecurityToken != "" { r.Header.Set("X-Amz-Security-Token", k.SecurityToken) } h := hmac.New(sha1.New, []byte(k.SecretKey)) s.writeSigData(h, r) sig := make([]byte, base64.StdEncoding.EncodedLen(h.Size())) base64.StdEncoding.Encode(sig, h.Sum(nil)) r.Header.Set("Authorization", "AWS "+k.AccessKey+":"+string(sig)) }
go
func (s *Service) Sign(r *http.Request, k Keys) { if k.SecurityToken != "" { r.Header.Set("X-Amz-Security-Token", k.SecurityToken) } h := hmac.New(sha1.New, []byte(k.SecretKey)) s.writeSigData(h, r) sig := make([]byte, base64.StdEncoding.EncodedLen(h.Size())) base64.StdEncoding.Encode(sig, h.Sum(nil)) r.Header.Set("Authorization", "AWS "+k.AccessKey+":"+string(sig)) }
[ "func", "(", "s", "*", "Service", ")", "Sign", "(", "r", "*", "http", ".", "Request", ",", "k", "Keys", ")", "{", "if", "k", ".", "SecurityToken", "!=", "\"\"", "{", "r", ".", "Header", ".", "Set", "(", "\"X-Amz-Security-Token\"", ",", "k", ".", "SecurityToken", ")", "\n", "}", "\n", "h", ":=", "hmac", ".", "New", "(", "sha1", ".", "New", ",", "[", "]", "byte", "(", "k", ".", "SecretKey", ")", ")", "\n", "s", ".", "writeSigData", "(", "h", ",", "r", ")", "\n", "sig", ":=", "make", "(", "[", "]", "byte", ",", "base64", ".", "StdEncoding", ".", "EncodedLen", "(", "h", ".", "Size", "(", ")", ")", ")", "\n", "base64", ".", "StdEncoding", ".", "Encode", "(", "sig", ",", "h", ".", "Sum", "(", "nil", ")", ")", "\n", "r", ".", "Header", ".", "Set", "(", "\"Authorization\"", ",", "\"AWS \"", "+", "k", ".", "AccessKey", "+", "\":\"", "+", "string", "(", "sig", ")", ")", "\n", "}" ]
// Sign signs an HTTP request with the given S3 keys for use on service s.
[ "Sign", "signs", "an", "HTTP", "request", "with", "the", "given", "S3", "keys", "for", "use", "on", "service", "s", "." ]
c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/sign.go#L98-L107
test
kr/s3
s3util/readdir.go
Readdir
func (f *File) Readdir(n int) ([]os.FileInfo, error) { if f.result != nil && !f.result.IsTruncated { return make([]os.FileInfo, 0), io.EOF } reader, err := f.sendRequest(n) if err != nil { return nil, err } defer reader.Close() return f.parseResponse(reader) }
go
func (f *File) Readdir(n int) ([]os.FileInfo, error) { if f.result != nil && !f.result.IsTruncated { return make([]os.FileInfo, 0), io.EOF } reader, err := f.sendRequest(n) if err != nil { return nil, err } defer reader.Close() return f.parseResponse(reader) }
[ "func", "(", "f", "*", "File", ")", "Readdir", "(", "n", "int", ")", "(", "[", "]", "os", ".", "FileInfo", ",", "error", ")", "{", "if", "f", ".", "result", "!=", "nil", "&&", "!", "f", ".", "result", ".", "IsTruncated", "{", "return", "make", "(", "[", "]", "os", ".", "FileInfo", ",", "0", ")", ",", "io", ".", "EOF", "\n", "}", "\n", "reader", ",", "err", ":=", "f", ".", "sendRequest", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "reader", ".", "Close", "(", ")", "\n", "return", "f", ".", "parseResponse", "(", "reader", ")", "\n", "}" ]
// Readdir requests a list of entries in the S3 directory // represented by f and returns a slice of up to n FileInfo // values, in alphabetical order. Subsequent calls // on the same File will yield further FileInfos. // Only direct children are returned, not deeper descendants.
[ "Readdir", "requests", "a", "list", "of", "entries", "in", "the", "S3", "directory", "represented", "by", "f", "and", "returns", "a", "slice", "of", "up", "to", "n", "FileInfo", "values", "in", "alphabetical", "order", ".", "Subsequent", "calls", "on", "the", "same", "File", "will", "yield", "further", "FileInfos", ".", "Only", "direct", "children", "are", "returned", "not", "deeper", "descendants", "." ]
c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/s3util/readdir.go#L103-L115
test
ChrisTrenkamp/goxpath
internal/execxp/findutil/findUtil.go
Find
func Find(x tree.Node, p pathexpr.PathExpr) []tree.Node { ret := []tree.Node{} if p.Axis == "" { findChild(x, &p, &ret) return ret } f := findMap[p.Axis] f(x, &p, &ret) return ret }
go
func Find(x tree.Node, p pathexpr.PathExpr) []tree.Node { ret := []tree.Node{} if p.Axis == "" { findChild(x, &p, &ret) return ret } f := findMap[p.Axis] f(x, &p, &ret) return ret }
[ "func", "Find", "(", "x", "tree", ".", "Node", ",", "p", "pathexpr", ".", "PathExpr", ")", "[", "]", "tree", ".", "Node", "{", "ret", ":=", "[", "]", "tree", ".", "Node", "{", "}", "\n", "if", "p", ".", "Axis", "==", "\"\"", "{", "findChild", "(", "x", ",", "&", "p", ",", "&", "ret", ")", "\n", "return", "ret", "\n", "}", "\n", "f", ":=", "findMap", "[", "p", ".", "Axis", "]", "\n", "f", "(", "x", ",", "&", "p", ",", "&", "ret", ")", "\n", "return", "ret", "\n", "}" ]
//Find finds nodes based on the pathexpr.PathExpr
[ "Find", "finds", "nodes", "based", "on", "the", "pathexpr", ".", "PathExpr" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/internal/execxp/findutil/findUtil.go#L34-L46
test
ChrisTrenkamp/goxpath
lexer/lexer.go
Lex
func Lex(xpath string) chan XItem { l := &Lexer{ input: xpath, items: make(chan XItem), } go l.run() return l.items }
go
func Lex(xpath string) chan XItem { l := &Lexer{ input: xpath, items: make(chan XItem), } go l.run() return l.items }
[ "func", "Lex", "(", "xpath", "string", ")", "chan", "XItem", "{", "l", ":=", "&", "Lexer", "{", "input", ":", "xpath", ",", "items", ":", "make", "(", "chan", "XItem", ")", ",", "}", "\n", "go", "l", ".", "run", "(", ")", "\n", "return", "l", ".", "items", "\n", "}" ]
//Lex an XPath expresion on the io.Reader
[ "Lex", "an", "XPath", "expresion", "on", "the", "io", ".", "Reader" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/lexer/lexer.go#L80-L87
test
ChrisTrenkamp/goxpath
tree/xmltree/xmltree.go
MustParseXML
func MustParseXML(r io.Reader, op ...ParseSettings) tree.Node { ret, err := ParseXML(r, op...) if err != nil { panic(err) } return ret }
go
func MustParseXML(r io.Reader, op ...ParseSettings) tree.Node { ret, err := ParseXML(r, op...) if err != nil { panic(err) } return ret }
[ "func", "MustParseXML", "(", "r", "io", ".", "Reader", ",", "op", "...", "ParseSettings", ")", "tree", ".", "Node", "{", "ret", ",", "err", ":=", "ParseXML", "(", "r", ",", "op", "...", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
//MustParseXML is like ParseXML, but panics instead of returning an error.
[ "MustParseXML", "is", "like", "ParseXML", "but", "panics", "instead", "of", "returning", "an", "error", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmltree.go#L34-L42
test
ChrisTrenkamp/goxpath
tree/xmltree/xmltree.go
ParseXML
func ParseXML(r io.Reader, op ...ParseSettings) (tree.Node, error) { ov := ParseOptions{ Strict: true, XMLRoot: xmlele.Root, } for _, i := range op { i(&ov) } dec := xml.NewDecoder(r) dec.CharsetReader = charset.NewReaderLabel dec.Strict = ov.Strict ordrPos := 1 xmlTree := ov.XMLRoot() t, err := dec.Token() if err != nil { return nil, err } if head, ok := t.(xml.ProcInst); ok && head.Target == "xml" { t, err = dec.Token() } opts := xmlbuilder.BuilderOpts{ Dec: dec, } for err == nil { switch xt := t.(type) { case xml.StartElement: setEle(&opts, xmlTree, xt, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.CharData: setNode(&opts, xmlTree, xt, tree.NtChd, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.Comment: setNode(&opts, xmlTree, xt, tree.NtComm, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.ProcInst: setNode(&opts, xmlTree, xt, tree.NtPi, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.EndElement: xmlTree = xmlTree.EndElem() case xml.Directive: if dp, ok := xmlTree.(DirectiveParser); ok { dp.Directive(xt.Copy(), dec) } } t, err = dec.Token() } if err == io.EOF { err = nil } return xmlTree, err }
go
func ParseXML(r io.Reader, op ...ParseSettings) (tree.Node, error) { ov := ParseOptions{ Strict: true, XMLRoot: xmlele.Root, } for _, i := range op { i(&ov) } dec := xml.NewDecoder(r) dec.CharsetReader = charset.NewReaderLabel dec.Strict = ov.Strict ordrPos := 1 xmlTree := ov.XMLRoot() t, err := dec.Token() if err != nil { return nil, err } if head, ok := t.(xml.ProcInst); ok && head.Target == "xml" { t, err = dec.Token() } opts := xmlbuilder.BuilderOpts{ Dec: dec, } for err == nil { switch xt := t.(type) { case xml.StartElement: setEle(&opts, xmlTree, xt, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.CharData: setNode(&opts, xmlTree, xt, tree.NtChd, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.Comment: setNode(&opts, xmlTree, xt, tree.NtComm, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.ProcInst: setNode(&opts, xmlTree, xt, tree.NtPi, &ordrPos) xmlTree = xmlTree.CreateNode(&opts) case xml.EndElement: xmlTree = xmlTree.EndElem() case xml.Directive: if dp, ok := xmlTree.(DirectiveParser); ok { dp.Directive(xt.Copy(), dec) } } t, err = dec.Token() } if err == io.EOF { err = nil } return xmlTree, err }
[ "func", "ParseXML", "(", "r", "io", ".", "Reader", ",", "op", "...", "ParseSettings", ")", "(", "tree", ".", "Node", ",", "error", ")", "{", "ov", ":=", "ParseOptions", "{", "Strict", ":", "true", ",", "XMLRoot", ":", "xmlele", ".", "Root", ",", "}", "\n", "for", "_", ",", "i", ":=", "range", "op", "{", "i", "(", "&", "ov", ")", "\n", "}", "\n", "dec", ":=", "xml", ".", "NewDecoder", "(", "r", ")", "\n", "dec", ".", "CharsetReader", "=", "charset", ".", "NewReaderLabel", "\n", "dec", ".", "Strict", "=", "ov", ".", "Strict", "\n", "ordrPos", ":=", "1", "\n", "xmlTree", ":=", "ov", ".", "XMLRoot", "(", ")", "\n", "t", ",", "err", ":=", "dec", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "head", ",", "ok", ":=", "t", ".", "(", "xml", ".", "ProcInst", ")", ";", "ok", "&&", "head", ".", "Target", "==", "\"xml\"", "{", "t", ",", "err", "=", "dec", ".", "Token", "(", ")", "\n", "}", "\n", "opts", ":=", "xmlbuilder", ".", "BuilderOpts", "{", "Dec", ":", "dec", ",", "}", "\n", "for", "err", "==", "nil", "{", "switch", "xt", ":=", "t", ".", "(", "type", ")", "{", "case", "xml", ".", "StartElement", ":", "setEle", "(", "&", "opts", ",", "xmlTree", ",", "xt", ",", "&", "ordrPos", ")", "\n", "xmlTree", "=", "xmlTree", ".", "CreateNode", "(", "&", "opts", ")", "\n", "case", "xml", ".", "CharData", ":", "setNode", "(", "&", "opts", ",", "xmlTree", ",", "xt", ",", "tree", ".", "NtChd", ",", "&", "ordrPos", ")", "\n", "xmlTree", "=", "xmlTree", ".", "CreateNode", "(", "&", "opts", ")", "\n", "case", "xml", ".", "Comment", ":", "setNode", "(", "&", "opts", ",", "xmlTree", ",", "xt", ",", "tree", ".", "NtComm", ",", "&", "ordrPos", ")", "\n", "xmlTree", "=", "xmlTree", ".", "CreateNode", "(", "&", "opts", ")", "\n", "case", "xml", ".", "ProcInst", ":", "setNode", "(", "&", "opts", ",", "xmlTree", ",", "xt", ",", "tree", ".", "NtPi", ",", "&", "ordrPos", ")", "\n", "xmlTree", "=", "xmlTree", ".", "CreateNode", "(", "&", "opts", ")", "\n", "case", "xml", ".", "EndElement", ":", "xmlTree", "=", "xmlTree", ".", "EndElem", "(", ")", "\n", "case", "xml", ".", "Directive", ":", "if", "dp", ",", "ok", ":=", "xmlTree", ".", "(", "DirectiveParser", ")", ";", "ok", "{", "dp", ".", "Directive", "(", "xt", ".", "Copy", "(", ")", ",", "dec", ")", "\n", "}", "\n", "}", "\n", "t", ",", "err", "=", "dec", ".", "Token", "(", ")", "\n", "}", "\n", "if", "err", "==", "io", ".", "EOF", "{", "err", "=", "nil", "\n", "}", "\n", "return", "xmlTree", ",", "err", "\n", "}" ]
//ParseXML creates an XMLTree structure from an io.Reader.
[ "ParseXML", "creates", "an", "XMLTree", "structure", "from", "an", "io", ".", "Reader", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmltree.go#L45-L105
test
ChrisTrenkamp/goxpath
tree/xfn.go
Call
func (w Wrap) Call(c Ctx, args ...Result) (Result, error) { switch w.LastArgOpt { case Optional: if len(args) == w.NArgs || len(args) == w.NArgs-1 { return w.Fn(c, args...) } case Variadic: if len(args) >= w.NArgs-1 { return w.Fn(c, args...) } default: if len(args) == w.NArgs { return w.Fn(c, args...) } } return nil, fmt.Errorf("Invalid number of arguments") }
go
func (w Wrap) Call(c Ctx, args ...Result) (Result, error) { switch w.LastArgOpt { case Optional: if len(args) == w.NArgs || len(args) == w.NArgs-1 { return w.Fn(c, args...) } case Variadic: if len(args) >= w.NArgs-1 { return w.Fn(c, args...) } default: if len(args) == w.NArgs { return w.Fn(c, args...) } } return nil, fmt.Errorf("Invalid number of arguments") }
[ "func", "(", "w", "Wrap", ")", "Call", "(", "c", "Ctx", ",", "args", "...", "Result", ")", "(", "Result", ",", "error", ")", "{", "switch", "w", ".", "LastArgOpt", "{", "case", "Optional", ":", "if", "len", "(", "args", ")", "==", "w", ".", "NArgs", "||", "len", "(", "args", ")", "==", "w", ".", "NArgs", "-", "1", "{", "return", "w", ".", "Fn", "(", "c", ",", "args", "...", ")", "\n", "}", "\n", "case", "Variadic", ":", "if", "len", "(", "args", ")", ">=", "w", ".", "NArgs", "-", "1", "{", "return", "w", ".", "Fn", "(", "c", ",", "args", "...", ")", "\n", "}", "\n", "default", ":", "if", "len", "(", "args", ")", "==", "w", ".", "NArgs", "{", "return", "w", ".", "Fn", "(", "c", ",", "args", "...", ")", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Invalid number of arguments\"", ")", "\n", "}" ]
//Call checks the arguments and calls Fn if they are valid
[ "Call", "checks", "the", "arguments", "and", "calls", "Fn", "if", "they", "are", "valid" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xfn.go#L36-L52
test
ChrisTrenkamp/goxpath
goxpath.go
Parse
func Parse(xp string) (XPathExec, error) { n, err := parser.Parse(xp) return XPathExec{n: n}, err }
go
func Parse(xp string) (XPathExec, error) { n, err := parser.Parse(xp) return XPathExec{n: n}, err }
[ "func", "Parse", "(", "xp", "string", ")", "(", "XPathExec", ",", "error", ")", "{", "n", ",", "err", ":=", "parser", ".", "Parse", "(", "xp", ")", "\n", "return", "XPathExec", "{", "n", ":", "n", "}", ",", "err", "\n", "}" ]
//Parse parses the XPath expression, xp, returning an XPath executor.
[ "Parse", "parses", "the", "XPath", "expression", "xp", "returning", "an", "XPath", "executor", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L28-L31
test
ChrisTrenkamp/goxpath
goxpath.go
MustParse
func MustParse(xp string) XPathExec { ret, err := Parse(xp) if err != nil { panic(err) } return ret }
go
func MustParse(xp string) XPathExec { ret, err := Parse(xp) if err != nil { panic(err) } return ret }
[ "func", "MustParse", "(", "xp", "string", ")", "XPathExec", "{", "ret", ",", "err", ":=", "Parse", "(", "xp", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
//MustParse is like Parse, but panics instead of returning an error.
[ "MustParse", "is", "like", "Parse", "but", "panics", "instead", "of", "returning", "an", "error", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L34-L40
test
ChrisTrenkamp/goxpath
goxpath.go
Exec
func (xp XPathExec) Exec(t tree.Node, opts ...FuncOpts) (tree.Result, error) { o := &Opts{ NS: make(map[string]string), Funcs: make(map[xml.Name]tree.Wrap), Vars: make(map[string]tree.Result), } for _, i := range opts { i(o) } return execxp.Exec(xp.n, t, o.NS, o.Funcs, o.Vars) }
go
func (xp XPathExec) Exec(t tree.Node, opts ...FuncOpts) (tree.Result, error) { o := &Opts{ NS: make(map[string]string), Funcs: make(map[xml.Name]tree.Wrap), Vars: make(map[string]tree.Result), } for _, i := range opts { i(o) } return execxp.Exec(xp.n, t, o.NS, o.Funcs, o.Vars) }
[ "func", "(", "xp", "XPathExec", ")", "Exec", "(", "t", "tree", ".", "Node", ",", "opts", "...", "FuncOpts", ")", "(", "tree", ".", "Result", ",", "error", ")", "{", "o", ":=", "&", "Opts", "{", "NS", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "Funcs", ":", "make", "(", "map", "[", "xml", ".", "Name", "]", "tree", ".", "Wrap", ")", ",", "Vars", ":", "make", "(", "map", "[", "string", "]", "tree", ".", "Result", ")", ",", "}", "\n", "for", "_", ",", "i", ":=", "range", "opts", "{", "i", "(", "o", ")", "\n", "}", "\n", "return", "execxp", ".", "Exec", "(", "xp", ".", "n", ",", "t", ",", "o", ".", "NS", ",", "o", ".", "Funcs", ",", "o", ".", "Vars", ")", "\n", "}" ]
//Exec executes the XPath expression, xp, against the tree, t, with the //namespace mappings, ns, and returns the result as a stringer.
[ "Exec", "executes", "the", "XPath", "expression", "xp", "against", "the", "tree", "t", "with", "the", "namespace", "mappings", "ns", "and", "returns", "the", "result", "as", "a", "stringer", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L44-L54
test
ChrisTrenkamp/goxpath
goxpath.go
ExecBool
func (xp XPathExec) ExecBool(t tree.Node, opts ...FuncOpts) (bool, error) { res, err := xp.Exec(t, opts...) if err != nil { return false, err } b, ok := res.(tree.IsBool) if !ok { return false, fmt.Errorf("Cannot convert result to a boolean") } return bool(b.Bool()), nil }
go
func (xp XPathExec) ExecBool(t tree.Node, opts ...FuncOpts) (bool, error) { res, err := xp.Exec(t, opts...) if err != nil { return false, err } b, ok := res.(tree.IsBool) if !ok { return false, fmt.Errorf("Cannot convert result to a boolean") } return bool(b.Bool()), nil }
[ "func", "(", "xp", "XPathExec", ")", "ExecBool", "(", "t", "tree", ".", "Node", ",", "opts", "...", "FuncOpts", ")", "(", "bool", ",", "error", ")", "{", "res", ",", "err", ":=", "xp", ".", "Exec", "(", "t", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "b", ",", "ok", ":=", "res", ".", "(", "tree", ".", "IsBool", ")", "\n", "if", "!", "ok", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"Cannot convert result to a boolean\"", ")", "\n", "}", "\n", "return", "bool", "(", "b", ".", "Bool", "(", ")", ")", ",", "nil", "\n", "}" ]
//ExecBool is like Exec, except it will attempt to convert the result to its boolean value.
[ "ExecBool", "is", "like", "Exec", "except", "it", "will", "attempt", "to", "convert", "the", "result", "to", "its", "boolean", "value", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L57-L69
test
ChrisTrenkamp/goxpath
goxpath.go
ExecNum
func (xp XPathExec) ExecNum(t tree.Node, opts ...FuncOpts) (float64, error) { res, err := xp.Exec(t, opts...) if err != nil { return 0, err } n, ok := res.(tree.IsNum) if !ok { return 0, fmt.Errorf("Cannot convert result to a number") } return float64(n.Num()), nil }
go
func (xp XPathExec) ExecNum(t tree.Node, opts ...FuncOpts) (float64, error) { res, err := xp.Exec(t, opts...) if err != nil { return 0, err } n, ok := res.(tree.IsNum) if !ok { return 0, fmt.Errorf("Cannot convert result to a number") } return float64(n.Num()), nil }
[ "func", "(", "xp", "XPathExec", ")", "ExecNum", "(", "t", "tree", ".", "Node", ",", "opts", "...", "FuncOpts", ")", "(", "float64", ",", "error", ")", "{", "res", ",", "err", ":=", "xp", ".", "Exec", "(", "t", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "n", ",", "ok", ":=", "res", ".", "(", "tree", ".", "IsNum", ")", "\n", "if", "!", "ok", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"Cannot convert result to a number\"", ")", "\n", "}", "\n", "return", "float64", "(", "n", ".", "Num", "(", ")", ")", ",", "nil", "\n", "}" ]
//ExecNum is like Exec, except it will attempt to convert the result to its number value.
[ "ExecNum", "is", "like", "Exec", "except", "it", "will", "attempt", "to", "convert", "the", "result", "to", "its", "number", "value", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L72-L84
test
ChrisTrenkamp/goxpath
goxpath.go
ExecNode
func (xp XPathExec) ExecNode(t tree.Node, opts ...FuncOpts) (tree.NodeSet, error) { res, err := xp.Exec(t, opts...) if err != nil { return nil, err } n, ok := res.(tree.NodeSet) if !ok { return nil, fmt.Errorf("Cannot convert result to a node-set") } return n, nil }
go
func (xp XPathExec) ExecNode(t tree.Node, opts ...FuncOpts) (tree.NodeSet, error) { res, err := xp.Exec(t, opts...) if err != nil { return nil, err } n, ok := res.(tree.NodeSet) if !ok { return nil, fmt.Errorf("Cannot convert result to a node-set") } return n, nil }
[ "func", "(", "xp", "XPathExec", ")", "ExecNode", "(", "t", "tree", ".", "Node", ",", "opts", "...", "FuncOpts", ")", "(", "tree", ".", "NodeSet", ",", "error", ")", "{", "res", ",", "err", ":=", "xp", ".", "Exec", "(", "t", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "n", ",", "ok", ":=", "res", ".", "(", "tree", ".", "NodeSet", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Cannot convert result to a node-set\"", ")", "\n", "}", "\n", "return", "n", ",", "nil", "\n", "}" ]
//ExecNode is like Exec, except it will attempt to return the result as a node-set.
[ "ExecNode", "is", "like", "Exec", "except", "it", "will", "attempt", "to", "return", "the", "result", "as", "a", "node", "-", "set", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L87-L99
test
ChrisTrenkamp/goxpath
goxpath.go
MustExec
func (xp XPathExec) MustExec(t tree.Node, opts ...FuncOpts) tree.Result { res, err := xp.Exec(t, opts...) if err != nil { panic(err) } return res }
go
func (xp XPathExec) MustExec(t tree.Node, opts ...FuncOpts) tree.Result { res, err := xp.Exec(t, opts...) if err != nil { panic(err) } return res }
[ "func", "(", "xp", "XPathExec", ")", "MustExec", "(", "t", "tree", ".", "Node", ",", "opts", "...", "FuncOpts", ")", "tree", ".", "Result", "{", "res", ",", "err", ":=", "xp", ".", "Exec", "(", "t", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
//MustExec is like Exec, but panics instead of returning an error.
[ "MustExec", "is", "like", "Exec", "but", "panics", "instead", "of", "returning", "an", "error", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L102-L108
test
ChrisTrenkamp/goxpath
goxpath.go
ParseExec
func ParseExec(xpstr string, t tree.Node, opts ...FuncOpts) (tree.Result, error) { xp, err := Parse(xpstr) if err != nil { return nil, err } return xp.Exec(t, opts...) }
go
func ParseExec(xpstr string, t tree.Node, opts ...FuncOpts) (tree.Result, error) { xp, err := Parse(xpstr) if err != nil { return nil, err } return xp.Exec(t, opts...) }
[ "func", "ParseExec", "(", "xpstr", "string", ",", "t", "tree", ".", "Node", ",", "opts", "...", "FuncOpts", ")", "(", "tree", ".", "Result", ",", "error", ")", "{", "xp", ",", "err", ":=", "Parse", "(", "xpstr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "xp", ".", "Exec", "(", "t", ",", "opts", "...", ")", "\n", "}" ]
//ParseExec parses the XPath string, xpstr, and runs Exec.
[ "ParseExec", "parses", "the", "XPath", "string", "xpstr", "and", "runs", "Exec", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L111-L117
test
ChrisTrenkamp/goxpath
tree/xmltree/xmlele/xmlele.go
CreateNode
func (x *XMLEle) CreateNode(opts *xmlbuilder.BuilderOpts) xmlbuilder.XMLBuilder { if opts.NodeType == tree.NtElem { ele := &XMLEle{ StartElement: opts.Tok.(xml.StartElement), NSBuilder: tree.NSBuilder{NS: opts.NS}, Attrs: make([]tree.Node, len(opts.Attrs)), Parent: x, NodePos: tree.NodePos(opts.NodePos), NodeType: opts.NodeType, } for i := range opts.Attrs { ele.Attrs[i] = xmlnode.XMLNode{ Token: opts.Attrs[i], NodePos: tree.NodePos(opts.AttrStartPos + i), NodeType: tree.NtAttr, Parent: ele, } } x.Children = append(x.Children, ele) return ele } node := xmlnode.XMLNode{ Token: opts.Tok, NodePos: tree.NodePos(opts.NodePos), NodeType: opts.NodeType, Parent: x, } x.Children = append(x.Children, node) return x }
go
func (x *XMLEle) CreateNode(opts *xmlbuilder.BuilderOpts) xmlbuilder.XMLBuilder { if opts.NodeType == tree.NtElem { ele := &XMLEle{ StartElement: opts.Tok.(xml.StartElement), NSBuilder: tree.NSBuilder{NS: opts.NS}, Attrs: make([]tree.Node, len(opts.Attrs)), Parent: x, NodePos: tree.NodePos(opts.NodePos), NodeType: opts.NodeType, } for i := range opts.Attrs { ele.Attrs[i] = xmlnode.XMLNode{ Token: opts.Attrs[i], NodePos: tree.NodePos(opts.AttrStartPos + i), NodeType: tree.NtAttr, Parent: ele, } } x.Children = append(x.Children, ele) return ele } node := xmlnode.XMLNode{ Token: opts.Tok, NodePos: tree.NodePos(opts.NodePos), NodeType: opts.NodeType, Parent: x, } x.Children = append(x.Children, node) return x }
[ "func", "(", "x", "*", "XMLEle", ")", "CreateNode", "(", "opts", "*", "xmlbuilder", ".", "BuilderOpts", ")", "xmlbuilder", ".", "XMLBuilder", "{", "if", "opts", ".", "NodeType", "==", "tree", ".", "NtElem", "{", "ele", ":=", "&", "XMLEle", "{", "StartElement", ":", "opts", ".", "Tok", ".", "(", "xml", ".", "StartElement", ")", ",", "NSBuilder", ":", "tree", ".", "NSBuilder", "{", "NS", ":", "opts", ".", "NS", "}", ",", "Attrs", ":", "make", "(", "[", "]", "tree", ".", "Node", ",", "len", "(", "opts", ".", "Attrs", ")", ")", ",", "Parent", ":", "x", ",", "NodePos", ":", "tree", ".", "NodePos", "(", "opts", ".", "NodePos", ")", ",", "NodeType", ":", "opts", ".", "NodeType", ",", "}", "\n", "for", "i", ":=", "range", "opts", ".", "Attrs", "{", "ele", ".", "Attrs", "[", "i", "]", "=", "xmlnode", ".", "XMLNode", "{", "Token", ":", "opts", ".", "Attrs", "[", "i", "]", ",", "NodePos", ":", "tree", ".", "NodePos", "(", "opts", ".", "AttrStartPos", "+", "i", ")", ",", "NodeType", ":", "tree", ".", "NtAttr", ",", "Parent", ":", "ele", ",", "}", "\n", "}", "\n", "x", ".", "Children", "=", "append", "(", "x", ".", "Children", ",", "ele", ")", "\n", "return", "ele", "\n", "}", "\n", "node", ":=", "xmlnode", ".", "XMLNode", "{", "Token", ":", "opts", ".", "Tok", ",", "NodePos", ":", "tree", ".", "NodePos", "(", "opts", ".", "NodePos", ")", ",", "NodeType", ":", "opts", ".", "NodeType", ",", "Parent", ":", "x", ",", "}", "\n", "x", ".", "Children", "=", "append", "(", "x", ".", "Children", ",", "node", ")", "\n", "return", "x", "\n", "}" ]
//CreateNode is an implementation of xmlbuilder.XMLBuilder. It appends the node //specified in opts and returns the child if it is an element. Otherwise, it returns x.
[ "CreateNode", "is", "an", "implementation", "of", "xmlbuilder", ".", "XMLBuilder", ".", "It", "appends", "the", "node", "specified", "in", "opts", "and", "returns", "the", "child", "if", "it", "is", "an", "element", ".", "Otherwise", "it", "returns", "x", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlele/xmlele.go#L29-L59
test
ChrisTrenkamp/goxpath
tree/xmltree/xmlele/xmlele.go
GetChildren
func (x *XMLEle) GetChildren() []tree.Node { ret := make([]tree.Node, len(x.Children)) for i := range x.Children { ret[i] = x.Children[i] } return ret }
go
func (x *XMLEle) GetChildren() []tree.Node { ret := make([]tree.Node, len(x.Children)) for i := range x.Children { ret[i] = x.Children[i] } return ret }
[ "func", "(", "x", "*", "XMLEle", ")", "GetChildren", "(", ")", "[", "]", "tree", ".", "Node", "{", "ret", ":=", "make", "(", "[", "]", "tree", ".", "Node", ",", "len", "(", "x", ".", "Children", ")", ")", "\n", "for", "i", ":=", "range", "x", ".", "Children", "{", "ret", "[", "i", "]", "=", "x", ".", "Children", "[", "i", "]", "\n", "}", "\n", "return", "ret", "\n", "}" ]
//GetChildren returns all child nodes of the element
[ "GetChildren", "returns", "all", "child", "nodes", "of", "the", "element" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlele/xmlele.go#L77-L85
test