_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q180900 | Merge | test | func (d *APIDescriptor) Merge(other *APIDescriptor) error {
if d.Version != other.Version {
return fmt.Errorf("Can't merge API descriptors with different versions")
}
for _, name := range d.ResourceNames {
for _, otherName := range other.ResourceNames {
if name == otherName {
return fmt.Errorf("%s is a resource that exists in multiple APIs, generate separate clients", name)
}
}
}
for _, name := range d.TypeNames {
for i, otherName := range other.TypeNames {
if name == otherName {
newName := MakeUniq(otherName, append(d.TypeNames, other.TypeNames...))
first := other.TypeNames[:i]
last := append([]string{newName}, other.TypeNames[i+1:]...)
other.TypeNames = append(first, last...)
typ := other.Types[name]
delete(other.Types, name)
typ.TypeName = newName
other.Types[newName] = typ
}
}
}
for name, resource := range other.Resources {
d.Resources[name] = resource
}
for name, typ := range other.Types {
d.Types[name] = typ
}
d.ResourceNames = append(d.ResourceNames, other.ResourceNames...)
d.TypeNames = append(d.TypeNames, other.TypeNames...)
return nil
} | go | {
"resource": ""
} |
q180901 | FinalizeTypeNames | test | func (d *APIDescriptor) FinalizeTypeNames(rawTypes map[string][]*ObjectDataType) {
// 1. Make sure data type names don't clash with resource names
rawTypeNames := make([]string, len(rawTypes))
idx := 0
for n := range rawTypes {
rawTypeNames[idx] = n
idx++
}
sort.Strings(rawTypeNames)
for _, tn := range rawTypeNames {
types := rawTypes[tn]
for rn := range d.Resources {
if tn == rn {
oldTn := tn
if strings.HasSuffix(tn, "Param") {
tn = fmt.Sprintf("%s2", tn)
} else {
tn = fmt.Sprintf("%sParam", tn)
}
for _, ty := range types {
ty.TypeName = tn
}
rawTypes[tn] = types
delete(rawTypes, oldTn)
}
}
}
// 2. Make data type names unique
idx = 0
for n := range rawTypes {
rawTypeNames[idx] = n
idx++
}
sort.Strings(rawTypeNames)
for _, tn := range rawTypeNames {
types := rawTypes[tn]
first := types[0]
d.Types[tn] = first
if len(types) > 1 {
for i, ty := range types[1:] {
found := false
for j := 0; j < i+1; j++ {
if ty.IsEquivalent(types[j]) {
found = true
break
}
}
if !found {
newName := d.uniqueTypeName(tn)
ty.TypeName = newName
d.Types[newName] = ty
d.TypeNames = append(d.TypeNames, newName)
}
}
}
}
// 3. Finally initialize .ResourceNames and .TypeNames
idx = 0
resourceNames := make([]string, len(d.Resources))
for n := range d.Resources {
resourceNames[idx] = n
idx++
}
sort.Strings(resourceNames)
d.ResourceNames = resourceNames
typeNames := make([]string, len(d.Types))
idx = 0
for tn := range d.Types {
typeNames[idx] = tn
idx++
}
sort.Strings(typeNames)
d.TypeNames = typeNames
} | go | {
"resource": ""
} |
q180902 | uniqueTypeName | test | func (d *APIDescriptor) uniqueTypeName(prefix string) string {
u := fmt.Sprintf("%s%d", prefix, 2)
taken := false
for _, tn := range d.TypeNames {
if tn == u {
taken = true
break
}
}
idx := 3
for taken {
u = fmt.Sprintf("%s%d", prefix, idx)
taken = false
for _, tn := range d.TypeNames {
if tn == u {
taken = true
break
}
}
if taken {
idx++
}
}
return u
} | go | {
"resource": ""
} |
q180903 | MandatoryParams | test | func (a *Action) MandatoryParams() []*ActionParam {
m := make([]*ActionParam, len(a.Params))
i := 0
for _, p := range a.Params {
if p.Mandatory {
m[i] = p
i++
}
}
return m[:i]
} | go | {
"resource": ""
} |
q180904 | HasOptionalParams | test | func (a *Action) HasOptionalParams() bool {
for _, param := range a.Params {
if !param.Mandatory {
return true
}
}
return false
} | go | {
"resource": ""
} |
q180905 | MakeUniq | test | func MakeUniq(base string, taken []string) string {
idx := 1
uniq := base
inuse := true
for inuse {
inuse = false
for _, gn := range taken {
if gn == uniq {
inuse = true
break
}
}
if inuse {
idx++
uniq = base + strconv.Itoa(idx)
}
}
return uniq
} | go | {
"resource": ""
} |
q180906 | NewClientWriter | test | func NewClientWriter() (*ClientWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"commandLine": commandLine,
"parameters": parameters,
"paramsInitializer": paramsInitializer,
"blankCondition": blankCondition,
"stripStar": stripStar,
}
headerT, err := template.New("header-client").Funcs(funcMap).Parse(headerTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(resourceTmpl)
if err != nil {
return nil, err
}
return &ClientWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
} | go | {
"resource": ""
} |
q180907 | WriteHeader | test | func (c *ClientWriter) WriteHeader(pkg, version string, needTime, needJSON bool, w io.Writer) error {
ctx := map[string]interface{}{
"Pkg": pkg,
"APIVersion": version,
"NeedTime": needTime,
"NeedJSON": needJSON,
}
return c.headerTmpl.Execute(w, ctx)
} | go | {
"resource": ""
} |
q180908 | WriteResourceHeader | test | func (c *ClientWriter) WriteResourceHeader(name string, w io.Writer) {
fmt.Fprintf(w, "/****** %s ******/\n\n", name)
} | go | {
"resource": ""
} |
q180909 | WriteType | test | func (c *ClientWriter) WriteType(o *gen.ObjectDataType, w io.Writer) {
fields := make([]string, len(o.Fields))
for i, f := range o.Fields {
fields[i] = fmt.Sprintf("%s %s `json:\"%s,omitempty\"`", strings.Title(f.VarName),
f.Signature(), f.Name)
}
decl := fmt.Sprintf("type %s struct {\n%s\n}", o.TypeName,
strings.Join(fields, "\n\t"))
fmt.Fprintf(w, "%s\n\n", decl)
} | go | {
"resource": ""
} |
q180910 | WriteResource | test | func (c *ClientWriter) WriteResource(resource *gen.Resource, w io.Writer) error {
return c.resourceTmpl.Execute(w, resource)
} | go | {
"resource": ""
} |
q180911 | WithTrail | test | func (ec EvalCtx) WithTrail(t string) EvalCtx {
newEC := ec
trailCopy := make([]string, 0, len(ec.Trail)+1)
for _, val := range ec.Trail {
trailCopy = append(trailCopy, val)
}
newEC.Trail = append(trailCopy, t)
return newEC
} | go | {
"resource": ""
} |
q180912 | AnalyzeEndpoint | test | func (a *APIAnalyzer) AnalyzeEndpoint(verb string, path string, ep *Endpoint) error {
path = joinPath(a.Doc.BasePath, path)
dbg("\n------\nDEBUG AnalyzeEndpoint %s %s %+v\n", verb, path, ep)
pattern := toPattern(verb, path)
dbg("DEBUG AnalyzeEndpoint pattern %v\n", pattern)
svc := ep.Service()
// Get Resource -- base it on the service name for now
res := a.api.Resources[svc]
if res == nil {
res = &gen.Resource{
Name: svc,
ClientName: a.ClientName,
Actions: []*gen.Action{},
}
a.api.Resources[svc] = res
}
action := &gen.Action{
Name: ep.Method(),
MethodName: toMethodName(ep.Method()),
Description: cleanDescription(ep.Description),
ResourceName: svc,
PathPatterns: []*gen.PathPattern{pattern},
}
res.Actions = append(res.Actions, action)
var returnDT gen.DataType
var hasLocation bool
for code, response := range ep.Responses {
if code >= 300 {
continue
}
if response.Headers != nil {
if _, ok := response.Headers["Location"]; ok {
hasLocation = true
}
}
if response.Schema == nil {
dbg("DEBUG MISSING SCHEMA SKIP!\n")
break
}
dbg("DEBUG AnalyzeEndpoint %d RESPONSE %#v\n", code, response)
returnDef := a.Doc.Ref(response.Schema)
if returnDef != nil {
ec := EvalCtx{IsResult: true, Trail: nil, Svc: res, Method: action}
if mediaType(returnDef.Title) == "" {
warn("Warning: AnalyzeEndpoint: MediaType not set for %s, will be hard to guess the result type\n", response.Schema.ID())
continue
}
returnDT = a.AnalyzeDefinition(ec, returnDef, response.Schema.ID())
if returnObj, ok := returnDT.(*gen.ObjectDataType); ok {
isResourceType := verb == "get" && returnObj.TypeName == svc
dbg("DEBUG AnalyzeEndpoint Path %s Verb %s returnTypeName %s svc %s\n", path, verb, returnObj.TypeName, svc)
if isResourceType {
res.Description = cleanDescription(ep.Description)
res.Identifier = mediaType(returnDef.Title)
}
a.addType(ec, returnObj, response.Schema)
}
} else {
returnDT = basicType(response.Schema.Type())
}
break
}
for _, p := range ep.Parameters {
ec := EvalCtx{IsResult: false, Trail: nil, Svc: res, Method: action}
ap := a.AnalyzeParam(ec, p)
switch p.In {
case "header":
action.HeaderParamNames = append(action.HeaderParamNames, p.Name)
action.Params = append(action.Params, ap)
case "query":
action.QueryParamNames = append(action.QueryParamNames, p.Name)
action.Params = append(action.Params, ap)
case "path":
action.PathParamNames = append(action.PathParamNames, p.Name)
action.Params = append(action.Params, ap)
case "body":
def := a.Doc.Ref(p.Schema)
if def != nil {
if def.Type == "array" {
fail("Array type for body not implemented yet")
} else if def.Type == "object" {
// Flatten the first level of object
dt := a.AnalyzeDefinition(ec, def, p.Schema.ID())
if obj, ok := dt.(*gen.ObjectDataType); ok {
a.addType(ec, obj, p.Schema)
action.Payload = obj
for _, f := range obj.Fields {
action.PayloadParamNames = append(action.PayloadParamNames, f.Name)
action.Params = append(action.Params, f)
}
}
}
}
}
}
if returnDT != nil {
action.Return = signature(returnDT)
}
action.ReturnLocation = hasLocation
dbg("DEBUG ACTION %s", prettify(action))
return nil
} | go | {
"resource": ""
} |
q180913 | NetworkInterfaceLocator | test | func (api *API) NetworkInterfaceLocator(href string) *NetworkInterfaceLocator {
return &NetworkInterfaceLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180914 | NetworkInterfaceAttachmentLocator | test | func (api *API) NetworkInterfaceAttachmentLocator(href string) *NetworkInterfaceAttachmentLocator {
return &NetworkInterfaceAttachmentLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180915 | UnmarshalJSON | test | 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 | {
"resource": ""
} |
q180916 | ExecutionLocator | test | func (api *API) ExecutionLocator(href string) *ExecutionLocator {
return &ExecutionLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180917 | NotificationLocator | test | func (api *API) NotificationLocator(href string) *NotificationLocator {
return &NotificationLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180918 | OperationLocator | test | func (api *API) OperationLocator(href string) *OperationLocator {
return &OperationLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180919 | ScheduledActionLocator | test | func (api *API) ScheduledActionLocator(href string) *ScheduledActionLocator {
return &ScheduledActionLocator{Href(href), api}
} | go | {
"resource": ""
} |
q180920 | NewBasicAuthenticator | test | func NewBasicAuthenticator(username, password string, accountID int) Authenticator {
builder := basicLoginRequestBuilder{username: username, password: password, accountID: accountID}
return newCookieSigner(&builder, accountID)
} | go | {
"resource": ""
} |
q180921 | NewSSAuthenticator | test | 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 | {
"resource": ""
} |
q180922 | newCookieSigner | test | func newCookieSigner(builder loginRequestBuilder, accountID int) Authenticator {
return &cookieSigner{
builder: builder,
accountID: accountID,
refreshAt: time.Now().Add(-2 * time.Minute),
client: httpclient.NewNoRedirect(),
}
} | go | {
"resource": ""
} |
q180923 | Sign | test | 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 | {
"resource": ""
} |
q180924 | CanAuthenticate | test | func (s *cookieSigner) CanAuthenticate(host string) error {
_, instance := s.builder.(*instanceLoginRequestBuilder)
return testAuth(s, s.client, host, instance)
} | go | {
"resource": ""
} |
q180925 | refresh | test | 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 | {
"resource": ""
} |
q180926 | Sign | test | 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 | {
"resource": ""
} |
q180927 | Sign | test | func (a *rl10Authenticator) Sign(r *http.Request) error {
r.Header.Set("X-RLL-Secret", a.secret)
return nil
} | go | {
"resource": ""
} |
q180928 | Sign | test | 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 | {
"resource": ""
} |
q180929 | SetHost | test | 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 | {
"resource": ""
} |
q180930 | CanAuthenticate | test | 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 | {
"resource": ""
} |
q180931 | extractRedirectURL | test | 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 | {
"resource": ""
} |
q180932 | buildURL | test | 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 | {
"resource": ""
} |
q180933 | GetAction | test | func (r *Resource) GetAction(name string) *Action {
for _, a := range r.Actions {
if a.Name == name {
return a
}
}
return nil
} | go | {
"resource": ""
} |
q180934 | HasLink | test | func (r *Resource) HasLink(name string) bool {
for n, _ := range r.Links {
if n == name {
return true
}
}
return false
} | go | {
"resource": ""
} |
q180935 | findMatches | test | 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 | {
"resource": ""
} |
q180936 | NewPB | test | 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 | {
"resource": ""
} |
q180937 | newVariableDumpClient | test | 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 | {
"resource": ""
} |
q180938 | newRawClient | test | 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 | {
"resource": ""
} |
q180939 | DoHidden | test | func (d *dumpClient) DoHidden(req *http.Request) (*http.Response, error) {
return d.doImp(req, true, nil)
} | go | {
"resource": ""
} |
q180940 | Do | test | func (d *dumpClient) Do(req *http.Request) (*http.Response, error) {
return d.doImp(req, false, nil)
} | go | {
"resource": ""
} |
q180941 | doImp | test | 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 | {
"resource": ""
} |
q180942 | getClientWithoutTimeout | test | 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 | {
"resource": ""
} |
q180943 | dumpRequest | test | 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 | {
"resource": ""
} |
q180944 | writeHeaders | test | 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 | {
"resource": ""
} |
q180945 | copyHiddenHeaders | test | 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 | {
"resource": ""
} |
q180946 | validateCommandLine | test | 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 | {
"resource": ""
} |
q180947 | APIClient | test | 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 | {
"resource": ""
} |
q180948 | RegisterClientCommands | test | func RegisterClientCommands(app *kingpin.Application) {
cm15Cmd := app.Command(Cm15Command, cm15.APIName)
registrar := rsapi.Registrar{APICmd: cm15Cmd}
cm15.RegisterCommands(®istrar)
cm16Cmd := app.Command(Cm16Command, cm16.APIName)
registrar = rsapi.Registrar{APICmd: cm16Cmd}
cm16.RegisterCommands(®istrar)
ssCmd := app.Command(SsCommand, ss.APIName)
registrar = rsapi.Registrar{APICmd: ssCmd}
ss.RegisterCommands(®istrar)
rl10Cmd := app.Command(Rl10Command, rl10.APIName)
registrar = rsapi.Registrar{APICmd: rl10Cmd}
rl10.RegisterCommands(®istrar)
caCmd := app.Command(CaCommand, ca.APIName)
registrar = rsapi.Registrar{APICmd: caCmd}
ca.RegisterCommands(®istrar)
policyCmd := app.Command(PolicyCommand, policy.APIName)
registrar = rsapi.Registrar{APICmd: policyCmd}
policy.RegisterCommands(®istrar)
} | go | {
"resource": ""
} |
q180949 | Interactive | test | func Interactive() {
Logger.SetHandler(log15.MultiHandler(
log15.LvlFilterHandler(
log15.LvlError,
log15.StderrHandler)))
} | go | {
"resource": ""
} |
q180950 | toPattern | test | 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 | {
"resource": ""
} |
q180951 | WithClientIP | test | func WithClientIP(ctx context.Context, ip net.IP) context.Context {
if ip == nil {
return ctx
}
return context.WithValue(ctx, clientIPKey{}, ip)
} | go | {
"resource": ""
} |
q180952 | ClientIP | test | func ClientIP(ctx context.Context) net.IP {
ip, _ := ctx.Value(clientIPKey{}).(net.IP)
return ip
} | go | {
"resource": ""
} |
q180953 | NewProducer | test | 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 | {
"resource": ""
} |
q180954 | StartProducer | test | func StartProducer(config ProducerConfig) (p *Producer, err error) {
p, err = NewProducer(config)
if err != nil {
return
}
p.Start()
return
} | go | {
"resource": ""
} |
q180955 | Start | test | 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 | {
"resource": ""
} |
q180956 | Stop | test | 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 | {
"resource": ""
} |
q180957 | Publish | test | func (p *Producer) Publish(message []byte) (err error) {
return p.PublishTo(p.topic, message)
} | go | {
"resource": ""
} |
q180958 | PublishTo | test | 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 | {
"resource": ""
} |
q180959 | NewLocalEngine | test | 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 | {
"resource": ""
} |
q180960 | validate | test | 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 | {
"resource": ""
} |
q180961 | defaults | test | 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 | {
"resource": ""
} |
q180962 | NewConsumer | test | 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 | {
"resource": ""
} |
q180963 | StartConsumer | test | func StartConsumer(config ConsumerConfig) (c *Consumer, err error) {
c, err = NewConsumer(config)
if err != nil {
return
}
c.Start()
return
} | go | {
"resource": ""
} |
q180964 | Start | test | func (c *Consumer) Start() {
if c.started {
panic("(*Consumer).Start has already been called")
}
go c.run()
c.started = true
} | go | {
"resource": ""
} |
q180965 | RateLimit | test | 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 | {
"resource": ""
} |
q180966 | Write | test | func (r RawResponse) Write(w *bufio.Writer) error {
return writeResponse(w, []byte(r))
} | go | {
"resource": ""
} |
q180967 | ReadResponse | test | 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 | {
"resource": ""
} |
q180968 | backoff | test | 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 | {
"resource": ""
} |
q180969 | String | test | 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 | {
"resource": ""
} |
q180970 | NewConsulEngine | test | 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 | {
"resource": ""
} |
q180971 | ParseMessageID | test | func ParseMessageID(s string) (id MessageID, err error) {
var v uint64
v, err = strconv.ParseUint(s, 16, 64)
id = MessageID(v)
return
} | go | {
"resource": ""
} |
q180972 | WriteTo | test | 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 | {
"resource": ""
} |
q180973 | NewMessage | test | func NewMessage(id MessageID, body []byte, cmdChan chan<- Command) *Message {
return &Message{
ID: id,
Body: body,
cmdChan: cmdChan,
}
} | go | {
"resource": ""
} |
q180974 | Finish | test | 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 | {
"resource": ""
} |
q180975 | Requeue | test | 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 | {
"resource": ""
} |
q180976 | ReadCommand | test | 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 | {
"resource": ""
} |
q180977 | funcMapMaker | test | 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 | {
"resource": ""
} |
q180978 | Funcs | test | func (tmpl *Template) Funcs(funcMap template.FuncMap) *Template {
tmpl.funcMap = funcMap
return tmpl
} | go | {
"resource": ""
} |
q180979 | Execute | test | 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 | {
"resource": ""
} |
q180980 | RegisterPath | test | 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 | {
"resource": ""
} |
q180981 | Asset | test | 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 | {
"resource": ""
} |
q180982 | Glob | test | 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 | {
"resource": ""
} |
q180983 | NameSpace | test | 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 | {
"resource": ""
} |
q180984 | New | test | 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 | {
"resource": ""
} |
q180985 | RegisterViewPath | test | 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 | {
"resource": ""
} |
q180986 | SetAssetFS | test | func (render *Render) SetAssetFS(assetFS assetfs.Interface) {
for _, viewPath := range render.ViewPaths {
assetFS.RegisterPath(viewPath)
}
render.AssetFileSystem = assetFS
} | go | {
"resource": ""
} |
q180987 | Layout | test | func (render *Render) Layout(name string) *Template {
return &Template{render: render, layout: name}
} | go | {
"resource": ""
} |
q180988 | Funcs | test | func (render *Render) Funcs(funcMap template.FuncMap) *Template {
tmpl := &Template{render: render, usingDefaultLayout: true}
return tmpl.Funcs(funcMap)
} | go | {
"resource": ""
} |
q180989 | Execute | test | 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 | {
"resource": ""
} |
q180990 | RegisterFuncMap | test | func (render *Render) RegisterFuncMap(name string, fc interface{}) {
if render.funcMaps == nil {
render.funcMaps = template.FuncMap{}
}
render.funcMaps[name] = fc
} | go | {
"resource": ""
} |
q180991 | Asset | test | func (render *Render) Asset(name string) ([]byte, error) {
return render.AssetFileSystem.Asset(name)
} | go | {
"resource": ""
} |
q180992 | NewPlainClient | test | func NewPlainClient(identity, username, password string) Client {
return &plainClient{identity, username, password}
} | go | {
"resource": ""
} |
q180993 | Create | test | func Create(url string, h http.Header, c *Config) (io.WriteCloser, error) {
if c == nil {
c = DefaultConfig
}
return newUploader(url, h, c)
} | go | {
"resource": ""
} |
q180994 | Open | test | 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 | {
"resource": ""
} |
q180995 | Sign | test | func Sign(r *http.Request, k Keys) {
DefaultService.Sign(r, k)
} | go | {
"resource": ""
} |
q180996 | Sign | test | 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 | {
"resource": ""
} |
q180997 | Readdir | test | 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 | {
"resource": ""
} |
q180998 | Find | test | 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 | {
"resource": ""
} |
q180999 | Lex | test | func Lex(xpath string) chan XItem {
l := &Lexer{
input: xpath,
items: make(chan XItem),
}
go l.run()
return l.items
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.