id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
12,100 | mccutchen/go-httpbin | httpbin/handlers.go | Index | func (h *HTTPBin) Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' camo.githubusercontent.com")
writeHTML(w, assets.MustAsset("index.html"), http.StatusOK)
} | go | func (h *HTTPBin) Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' camo.githubusercontent.com")
writeHTML(w, assets.MustAsset("index.html"), http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Index",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"URL",
".",
"Path",
"!=",
"\"",
"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"writeHTML",
"(",
"w",
",",
"assets",
".",
"MustAsset",
"(",
"\"",
"\"",
")",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // Index renders an HTML index page | [
"Index",
"renders",
"an",
"HTML",
"index",
"page"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L32-L39 |
12,101 | mccutchen/go-httpbin | httpbin/handlers.go | Get | func (h *HTTPBin) Get(w http.ResponseWriter, r *http.Request) {
resp := &getResponse{
Args: r.URL.Query(),
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
URL: getURL(r).String(),
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
} | go | func (h *HTTPBin) Get(w http.ResponseWriter, r *http.Request) {
resp := &getResponse{
Args: r.URL.Query(),
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
URL: getURL(r).String(),
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Get",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"resp",
":=",
"&",
"getResponse",
"{",
"Args",
":",
"r",
".",
"URL",
".",
"Query",
"(",
")",
",",
"Headers",
":",
"getRequestHeaders",
"(",
"r",
")",
",",
"Origin",
":",
"getOrigin",
"(",
"r",
")",
",",
"URL",
":",
"getURL",
"(",
"r",
")",
".",
"String",
"(",
")",
",",
"}",
"\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"resp",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"body",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // Get handles HTTP GET requests | [
"Get",
"handles",
"HTTP",
"GET",
"requests"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L52-L61 |
12,102 | mccutchen/go-httpbin | httpbin/handlers.go | RequestWithBody | func (h *HTTPBin) RequestWithBody(w http.ResponseWriter, r *http.Request) {
resp := &bodyResponse{
Args: r.URL.Query(),
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
URL: getURL(r).String(),
}
err := parseBody(w, r, resp)
if err != nil {
http.Error(w, fmt.Sprintf("error parsing request body: %s", err), http.StatusBadRequest)
return
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
} | go | func (h *HTTPBin) RequestWithBody(w http.ResponseWriter, r *http.Request) {
resp := &bodyResponse{
Args: r.URL.Query(),
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
URL: getURL(r).String(),
}
err := parseBody(w, r, resp)
if err != nil {
http.Error(w, fmt.Sprintf("error parsing request body: %s", err), http.StatusBadRequest)
return
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"RequestWithBody",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"resp",
":=",
"&",
"bodyResponse",
"{",
"Args",
":",
"r",
".",
"URL",
".",
"Query",
"(",
")",
",",
"Headers",
":",
"getRequestHeaders",
"(",
"r",
")",
",",
"Origin",
":",
"getOrigin",
"(",
"r",
")",
",",
"URL",
":",
"getURL",
"(",
"r",
")",
".",
"String",
"(",
")",
",",
"}",
"\n\n",
"err",
":=",
"parseBody",
"(",
"w",
",",
"r",
",",
"resp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"resp",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"body",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // RequestWithBody handles POST, PUT, and PATCH requests | [
"RequestWithBody",
"handles",
"POST",
"PUT",
"and",
"PATCH",
"requests"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L64-L80 |
12,103 | mccutchen/go-httpbin | httpbin/handlers.go | Gzip | func (h *HTTPBin) Gzip(w http.ResponseWriter, r *http.Request) {
resp := &gzipResponse{
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
Gzipped: true,
}
body, _ := json.Marshal(resp)
buf := &bytes.Buffer{}
gzw := gzip.NewWriter(buf)
gzw.Write(body)
gzw.Close()
gzBody := buf.Bytes()
w.Header().Set("Content-Encoding", "gzip")
writeJSON(w, gzBody, http.StatusOK)
} | go | func (h *HTTPBin) Gzip(w http.ResponseWriter, r *http.Request) {
resp := &gzipResponse{
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
Gzipped: true,
}
body, _ := json.Marshal(resp)
buf := &bytes.Buffer{}
gzw := gzip.NewWriter(buf)
gzw.Write(body)
gzw.Close()
gzBody := buf.Bytes()
w.Header().Set("Content-Encoding", "gzip")
writeJSON(w, gzBody, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Gzip",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"resp",
":=",
"&",
"gzipResponse",
"{",
"Headers",
":",
"getRequestHeaders",
"(",
"r",
")",
",",
"Origin",
":",
"getOrigin",
"(",
"r",
")",
",",
"Gzipped",
":",
"true",
",",
"}",
"\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"resp",
")",
"\n\n",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"gzw",
":=",
"gzip",
".",
"NewWriter",
"(",
"buf",
")",
"\n",
"gzw",
".",
"Write",
"(",
"body",
")",
"\n",
"gzw",
".",
"Close",
"(",
")",
"\n\n",
"gzBody",
":=",
"buf",
".",
"Bytes",
"(",
")",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"gzBody",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // Gzip returns a gzipped response | [
"Gzip",
"returns",
"a",
"gzipped",
"response"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L83-L100 |
12,104 | mccutchen/go-httpbin | httpbin/handlers.go | Deflate | func (h *HTTPBin) Deflate(w http.ResponseWriter, r *http.Request) {
resp := &deflateResponse{
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
Deflated: true,
}
body, _ := json.Marshal(resp)
buf := &bytes.Buffer{}
w2 := zlib.NewWriter(buf)
w2.Write(body)
w2.Close()
compressedBody := buf.Bytes()
w.Header().Set("Content-Encoding", "deflate")
writeJSON(w, compressedBody, http.StatusOK)
} | go | func (h *HTTPBin) Deflate(w http.ResponseWriter, r *http.Request) {
resp := &deflateResponse{
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
Deflated: true,
}
body, _ := json.Marshal(resp)
buf := &bytes.Buffer{}
w2 := zlib.NewWriter(buf)
w2.Write(body)
w2.Close()
compressedBody := buf.Bytes()
w.Header().Set("Content-Encoding", "deflate")
writeJSON(w, compressedBody, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Deflate",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"resp",
":=",
"&",
"deflateResponse",
"{",
"Headers",
":",
"getRequestHeaders",
"(",
"r",
")",
",",
"Origin",
":",
"getOrigin",
"(",
"r",
")",
",",
"Deflated",
":",
"true",
",",
"}",
"\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"resp",
")",
"\n\n",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"w2",
":=",
"zlib",
".",
"NewWriter",
"(",
"buf",
")",
"\n",
"w2",
".",
"Write",
"(",
"body",
")",
"\n",
"w2",
".",
"Close",
"(",
")",
"\n\n",
"compressedBody",
":=",
"buf",
".",
"Bytes",
"(",
")",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"compressedBody",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // Deflate returns a gzipped response | [
"Deflate",
"returns",
"a",
"gzipped",
"response"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L103-L120 |
12,105 | mccutchen/go-httpbin | httpbin/handlers.go | IP | func (h *HTTPBin) IP(w http.ResponseWriter, r *http.Request) {
body, _ := json.Marshal(&ipResponse{
Origin: getOrigin(r),
})
writeJSON(w, body, http.StatusOK)
} | go | func (h *HTTPBin) IP(w http.ResponseWriter, r *http.Request) {
body, _ := json.Marshal(&ipResponse{
Origin: getOrigin(r),
})
writeJSON(w, body, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"IP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"&",
"ipResponse",
"{",
"Origin",
":",
"getOrigin",
"(",
"r",
")",
",",
"}",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"body",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // IP echoes the IP address of the incoming request | [
"IP",
"echoes",
"the",
"IP",
"address",
"of",
"the",
"incoming",
"request"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L123-L128 |
12,106 | mccutchen/go-httpbin | httpbin/handlers.go | UserAgent | func (h *HTTPBin) UserAgent(w http.ResponseWriter, r *http.Request) {
body, _ := json.Marshal(&userAgentResponse{
UserAgent: r.Header.Get("User-Agent"),
})
writeJSON(w, body, http.StatusOK)
} | go | func (h *HTTPBin) UserAgent(w http.ResponseWriter, r *http.Request) {
body, _ := json.Marshal(&userAgentResponse{
UserAgent: r.Header.Get("User-Agent"),
})
writeJSON(w, body, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"UserAgent",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"&",
"userAgentResponse",
"{",
"UserAgent",
":",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"}",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"body",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // UserAgent echoes the incoming User-Agent header | [
"UserAgent",
"echoes",
"the",
"incoming",
"User",
"-",
"Agent",
"header"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L131-L136 |
12,107 | mccutchen/go-httpbin | httpbin/handlers.go | Headers | func (h *HTTPBin) Headers(w http.ResponseWriter, r *http.Request) {
body, _ := json.Marshal(&headersResponse{
Headers: getRequestHeaders(r),
})
writeJSON(w, body, http.StatusOK)
} | go | func (h *HTTPBin) Headers(w http.ResponseWriter, r *http.Request) {
body, _ := json.Marshal(&headersResponse{
Headers: getRequestHeaders(r),
})
writeJSON(w, body, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Headers",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"&",
"headersResponse",
"{",
"Headers",
":",
"getRequestHeaders",
"(",
"r",
")",
",",
"}",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"body",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // Headers echoes the incoming request headers | [
"Headers",
"echoes",
"the",
"incoming",
"request",
"headers"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L139-L144 |
12,108 | mccutchen/go-httpbin | httpbin/handlers.go | ResponseHeaders | func (h *HTTPBin) ResponseHeaders(w http.ResponseWriter, r *http.Request) {
args := r.URL.Query()
for k, vs := range args {
for _, v := range vs {
w.Header().Add(http.CanonicalHeaderKey(k), v)
}
}
body, _ := json.Marshal(args)
if contentType := w.Header().Get("Content-Type"); contentType == "" {
w.Header().Set("Content-Type", jsonContentType)
}
w.Write(body)
} | go | func (h *HTTPBin) ResponseHeaders(w http.ResponseWriter, r *http.Request) {
args := r.URL.Query()
for k, vs := range args {
for _, v := range vs {
w.Header().Add(http.CanonicalHeaderKey(k), v)
}
}
body, _ := json.Marshal(args)
if contentType := w.Header().Get("Content-Type"); contentType == "" {
w.Header().Set("Content-Type", jsonContentType)
}
w.Write(body)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"ResponseHeaders",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"args",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"for",
"k",
",",
"vs",
":=",
"range",
"args",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vs",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"http",
".",
"CanonicalHeaderKey",
"(",
"k",
")",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"args",
")",
"\n",
"if",
"contentType",
":=",
"w",
".",
"Header",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"contentType",
"==",
"\"",
"\"",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"jsonContentType",
")",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"body",
")",
"\n",
"}"
] | // ResponseHeaders responds with a map of header values | [
"ResponseHeaders",
"responds",
"with",
"a",
"map",
"of",
"header",
"values"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L227-L239 |
12,109 | mccutchen/go-httpbin | httpbin/handlers.go | Redirect | func (h *HTTPBin) Redirect(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
relative := strings.ToLower(params.Get("absolute")) != "true"
doRedirect(w, r, relative)
} | go | func (h *HTTPBin) Redirect(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
relative := strings.ToLower(params.Get("absolute")) != "true"
doRedirect(w, r, relative)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Redirect",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"params",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"relative",
":=",
"strings",
".",
"ToLower",
"(",
"params",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"!=",
"\"",
"\"",
"\n",
"doRedirect",
"(",
"w",
",",
"r",
",",
"relative",
")",
"\n",
"}"
] | // Redirect responds with 302 redirect a given number of times. Defaults to a
// relative redirect, but an ?absolute=true query param will trigger an
// absolute redirect. | [
"Redirect",
"responds",
"with",
"302",
"redirect",
"a",
"given",
"number",
"of",
"times",
".",
"Defaults",
"to",
"a",
"relative",
"redirect",
"but",
"an",
"?absolute",
"=",
"true",
"query",
"param",
"will",
"trigger",
"an",
"absolute",
"redirect",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L284-L288 |
12,110 | mccutchen/go-httpbin | httpbin/handlers.go | RelativeRedirect | func (h *HTTPBin) RelativeRedirect(w http.ResponseWriter, r *http.Request) {
doRedirect(w, r, true)
} | go | func (h *HTTPBin) RelativeRedirect(w http.ResponseWriter, r *http.Request) {
doRedirect(w, r, true)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"RelativeRedirect",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"doRedirect",
"(",
"w",
",",
"r",
",",
"true",
")",
"\n",
"}"
] | // RelativeRedirect responds with an HTTP 302 redirect a given number of times | [
"RelativeRedirect",
"responds",
"with",
"an",
"HTTP",
"302",
"redirect",
"a",
"given",
"number",
"of",
"times"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L291-L293 |
12,111 | mccutchen/go-httpbin | httpbin/handlers.go | AbsoluteRedirect | func (h *HTTPBin) AbsoluteRedirect(w http.ResponseWriter, r *http.Request) {
doRedirect(w, r, false)
} | go | func (h *HTTPBin) AbsoluteRedirect(w http.ResponseWriter, r *http.Request) {
doRedirect(w, r, false)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"AbsoluteRedirect",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"doRedirect",
"(",
"w",
",",
"r",
",",
"false",
")",
"\n",
"}"
] | // AbsoluteRedirect responds with an HTTP 302 redirect a given number of times | [
"AbsoluteRedirect",
"responds",
"with",
"an",
"HTTP",
"302",
"redirect",
"a",
"given",
"number",
"of",
"times"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L296-L298 |
12,112 | mccutchen/go-httpbin | httpbin/handlers.go | RedirectTo | func (h *HTTPBin) RedirectTo(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
url := q.Get("url")
if url == "" {
http.Error(w, "Missing URL", http.StatusBadRequest)
return
}
var err error
statusCode := http.StatusFound
rawStatusCode := q.Get("status_code")
if rawStatusCode != "" {
statusCode, err = strconv.Atoi(q.Get("status_code"))
if err != nil || statusCode < 300 || statusCode > 399 {
http.Error(w, "Invalid status code", http.StatusBadRequest)
return
}
}
w.Header().Set("Location", url)
w.WriteHeader(statusCode)
} | go | func (h *HTTPBin) RedirectTo(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
url := q.Get("url")
if url == "" {
http.Error(w, "Missing URL", http.StatusBadRequest)
return
}
var err error
statusCode := http.StatusFound
rawStatusCode := q.Get("status_code")
if rawStatusCode != "" {
statusCode, err = strconv.Atoi(q.Get("status_code"))
if err != nil || statusCode < 300 || statusCode > 399 {
http.Error(w, "Invalid status code", http.StatusBadRequest)
return
}
}
w.Header().Set("Location", url)
w.WriteHeader(statusCode)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"RedirectTo",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"q",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n\n",
"url",
":=",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"url",
"==",
"\"",
"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"statusCode",
":=",
"http",
".",
"StatusFound",
"\n",
"rawStatusCode",
":=",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"rawStatusCode",
"!=",
"\"",
"\"",
"{",
"statusCode",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"statusCode",
"<",
"300",
"||",
"statusCode",
">",
"399",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"statusCode",
")",
"\n",
"}"
] | // RedirectTo responds with a redirect to a specific URL with an optional
// status code, which defaults to 302 | [
"RedirectTo",
"responds",
"with",
"a",
"redirect",
"to",
"a",
"specific",
"URL",
"with",
"an",
"optional",
"status",
"code",
"which",
"defaults",
"to",
"302"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L302-L324 |
12,113 | mccutchen/go-httpbin | httpbin/handlers.go | Cookies | func (h *HTTPBin) Cookies(w http.ResponseWriter, r *http.Request) {
resp := cookiesResponse{}
for _, c := range r.Cookies() {
resp[c.Name] = c.Value
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
} | go | func (h *HTTPBin) Cookies(w http.ResponseWriter, r *http.Request) {
resp := cookiesResponse{}
for _, c := range r.Cookies() {
resp[c.Name] = c.Value
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Cookies",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"resp",
":=",
"cookiesResponse",
"{",
"}",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"r",
".",
"Cookies",
"(",
")",
"{",
"resp",
"[",
"c",
".",
"Name",
"]",
"=",
"c",
".",
"Value",
"\n",
"}",
"\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"resp",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"body",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // Cookies responds with the cookies in the incoming request | [
"Cookies",
"responds",
"with",
"the",
"cookies",
"in",
"the",
"incoming",
"request"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L327-L334 |
12,114 | mccutchen/go-httpbin | httpbin/handlers.go | SetCookies | func (h *HTTPBin) SetCookies(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
for k := range params {
http.SetCookie(w, &http.Cookie{
Name: k,
Value: params.Get(k),
HttpOnly: true,
})
}
w.Header().Set("Location", "/cookies")
w.WriteHeader(http.StatusFound)
} | go | func (h *HTTPBin) SetCookies(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
for k := range params {
http.SetCookie(w, &http.Cookie{
Name: k,
Value: params.Get(k),
HttpOnly: true,
})
}
w.Header().Set("Location", "/cookies")
w.WriteHeader(http.StatusFound)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"SetCookies",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"params",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"for",
"k",
":=",
"range",
"params",
"{",
"http",
".",
"SetCookie",
"(",
"w",
",",
"&",
"http",
".",
"Cookie",
"{",
"Name",
":",
"k",
",",
"Value",
":",
"params",
".",
"Get",
"(",
"k",
")",
",",
"HttpOnly",
":",
"true",
",",
"}",
")",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusFound",
")",
"\n",
"}"
] | // SetCookies sets cookies as specified in query params and redirects to
// Cookies endpoint | [
"SetCookies",
"sets",
"cookies",
"as",
"specified",
"in",
"query",
"params",
"and",
"redirects",
"to",
"Cookies",
"endpoint"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L338-L349 |
12,115 | mccutchen/go-httpbin | httpbin/handlers.go | DeleteCookies | func (h *HTTPBin) DeleteCookies(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
for k := range params {
http.SetCookie(w, &http.Cookie{
Name: k,
Value: params.Get(k),
HttpOnly: true,
MaxAge: -1,
Expires: time.Now().Add(-1 * 24 * 365 * time.Hour),
})
}
w.Header().Set("Location", "/cookies")
w.WriteHeader(http.StatusFound)
} | go | func (h *HTTPBin) DeleteCookies(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
for k := range params {
http.SetCookie(w, &http.Cookie{
Name: k,
Value: params.Get(k),
HttpOnly: true,
MaxAge: -1,
Expires: time.Now().Add(-1 * 24 * 365 * time.Hour),
})
}
w.Header().Set("Location", "/cookies")
w.WriteHeader(http.StatusFound)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"DeleteCookies",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"params",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"for",
"k",
":=",
"range",
"params",
"{",
"http",
".",
"SetCookie",
"(",
"w",
",",
"&",
"http",
".",
"Cookie",
"{",
"Name",
":",
"k",
",",
"Value",
":",
"params",
".",
"Get",
"(",
"k",
")",
",",
"HttpOnly",
":",
"true",
",",
"MaxAge",
":",
"-",
"1",
",",
"Expires",
":",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"1",
"*",
"24",
"*",
"365",
"*",
"time",
".",
"Hour",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusFound",
")",
"\n",
"}"
] | // DeleteCookies deletes cookies specified in query params and redirects to
// Cookies endpoint | [
"DeleteCookies",
"deletes",
"cookies",
"specified",
"in",
"query",
"params",
"and",
"redirects",
"to",
"Cookies",
"endpoint"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L353-L366 |
12,116 | mccutchen/go-httpbin | httpbin/handlers.go | HiddenBasicAuth | func (h *HTTPBin) HiddenBasicAuth(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 4 {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
expectedUser := parts[2]
expectedPass := parts[3]
givenUser, givenPass, _ := r.BasicAuth()
authorized := givenUser == expectedUser && givenPass == expectedPass
if !authorized {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
body, _ := json.Marshal(&authResponse{
Authorized: authorized,
User: givenUser,
})
writeJSON(w, body, http.StatusOK)
} | go | func (h *HTTPBin) HiddenBasicAuth(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 4 {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
expectedUser := parts[2]
expectedPass := parts[3]
givenUser, givenPass, _ := r.BasicAuth()
authorized := givenUser == expectedUser && givenPass == expectedPass
if !authorized {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
body, _ := json.Marshal(&authResponse{
Authorized: authorized,
User: givenUser,
})
writeJSON(w, body, http.StatusOK)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"HiddenBasicAuth",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"4",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"expectedUser",
":=",
"parts",
"[",
"2",
"]",
"\n",
"expectedPass",
":=",
"parts",
"[",
"3",
"]",
"\n\n",
"givenUser",
",",
"givenPass",
",",
"_",
":=",
"r",
".",
"BasicAuth",
"(",
")",
"\n\n",
"authorized",
":=",
"givenUser",
"==",
"expectedUser",
"&&",
"givenPass",
"==",
"expectedPass",
"\n",
"if",
"!",
"authorized",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"&",
"authResponse",
"{",
"Authorized",
":",
"authorized",
",",
"User",
":",
"givenUser",
",",
"}",
")",
"\n",
"writeJSON",
"(",
"w",
",",
"body",
",",
"http",
".",
"StatusOK",
")",
"\n",
"}"
] | // HiddenBasicAuth requires HTTP Basic authentication but returns a status of
// 404 if the request is unauthorized | [
"HiddenBasicAuth",
"requires",
"HTTP",
"Basic",
"authentication",
"but",
"returns",
"a",
"status",
"of",
"404",
"if",
"the",
"request",
"is",
"unauthorized"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L396-L418 |
12,117 | mccutchen/go-httpbin | httpbin/handlers.go | Delay | func (h *HTTPBin) Delay(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
delay, err := parseBoundedDuration(parts[2], 0, h.MaxDuration)
if err != nil {
http.Error(w, "Invalid duration", http.StatusBadRequest)
return
}
select {
case <-r.Context().Done():
return
case <-time.After(delay):
}
h.RequestWithBody(w, r)
} | go | func (h *HTTPBin) Delay(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
delay, err := parseBoundedDuration(parts[2], 0, h.MaxDuration)
if err != nil {
http.Error(w, "Invalid duration", http.StatusBadRequest)
return
}
select {
case <-r.Context().Done():
return
case <-time.After(delay):
}
h.RequestWithBody(w, r)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Delay",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"delay",
",",
"err",
":=",
"parseBoundedDuration",
"(",
"parts",
"[",
"2",
"]",
",",
"0",
",",
"h",
".",
"MaxDuration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"r",
".",
"Context",
"(",
")",
".",
"Done",
"(",
")",
":",
"return",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"delay",
")",
":",
"}",
"\n",
"h",
".",
"RequestWithBody",
"(",
"w",
",",
"r",
")",
"\n",
"}"
] | // Delay waits for a given amount of time before responding, where the time may
// be specified as a golang-style duration or seconds in floating point. | [
"Delay",
"waits",
"for",
"a",
"given",
"amount",
"of",
"time",
"before",
"responding",
"where",
"the",
"time",
"may",
"be",
"specified",
"as",
"a",
"golang",
"-",
"style",
"duration",
"or",
"seconds",
"in",
"floating",
"point",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L458-L477 |
12,118 | mccutchen/go-httpbin | httpbin/handlers.go | Range | func (h *HTTPBin) Range(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
numBytes, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Add("ETag", fmt.Sprintf("range%d", numBytes))
w.Header().Add("Accept-Ranges", "bytes")
if numBytes <= 0 || numBytes > h.MaxBodySize {
http.Error(w, "Invalid number of bytes", http.StatusBadRequest)
return
}
content := newSyntheticByteStream(numBytes, func(offset int64) byte {
return byte(97 + (offset % 26))
})
var modtime time.Time
http.ServeContent(w, r, "", modtime, content)
} | go | func (h *HTTPBin) Range(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
numBytes, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Add("ETag", fmt.Sprintf("range%d", numBytes))
w.Header().Add("Accept-Ranges", "bytes")
if numBytes <= 0 || numBytes > h.MaxBodySize {
http.Error(w, "Invalid number of bytes", http.StatusBadRequest)
return
}
content := newSyntheticByteStream(numBytes, func(offset int64) byte {
return byte(97 + (offset % 26))
})
var modtime time.Time
http.ServeContent(w, r, "", modtime, content)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Range",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"numBytes",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"parts",
"[",
"2",
"]",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"numBytes",
")",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"numBytes",
"<=",
"0",
"||",
"numBytes",
">",
"h",
".",
"MaxBodySize",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"content",
":=",
"newSyntheticByteStream",
"(",
"numBytes",
",",
"func",
"(",
"offset",
"int64",
")",
"byte",
"{",
"return",
"byte",
"(",
"97",
"+",
"(",
"offset",
"%",
"26",
")",
")",
"\n",
"}",
")",
"\n",
"var",
"modtime",
"time",
".",
"Time",
"\n",
"http",
".",
"ServeContent",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"modtime",
",",
"content",
")",
"\n",
"}"
] | // Range returns up to N bytes, with support for HTTP Range requests.
//
// This departs from httpbin by not supporting the chunk_size or duration
// parameters. | [
"Range",
"returns",
"up",
"to",
"N",
"bytes",
"with",
"support",
"for",
"HTTP",
"Range",
"requests",
".",
"This",
"departs",
"from",
"httpbin",
"by",
"not",
"supporting",
"the",
"chunk_size",
"or",
"duration",
"parameters",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L560-L586 |
12,119 | mccutchen/go-httpbin | httpbin/handlers.go | Robots | func (h *HTTPBin) Robots(w http.ResponseWriter, r *http.Request) {
robotsTxt := []byte(`User-agent: *
Disallow: /deny
`)
writeResponse(w, http.StatusOK, "text/plain", robotsTxt)
} | go | func (h *HTTPBin) Robots(w http.ResponseWriter, r *http.Request) {
robotsTxt := []byte(`User-agent: *
Disallow: /deny
`)
writeResponse(w, http.StatusOK, "text/plain", robotsTxt)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Robots",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"robotsTxt",
":=",
"[",
"]",
"byte",
"(",
"`User-agent: *\nDisallow: /deny\n`",
")",
"\n",
"writeResponse",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"\"",
"\"",
",",
"robotsTxt",
")",
"\n",
"}"
] | // Robots renders a basic robots.txt file | [
"Robots",
"renders",
"a",
"basic",
"robots",
".",
"txt",
"file"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L594-L599 |
12,120 | mccutchen/go-httpbin | httpbin/handlers.go | Deny | func (h *HTTPBin) Deny(w http.ResponseWriter, r *http.Request) {
writeResponse(w, http.StatusOK, "text/plain", []byte(`YOU SHOULDN'T BE HERE`))
} | go | func (h *HTTPBin) Deny(w http.ResponseWriter, r *http.Request) {
writeResponse(w, http.StatusOK, "text/plain", []byte(`YOU SHOULDN'T BE HERE`))
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Deny",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"writeResponse",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"\"",
"\"",
",",
"[",
"]",
"byte",
"(",
"`YOU SHOULDN'T BE HERE`",
")",
")",
"\n",
"}"
] | // Deny renders a basic page that robots should never access | [
"Deny",
"renders",
"a",
"basic",
"page",
"that",
"robots",
"should",
"never",
"access"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L602-L604 |
12,121 | mccutchen/go-httpbin | httpbin/handlers.go | Cache | func (h *HTTPBin) Cache(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("If-Modified-Since") != "" || r.Header.Get("If-None-Match") != "" {
w.WriteHeader(http.StatusNotModified)
return
}
lastModified := time.Now().Format(time.RFC1123)
w.Header().Add("Last-Modified", lastModified)
w.Header().Add("ETag", sha1hash(lastModified))
h.Get(w, r)
} | go | func (h *HTTPBin) Cache(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("If-Modified-Since") != "" || r.Header.Get("If-None-Match") != "" {
w.WriteHeader(http.StatusNotModified)
return
}
lastModified := time.Now().Format(time.RFC1123)
w.Header().Add("Last-Modified", lastModified)
w.Header().Add("ETag", sha1hash(lastModified))
h.Get(w, r)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Cache",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"||",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotModified",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"lastModified",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"time",
".",
"RFC1123",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"lastModified",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"sha1hash",
"(",
"lastModified",
")",
")",
"\n",
"h",
".",
"Get",
"(",
"w",
",",
"r",
")",
"\n",
"}"
] | // Cache returns a 304 if an If-Modified-Since or an If-None-Match header is
// present, otherwise returns the same response as Get. | [
"Cache",
"returns",
"a",
"304",
"if",
"an",
"If",
"-",
"Modified",
"-",
"Since",
"or",
"an",
"If",
"-",
"None",
"-",
"Match",
"header",
"is",
"present",
"otherwise",
"returns",
"the",
"same",
"response",
"as",
"Get",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L608-L618 |
12,122 | mccutchen/go-httpbin | httpbin/handlers.go | ETag | func (h *HTTPBin) ETag(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
etag := parts[2]
w.Header().Set("ETag", fmt.Sprintf(`"%s"`, etag))
// TODO: This mostly duplicates the work of Get() above, should this be
// pulled into a little helper?
resp := &getResponse{
Args: r.URL.Query(),
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
URL: getURL(r).String(),
}
body, _ := json.Marshal(resp)
// Let http.ServeContent deal with If-None-Match and If-Match headers:
// https://golang.org/pkg/net/http/#ServeContent
http.ServeContent(w, r, "response.json", time.Now(), bytes.NewReader(body))
} | go | func (h *HTTPBin) ETag(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
etag := parts[2]
w.Header().Set("ETag", fmt.Sprintf(`"%s"`, etag))
// TODO: This mostly duplicates the work of Get() above, should this be
// pulled into a little helper?
resp := &getResponse{
Args: r.URL.Query(),
Headers: getRequestHeaders(r),
Origin: getOrigin(r),
URL: getURL(r).String(),
}
body, _ := json.Marshal(resp)
// Let http.ServeContent deal with If-None-Match and If-Match headers:
// https://golang.org/pkg/net/http/#ServeContent
http.ServeContent(w, r, "response.json", time.Now(), bytes.NewReader(body))
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"ETag",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"etag",
":=",
"parts",
"[",
"2",
"]",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"`\"%s\"`",
",",
"etag",
")",
")",
"\n\n",
"// TODO: This mostly duplicates the work of Get() above, should this be",
"// pulled into a little helper?",
"resp",
":=",
"&",
"getResponse",
"{",
"Args",
":",
"r",
".",
"URL",
".",
"Query",
"(",
")",
",",
"Headers",
":",
"getRequestHeaders",
"(",
"r",
")",
",",
"Origin",
":",
"getOrigin",
"(",
"r",
")",
",",
"URL",
":",
"getURL",
"(",
"r",
")",
".",
"String",
"(",
")",
",",
"}",
"\n",
"body",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"resp",
")",
"\n\n",
"// Let http.ServeContent deal with If-None-Match and If-Match headers:",
"// https://golang.org/pkg/net/http/#ServeContent",
"http",
".",
"ServeContent",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"time",
".",
"Now",
"(",
")",
",",
"bytes",
".",
"NewReader",
"(",
"body",
")",
")",
"\n",
"}"
] | // ETag assumes the resource has the given etag and response to If-None-Match
// and If-Match headers appropriately. | [
"ETag",
"assumes",
"the",
"resource",
"has",
"the",
"given",
"etag",
"and",
"response",
"to",
"If",
"-",
"None",
"-",
"Match",
"and",
"If",
"-",
"Match",
"headers",
"appropriately",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L640-L663 |
12,123 | mccutchen/go-httpbin | httpbin/handlers.go | Bytes | func (h *HTTPBin) Bytes(w http.ResponseWriter, r *http.Request) {
handleBytes(w, r, false)
} | go | func (h *HTTPBin) Bytes(w http.ResponseWriter, r *http.Request) {
handleBytes(w, r, false)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Bytes",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"handleBytes",
"(",
"w",
",",
"r",
",",
"false",
")",
"\n",
"}"
] | // Bytes returns N random bytes generated with an optional seed | [
"Bytes",
"returns",
"N",
"random",
"bytes",
"generated",
"with",
"an",
"optional",
"seed"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L666-L668 |
12,124 | mccutchen/go-httpbin | httpbin/handlers.go | StreamBytes | func (h *HTTPBin) StreamBytes(w http.ResponseWriter, r *http.Request) {
handleBytes(w, r, true)
} | go | func (h *HTTPBin) StreamBytes(w http.ResponseWriter, r *http.Request) {
handleBytes(w, r, true)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"StreamBytes",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"handleBytes",
"(",
"w",
",",
"r",
",",
"true",
")",
"\n",
"}"
] | // StreamBytes streams N random bytes generated with an optional seed in chunks
// of a given size. | [
"StreamBytes",
"streams",
"N",
"random",
"bytes",
"generated",
"with",
"an",
"optional",
"seed",
"in",
"chunks",
"of",
"a",
"given",
"size",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L672-L674 |
12,125 | mccutchen/go-httpbin | httpbin/handlers.go | handleBytes | func handleBytes(w http.ResponseWriter, r *http.Request, streaming bool) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
numBytes, err := strconv.Atoi(parts[2])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if numBytes < 1 {
numBytes = 1
} else if numBytes > 100*1024 {
numBytes = 100 * 1024
}
var chunkSize int
var write func([]byte)
if streaming {
if r.URL.Query().Get("chunk_size") != "" {
chunkSize, err = strconv.Atoi(r.URL.Query().Get("chunk_size"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
} else {
chunkSize = 10 * 1024
}
write = func() func(chunk []byte) {
f := w.(http.Flusher)
return func(chunk []byte) {
w.Write(chunk)
f.Flush()
}
}()
} else {
chunkSize = numBytes
write = func(chunk []byte) {
w.Header().Set("Content-Length", strconv.Itoa(len(chunk)))
w.Write(chunk)
}
}
var seed int64
rawSeed := r.URL.Query().Get("seed")
if rawSeed != "" {
seed, err = strconv.ParseInt(rawSeed, 10, 64)
if err != nil {
http.Error(w, "invalid seed", http.StatusBadRequest)
return
}
} else {
seed = time.Now().Unix()
}
src := rand.NewSource(seed)
rng := rand.New(src)
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
var chunk []byte
for i := 0; i < numBytes; i++ {
chunk = append(chunk, byte(rng.Intn(256)))
if len(chunk) == chunkSize {
write(chunk)
chunk = nil
}
}
if len(chunk) > 0 {
write(chunk)
}
} | go | func handleBytes(w http.ResponseWriter, r *http.Request, streaming bool) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
numBytes, err := strconv.Atoi(parts[2])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if numBytes < 1 {
numBytes = 1
} else if numBytes > 100*1024 {
numBytes = 100 * 1024
}
var chunkSize int
var write func([]byte)
if streaming {
if r.URL.Query().Get("chunk_size") != "" {
chunkSize, err = strconv.Atoi(r.URL.Query().Get("chunk_size"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
} else {
chunkSize = 10 * 1024
}
write = func() func(chunk []byte) {
f := w.(http.Flusher)
return func(chunk []byte) {
w.Write(chunk)
f.Flush()
}
}()
} else {
chunkSize = numBytes
write = func(chunk []byte) {
w.Header().Set("Content-Length", strconv.Itoa(len(chunk)))
w.Write(chunk)
}
}
var seed int64
rawSeed := r.URL.Query().Get("seed")
if rawSeed != "" {
seed, err = strconv.ParseInt(rawSeed, 10, 64)
if err != nil {
http.Error(w, "invalid seed", http.StatusBadRequest)
return
}
} else {
seed = time.Now().Unix()
}
src := rand.NewSource(seed)
rng := rand.New(src)
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
var chunk []byte
for i := 0; i < numBytes; i++ {
chunk = append(chunk, byte(rng.Intn(256)))
if len(chunk) == chunkSize {
write(chunk)
chunk = nil
}
}
if len(chunk) > 0 {
write(chunk)
}
} | [
"func",
"handleBytes",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"streaming",
"bool",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"numBytes",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"parts",
"[",
"2",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"numBytes",
"<",
"1",
"{",
"numBytes",
"=",
"1",
"\n",
"}",
"else",
"if",
"numBytes",
">",
"100",
"*",
"1024",
"{",
"numBytes",
"=",
"100",
"*",
"1024",
"\n",
"}",
"\n\n",
"var",
"chunkSize",
"int",
"\n",
"var",
"write",
"func",
"(",
"[",
"]",
"byte",
")",
"\n\n",
"if",
"streaming",
"{",
"if",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"chunkSize",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"chunkSize",
"=",
"10",
"*",
"1024",
"\n",
"}",
"\n\n",
"write",
"=",
"func",
"(",
")",
"func",
"(",
"chunk",
"[",
"]",
"byte",
")",
"{",
"f",
":=",
"w",
".",
"(",
"http",
".",
"Flusher",
")",
"\n",
"return",
"func",
"(",
"chunk",
"[",
"]",
"byte",
")",
"{",
"w",
".",
"Write",
"(",
"chunk",
")",
"\n",
"f",
".",
"Flush",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"else",
"{",
"chunkSize",
"=",
"numBytes",
"\n",
"write",
"=",
"func",
"(",
"chunk",
"[",
"]",
"byte",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"chunk",
")",
")",
")",
"\n",
"w",
".",
"Write",
"(",
"chunk",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"seed",
"int64",
"\n",
"rawSeed",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"rawSeed",
"!=",
"\"",
"\"",
"{",
"seed",
",",
"err",
"=",
"strconv",
".",
"ParseInt",
"(",
"rawSeed",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"seed",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"}",
"\n\n",
"src",
":=",
"rand",
".",
"NewSource",
"(",
"seed",
")",
"\n",
"rng",
":=",
"rand",
".",
"New",
"(",
"src",
")",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n\n",
"var",
"chunk",
"[",
"]",
"byte",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numBytes",
";",
"i",
"++",
"{",
"chunk",
"=",
"append",
"(",
"chunk",
",",
"byte",
"(",
"rng",
".",
"Intn",
"(",
"256",
")",
")",
")",
"\n",
"if",
"len",
"(",
"chunk",
")",
"==",
"chunkSize",
"{",
"write",
"(",
"chunk",
")",
"\n",
"chunk",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"chunk",
")",
">",
"0",
"{",
"write",
"(",
"chunk",
")",
"\n",
"}",
"\n",
"}"
] | // handleBytes consolidates the logic for validating input params of the Bytes
// and StreamBytes endpoints and knows how to write the response in chunks if
// streaming is true. | [
"handleBytes",
"consolidates",
"the",
"logic",
"for",
"validating",
"input",
"params",
"of",
"the",
"Bytes",
"and",
"StreamBytes",
"endpoints",
"and",
"knows",
"how",
"to",
"write",
"the",
"response",
"in",
"chunks",
"if",
"streaming",
"is",
"true",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L679-L756 |
12,126 | mccutchen/go-httpbin | httpbin/handlers.go | Links | func (h *HTTPBin) Links(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 && len(parts) != 4 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
n, err := strconv.Atoi(parts[2])
if err != nil || n < 0 || n > 256 {
http.Error(w, "Invalid link count", http.StatusBadRequest)
return
}
// Are we handling /links/<n>/<offset>? If so, render an HTML page
if len(parts) == 4 {
offset, err := strconv.Atoi(parts[3])
if err != nil {
http.Error(w, "Invalid offset", http.StatusBadRequest)
}
doLinksPage(w, r, n, offset)
return
}
// Otherwise, redirect from /links/<n> to /links/<n>/0
r.URL.Path = r.URL.Path + "/0"
w.Header().Set("Location", r.URL.String())
w.WriteHeader(http.StatusFound)
} | go | func (h *HTTPBin) Links(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 && len(parts) != 4 {
http.Error(w, "Not found", http.StatusNotFound)
return
}
n, err := strconv.Atoi(parts[2])
if err != nil || n < 0 || n > 256 {
http.Error(w, "Invalid link count", http.StatusBadRequest)
return
}
// Are we handling /links/<n>/<offset>? If so, render an HTML page
if len(parts) == 4 {
offset, err := strconv.Atoi(parts[3])
if err != nil {
http.Error(w, "Invalid offset", http.StatusBadRequest)
}
doLinksPage(w, r, n, offset)
return
}
// Otherwise, redirect from /links/<n> to /links/<n>/0
r.URL.Path = r.URL.Path + "/0"
w.Header().Set("Location", r.URL.String())
w.WriteHeader(http.StatusFound)
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"Links",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"&&",
"len",
"(",
"parts",
")",
"!=",
"4",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"n",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"parts",
"[",
"2",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"n",
"<",
"0",
"||",
"n",
">",
"256",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Are we handling /links/<n>/<offset>? If so, render an HTML page",
"if",
"len",
"(",
"parts",
")",
"==",
"4",
"{",
"offset",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"parts",
"[",
"3",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n",
"doLinksPage",
"(",
"w",
",",
"r",
",",
"n",
",",
"offset",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Otherwise, redirect from /links/<n> to /links/<n>/0",
"r",
".",
"URL",
".",
"Path",
"=",
"r",
".",
"URL",
".",
"Path",
"+",
"\"",
"\"",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"r",
".",
"URL",
".",
"String",
"(",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusFound",
")",
"\n",
"}"
] | // Links redirects to the first page in a series of N links | [
"Links",
"redirects",
"to",
"the",
"first",
"page",
"in",
"a",
"series",
"of",
"N",
"links"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L759-L786 |
12,127 | mccutchen/go-httpbin | httpbin/handlers.go | doLinksPage | func doLinksPage(w http.ResponseWriter, r *http.Request, n int, offset int) {
w.Header().Add("Content-Type", htmlContentType)
w.WriteHeader(http.StatusOK)
w.Write([]byte("<html><head><title>Links</title></head><body>"))
for i := 0; i < n; i++ {
if i == offset {
fmt.Fprintf(w, "%d ", i)
} else {
fmt.Fprintf(w, `<a href="/links/%d/%d">%d</a> `, n, i, i)
}
}
w.Write([]byte("</body></html>"))
} | go | func doLinksPage(w http.ResponseWriter, r *http.Request, n int, offset int) {
w.Header().Add("Content-Type", htmlContentType)
w.WriteHeader(http.StatusOK)
w.Write([]byte("<html><head><title>Links</title></head><body>"))
for i := 0; i < n; i++ {
if i == offset {
fmt.Fprintf(w, "%d ", i)
} else {
fmt.Fprintf(w, `<a href="/links/%d/%d">%d</a> `, n, i, i)
}
}
w.Write([]byte("</body></html>"))
} | [
"func",
"doLinksPage",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"n",
"int",
",",
"offset",
"int",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"htmlContentType",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"if",
"i",
"==",
"offset",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
",",
"i",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"`<a href=\"/links/%d/%d\">%d</a> `",
",",
"n",
",",
"i",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // doLinksPage renders a page with a series of N links | [
"doLinksPage",
"renders",
"a",
"page",
"with",
"a",
"series",
"of",
"N",
"links"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L789-L802 |
12,128 | mccutchen/go-httpbin | httpbin/handlers.go | ImageAccept | func (h *HTTPBin) ImageAccept(w http.ResponseWriter, r *http.Request) {
accept := r.Header.Get("Accept")
if accept == "" || strings.Contains(accept, "image/png") || strings.Contains(accept, "image/*") {
doImage(w, "png")
} else if strings.Contains(accept, "image/webp") {
doImage(w, "webp")
} else if strings.Contains(accept, "image/svg+xml") {
doImage(w, "svg")
} else if strings.Contains(accept, "image/jpeg") {
doImage(w, "jpeg")
} else {
http.Error(w, "Unsupported media type", http.StatusUnsupportedMediaType)
}
} | go | func (h *HTTPBin) ImageAccept(w http.ResponseWriter, r *http.Request) {
accept := r.Header.Get("Accept")
if accept == "" || strings.Contains(accept, "image/png") || strings.Contains(accept, "image/*") {
doImage(w, "png")
} else if strings.Contains(accept, "image/webp") {
doImage(w, "webp")
} else if strings.Contains(accept, "image/svg+xml") {
doImage(w, "svg")
} else if strings.Contains(accept, "image/jpeg") {
doImage(w, "jpeg")
} else {
http.Error(w, "Unsupported media type", http.StatusUnsupportedMediaType)
}
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"ImageAccept",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"accept",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"accept",
"==",
"\"",
"\"",
"||",
"strings",
".",
"Contains",
"(",
"accept",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"accept",
",",
"\"",
"\"",
")",
"{",
"doImage",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"Contains",
"(",
"accept",
",",
"\"",
"\"",
")",
"{",
"doImage",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"Contains",
"(",
"accept",
",",
"\"",
"\"",
")",
"{",
"doImage",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"Contains",
"(",
"accept",
",",
"\"",
"\"",
")",
"{",
"doImage",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusUnsupportedMediaType",
")",
"\n",
"}",
"\n",
"}"
] | // ImageAccept responds with an appropriate image based on the Accept header | [
"ImageAccept",
"responds",
"with",
"an",
"appropriate",
"image",
"based",
"on",
"the",
"Accept",
"header"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L805-L818 |
12,129 | mccutchen/go-httpbin | httpbin/handlers.go | doImage | func doImage(w http.ResponseWriter, kind string) {
img, err := assets.Asset("image." + kind)
if err != nil {
http.Error(w, "Not Found", http.StatusNotFound)
}
contentType := "image/" + kind
if kind == "svg" {
contentType = "image/svg+xml"
}
writeResponse(w, http.StatusOK, contentType, img)
} | go | func doImage(w http.ResponseWriter, kind string) {
img, err := assets.Asset("image." + kind)
if err != nil {
http.Error(w, "Not Found", http.StatusNotFound)
}
contentType := "image/" + kind
if kind == "svg" {
contentType = "image/svg+xml"
}
writeResponse(w, http.StatusOK, contentType, img)
} | [
"func",
"doImage",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"kind",
"string",
")",
"{",
"img",
",",
"err",
":=",
"assets",
".",
"Asset",
"(",
"\"",
"\"",
"+",
"kind",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"\n",
"contentType",
":=",
"\"",
"\"",
"+",
"kind",
"\n",
"if",
"kind",
"==",
"\"",
"\"",
"{",
"contentType",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"writeResponse",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"contentType",
",",
"img",
")",
"\n",
"}"
] | // doImage responds with a specific kind of image, if there is an image asset
// of the given kind. | [
"doImage",
"responds",
"with",
"a",
"specific",
"kind",
"of",
"image",
"if",
"there",
"is",
"an",
"image",
"asset",
"of",
"the",
"given",
"kind",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L832-L842 |
12,130 | mccutchen/go-httpbin | httpbin/handlers.go | XML | func (h *HTTPBin) XML(w http.ResponseWriter, r *http.Request) {
writeResponse(w, http.StatusOK, "application/xml", assets.MustAsset("sample.xml"))
} | go | func (h *HTTPBin) XML(w http.ResponseWriter, r *http.Request) {
writeResponse(w, http.StatusOK, "application/xml", assets.MustAsset("sample.xml"))
} | [
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"XML",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"writeResponse",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"\"",
"\"",
",",
"assets",
".",
"MustAsset",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // XML responds with an XML document | [
"XML",
"responds",
"with",
"an",
"XML",
"document"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/handlers.go#L845-L847 |
12,131 | mccutchen/go-httpbin | httpbin/middleware.go | autohead | func autohead(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "HEAD" {
w = &headResponseWriter{w}
}
h.ServeHTTP(w, r)
})
} | go | func autohead(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "HEAD" {
w = &headResponseWriter{w}
}
h.ServeHTTP(w, r)
})
} | [
"func",
"autohead",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"\"",
"\"",
"{",
"w",
"=",
"&",
"headResponseWriter",
"{",
"w",
"}",
"\n",
"}",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] | // autohead automatically discards the body of responses to HEAD requests | [
"autohead",
"automatically",
"discards",
"the",
"body",
"of",
"responses",
"to",
"HEAD",
"requests"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/middleware.go#L72-L79 |
12,132 | mccutchen/go-httpbin | httpbin/middleware.go | StdLogObserver | func StdLogObserver(l *log.Logger) Observer {
const (
logFmt = "time=%q status=%d method=%q uri=%q size_bytes=%d duration_ms=%0.02f"
dateFmt = "2006-01-02T15:04:05.9999"
)
return func(result Result) {
l.Printf(
logFmt,
time.Now().Format(dateFmt),
result.Status,
result.Method,
result.URI,
result.Size,
result.Duration.Seconds()*1e3, // https://github.com/golang/go/issues/5491#issuecomment-66079585
)
}
} | go | func StdLogObserver(l *log.Logger) Observer {
const (
logFmt = "time=%q status=%d method=%q uri=%q size_bytes=%d duration_ms=%0.02f"
dateFmt = "2006-01-02T15:04:05.9999"
)
return func(result Result) {
l.Printf(
logFmt,
time.Now().Format(dateFmt),
result.Status,
result.Method,
result.URI,
result.Size,
result.Duration.Seconds()*1e3, // https://github.com/golang/go/issues/5491#issuecomment-66079585
)
}
} | [
"func",
"StdLogObserver",
"(",
"l",
"*",
"log",
".",
"Logger",
")",
"Observer",
"{",
"const",
"(",
"logFmt",
"=",
"\"",
"\"",
"\n",
"dateFmt",
"=",
"\"",
"\"",
"\n",
")",
"\n",
"return",
"func",
"(",
"result",
"Result",
")",
"{",
"l",
".",
"Printf",
"(",
"logFmt",
",",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"dateFmt",
")",
",",
"result",
".",
"Status",
",",
"result",
".",
"Method",
",",
"result",
".",
"URI",
",",
"result",
".",
"Size",
",",
"result",
".",
"Duration",
".",
"Seconds",
"(",
")",
"*",
"1e3",
",",
"// https://github.com/golang/go/issues/5491#issuecomment-66079585",
")",
"\n",
"}",
"\n",
"}"
] | // StdLogObserver creates an Observer that will log each request in structured
// format using the given stdlib logger | [
"StdLogObserver",
"creates",
"an",
"Observer",
"that",
"will",
"log",
"each",
"request",
"in",
"structured",
"format",
"using",
"the",
"given",
"stdlib",
"logger"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/middleware.go#L150-L166 |
12,133 | mccutchen/go-httpbin | httpbin/helpers.go | getRequestHeaders | func getRequestHeaders(r *http.Request) http.Header {
h := r.Header
h.Set("Host", r.Host)
return h
} | go | func getRequestHeaders(r *http.Request) http.Header {
h := r.Header
h.Set("Host", r.Host)
return h
} | [
"func",
"getRequestHeaders",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"http",
".",
"Header",
"{",
"h",
":=",
"r",
".",
"Header",
"\n",
"h",
".",
"Set",
"(",
"\"",
"\"",
",",
"r",
".",
"Host",
")",
"\n",
"return",
"h",
"\n",
"}"
] | // requestHeaders takes in incoming request and returns an http.Header map
// suitable for inclusion in our response data structures.
//
// This is necessary to ensure that the incoming Host header is included,
// because golang only exposes that header on the http.Request struct itself. | [
"requestHeaders",
"takes",
"in",
"incoming",
"request",
"and",
"returns",
"an",
"http",
".",
"Header",
"map",
"suitable",
"for",
"inclusion",
"in",
"our",
"response",
"data",
"structures",
".",
"This",
"is",
"necessary",
"to",
"ensure",
"that",
"the",
"incoming",
"Host",
"header",
"is",
"included",
"because",
"golang",
"only",
"exposes",
"that",
"header",
"on",
"the",
"http",
".",
"Request",
"struct",
"itself",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/helpers.go#L24-L28 |
12,134 | mccutchen/go-httpbin | httpbin/helpers.go | parseDuration | func parseDuration(input string) (time.Duration, error) {
d, err := time.ParseDuration(input)
if err != nil {
n, err := strconv.ParseFloat(input, 64)
if err != nil {
return 0, err
}
d = time.Duration(n*1000) * time.Millisecond
}
return d, nil
} | go | func parseDuration(input string) (time.Duration, error) {
d, err := time.ParseDuration(input)
if err != nil {
n, err := strconv.ParseFloat(input, 64)
if err != nil {
return 0, err
}
d = time.Duration(n*1000) * time.Millisecond
}
return d, nil
} | [
"func",
"parseDuration",
"(",
"input",
"string",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"d",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"n",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"input",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"d",
"=",
"time",
".",
"Duration",
"(",
"n",
"*",
"1000",
")",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"\n",
"return",
"d",
",",
"nil",
"\n",
"}"
] | // parseDuration takes a user's input as a string and attempts to convert it
// into a time.Duration. If not given as a go-style duration string, the input
// is assumed to be seconds as a float. | [
"parseDuration",
"takes",
"a",
"user",
"s",
"input",
"as",
"a",
"string",
"and",
"attempts",
"to",
"convert",
"it",
"into",
"a",
"time",
".",
"Duration",
".",
"If",
"not",
"given",
"as",
"a",
"go",
"-",
"style",
"duration",
"string",
"the",
"input",
"is",
"assumed",
"to",
"be",
"seconds",
"as",
"a",
"float",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/helpers.go#L136-L146 |
12,135 | mccutchen/go-httpbin | httpbin/helpers.go | parseBoundedDuration | func parseBoundedDuration(input string, min, max time.Duration) (time.Duration, error) {
d, err := parseDuration(input)
if err != nil {
return 0, err
}
if d > max {
err = fmt.Errorf("duration %s longer than %s", d, max)
} else if d < min {
err = fmt.Errorf("duration %s shorter than %s", d, min)
}
return d, err
} | go | func parseBoundedDuration(input string, min, max time.Duration) (time.Duration, error) {
d, err := parseDuration(input)
if err != nil {
return 0, err
}
if d > max {
err = fmt.Errorf("duration %s longer than %s", d, max)
} else if d < min {
err = fmt.Errorf("duration %s shorter than %s", d, min)
}
return d, err
} | [
"func",
"parseBoundedDuration",
"(",
"input",
"string",
",",
"min",
",",
"max",
"time",
".",
"Duration",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"d",
",",
"err",
":=",
"parseDuration",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"d",
">",
"max",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
",",
"max",
")",
"\n",
"}",
"else",
"if",
"d",
"<",
"min",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
",",
"min",
")",
"\n",
"}",
"\n",
"return",
"d",
",",
"err",
"\n",
"}"
] | // parseBoundedDuration parses a time.Duration from user input and ensures that
// it is within a given maximum and minimum time | [
"parseBoundedDuration",
"parses",
"a",
"time",
".",
"Duration",
"from",
"user",
"input",
"and",
"ensures",
"that",
"it",
"is",
"within",
"a",
"given",
"maximum",
"and",
"minimum",
"time"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/helpers.go#L150-L162 |
12,136 | mccutchen/go-httpbin | httpbin/helpers.go | newSyntheticByteStream | func newSyntheticByteStream(size int64, factory func(int64) byte) io.ReadSeeker {
return &syntheticByteStream{
size: size,
factory: factory,
}
} | go | func newSyntheticByteStream(size int64, factory func(int64) byte) io.ReadSeeker {
return &syntheticByteStream{
size: size,
factory: factory,
}
} | [
"func",
"newSyntheticByteStream",
"(",
"size",
"int64",
",",
"factory",
"func",
"(",
"int64",
")",
"byte",
")",
"io",
".",
"ReadSeeker",
"{",
"return",
"&",
"syntheticByteStream",
"{",
"size",
":",
"size",
",",
"factory",
":",
"factory",
",",
"}",
"\n",
"}"
] | // newSyntheticByteStream returns a new stream of bytes of a specific size,
// given a factory function for generating the byte at a given offset. | [
"newSyntheticByteStream",
"returns",
"a",
"new",
"stream",
"of",
"bytes",
"of",
"a",
"specific",
"size",
"given",
"a",
"factory",
"function",
"for",
"generating",
"the",
"byte",
"at",
"a",
"given",
"offset",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/helpers.go#L177-L182 |
12,137 | mccutchen/go-httpbin | httpbin/helpers.go | Read | func (s *syntheticByteStream) Read(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
start := s.offset
end := start + int64(len(p))
var err error
if end >= s.size {
err = io.EOF
end = s.size
}
for idx := start; idx < end; idx++ {
p[idx-start] = s.factory(idx)
}
s.offset = end
return int(end - start), err
} | go | func (s *syntheticByteStream) Read(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
start := s.offset
end := start + int64(len(p))
var err error
if end >= s.size {
err = io.EOF
end = s.size
}
for idx := start; idx < end; idx++ {
p[idx-start] = s.factory(idx)
}
s.offset = end
return int(end - start), err
} | [
"func",
"(",
"s",
"*",
"syntheticByteStream",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"start",
":=",
"s",
".",
"offset",
"\n",
"end",
":=",
"start",
"+",
"int64",
"(",
"len",
"(",
"p",
")",
")",
"\n",
"var",
"err",
"error",
"\n",
"if",
"end",
">=",
"s",
".",
"size",
"{",
"err",
"=",
"io",
".",
"EOF",
"\n",
"end",
"=",
"s",
".",
"size",
"\n",
"}",
"\n\n",
"for",
"idx",
":=",
"start",
";",
"idx",
"<",
"end",
";",
"idx",
"++",
"{",
"p",
"[",
"idx",
"-",
"start",
"]",
"=",
"s",
".",
"factory",
"(",
"idx",
")",
"\n",
"}",
"\n\n",
"s",
".",
"offset",
"=",
"end",
"\n\n",
"return",
"int",
"(",
"end",
"-",
"start",
")",
",",
"err",
"\n",
"}"
] | // Read implements the Reader interface for syntheticByteStream | [
"Read",
"implements",
"the",
"Reader",
"interface",
"for",
"syntheticByteStream"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/helpers.go#L185-L204 |
12,138 | mccutchen/go-httpbin | httpbin/helpers.go | Seek | func (s *syntheticByteStream) Seek(offset int64, whence int) (int64, error) {
s.mu.Lock()
defer s.mu.Unlock()
switch whence {
case io.SeekStart:
s.offset = offset
case io.SeekCurrent:
s.offset += offset
case io.SeekEnd:
s.offset = s.size - offset
default:
return 0, errors.New("Seek: invalid whence")
}
if s.offset < 0 {
return 0, errors.New("Seek: invalid offset")
}
return s.offset, nil
} | go | func (s *syntheticByteStream) Seek(offset int64, whence int) (int64, error) {
s.mu.Lock()
defer s.mu.Unlock()
switch whence {
case io.SeekStart:
s.offset = offset
case io.SeekCurrent:
s.offset += offset
case io.SeekEnd:
s.offset = s.size - offset
default:
return 0, errors.New("Seek: invalid whence")
}
if s.offset < 0 {
return 0, errors.New("Seek: invalid offset")
}
return s.offset, nil
} | [
"func",
"(",
"s",
"*",
"syntheticByteStream",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"switch",
"whence",
"{",
"case",
"io",
".",
"SeekStart",
":",
"s",
".",
"offset",
"=",
"offset",
"\n",
"case",
"io",
".",
"SeekCurrent",
":",
"s",
".",
"offset",
"+=",
"offset",
"\n",
"case",
"io",
".",
"SeekEnd",
":",
"s",
".",
"offset",
"=",
"s",
".",
"size",
"-",
"offset",
"\n",
"default",
":",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"offset",
"<",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"s",
".",
"offset",
",",
"nil",
"\n",
"}"
] | // Seek implements the Seeker interface for syntheticByteStream | [
"Seek",
"implements",
"the",
"Seeker",
"interface",
"for",
"syntheticByteStream"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/helpers.go#L207-L227 |
12,139 | mccutchen/go-httpbin | httpbin/httpbin.go | New | func New(opts ...OptionFunc) *HTTPBin {
h := &HTTPBin{
MaxBodySize: DefaultMaxBodySize,
MaxDuration: DefaultMaxDuration,
}
for _, opt := range opts {
opt(h)
}
return h
} | go | func New(opts ...OptionFunc) *HTTPBin {
h := &HTTPBin{
MaxBodySize: DefaultMaxBodySize,
MaxDuration: DefaultMaxDuration,
}
for _, opt := range opts {
opt(h)
}
return h
} | [
"func",
"New",
"(",
"opts",
"...",
"OptionFunc",
")",
"*",
"HTTPBin",
"{",
"h",
":=",
"&",
"HTTPBin",
"{",
"MaxBodySize",
":",
"DefaultMaxBodySize",
",",
"MaxDuration",
":",
"DefaultMaxDuration",
",",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"h",
")",
"\n",
"}",
"\n",
"return",
"h",
"\n",
"}"
] | // New creates a new HTTPBin instance | [
"New",
"creates",
"a",
"new",
"HTTPBin",
"instance"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/httpbin.go#L184-L193 |
12,140 | mccutchen/go-httpbin | httpbin/httpbin.go | WithMaxDuration | func WithMaxDuration(d time.Duration) OptionFunc {
return func(h *HTTPBin) {
h.MaxDuration = d
}
} | go | func WithMaxDuration(d time.Duration) OptionFunc {
return func(h *HTTPBin) {
h.MaxDuration = d
}
} | [
"func",
"WithMaxDuration",
"(",
"d",
"time",
".",
"Duration",
")",
"OptionFunc",
"{",
"return",
"func",
"(",
"h",
"*",
"HTTPBin",
")",
"{",
"h",
".",
"MaxDuration",
"=",
"d",
"\n",
"}",
"\n",
"}"
] | // WithMaxDuration sets the maximum amount of time httpbin may take to respond | [
"WithMaxDuration",
"sets",
"the",
"maximum",
"amount",
"of",
"time",
"httpbin",
"may",
"take",
"to",
"respond"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/httpbin.go#L207-L211 |
12,141 | mccutchen/go-httpbin | httpbin/digest/digest.go | Check | func Check(req *http.Request, username, password string) bool {
auth := parseAuthorizationHeader(req.Header.Get("Authorization"))
if auth == nil || auth.username != username {
return false
}
expectedResponse := response(auth, password, req.Method, req.RequestURI)
return compare(auth.response, expectedResponse)
} | go | func Check(req *http.Request, username, password string) bool {
auth := parseAuthorizationHeader(req.Header.Get("Authorization"))
if auth == nil || auth.username != username {
return false
}
expectedResponse := response(auth, password, req.Method, req.RequestURI)
return compare(auth.response, expectedResponse)
} | [
"func",
"Check",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"username",
",",
"password",
"string",
")",
"bool",
"{",
"auth",
":=",
"parseAuthorizationHeader",
"(",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"auth",
"==",
"nil",
"||",
"auth",
".",
"username",
"!=",
"username",
"{",
"return",
"false",
"\n",
"}",
"\n",
"expectedResponse",
":=",
"response",
"(",
"auth",
",",
"password",
",",
"req",
".",
"Method",
",",
"req",
".",
"RequestURI",
")",
"\n",
"return",
"compare",
"(",
"auth",
".",
"response",
",",
"expectedResponse",
")",
"\n",
"}"
] | // Check returns a bool indicating whether the request is correctly
// authenticated for the given username and password. | [
"Check",
"returns",
"a",
"bool",
"indicating",
"whether",
"the",
"request",
"is",
"correctly",
"authenticated",
"for",
"the",
"given",
"username",
"and",
"password",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/digest/digest.go#L45-L52 |
12,142 | mccutchen/go-httpbin | httpbin/digest/digest.go | Challenge | func Challenge(realm string, algorithm digestAlgorithm) string {
entropy := make([]byte, 32)
rand.Read(entropy)
opaqueVal := entropy[:16]
nonceVal := fmt.Sprintf("%s:%x", time.Now(), entropy[16:31])
// we use MD5 to hash nonces regardless of hash used for authentication
opaque := hash(opaqueVal, MD5)
nonce := hash([]byte(nonceVal), MD5)
return fmt.Sprintf("Digest qop=auth, realm=%#v, algorithm=%s, nonce=%s, opaque=%s", sanitizeRealm(realm), algorithm, nonce, opaque)
} | go | func Challenge(realm string, algorithm digestAlgorithm) string {
entropy := make([]byte, 32)
rand.Read(entropy)
opaqueVal := entropy[:16]
nonceVal := fmt.Sprintf("%s:%x", time.Now(), entropy[16:31])
// we use MD5 to hash nonces regardless of hash used for authentication
opaque := hash(opaqueVal, MD5)
nonce := hash([]byte(nonceVal), MD5)
return fmt.Sprintf("Digest qop=auth, realm=%#v, algorithm=%s, nonce=%s, opaque=%s", sanitizeRealm(realm), algorithm, nonce, opaque)
} | [
"func",
"Challenge",
"(",
"realm",
"string",
",",
"algorithm",
"digestAlgorithm",
")",
"string",
"{",
"entropy",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"rand",
".",
"Read",
"(",
"entropy",
")",
"\n\n",
"opaqueVal",
":=",
"entropy",
"[",
":",
"16",
"]",
"\n",
"nonceVal",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"time",
".",
"Now",
"(",
")",
",",
"entropy",
"[",
"16",
":",
"31",
"]",
")",
"\n\n",
"// we use MD5 to hash nonces regardless of hash used for authentication",
"opaque",
":=",
"hash",
"(",
"opaqueVal",
",",
"MD5",
")",
"\n",
"nonce",
":=",
"hash",
"(",
"[",
"]",
"byte",
"(",
"nonceVal",
")",
",",
"MD5",
")",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sanitizeRealm",
"(",
"realm",
")",
",",
"algorithm",
",",
"nonce",
",",
"opaque",
")",
"\n",
"}"
] | // Challenge returns a WWW-Authenticate header value for the given realm and
// algorithm. If an invalid realm or an unsupported algorithm is given | [
"Challenge",
"returns",
"a",
"WWW",
"-",
"Authenticate",
"header",
"value",
"for",
"the",
"given",
"realm",
"and",
"algorithm",
".",
"If",
"an",
"invalid",
"realm",
"or",
"an",
"unsupported",
"algorithm",
"is",
"given"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/digest/digest.go#L56-L68 |
12,143 | mccutchen/go-httpbin | httpbin/digest/digest.go | sanitizeRealm | func sanitizeRealm(realm string) string {
realm = strings.Replace(realm, `"`, "", -1)
realm = strings.Replace(realm, ",", "", -1)
return realm
} | go | func sanitizeRealm(realm string) string {
realm = strings.Replace(realm, `"`, "", -1)
realm = strings.Replace(realm, ",", "", -1)
return realm
} | [
"func",
"sanitizeRealm",
"(",
"realm",
"string",
")",
"string",
"{",
"realm",
"=",
"strings",
".",
"Replace",
"(",
"realm",
",",
"`\"`",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"realm",
"=",
"strings",
".",
"Replace",
"(",
"realm",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"return",
"realm",
"\n",
"}"
] | // sanitizeRealm tries to ensure that a given realm does not include any
// characters that will trip up our extremely simplistic header parser. | [
"sanitizeRealm",
"tries",
"to",
"ensure",
"that",
"a",
"given",
"realm",
"does",
"not",
"include",
"any",
"characters",
"that",
"will",
"trip",
"up",
"our",
"extremely",
"simplistic",
"header",
"parser",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/digest/digest.go#L72-L76 |
12,144 | mccutchen/go-httpbin | httpbin/digest/digest.go | parseDictHeader | func parseDictHeader(value string) map[string]string {
pairs := strings.Split(value, ",")
res := make(map[string]string, len(pairs))
for _, pair := range pairs {
parts := strings.SplitN(strings.TrimSpace(pair), "=", 2)
key := strings.TrimSpace(parts[0])
if len(key) == 0 {
continue
}
val := ""
if len(parts) > 1 {
val = strings.TrimSpace(parts[1])
if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) {
val = val[1 : len(val)-1]
}
}
res[key] = val
}
return res
} | go | func parseDictHeader(value string) map[string]string {
pairs := strings.Split(value, ",")
res := make(map[string]string, len(pairs))
for _, pair := range pairs {
parts := strings.SplitN(strings.TrimSpace(pair), "=", 2)
key := strings.TrimSpace(parts[0])
if len(key) == 0 {
continue
}
val := ""
if len(parts) > 1 {
val = strings.TrimSpace(parts[1])
if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) {
val = val[1 : len(val)-1]
}
}
res[key] = val
}
return res
} | [
"func",
"parseDictHeader",
"(",
"value",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"pairs",
":=",
"strings",
".",
"Split",
"(",
"value",
",",
"\"",
"\"",
")",
"\n",
"res",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"pairs",
")",
")",
"\n",
"for",
"_",
",",
"pair",
":=",
"range",
"pairs",
"{",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"strings",
".",
"TrimSpace",
"(",
"pair",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"key",
":=",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"0",
"]",
")",
"\n",
"if",
"len",
"(",
"key",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"val",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"parts",
")",
">",
"1",
"{",
"val",
"=",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"1",
"]",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"val",
",",
"`\"`",
")",
"&&",
"strings",
".",
"HasSuffix",
"(",
"val",
",",
"`\"`",
")",
"{",
"val",
"=",
"val",
"[",
"1",
":",
"len",
"(",
"val",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"res",
"[",
"key",
"]",
"=",
"val",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] | // parseDictHeader is a simplistic, buggy, and incomplete implementation of
// parsing key-value pairs from a header value into a map. | [
"parseDictHeader",
"is",
"a",
"simplistic",
"buggy",
"and",
"incomplete",
"implementation",
"of",
"parsing",
"key",
"-",
"value",
"pairs",
"from",
"a",
"header",
"value",
"into",
"a",
"map",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/digest/digest.go#L143-L162 |
12,145 | mccutchen/go-httpbin | httpbin/digest/digest.go | hash | func hash(data []byte, algorithm digestAlgorithm) string {
switch algorithm {
case SHA256:
return fmt.Sprintf("%x", sha256.Sum256(data))
default:
return fmt.Sprintf("%x", md5.Sum(data))
}
} | go | func hash(data []byte, algorithm digestAlgorithm) string {
switch algorithm {
case SHA256:
return fmt.Sprintf("%x", sha256.Sum256(data))
default:
return fmt.Sprintf("%x", md5.Sum(data))
}
} | [
"func",
"hash",
"(",
"data",
"[",
"]",
"byte",
",",
"algorithm",
"digestAlgorithm",
")",
"string",
"{",
"switch",
"algorithm",
"{",
"case",
"SHA256",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sha256",
".",
"Sum256",
"(",
"data",
")",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"md5",
".",
"Sum",
"(",
"data",
")",
")",
"\n",
"}",
"\n",
"}"
] | // hash generates the hex digest of the given data using the given hashing
// algorithm, which must be one of MD5 or SHA256. | [
"hash",
"generates",
"the",
"hex",
"digest",
"of",
"the",
"given",
"data",
"using",
"the",
"given",
"hashing",
"algorithm",
"which",
"must",
"be",
"one",
"of",
"MD5",
"or",
"SHA256",
"."
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/digest/digest.go#L166-L173 |
12,146 | mccutchen/go-httpbin | httpbin/digest/digest.go | compare | func compare(x, y string) bool {
return subtle.ConstantTimeCompare([]byte(x), []byte(y)) == 1
} | go | func compare(x, y string) bool {
return subtle.ConstantTimeCompare([]byte(x), []byte(y)) == 1
} | [
"func",
"compare",
"(",
"x",
",",
"y",
"string",
")",
"bool",
"{",
"return",
"subtle",
".",
"ConstantTimeCompare",
"(",
"[",
"]",
"byte",
"(",
"x",
")",
",",
"[",
"]",
"byte",
"(",
"y",
")",
")",
"==",
"1",
"\n",
"}"
] | // compare is a constant-time string comparison | [
"compare",
"is",
"a",
"constant",
"-",
"time",
"string",
"comparison"
] | 24f381761ef06081553b1be8c87241688cdca845 | https://github.com/mccutchen/go-httpbin/blob/24f381761ef06081553b1be8c87241688cdca845/httpbin/digest/digest.go#L219-L221 |
12,147 | xanzy/ssh-agent | pageant_windows.go | query | func query(msg []byte) ([]byte, error) {
if len(msg) > MaxMessageLen {
return nil, ErrMessageTooLong
}
msgLen := binary.BigEndian.Uint32(msg[:4])
if len(msg) != int(msgLen)+4 {
return nil, ErrInvalidMessageFormat
}
lock.Lock()
defer lock.Unlock()
paWin := pageantWindow()
if paWin == 0 {
return nil, ErrPageantNotFound
}
thID, _, _ := winGetCurrentThreadID()
mapName := fmt.Sprintf("PageantRequest%08x", thID)
pMapName, _ := syscall.UTF16PtrFromString(mapName)
mmap, err := syscall.CreateFileMapping(syscall.InvalidHandle, nil, syscall.PAGE_READWRITE, 0, MaxMessageLen+4, pMapName)
if err != nil {
return nil, err
}
defer syscall.CloseHandle(mmap)
ptr, err := syscall.MapViewOfFile(mmap, syscall.FILE_MAP_WRITE, 0, 0, 0)
if err != nil {
return nil, err
}
defer syscall.UnmapViewOfFile(ptr)
mmSlice := (*(*[MaxMessageLen]byte)(unsafe.Pointer(ptr)))[:]
copy(mmSlice, msg)
mapNameBytesZ := append([]byte(mapName), 0)
cds := copyData{
dwData: agentCopydataID,
cbData: uint32(len(mapNameBytesZ)),
lpData: unsafe.Pointer(&(mapNameBytesZ[0])),
}
resp, _, _ := winSendMessage(paWin, wmCopydata, 0, uintptr(unsafe.Pointer(&cds)))
if resp == 0 {
return nil, ErrSendMessage
}
respLen := binary.BigEndian.Uint32(mmSlice[:4])
if respLen > MaxMessageLen-4 {
return nil, ErrResponseTooLong
}
respData := make([]byte, respLen+4)
copy(respData, mmSlice)
return respData, nil
} | go | func query(msg []byte) ([]byte, error) {
if len(msg) > MaxMessageLen {
return nil, ErrMessageTooLong
}
msgLen := binary.BigEndian.Uint32(msg[:4])
if len(msg) != int(msgLen)+4 {
return nil, ErrInvalidMessageFormat
}
lock.Lock()
defer lock.Unlock()
paWin := pageantWindow()
if paWin == 0 {
return nil, ErrPageantNotFound
}
thID, _, _ := winGetCurrentThreadID()
mapName := fmt.Sprintf("PageantRequest%08x", thID)
pMapName, _ := syscall.UTF16PtrFromString(mapName)
mmap, err := syscall.CreateFileMapping(syscall.InvalidHandle, nil, syscall.PAGE_READWRITE, 0, MaxMessageLen+4, pMapName)
if err != nil {
return nil, err
}
defer syscall.CloseHandle(mmap)
ptr, err := syscall.MapViewOfFile(mmap, syscall.FILE_MAP_WRITE, 0, 0, 0)
if err != nil {
return nil, err
}
defer syscall.UnmapViewOfFile(ptr)
mmSlice := (*(*[MaxMessageLen]byte)(unsafe.Pointer(ptr)))[:]
copy(mmSlice, msg)
mapNameBytesZ := append([]byte(mapName), 0)
cds := copyData{
dwData: agentCopydataID,
cbData: uint32(len(mapNameBytesZ)),
lpData: unsafe.Pointer(&(mapNameBytesZ[0])),
}
resp, _, _ := winSendMessage(paWin, wmCopydata, 0, uintptr(unsafe.Pointer(&cds)))
if resp == 0 {
return nil, ErrSendMessage
}
respLen := binary.BigEndian.Uint32(mmSlice[:4])
if respLen > MaxMessageLen-4 {
return nil, ErrResponseTooLong
}
respData := make([]byte, respLen+4)
copy(respData, mmSlice)
return respData, nil
} | [
"func",
"query",
"(",
"msg",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"msg",
")",
">",
"MaxMessageLen",
"{",
"return",
"nil",
",",
"ErrMessageTooLong",
"\n",
"}",
"\n\n",
"msgLen",
":=",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"msg",
"[",
":",
"4",
"]",
")",
"\n",
"if",
"len",
"(",
"msg",
")",
"!=",
"int",
"(",
"msgLen",
")",
"+",
"4",
"{",
"return",
"nil",
",",
"ErrInvalidMessageFormat",
"\n",
"}",
"\n\n",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"paWin",
":=",
"pageantWindow",
"(",
")",
"\n\n",
"if",
"paWin",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrPageantNotFound",
"\n",
"}",
"\n\n",
"thID",
",",
"_",
",",
"_",
":=",
"winGetCurrentThreadID",
"(",
")",
"\n",
"mapName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"thID",
")",
"\n",
"pMapName",
",",
"_",
":=",
"syscall",
".",
"UTF16PtrFromString",
"(",
"mapName",
")",
"\n\n",
"mmap",
",",
"err",
":=",
"syscall",
".",
"CreateFileMapping",
"(",
"syscall",
".",
"InvalidHandle",
",",
"nil",
",",
"syscall",
".",
"PAGE_READWRITE",
",",
"0",
",",
"MaxMessageLen",
"+",
"4",
",",
"pMapName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"syscall",
".",
"CloseHandle",
"(",
"mmap",
")",
"\n\n",
"ptr",
",",
"err",
":=",
"syscall",
".",
"MapViewOfFile",
"(",
"mmap",
",",
"syscall",
".",
"FILE_MAP_WRITE",
",",
"0",
",",
"0",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"syscall",
".",
"UnmapViewOfFile",
"(",
"ptr",
")",
"\n\n",
"mmSlice",
":=",
"(",
"*",
"(",
"*",
"[",
"MaxMessageLen",
"]",
"byte",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"ptr",
")",
")",
")",
"[",
":",
"]",
"\n\n",
"copy",
"(",
"mmSlice",
",",
"msg",
")",
"\n\n",
"mapNameBytesZ",
":=",
"append",
"(",
"[",
"]",
"byte",
"(",
"mapName",
")",
",",
"0",
")",
"\n\n",
"cds",
":=",
"copyData",
"{",
"dwData",
":",
"agentCopydataID",
",",
"cbData",
":",
"uint32",
"(",
"len",
"(",
"mapNameBytesZ",
")",
")",
",",
"lpData",
":",
"unsafe",
".",
"Pointer",
"(",
"&",
"(",
"mapNameBytesZ",
"[",
"0",
"]",
")",
")",
",",
"}",
"\n\n",
"resp",
",",
"_",
",",
"_",
":=",
"winSendMessage",
"(",
"paWin",
",",
"wmCopydata",
",",
"0",
",",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"cds",
")",
")",
")",
"\n\n",
"if",
"resp",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrSendMessage",
"\n",
"}",
"\n\n",
"respLen",
":=",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"mmSlice",
"[",
":",
"4",
"]",
")",
"\n",
"if",
"respLen",
">",
"MaxMessageLen",
"-",
"4",
"{",
"return",
"nil",
",",
"ErrResponseTooLong",
"\n",
"}",
"\n\n",
"respData",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"respLen",
"+",
"4",
")",
"\n",
"copy",
"(",
"respData",
",",
"mmSlice",
")",
"\n\n",
"return",
"respData",
",",
"nil",
"\n",
"}"
] | // Query sends message msg to Pageant and returns response or error.
// 'msg' is raw agent request with length prefix
// Response is raw agent response with length prefix | [
"Query",
"sends",
"message",
"msg",
"to",
"Pageant",
"and",
"returns",
"response",
"or",
"error",
".",
"msg",
"is",
"raw",
"agent",
"request",
"with",
"length",
"prefix",
"Response",
"is",
"raw",
"agent",
"response",
"with",
"length",
"prefix"
] | 6a3e2ff9e7c564f36873c2e36413f634534f1c44 | https://github.com/xanzy/ssh-agent/blob/6a3e2ff9e7c564f36873c2e36413f634534f1c44/pageant_windows.go#L78-L140 |
12,148 | xanzy/ssh-agent | sshagent.go | New | func New() (agent.Agent, net.Conn, error) {
if !Available() {
return nil, nil, errors.New("SSH agent requested but SSH_AUTH_SOCK not-specified")
}
sshAuthSock := os.Getenv("SSH_AUTH_SOCK")
conn, err := net.Dial("unix", sshAuthSock)
if err != nil {
return nil, nil, fmt.Errorf("Error connecting to SSH_AUTH_SOCK: %v", err)
}
return agent.NewClient(conn), conn, nil
} | go | func New() (agent.Agent, net.Conn, error) {
if !Available() {
return nil, nil, errors.New("SSH agent requested but SSH_AUTH_SOCK not-specified")
}
sshAuthSock := os.Getenv("SSH_AUTH_SOCK")
conn, err := net.Dial("unix", sshAuthSock)
if err != nil {
return nil, nil, fmt.Errorf("Error connecting to SSH_AUTH_SOCK: %v", err)
}
return agent.NewClient(conn), conn, nil
} | [
"func",
"New",
"(",
")",
"(",
"agent",
".",
"Agent",
",",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"if",
"!",
"Available",
"(",
")",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"sshAuthSock",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n\n",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"",
"\"",
",",
"sshAuthSock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"agent",
".",
"NewClient",
"(",
"conn",
")",
",",
"conn",
",",
"nil",
"\n",
"}"
] | // New returns a new agent.Agent that uses a unix socket | [
"New",
"returns",
"a",
"new",
"agent",
".",
"Agent",
"that",
"uses",
"a",
"unix",
"socket"
] | 6a3e2ff9e7c564f36873c2e36413f634534f1c44 | https://github.com/xanzy/ssh-agent/blob/6a3e2ff9e7c564f36873c2e36413f634534f1c44/sshagent.go#L31-L44 |
12,149 | steveyen/gtreap | treap.go | join | func (t *Treap) join(this *node, that *node) *node {
if this == nil {
return that
}
if that == nil {
return this
}
if this.priority > that.priority {
return &node{
item: this.item,
priority: this.priority,
left: this.left,
right: t.join(this.right, that),
}
}
return &node{
item: that.item,
priority: that.priority,
left: t.join(this, that.left),
right: that.right,
}
} | go | func (t *Treap) join(this *node, that *node) *node {
if this == nil {
return that
}
if that == nil {
return this
}
if this.priority > that.priority {
return &node{
item: this.item,
priority: this.priority,
left: this.left,
right: t.join(this.right, that),
}
}
return &node{
item: that.item,
priority: that.priority,
left: t.join(this, that.left),
right: that.right,
}
} | [
"func",
"(",
"t",
"*",
"Treap",
")",
"join",
"(",
"this",
"*",
"node",
",",
"that",
"*",
"node",
")",
"*",
"node",
"{",
"if",
"this",
"==",
"nil",
"{",
"return",
"that",
"\n",
"}",
"\n",
"if",
"that",
"==",
"nil",
"{",
"return",
"this",
"\n",
"}",
"\n",
"if",
"this",
".",
"priority",
">",
"that",
".",
"priority",
"{",
"return",
"&",
"node",
"{",
"item",
":",
"this",
".",
"item",
",",
"priority",
":",
"this",
".",
"priority",
",",
"left",
":",
"this",
".",
"left",
",",
"right",
":",
"t",
".",
"join",
"(",
"this",
".",
"right",
",",
"that",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"&",
"node",
"{",
"item",
":",
"that",
".",
"item",
",",
"priority",
":",
"that",
".",
"priority",
",",
"left",
":",
"t",
".",
"join",
"(",
"this",
",",
"that",
".",
"left",
")",
",",
"right",
":",
"that",
".",
"right",
",",
"}",
"\n",
"}"
] | // All the items from this are < items from that. | [
"All",
"the",
"items",
"from",
"this",
"are",
"<",
"items",
"from",
"that",
"."
] | 0abe01ef9be25c4aedc174758ec2d917314d6d70 | https://github.com/steveyen/gtreap/blob/0abe01ef9be25c4aedc174758ec2d917314d6d70/treap.go#L145-L166 |
12,150 | steveyen/gtreap | treap.go | VisitAscend | func (t *Treap) VisitAscend(pivot Item, visitor ItemVisitor) {
t.visitAscend(t.root, pivot, visitor)
} | go | func (t *Treap) VisitAscend(pivot Item, visitor ItemVisitor) {
t.visitAscend(t.root, pivot, visitor)
} | [
"func",
"(",
"t",
"*",
"Treap",
")",
"VisitAscend",
"(",
"pivot",
"Item",
",",
"visitor",
"ItemVisitor",
")",
"{",
"t",
".",
"visitAscend",
"(",
"t",
".",
"root",
",",
"pivot",
",",
"visitor",
")",
"\n",
"}"
] | // Visit items greater-than-or-equal to the pivot. | [
"Visit",
"items",
"greater",
"-",
"than",
"-",
"or",
"-",
"equal",
"to",
"the",
"pivot",
"."
] | 0abe01ef9be25c4aedc174758ec2d917314d6d70 | https://github.com/steveyen/gtreap/blob/0abe01ef9be25c4aedc174758ec2d917314d6d70/treap.go#L171-L173 |
12,151 | codemodus/parth | parth.go | Sequent | func Sequent(path, key string, v interface{}) error {
return SubSeg(path, key, 0, v)
} | go | func Sequent(path, key string, v interface{}) error {
return SubSeg(path, key, 0, v)
} | [
"func",
"Sequent",
"(",
"path",
",",
"key",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"SubSeg",
"(",
"path",
",",
"key",
",",
"0",
",",
"v",
")",
"\n",
"}"
] | // Sequent is similar to Segment, but uses a key to locate a segment and then
// unmarshal the subsequent segment. It is a simple wrapper over SubSeg with an
// index of 0. | [
"Sequent",
"is",
"similar",
"to",
"Segment",
"but",
"uses",
"a",
"key",
"to",
"locate",
"a",
"segment",
"and",
"then",
"unmarshal",
"the",
"subsequent",
"segment",
".",
"It",
"is",
"a",
"simple",
"wrapper",
"over",
"SubSeg",
"with",
"an",
"index",
"of",
"0",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L122-L124 |
12,152 | codemodus/parth | parth.go | SubSpan | func SubSpan(path, key string, i, j int) (string, error) {
si, ok := segIndexByKey(path, key)
if !ok {
return "", ErrKeySegNotFound
}
if i >= 0 {
i++
}
if j > 0 {
j++
}
s, err := Span(path[si:], i, j)
if err != nil {
return "", err
}
return s, nil
} | go | func SubSpan(path, key string, i, j int) (string, error) {
si, ok := segIndexByKey(path, key)
if !ok {
return "", ErrKeySegNotFound
}
if i >= 0 {
i++
}
if j > 0 {
j++
}
s, err := Span(path[si:], i, j)
if err != nil {
return "", err
}
return s, nil
} | [
"func",
"SubSpan",
"(",
"path",
",",
"key",
"string",
",",
"i",
",",
"j",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"si",
",",
"ok",
":=",
"segIndexByKey",
"(",
"path",
",",
"key",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"ErrKeySegNotFound",
"\n",
"}",
"\n\n",
"if",
"i",
">=",
"0",
"{",
"i",
"++",
"\n",
"}",
"\n",
"if",
"j",
">",
"0",
"{",
"j",
"++",
"\n",
"}",
"\n\n",
"s",
",",
"err",
":=",
"Span",
"(",
"path",
"[",
"si",
":",
"]",
",",
"i",
",",
"j",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // SubSpan is similar to Span, but only handles the portion of the path
// subsequent to the provided key. An error is returned if the key cannot be
// found in the path. | [
"SubSpan",
"is",
"similar",
"to",
"Span",
"but",
"only",
"handles",
"the",
"portion",
"of",
"the",
"path",
"subsequent",
"to",
"the",
"provided",
"key",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"key",
"cannot",
"be",
"found",
"in",
"the",
"path",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L251-L270 |
12,153 | codemodus/parth | parth.go | NewBySpan | func NewBySpan(path string, i, j int) *Parth {
s, err := Span(path, i, j)
return &Parth{s, err}
} | go | func NewBySpan(path string, i, j int) *Parth {
s, err := Span(path, i, j)
return &Parth{s, err}
} | [
"func",
"NewBySpan",
"(",
"path",
"string",
",",
"i",
",",
"j",
"int",
")",
"*",
"Parth",
"{",
"s",
",",
"err",
":=",
"Span",
"(",
"path",
",",
"i",
",",
"j",
")",
"\n",
"return",
"&",
"Parth",
"{",
"s",
",",
"err",
"}",
"\n",
"}"
] | // NewBySpan constructs a pointer to an instance of Parth after preprocessing
// the provided path with Span. | [
"NewBySpan",
"constructs",
"a",
"pointer",
"to",
"an",
"instance",
"of",
"Parth",
"after",
"preprocessing",
"the",
"provided",
"path",
"with",
"Span",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L287-L290 |
12,154 | codemodus/parth | parth.go | NewBySubSpan | func NewBySubSpan(path, key string, i, j int) *Parth {
s, err := SubSpan(path, key, i, j)
return &Parth{s, err}
} | go | func NewBySubSpan(path, key string, i, j int) *Parth {
s, err := SubSpan(path, key, i, j)
return &Parth{s, err}
} | [
"func",
"NewBySubSpan",
"(",
"path",
",",
"key",
"string",
",",
"i",
",",
"j",
"int",
")",
"*",
"Parth",
"{",
"s",
",",
"err",
":=",
"SubSpan",
"(",
"path",
",",
"key",
",",
"i",
",",
"j",
")",
"\n",
"return",
"&",
"Parth",
"{",
"s",
",",
"err",
"}",
"\n",
"}"
] | // NewBySubSpan constructs a pointer to an instance of Parth after
// preprocessing the provided path with SubSpan. | [
"NewBySubSpan",
"constructs",
"a",
"pointer",
"to",
"an",
"instance",
"of",
"Parth",
"after",
"preprocessing",
"the",
"provided",
"path",
"with",
"SubSpan",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L294-L297 |
12,155 | codemodus/parth | parth.go | Segment | func (p *Parth) Segment(i int, v interface{}) {
if p.err != nil {
return
}
p.err = Segment(p.path, i, v)
} | go | func (p *Parth) Segment(i int, v interface{}) {
if p.err != nil {
return
}
p.err = Segment(p.path, i, v)
} | [
"func",
"(",
"p",
"*",
"Parth",
")",
"Segment",
"(",
"i",
"int",
",",
"v",
"interface",
"{",
"}",
")",
"{",
"if",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"err",
"=",
"Segment",
"(",
"p",
".",
"path",
",",
"i",
",",
"v",
")",
"\n",
"}"
] | // Segment operates the same as the package-level function Segment. | [
"Segment",
"operates",
"the",
"same",
"as",
"the",
"package",
"-",
"level",
"function",
"Segment",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L305-L311 |
12,156 | codemodus/parth | parth.go | Sequent | func (p *Parth) Sequent(key string, v interface{}) {
p.SubSeg(key, 0, v)
} | go | func (p *Parth) Sequent(key string, v interface{}) {
p.SubSeg(key, 0, v)
} | [
"func",
"(",
"p",
"*",
"Parth",
")",
"Sequent",
"(",
"key",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"{",
"p",
".",
"SubSeg",
"(",
"key",
",",
"0",
",",
"v",
")",
"\n",
"}"
] | // Sequent operates the same as the package-level function Sequent. | [
"Sequent",
"operates",
"the",
"same",
"as",
"the",
"package",
"-",
"level",
"function",
"Sequent",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L314-L316 |
12,157 | codemodus/parth | parth.go | Span | func (p *Parth) Span(i, j int) string {
if p.err != nil {
return ""
}
s, err := Span(p.path, i, j)
p.err = err
return s
} | go | func (p *Parth) Span(i, j int) string {
if p.err != nil {
return ""
}
s, err := Span(p.path, i, j)
p.err = err
return s
} | [
"func",
"(",
"p",
"*",
"Parth",
")",
"Span",
"(",
"i",
",",
"j",
"int",
")",
"string",
"{",
"if",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"s",
",",
"err",
":=",
"Span",
"(",
"p",
".",
"path",
",",
"i",
",",
"j",
")",
"\n",
"p",
".",
"err",
"=",
"err",
"\n\n",
"return",
"s",
"\n",
"}"
] | // Span operates the same as the package-level function Span. | [
"Span",
"operates",
"the",
"same",
"as",
"the",
"package",
"-",
"level",
"function",
"Span",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L319-L328 |
12,158 | codemodus/parth | parth.go | SubSeg | func (p *Parth) SubSeg(key string, i int, v interface{}) {
if p.err != nil {
return
}
p.err = SubSeg(p.path, key, i, v)
} | go | func (p *Parth) SubSeg(key string, i int, v interface{}) {
if p.err != nil {
return
}
p.err = SubSeg(p.path, key, i, v)
} | [
"func",
"(",
"p",
"*",
"Parth",
")",
"SubSeg",
"(",
"key",
"string",
",",
"i",
"int",
",",
"v",
"interface",
"{",
"}",
")",
"{",
"if",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"err",
"=",
"SubSeg",
"(",
"p",
".",
"path",
",",
"key",
",",
"i",
",",
"v",
")",
"\n",
"}"
] | // SubSeg operates the same as the package-level function SubSeg. | [
"SubSeg",
"operates",
"the",
"same",
"as",
"the",
"package",
"-",
"level",
"function",
"SubSeg",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L331-L337 |
12,159 | codemodus/parth | parth.go | SubSpan | func (p *Parth) SubSpan(key string, i, j int) string {
if p.err != nil {
return ""
}
s, err := SubSpan(p.path, key, i, j)
p.err = err
return s
} | go | func (p *Parth) SubSpan(key string, i, j int) string {
if p.err != nil {
return ""
}
s, err := SubSpan(p.path, key, i, j)
p.err = err
return s
} | [
"func",
"(",
"p",
"*",
"Parth",
")",
"SubSpan",
"(",
"key",
"string",
",",
"i",
",",
"j",
"int",
")",
"string",
"{",
"if",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"s",
",",
"err",
":=",
"SubSpan",
"(",
"p",
".",
"path",
",",
"key",
",",
"i",
",",
"j",
")",
"\n",
"p",
".",
"err",
"=",
"err",
"\n\n",
"return",
"s",
"\n",
"}"
] | // SubSpan operates the same as the package-level function SubSpan. | [
"SubSpan",
"operates",
"the",
"same",
"as",
"the",
"package",
"-",
"level",
"function",
"SubSpan",
"."
] | 65f24a70f1b23677921ebfbfc9040627234cd786 | https://github.com/codemodus/parth/blob/65f24a70f1b23677921ebfbfc9040627234cd786/parth.go#L340-L349 |
12,160 | spkg/bom | bom.go | Clean | func Clean(b []byte) []byte {
if len(b) >= 3 &&
b[0] == bom0 &&
b[1] == bom1 &&
b[2] == bom2 {
return b[3:]
}
return b
} | go | func Clean(b []byte) []byte {
if len(b) >= 3 &&
b[0] == bom0 &&
b[1] == bom1 &&
b[2] == bom2 {
return b[3:]
}
return b
} | [
"func",
"Clean",
"(",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"len",
"(",
"b",
")",
">=",
"3",
"&&",
"b",
"[",
"0",
"]",
"==",
"bom0",
"&&",
"b",
"[",
"1",
"]",
"==",
"bom1",
"&&",
"b",
"[",
"2",
"]",
"==",
"bom2",
"{",
"return",
"b",
"[",
"3",
":",
"]",
"\n",
"}",
"\n",
"return",
"b",
"\n",
"}"
] | // Clean returns b with the 3 byte BOM stripped off the front if it is present.
// If the BOM is not present, then b is returned. | [
"Clean",
"returns",
"b",
"with",
"the",
"3",
"byte",
"BOM",
"stripped",
"off",
"the",
"front",
"if",
"it",
"is",
"present",
".",
"If",
"the",
"BOM",
"is",
"not",
"present",
"then",
"b",
"is",
"returned",
"."
] | 59b7046e48ad6bac800c5e1dd5142282cbfcf154 | https://github.com/spkg/bom/blob/59b7046e48ad6bac800c5e1dd5142282cbfcf154/bom.go#L17-L25 |
12,161 | spkg/bom | bom.go | NewReader | func NewReader(r io.Reader) io.Reader {
buf := bufio.NewReader(r)
b, err := buf.Peek(3)
if err != nil {
// not enough bytes
return buf
}
if b[0] == bom0 && b[1] == bom1 && b[2] == bom2 {
discardBytes(buf, 3)
}
return buf
} | go | func NewReader(r io.Reader) io.Reader {
buf := bufio.NewReader(r)
b, err := buf.Peek(3)
if err != nil {
// not enough bytes
return buf
}
if b[0] == bom0 && b[1] == bom1 && b[2] == bom2 {
discardBytes(buf, 3)
}
return buf
} | [
"func",
"NewReader",
"(",
"r",
"io",
".",
"Reader",
")",
"io",
".",
"Reader",
"{",
"buf",
":=",
"bufio",
".",
"NewReader",
"(",
"r",
")",
"\n",
"b",
",",
"err",
":=",
"buf",
".",
"Peek",
"(",
"3",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// not enough bytes",
"return",
"buf",
"\n",
"}",
"\n",
"if",
"b",
"[",
"0",
"]",
"==",
"bom0",
"&&",
"b",
"[",
"1",
"]",
"==",
"bom1",
"&&",
"b",
"[",
"2",
"]",
"==",
"bom2",
"{",
"discardBytes",
"(",
"buf",
",",
"3",
")",
"\n",
"}",
"\n",
"return",
"buf",
"\n",
"}"
] | // NewReader returns an io.Reader that will skip over initial UTF-8 byte order marks. | [
"NewReader",
"returns",
"an",
"io",
".",
"Reader",
"that",
"will",
"skip",
"over",
"initial",
"UTF",
"-",
"8",
"byte",
"order",
"marks",
"."
] | 59b7046e48ad6bac800c5e1dd5142282cbfcf154 | https://github.com/spkg/bom/blob/59b7046e48ad6bac800c5e1dd5142282cbfcf154/bom.go#L28-L39 |
12,162 | piotrkowalczuk/promgrpc | v3/prometheus.go | TagConn | func (i *Interceptor) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context {
return context.WithValue(ctx, tagConnKey, prometheus.Labels{
"remote_addr": info.RemoteAddr.String(),
"local_addr": info.LocalAddr.String(),
})
} | go | func (i *Interceptor) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context {
return context.WithValue(ctx, tagConnKey, prometheus.Labels{
"remote_addr": info.RemoteAddr.String(),
"local_addr": info.LocalAddr.String(),
})
} | [
"func",
"(",
"i",
"*",
"Interceptor",
")",
"TagConn",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"*",
"stats",
".",
"ConnTagInfo",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"tagConnKey",
",",
"prometheus",
".",
"Labels",
"{",
"\"",
"\"",
":",
"info",
".",
"RemoteAddr",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"info",
".",
"LocalAddr",
".",
"String",
"(",
")",
",",
"}",
")",
"\n",
"}"
] | // TagConn implements stats Handler interface. | [
"TagConn",
"implements",
"stats",
"Handler",
"interface",
"."
] | 51225c964507a856d4f2800076727f2f95c9f8bc | https://github.com/piotrkowalczuk/promgrpc/blob/51225c964507a856d4f2800076727f2f95c9f8bc/v3/prometheus.go#L309-L314 |
12,163 | piotrkowalczuk/promgrpc | v3/prometheus.go | HandleConn | func (i *Interceptor) HandleConn(ctx context.Context, stat stats.ConnStats) {
lab, _ := ctx.Value(tagConnKey).(prometheus.Labels)
switch in := stat.(type) {
case *stats.ConnBegin:
if in.IsClient() {
i.monitoring.client.connections.With(lab).Inc()
} else {
i.monitoring.server.connections.With(withUserAgentLabel(ctx, lab)).Inc()
}
case *stats.ConnEnd:
if in.IsClient() {
i.monitoring.client.connections.With(lab).Dec()
} else {
i.monitoring.server.connections.With(withUserAgentLabel(ctx, lab)).Dec()
}
}
} | go | func (i *Interceptor) HandleConn(ctx context.Context, stat stats.ConnStats) {
lab, _ := ctx.Value(tagConnKey).(prometheus.Labels)
switch in := stat.(type) {
case *stats.ConnBegin:
if in.IsClient() {
i.monitoring.client.connections.With(lab).Inc()
} else {
i.monitoring.server.connections.With(withUserAgentLabel(ctx, lab)).Inc()
}
case *stats.ConnEnd:
if in.IsClient() {
i.monitoring.client.connections.With(lab).Dec()
} else {
i.monitoring.server.connections.With(withUserAgentLabel(ctx, lab)).Dec()
}
}
} | [
"func",
"(",
"i",
"*",
"Interceptor",
")",
"HandleConn",
"(",
"ctx",
"context",
".",
"Context",
",",
"stat",
"stats",
".",
"ConnStats",
")",
"{",
"lab",
",",
"_",
":=",
"ctx",
".",
"Value",
"(",
"tagConnKey",
")",
".",
"(",
"prometheus",
".",
"Labels",
")",
"\n\n",
"switch",
"in",
":=",
"stat",
".",
"(",
"type",
")",
"{",
"case",
"*",
"stats",
".",
"ConnBegin",
":",
"if",
"in",
".",
"IsClient",
"(",
")",
"{",
"i",
".",
"monitoring",
".",
"client",
".",
"connections",
".",
"With",
"(",
"lab",
")",
".",
"Inc",
"(",
")",
"\n",
"}",
"else",
"{",
"i",
".",
"monitoring",
".",
"server",
".",
"connections",
".",
"With",
"(",
"withUserAgentLabel",
"(",
"ctx",
",",
"lab",
")",
")",
".",
"Inc",
"(",
")",
"\n",
"}",
"\n",
"case",
"*",
"stats",
".",
"ConnEnd",
":",
"if",
"in",
".",
"IsClient",
"(",
")",
"{",
"i",
".",
"monitoring",
".",
"client",
".",
"connections",
".",
"With",
"(",
"lab",
")",
".",
"Dec",
"(",
")",
"\n",
"}",
"else",
"{",
"i",
".",
"monitoring",
".",
"server",
".",
"connections",
".",
"With",
"(",
"withUserAgentLabel",
"(",
"ctx",
",",
"lab",
")",
")",
".",
"Dec",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // HandleConn implements stats Handler interface. | [
"HandleConn",
"implements",
"stats",
"Handler",
"interface",
"."
] | 51225c964507a856d4f2800076727f2f95c9f8bc | https://github.com/piotrkowalczuk/promgrpc/blob/51225c964507a856d4f2800076727f2f95c9f8bc/v3/prometheus.go#L317-L334 |
12,164 | piotrkowalczuk/promgrpc | v4/metric_requests_total.go | NewRequestsTotalStatsHandler | func NewRequestsTotalStatsHandler(sub Subsystem, vec *prometheus.CounterVec) *RequestsTotalStatsHandler {
return &RequestsTotalStatsHandler{
baseStatsHandler: baseStatsHandler{
subsystem: sub,
collector: vec,
},
vec: vec,
}
} | go | func NewRequestsTotalStatsHandler(sub Subsystem, vec *prometheus.CounterVec) *RequestsTotalStatsHandler {
return &RequestsTotalStatsHandler{
baseStatsHandler: baseStatsHandler{
subsystem: sub,
collector: vec,
},
vec: vec,
}
} | [
"func",
"NewRequestsTotalStatsHandler",
"(",
"sub",
"Subsystem",
",",
"vec",
"*",
"prometheus",
".",
"CounterVec",
")",
"*",
"RequestsTotalStatsHandler",
"{",
"return",
"&",
"RequestsTotalStatsHandler",
"{",
"baseStatsHandler",
":",
"baseStatsHandler",
"{",
"subsystem",
":",
"sub",
",",
"collector",
":",
"vec",
",",
"}",
",",
"vec",
":",
"vec",
",",
"}",
"\n",
"}"
] | // NewRequestsTotalStatsHandler ...
// The GaugeVec must have zero, one, two, three or four non-const non-curried labels.
// For those, the only allowed label names are "fail_fast", "handler", "service" and "user_agent". | [
"NewRequestsTotalStatsHandler",
"...",
"The",
"GaugeVec",
"must",
"have",
"zero",
"one",
"two",
"three",
"or",
"four",
"non",
"-",
"const",
"non",
"-",
"curried",
"labels",
".",
"For",
"those",
"the",
"only",
"allowed",
"label",
"names",
"are",
"fail_fast",
"handler",
"service",
"and",
"user_agent",
"."
] | 51225c964507a856d4f2800076727f2f95c9f8bc | https://github.com/piotrkowalczuk/promgrpc/blob/51225c964507a856d4f2800076727f2f95c9f8bc/v4/metric_requests_total.go#L45-L53 |
12,165 | piotrkowalczuk/promgrpc | v4/metric_messages_sent_total.go | NewMessagesSentTotalStatsHandler | func NewMessagesSentTotalStatsHandler(sub Subsystem, vec *prometheus.CounterVec) *MessagesSentTotalStatsHandler {
return &MessagesSentTotalStatsHandler{
baseStatsHandler: baseStatsHandler{
subsystem: sub,
collector: vec,
},
vec: vec,
}
} | go | func NewMessagesSentTotalStatsHandler(sub Subsystem, vec *prometheus.CounterVec) *MessagesSentTotalStatsHandler {
return &MessagesSentTotalStatsHandler{
baseStatsHandler: baseStatsHandler{
subsystem: sub,
collector: vec,
},
vec: vec,
}
} | [
"func",
"NewMessagesSentTotalStatsHandler",
"(",
"sub",
"Subsystem",
",",
"vec",
"*",
"prometheus",
".",
"CounterVec",
")",
"*",
"MessagesSentTotalStatsHandler",
"{",
"return",
"&",
"MessagesSentTotalStatsHandler",
"{",
"baseStatsHandler",
":",
"baseStatsHandler",
"{",
"subsystem",
":",
"sub",
",",
"collector",
":",
"vec",
",",
"}",
",",
"vec",
":",
"vec",
",",
"}",
"\n",
"}"
] | // NewMessagesSentTotalStatsHandler ...
// The GaugeVec must have zero, one, two, three or four non-const non-curried labels.
// For those, the only allowed label names are "fail_fast", "handler", "service" and "user_agent". | [
"NewMessagesSentTotalStatsHandler",
"...",
"The",
"GaugeVec",
"must",
"have",
"zero",
"one",
"two",
"three",
"or",
"four",
"non",
"-",
"const",
"non",
"-",
"curried",
"labels",
".",
"For",
"those",
"the",
"only",
"allowed",
"label",
"names",
"are",
"fail_fast",
"handler",
"service",
"and",
"user_agent",
"."
] | 51225c964507a856d4f2800076727f2f95c9f8bc | https://github.com/piotrkowalczuk/promgrpc/blob/51225c964507a856d4f2800076727f2f95c9f8bc/v4/metric_messages_sent_total.go#L33-L41 |
12,166 | piotrkowalczuk/promgrpc | v4/metric_messages_received_total.go | NewMessagesReceivedTotalStatsHandler | func NewMessagesReceivedTotalStatsHandler(sub Subsystem, vec *prometheus.CounterVec) *MessagesReceivedTotalStatsHandler {
return &MessagesReceivedTotalStatsHandler{
baseStatsHandler: baseStatsHandler{
subsystem: sub,
collector: vec,
},
vec: vec,
}
} | go | func NewMessagesReceivedTotalStatsHandler(sub Subsystem, vec *prometheus.CounterVec) *MessagesReceivedTotalStatsHandler {
return &MessagesReceivedTotalStatsHandler{
baseStatsHandler: baseStatsHandler{
subsystem: sub,
collector: vec,
},
vec: vec,
}
} | [
"func",
"NewMessagesReceivedTotalStatsHandler",
"(",
"sub",
"Subsystem",
",",
"vec",
"*",
"prometheus",
".",
"CounterVec",
")",
"*",
"MessagesReceivedTotalStatsHandler",
"{",
"return",
"&",
"MessagesReceivedTotalStatsHandler",
"{",
"baseStatsHandler",
":",
"baseStatsHandler",
"{",
"subsystem",
":",
"sub",
",",
"collector",
":",
"vec",
",",
"}",
",",
"vec",
":",
"vec",
",",
"}",
"\n",
"}"
] | // NewMessagesReceivedTotalStatsHandler ...
// The GaugeVec must have zero, one, two, three or four non-const non-curried labels.
// For those, the only allowed label names are "fail_fast", "handler", "service" and "user_agent". | [
"NewMessagesReceivedTotalStatsHandler",
"...",
"The",
"GaugeVec",
"must",
"have",
"zero",
"one",
"two",
"three",
"or",
"four",
"non",
"-",
"const",
"non",
"-",
"curried",
"labels",
".",
"For",
"those",
"the",
"only",
"allowed",
"label",
"names",
"are",
"fail_fast",
"handler",
"service",
"and",
"user_agent",
"."
] | 51225c964507a856d4f2800076727f2f95c9f8bc | https://github.com/piotrkowalczuk/promgrpc/blob/51225c964507a856d4f2800076727f2f95c9f8bc/v4/metric_messages_received_total.go#L33-L41 |
12,167 | piotrkowalczuk/promgrpc | v4/stats_handler.go | HandleConn | func (h *StatsHandler) HandleConn(ctx context.Context, sts stats.ConnStats) {
for _, c := range h.handlers {
c.HandleConn(ctx, sts)
}
} | go | func (h *StatsHandler) HandleConn(ctx context.Context, sts stats.ConnStats) {
for _, c := range h.handlers {
c.HandleConn(ctx, sts)
}
} | [
"func",
"(",
"h",
"*",
"StatsHandler",
")",
"HandleConn",
"(",
"ctx",
"context",
".",
"Context",
",",
"sts",
"stats",
".",
"ConnStats",
")",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"h",
".",
"handlers",
"{",
"c",
".",
"HandleConn",
"(",
"ctx",
",",
"sts",
")",
"\n",
"}",
"\n",
"}"
] | // HandleConn processes the Conn stats. | [
"HandleConn",
"processes",
"the",
"Conn",
"stats",
"."
] | 51225c964507a856d4f2800076727f2f95c9f8bc | https://github.com/piotrkowalczuk/promgrpc/blob/51225c964507a856d4f2800076727f2f95c9f8bc/v4/stats_handler.go#L91-L95 |
12,168 | TV4/graceful | graceful.go | LogListenAndServe | func LogListenAndServe(s Server, loggers ...Logger) {
if hs, ok := s.(*http.Server); ok {
logger = getLogger(loggers...)
if host, port, err := net.SplitHostPort(hs.Addr); err == nil {
if host == "" {
host = net.IPv4zero.String()
}
logger.Printf(ListeningFormat, net.JoinHostPort(host, port))
}
}
ListenAndServe(s)
} | go | func LogListenAndServe(s Server, loggers ...Logger) {
if hs, ok := s.(*http.Server); ok {
logger = getLogger(loggers...)
if host, port, err := net.SplitHostPort(hs.Addr); err == nil {
if host == "" {
host = net.IPv4zero.String()
}
logger.Printf(ListeningFormat, net.JoinHostPort(host, port))
}
}
ListenAndServe(s)
} | [
"func",
"LogListenAndServe",
"(",
"s",
"Server",
",",
"loggers",
"...",
"Logger",
")",
"{",
"if",
"hs",
",",
"ok",
":=",
"s",
".",
"(",
"*",
"http",
".",
"Server",
")",
";",
"ok",
"{",
"logger",
"=",
"getLogger",
"(",
"loggers",
"...",
")",
"\n\n",
"if",
"host",
",",
"port",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"hs",
".",
"Addr",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"host",
"==",
"\"",
"\"",
"{",
"host",
"=",
"net",
".",
"IPv4zero",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Printf",
"(",
"ListeningFormat",
",",
"net",
".",
"JoinHostPort",
"(",
"host",
",",
"port",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"ListenAndServe",
"(",
"s",
")",
"\n",
"}"
] | // LogListenAndServe logs using the logger and then calls ListenAndServe | [
"LogListenAndServe",
"logs",
"using",
"the",
"logger",
"and",
"then",
"calls",
"ListenAndServe"
] | a43e9ed005c82d373a50315e7684c364c1d35347 | https://github.com/TV4/graceful/blob/a43e9ed005c82d373a50315e7684c364c1d35347/graceful.go#L110-L124 |
12,169 | TV4/graceful | graceful.go | ListenAndServe | func ListenAndServe(s Server) {
go func() {
if err := s.ListenAndServe(); err != http.ErrServerClosed {
logger.Fatal(err)
}
}()
Shutdown(s)
} | go | func ListenAndServe(s Server) {
go func() {
if err := s.ListenAndServe(); err != http.ErrServerClosed {
logger.Fatal(err)
}
}()
Shutdown(s)
} | [
"func",
"ListenAndServe",
"(",
"s",
"Server",
")",
"{",
"go",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"s",
".",
"ListenAndServe",
"(",
")",
";",
"err",
"!=",
"http",
".",
"ErrServerClosed",
"{",
"logger",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"Shutdown",
"(",
"s",
")",
"\n",
"}"
] | // ListenAndServe starts the server in a goroutine and then calls Shutdown | [
"ListenAndServe",
"starts",
"the",
"server",
"in",
"a",
"goroutine",
"and",
"then",
"calls",
"Shutdown"
] | a43e9ed005c82d373a50315e7684c364c1d35347 | https://github.com/TV4/graceful/blob/a43e9ed005c82d373a50315e7684c364c1d35347/graceful.go#L127-L135 |
12,170 | TV4/graceful | graceful.go | ListenAndServeTLS | func ListenAndServeTLS(s TLSServer, certFile, keyFile string) {
go func() {
if err := s.ListenAndServeTLS(certFile, keyFile); err != http.ErrServerClosed {
logger.Fatal(err)
}
}()
Shutdown(s)
} | go | func ListenAndServeTLS(s TLSServer, certFile, keyFile string) {
go func() {
if err := s.ListenAndServeTLS(certFile, keyFile); err != http.ErrServerClosed {
logger.Fatal(err)
}
}()
Shutdown(s)
} | [
"func",
"ListenAndServeTLS",
"(",
"s",
"TLSServer",
",",
"certFile",
",",
"keyFile",
"string",
")",
"{",
"go",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"s",
".",
"ListenAndServeTLS",
"(",
"certFile",
",",
"keyFile",
")",
";",
"err",
"!=",
"http",
".",
"ErrServerClosed",
"{",
"logger",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"Shutdown",
"(",
"s",
")",
"\n",
"}"
] | // ListenAndServeTLS starts the server in a goroutine and then calls Shutdown | [
"ListenAndServeTLS",
"starts",
"the",
"server",
"in",
"a",
"goroutine",
"and",
"then",
"calls",
"Shutdown"
] | a43e9ed005c82d373a50315e7684c364c1d35347 | https://github.com/TV4/graceful/blob/a43e9ed005c82d373a50315e7684c364c1d35347/graceful.go#L138-L146 |
12,171 | piotrkowalczuk/promgrpc | prometheus.go | NewInterceptor | func NewInterceptor(opts InterceptorOpts) *Interceptor {
return &Interceptor{
monitoring: initMonitoring(opts.TrackPeers),
trackPeers: opts.TrackPeers,
}
} | go | func NewInterceptor(opts InterceptorOpts) *Interceptor {
return &Interceptor{
monitoring: initMonitoring(opts.TrackPeers),
trackPeers: opts.TrackPeers,
}
} | [
"func",
"NewInterceptor",
"(",
"opts",
"InterceptorOpts",
")",
"*",
"Interceptor",
"{",
"return",
"&",
"Interceptor",
"{",
"monitoring",
":",
"initMonitoring",
"(",
"opts",
".",
"TrackPeers",
")",
",",
"trackPeers",
":",
"opts",
".",
"TrackPeers",
",",
"}",
"\n",
"}"
] | // NewInterceptor implements both prometheus Collector interface and methods required by grpc Interceptor. | [
"NewInterceptor",
"implements",
"both",
"prometheus",
"Collector",
"interface",
"and",
"methods",
"required",
"by",
"grpc",
"Interceptor",
"."
] | 51225c964507a856d4f2800076727f2f95c9f8bc | https://github.com/piotrkowalczuk/promgrpc/blob/51225c964507a856d4f2800076727f2f95c9f8bc/prometheus.go#L92-L97 |
12,172 | solher/arangolite | errors.go | HasStatusCode | func HasStatusCode(err error, statusCode ...int) bool {
e, ok := err.(arangoError)
if !ok {
return false
}
code := e.statusCode
for _, c := range statusCode {
if code == c {
return true
}
break
}
return false
} | go | func HasStatusCode(err error, statusCode ...int) bool {
e, ok := err.(arangoError)
if !ok {
return false
}
code := e.statusCode
for _, c := range statusCode {
if code == c {
return true
}
break
}
return false
} | [
"func",
"HasStatusCode",
"(",
"err",
"error",
",",
"statusCode",
"...",
"int",
")",
"bool",
"{",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"arangoError",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"code",
":=",
"e",
".",
"statusCode",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"statusCode",
"{",
"if",
"code",
"==",
"c",
"{",
"return",
"true",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasStatusCode returns true when one of the given error status code matches the one returned by the database. | [
"HasStatusCode",
"returns",
"true",
"when",
"one",
"of",
"the",
"given",
"error",
"status",
"code",
"matches",
"the",
"one",
"returned",
"by",
"the",
"database",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/errors.go#L41-L54 |
12,173 | solher/arangolite | errors.go | GetStatusCode | func GetStatusCode(err error) (code int, ok bool) {
e, ok := err.(arangoError)
if !ok || e.statusCode == 0 {
return 0, false
}
return e.statusCode, true
} | go | func GetStatusCode(err error) (code int, ok bool) {
e, ok := err.(arangoError)
if !ok || e.statusCode == 0 {
return 0, false
}
return e.statusCode, true
} | [
"func",
"GetStatusCode",
"(",
"err",
"error",
")",
"(",
"code",
"int",
",",
"ok",
"bool",
")",
"{",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"arangoError",
")",
"\n",
"if",
"!",
"ok",
"||",
"e",
".",
"statusCode",
"==",
"0",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n",
"return",
"e",
".",
"statusCode",
",",
"true",
"\n",
"}"
] | // GetStatusCode returns the status code encapsulated in the error. | [
"GetStatusCode",
"returns",
"the",
"status",
"code",
"encapsulated",
"in",
"the",
"error",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/errors.go#L57-L63 |
12,174 | solher/arangolite | errors.go | HasErrorNum | func HasErrorNum(err error, errorNum ...int) bool {
e, ok := err.(arangoError)
if !ok {
return false
}
num := e.errorNum
for _, n := range errorNum {
if num == n {
return true
}
break
}
return false
} | go | func HasErrorNum(err error, errorNum ...int) bool {
e, ok := err.(arangoError)
if !ok {
return false
}
num := e.errorNum
for _, n := range errorNum {
if num == n {
return true
}
break
}
return false
} | [
"func",
"HasErrorNum",
"(",
"err",
"error",
",",
"errorNum",
"...",
"int",
")",
"bool",
"{",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"arangoError",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"num",
":=",
"e",
".",
"errorNum",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"errorNum",
"{",
"if",
"num",
"==",
"n",
"{",
"return",
"true",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasErrorNum returns true when one of the given error num matches the one returned by the database. | [
"HasErrorNum",
"returns",
"true",
"when",
"one",
"of",
"the",
"given",
"error",
"num",
"matches",
"the",
"one",
"returned",
"by",
"the",
"database",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/errors.go#L66-L79 |
12,175 | solher/arangolite | errors.go | GetErrorNum | func GetErrorNum(err error) (errorNum int, ok bool) {
e, ok := err.(arangoError)
if !ok || e.errorNum == 0 {
return 0, false
}
return e.errorNum, true
} | go | func GetErrorNum(err error) (errorNum int, ok bool) {
e, ok := err.(arangoError)
if !ok || e.errorNum == 0 {
return 0, false
}
return e.errorNum, true
} | [
"func",
"GetErrorNum",
"(",
"err",
"error",
")",
"(",
"errorNum",
"int",
",",
"ok",
"bool",
")",
"{",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"arangoError",
")",
"\n",
"if",
"!",
"ok",
"||",
"e",
".",
"errorNum",
"==",
"0",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n",
"return",
"e",
".",
"errorNum",
",",
"true",
"\n",
"}"
] | // GetErrorNum returns the database error num encapsulated in the error. | [
"GetErrorNum",
"returns",
"the",
"database",
"error",
"num",
"encapsulated",
"in",
"the",
"error",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/errors.go#L82-L88 |
12,176 | solher/arangolite | requests/transaction.go | NewTransaction | func NewTransaction(readCol, writeCol []string) *Transaction {
if readCol == nil {
readCol = []string{}
}
if writeCol == nil {
writeCol = []string{}
}
return &Transaction{readCol: readCol, writeCol: writeCol}
} | go | func NewTransaction(readCol, writeCol []string) *Transaction {
if readCol == nil {
readCol = []string{}
}
if writeCol == nil {
writeCol = []string{}
}
return &Transaction{readCol: readCol, writeCol: writeCol}
} | [
"func",
"NewTransaction",
"(",
"readCol",
",",
"writeCol",
"[",
"]",
"string",
")",
"*",
"Transaction",
"{",
"if",
"readCol",
"==",
"nil",
"{",
"readCol",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"if",
"writeCol",
"==",
"nil",
"{",
"writeCol",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Transaction",
"{",
"readCol",
":",
"readCol",
",",
"writeCol",
":",
"writeCol",
"}",
"\n",
"}"
] | // NewTransaction returns a new Transaction object. | [
"NewTransaction",
"returns",
"a",
"new",
"Transaction",
"object",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/transaction.go#L22-L30 |
12,177 | solher/arangolite | requests/transaction.go | Return | func (t *Transaction) Return(resultVar string) *Transaction {
t.returnVar = resultVar
return t
} | go | func (t *Transaction) Return(resultVar string) *Transaction {
t.returnVar = resultVar
return t
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"Return",
"(",
"resultVar",
"string",
")",
"*",
"Transaction",
"{",
"t",
".",
"returnVar",
"=",
"resultVar",
"\n",
"return",
"t",
"\n",
"}"
] | // Return sets the final "resultVar" that is returned at the end of the transaction. | [
"Return",
"sets",
"the",
"final",
"resultVar",
"that",
"is",
"returned",
"at",
"the",
"end",
"of",
"the",
"transaction",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/transaction.go#L64-L67 |
12,178 | solher/arangolite | requests/transaction.go | LockTimeout | func (t *Transaction) LockTimeout(lockTimeout int) *Transaction {
t.lockTimeout = &lockTimeout
return t
} | go | func (t *Transaction) LockTimeout(lockTimeout int) *Transaction {
t.lockTimeout = &lockTimeout
return t
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"LockTimeout",
"(",
"lockTimeout",
"int",
")",
"*",
"Transaction",
"{",
"t",
".",
"lockTimeout",
"=",
"&",
"lockTimeout",
"\n",
"return",
"t",
"\n",
"}"
] | // LockTimeout sets the optional lockTimeout value. | [
"LockTimeout",
"sets",
"the",
"optional",
"lockTimeout",
"value",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/transaction.go#L70-L73 |
12,179 | solher/arangolite | requests/transaction.go | WaitForSync | func (t *Transaction) WaitForSync(waitForSync bool) *Transaction {
t.waitForSync = &waitForSync
return t
} | go | func (t *Transaction) WaitForSync(waitForSync bool) *Transaction {
t.waitForSync = &waitForSync
return t
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"WaitForSync",
"(",
"waitForSync",
"bool",
")",
"*",
"Transaction",
"{",
"t",
".",
"waitForSync",
"=",
"&",
"waitForSync",
"\n",
"return",
"t",
"\n",
"}"
] | // WaitForSync sets the optional waitForSync flag. | [
"WaitForSync",
"sets",
"the",
"optional",
"waitForSync",
"flag",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/transaction.go#L76-L79 |
12,180 | solher/arangolite | requests/transaction.go | writeQuery | func writeQuery(buff *bytes.Buffer, aql string, resultVarName string) {
if len(resultVarName) > 0 {
buff.WriteString("var ")
buff.WriteString(resultVarName)
buff.WriteString(" = ")
}
buff.WriteString("db._query(aqlQuery`")
buff.WriteString(aql)
buff.WriteString("`).toArray(); ")
} | go | func writeQuery(buff *bytes.Buffer, aql string, resultVarName string) {
if len(resultVarName) > 0 {
buff.WriteString("var ")
buff.WriteString(resultVarName)
buff.WriteString(" = ")
}
buff.WriteString("db._query(aqlQuery`")
buff.WriteString(aql)
buff.WriteString("`).toArray(); ")
} | [
"func",
"writeQuery",
"(",
"buff",
"*",
"bytes",
".",
"Buffer",
",",
"aql",
"string",
",",
"resultVarName",
"string",
")",
"{",
"if",
"len",
"(",
"resultVarName",
")",
">",
"0",
"{",
"buff",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buff",
".",
"WriteString",
"(",
"resultVarName",
")",
"\n",
"buff",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"buff",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buff",
".",
"WriteString",
"(",
"aql",
")",
"\n",
"buff",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // writeQuery translate a given aql query to bytes
// buff the buffer containing the resulting bytes
// aql the AQL query
// resultVarName the name of the variable that will accept the query result, if any - may be empty | [
"writeQuery",
"translate",
"a",
"given",
"aql",
"query",
"to",
"bytes",
"buff",
"the",
"buffer",
"containing",
"the",
"resulting",
"bytes",
"aql",
"the",
"AQL",
"query",
"resultVarName",
"the",
"name",
"of",
"the",
"variable",
"that",
"will",
"accept",
"the",
"query",
"result",
"if",
"any",
"-",
"may",
"be",
"empty"
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/transaction.go#L136-L146 |
12,181 | solher/arangolite | requests/aql.go | NewAQL | func NewAQL(query string, params ...interface{}) *AQL {
return &AQL{query: processAQL(fmt.Sprintf(query, params...))}
} | go | func NewAQL(query string, params ...interface{}) *AQL {
return &AQL{query: processAQL(fmt.Sprintf(query, params...))}
} | [
"func",
"NewAQL",
"(",
"query",
"string",
",",
"params",
"...",
"interface",
"{",
"}",
")",
"*",
"AQL",
"{",
"return",
"&",
"AQL",
"{",
"query",
":",
"processAQL",
"(",
"fmt",
".",
"Sprintf",
"(",
"query",
",",
"params",
"...",
")",
")",
"}",
"\n",
"}"
] | // NewAQL returns a new AQL object. | [
"NewAQL",
"returns",
"a",
"new",
"AQL",
"object",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/aql.go#L19-L21 |
12,182 | solher/arangolite | requests/aql.go | BatchSize | func (a *AQL) BatchSize(size int) *AQL {
a.batchSize = size
return a
} | go | func (a *AQL) BatchSize(size int) *AQL {
a.batchSize = size
return a
} | [
"func",
"(",
"a",
"*",
"AQL",
")",
"BatchSize",
"(",
"size",
"int",
")",
"*",
"AQL",
"{",
"a",
".",
"batchSize",
"=",
"size",
"\n",
"return",
"a",
"\n",
"}"
] | // BatchSize sets the batch size of the query | [
"BatchSize",
"sets",
"the",
"batch",
"size",
"of",
"the",
"query"
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/aql.go#L31-L34 |
12,183 | solher/arangolite | requests/aql.go | Bind | func (a *AQL) Bind(name string, value interface{}) *AQL {
if a.bindVars == nil {
a.bindVars = make(map[string]interface{})
}
a.bindVars[name] = value
return a
} | go | func (a *AQL) Bind(name string, value interface{}) *AQL {
if a.bindVars == nil {
a.bindVars = make(map[string]interface{})
}
a.bindVars[name] = value
return a
} | [
"func",
"(",
"a",
"*",
"AQL",
")",
"Bind",
"(",
"name",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"*",
"AQL",
"{",
"if",
"a",
".",
"bindVars",
"==",
"nil",
"{",
"a",
".",
"bindVars",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n",
"a",
".",
"bindVars",
"[",
"name",
"]",
"=",
"value",
"\n",
"return",
"a",
"\n",
"}"
] | // Bind sets the name and value of a bind parameter
// Binding parameters prevents AQL injection | [
"Bind",
"sets",
"the",
"name",
"and",
"value",
"of",
"a",
"bind",
"parameter",
"Binding",
"parameters",
"prevents",
"AQL",
"injection"
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/requests/aql.go#L38-L44 |
12,184 | solher/arangolite | database.go | OptBasicAuth | func OptBasicAuth(username, password string) Option {
return func(db *Database) {
db.auth = &basicAuth{username: username, password: password}
}
} | go | func OptBasicAuth(username, password string) Option {
return func(db *Database) {
db.auth = &basicAuth{username: username, password: password}
}
} | [
"func",
"OptBasicAuth",
"(",
"username",
",",
"password",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"db",
"*",
"Database",
")",
"{",
"db",
".",
"auth",
"=",
"&",
"basicAuth",
"{",
"username",
":",
"username",
",",
"password",
":",
"password",
"}",
"\n",
"}",
"\n",
"}"
] | // OptBasicAuth sets the username and password used to access the database
// using basic authentication. | [
"OptBasicAuth",
"sets",
"the",
"username",
"and",
"password",
"used",
"to",
"access",
"the",
"database",
"using",
"basic",
"authentication",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L30-L34 |
12,185 | solher/arangolite | database.go | OptJWTAuth | func OptJWTAuth(username, password string) Option {
return func(db *Database) {
db.auth = &jwtAuth{username: username, password: password}
}
} | go | func OptJWTAuth(username, password string) Option {
return func(db *Database) {
db.auth = &jwtAuth{username: username, password: password}
}
} | [
"func",
"OptJWTAuth",
"(",
"username",
",",
"password",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"db",
"*",
"Database",
")",
"{",
"db",
".",
"auth",
"=",
"&",
"jwtAuth",
"{",
"username",
":",
"username",
",",
"password",
":",
"password",
"}",
"\n",
"}",
"\n",
"}"
] | // OptJWTAuth sets the username and password used to access the database
// using JWT authentication. | [
"OptJWTAuth",
"sets",
"the",
"username",
"and",
"password",
"used",
"to",
"access",
"the",
"database",
"using",
"JWT",
"authentication",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L38-L42 |
12,186 | solher/arangolite | database.go | OptHTTPClient | func OptHTTPClient(cli *http.Client) Option {
return func(db *Database) {
if cli != nil {
db.cli = cli
}
}
} | go | func OptHTTPClient(cli *http.Client) Option {
return func(db *Database) {
if cli != nil {
db.cli = cli
}
}
} | [
"func",
"OptHTTPClient",
"(",
"cli",
"*",
"http",
".",
"Client",
")",
"Option",
"{",
"return",
"func",
"(",
"db",
"*",
"Database",
")",
"{",
"if",
"cli",
"!=",
"nil",
"{",
"db",
".",
"cli",
"=",
"cli",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // OptHTTPClient sets the HTTP client used to interact with the database.
// It is also the current solution to set a custom TLS config. | [
"OptHTTPClient",
"sets",
"the",
"HTTP",
"client",
"used",
"to",
"interact",
"with",
"the",
"database",
".",
"It",
"is",
"also",
"the",
"current",
"solution",
"to",
"set",
"a",
"custom",
"TLS",
"config",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L53-L59 |
12,187 | solher/arangolite | database.go | OptLogging | func OptLogging(logger Logger, verbosity LogVerbosity) Option {
return func(db *Database) {
if logger != nil {
db.sender = newLoggingSender(db.sender, logger, verbosity)
}
}
} | go | func OptLogging(logger Logger, verbosity LogVerbosity) Option {
return func(db *Database) {
if logger != nil {
db.sender = newLoggingSender(db.sender, logger, verbosity)
}
}
} | [
"func",
"OptLogging",
"(",
"logger",
"Logger",
",",
"verbosity",
"LogVerbosity",
")",
"Option",
"{",
"return",
"func",
"(",
"db",
"*",
"Database",
")",
"{",
"if",
"logger",
"!=",
"nil",
"{",
"db",
".",
"sender",
"=",
"newLoggingSender",
"(",
"db",
".",
"sender",
",",
"logger",
",",
"verbosity",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // OptLogging enables logging of the exchanges with the database. | [
"OptLogging",
"enables",
"logging",
"of",
"the",
"exchanges",
"with",
"the",
"database",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L62-L68 |
12,188 | solher/arangolite | database.go | NewDatabase | func NewDatabase(opts ...Option) *Database {
db := &Database{
endpoint: "http://localhost:8529",
dbName: "_system",
// These Transport parameters are derived from github.com/hashicorp/go-cleanhttp which is under Mozilla Public License.
cli: &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
},
Timeout: 10 * time.Minute,
},
sender: &basicSender{},
auth: &basicAuth{},
}
db.Options(opts...)
return db
} | go | func NewDatabase(opts ...Option) *Database {
db := &Database{
endpoint: "http://localhost:8529",
dbName: "_system",
// These Transport parameters are derived from github.com/hashicorp/go-cleanhttp which is under Mozilla Public License.
cli: &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
},
Timeout: 10 * time.Minute,
},
sender: &basicSender{},
auth: &basicAuth{},
}
db.Options(opts...)
return db
} | [
"func",
"NewDatabase",
"(",
"opts",
"...",
"Option",
")",
"*",
"Database",
"{",
"db",
":=",
"&",
"Database",
"{",
"endpoint",
":",
"\"",
"\"",
",",
"dbName",
":",
"\"",
"\"",
",",
"// These Transport parameters are derived from github.com/hashicorp/go-cleanhttp which is under Mozilla Public License.",
"cli",
":",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"DialContext",
":",
"(",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"30",
"*",
"time",
".",
"Second",
",",
"KeepAlive",
":",
"30",
"*",
"time",
".",
"Second",
",",
"}",
")",
".",
"DialContext",
",",
"MaxIdleConns",
":",
"100",
",",
"IdleConnTimeout",
":",
"90",
"*",
"time",
".",
"Second",
",",
"TLSHandshakeTimeout",
":",
"10",
"*",
"time",
".",
"Second",
",",
"ExpectContinueTimeout",
":",
"1",
"*",
"time",
".",
"Second",
",",
"MaxIdleConnsPerHost",
":",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
"+",
"1",
",",
"}",
",",
"Timeout",
":",
"10",
"*",
"time",
".",
"Minute",
",",
"}",
",",
"sender",
":",
"&",
"basicSender",
"{",
"}",
",",
"auth",
":",
"&",
"basicAuth",
"{",
"}",
",",
"}",
"\n\n",
"db",
".",
"Options",
"(",
"opts",
"...",
")",
"\n\n",
"return",
"db",
"\n",
"}"
] | // NewDatabase returns a new Database object. | [
"NewDatabase",
"returns",
"a",
"new",
"Database",
"object",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L109-L135 |
12,189 | solher/arangolite | database.go | Connect | func (db *Database) Connect(ctx context.Context) error {
if err := db.auth.Setup(ctx, db); err != nil {
return err
}
if _, err := db.Send(ctx, &requests.CurrentDatabase{}); err != nil {
return err
}
return nil
} | go | func (db *Database) Connect(ctx context.Context) error {
if err := db.auth.Setup(ctx, db); err != nil {
return err
}
if _, err := db.Send(ctx, &requests.CurrentDatabase{}); err != nil {
return err
}
return nil
} | [
"func",
"(",
"db",
"*",
"Database",
")",
"Connect",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"err",
":=",
"db",
".",
"auth",
".",
"Setup",
"(",
"ctx",
",",
"db",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"db",
".",
"Send",
"(",
"ctx",
",",
"&",
"requests",
".",
"CurrentDatabase",
"{",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Connect setups the database connection and check the connectivity. | [
"Connect",
"setups",
"the",
"database",
"connection",
"and",
"check",
"the",
"connectivity",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L138-L146 |
12,190 | solher/arangolite | database.go | Options | func (db *Database) Options(opts ...Option) {
for _, opt := range opts {
opt(db)
}
} | go | func (db *Database) Options(opts ...Option) {
for _, opt := range opts {
opt(db)
}
} | [
"func",
"(",
"db",
"*",
"Database",
")",
"Options",
"(",
"opts",
"...",
"Option",
")",
"{",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"db",
")",
"\n",
"}",
"\n",
"}"
] | // Options apply options to the database. | [
"Options",
"apply",
"options",
"to",
"the",
"database",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L149-L153 |
12,191 | solher/arangolite | database.go | Run | func (db *Database) Run(ctx context.Context, v interface{}, q Runnable) error {
if q == nil {
return nil
}
r, err := db.Send(ctx, q)
if err != nil {
return err
}
result, err := db.followCursor(ctx, r)
if err != nil {
return withMessage(err, "could not follow the query cursor")
}
if v == nil || result == nil || len(result) == 0 {
return nil
}
if err := json.Unmarshal(result, v); err != nil {
return withMessage(err, "run result unmarshalling failed")
}
return nil
} | go | func (db *Database) Run(ctx context.Context, v interface{}, q Runnable) error {
if q == nil {
return nil
}
r, err := db.Send(ctx, q)
if err != nil {
return err
}
result, err := db.followCursor(ctx, r)
if err != nil {
return withMessage(err, "could not follow the query cursor")
}
if v == nil || result == nil || len(result) == 0 {
return nil
}
if err := json.Unmarshal(result, v); err != nil {
return withMessage(err, "run result unmarshalling failed")
}
return nil
} | [
"func",
"(",
"db",
"*",
"Database",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"v",
"interface",
"{",
"}",
",",
"q",
"Runnable",
")",
"error",
"{",
"if",
"q",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"r",
",",
"err",
":=",
"db",
".",
"Send",
"(",
"ctx",
",",
"q",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"result",
",",
"err",
":=",
"db",
".",
"followCursor",
"(",
"ctx",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"withMessage",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"v",
"==",
"nil",
"||",
"result",
"==",
"nil",
"||",
"len",
"(",
"result",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"result",
",",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"withMessage",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Run runs the Runnable, follows the query cursor if any and unmarshal
// the result in the given object. | [
"Run",
"runs",
"the",
"Runnable",
"follows",
"the",
"query",
"cursor",
"if",
"any",
"and",
"unmarshal",
"the",
"result",
"in",
"the",
"given",
"object",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L157-L179 |
12,192 | solher/arangolite | database.go | Send | func (db *Database) Send(ctx context.Context, q Runnable) (Response, error) {
if q == nil {
return &response{}, nil
}
req, err := http.NewRequest(
q.Method(),
fmt.Sprintf("%s/_db/%s%s", db.endpoint, db.dbName, q.Path()),
bytes.NewBuffer(q.Generate()),
)
if err != nil {
return nil, withMessage(err, "the http request generation failed")
}
if err := db.auth.Apply(req); err != nil {
return nil, withMessage(err, "authentication returned an error")
}
res, err := db.sender.Send(ctx, db.cli, req)
if err != nil {
return nil, err
}
if res.parsed.Error {
err = withMessage(errors.New(res.parsed.ErrorMessage), "the database execution returned an error")
err = withErrorNum(err, res.parsed.ErrorNum)
}
if res.statusCode < 200 || res.statusCode >= 300 {
if err == nil {
err = fmt.Errorf("the database HTTP request failed: status code %d", res.statusCode)
}
err = withStatusCode(err, res.statusCode)
}
if err != nil {
// We also return the response in the case of a database error so the user
// can eventually do something with it
return res, err
}
return res, nil
} | go | func (db *Database) Send(ctx context.Context, q Runnable) (Response, error) {
if q == nil {
return &response{}, nil
}
req, err := http.NewRequest(
q.Method(),
fmt.Sprintf("%s/_db/%s%s", db.endpoint, db.dbName, q.Path()),
bytes.NewBuffer(q.Generate()),
)
if err != nil {
return nil, withMessage(err, "the http request generation failed")
}
if err := db.auth.Apply(req); err != nil {
return nil, withMessage(err, "authentication returned an error")
}
res, err := db.sender.Send(ctx, db.cli, req)
if err != nil {
return nil, err
}
if res.parsed.Error {
err = withMessage(errors.New(res.parsed.ErrorMessage), "the database execution returned an error")
err = withErrorNum(err, res.parsed.ErrorNum)
}
if res.statusCode < 200 || res.statusCode >= 300 {
if err == nil {
err = fmt.Errorf("the database HTTP request failed: status code %d", res.statusCode)
}
err = withStatusCode(err, res.statusCode)
}
if err != nil {
// We also return the response in the case of a database error so the user
// can eventually do something with it
return res, err
}
return res, nil
} | [
"func",
"(",
"db",
"*",
"Database",
")",
"Send",
"(",
"ctx",
"context",
".",
"Context",
",",
"q",
"Runnable",
")",
"(",
"Response",
",",
"error",
")",
"{",
"if",
"q",
"==",
"nil",
"{",
"return",
"&",
"response",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"q",
".",
"Method",
"(",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"db",
".",
"endpoint",
",",
"db",
".",
"dbName",
",",
"q",
".",
"Path",
"(",
")",
")",
",",
"bytes",
".",
"NewBuffer",
"(",
"q",
".",
"Generate",
"(",
")",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"withMessage",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"db",
".",
"auth",
".",
"Apply",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"withMessage",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"res",
",",
"err",
":=",
"db",
".",
"sender",
".",
"Send",
"(",
"ctx",
",",
"db",
".",
"cli",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"res",
".",
"parsed",
".",
"Error",
"{",
"err",
"=",
"withMessage",
"(",
"errors",
".",
"New",
"(",
"res",
".",
"parsed",
".",
"ErrorMessage",
")",
",",
"\"",
"\"",
")",
"\n",
"err",
"=",
"withErrorNum",
"(",
"err",
",",
"res",
".",
"parsed",
".",
"ErrorNum",
")",
"\n",
"}",
"\n",
"if",
"res",
".",
"statusCode",
"<",
"200",
"||",
"res",
".",
"statusCode",
">=",
"300",
"{",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"statusCode",
")",
"\n",
"}",
"\n",
"err",
"=",
"withStatusCode",
"(",
"err",
",",
"res",
".",
"statusCode",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// We also return the response in the case of a database error so the user",
"// can eventually do something with it",
"return",
"res",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // Send runs the Runnable and returns a "raw" Response object. | [
"Send",
"runs",
"the",
"Runnable",
"and",
"returns",
"a",
"raw",
"Response",
"object",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L182-L221 |
12,193 | solher/arangolite | database.go | followCursor | func (db *Database) followCursor(ctx context.Context, r Response) ([]byte, error) {
// If the result only has one page
if !r.HasMore() {
if len(r.RawResult()) != 0 {
// Parsed result is not empty, so return this
return r.RawResult(), nil
}
// Return the raw result
return r.Raw(), nil
}
buf := bytes.NewBuffer(r.RawResult()[:len(r.RawResult())-1])
buf.WriteRune(',')
q := &requests.FollowCursor{Cursor: r.Cursor()}
var err error
for r.HasMore() {
r, err = db.Send(ctx, q)
if err != nil {
return nil, err
}
buf.Write(r.RawResult()[1 : len(r.RawResult())-1])
buf.WriteRune(',')
}
buf.Truncate(buf.Len() - 1)
buf.WriteRune(']')
return buf.Bytes(), nil
} | go | func (db *Database) followCursor(ctx context.Context, r Response) ([]byte, error) {
// If the result only has one page
if !r.HasMore() {
if len(r.RawResult()) != 0 {
// Parsed result is not empty, so return this
return r.RawResult(), nil
}
// Return the raw result
return r.Raw(), nil
}
buf := bytes.NewBuffer(r.RawResult()[:len(r.RawResult())-1])
buf.WriteRune(',')
q := &requests.FollowCursor{Cursor: r.Cursor()}
var err error
for r.HasMore() {
r, err = db.Send(ctx, q)
if err != nil {
return nil, err
}
buf.Write(r.RawResult()[1 : len(r.RawResult())-1])
buf.WriteRune(',')
}
buf.Truncate(buf.Len() - 1)
buf.WriteRune(']')
return buf.Bytes(), nil
} | [
"func",
"(",
"db",
"*",
"Database",
")",
"followCursor",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"Response",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// If the result only has one page",
"if",
"!",
"r",
".",
"HasMore",
"(",
")",
"{",
"if",
"len",
"(",
"r",
".",
"RawResult",
"(",
")",
")",
"!=",
"0",
"{",
"// Parsed result is not empty, so return this",
"return",
"r",
".",
"RawResult",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"// Return the raw result",
"return",
"r",
".",
"Raw",
"(",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"r",
".",
"RawResult",
"(",
")",
"[",
":",
"len",
"(",
"r",
".",
"RawResult",
"(",
")",
")",
"-",
"1",
"]",
")",
"\n",
"buf",
".",
"WriteRune",
"(",
"','",
")",
"\n\n",
"q",
":=",
"&",
"requests",
".",
"FollowCursor",
"{",
"Cursor",
":",
"r",
".",
"Cursor",
"(",
")",
"}",
"\n",
"var",
"err",
"error",
"\n\n",
"for",
"r",
".",
"HasMore",
"(",
")",
"{",
"r",
",",
"err",
"=",
"db",
".",
"Send",
"(",
"ctx",
",",
"q",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"buf",
".",
"Write",
"(",
"r",
".",
"RawResult",
"(",
")",
"[",
"1",
":",
"len",
"(",
"r",
".",
"RawResult",
"(",
")",
")",
"-",
"1",
"]",
")",
"\n",
"buf",
".",
"WriteRune",
"(",
"','",
")",
"\n",
"}",
"\n\n",
"buf",
".",
"Truncate",
"(",
"buf",
".",
"Len",
"(",
")",
"-",
"1",
")",
"\n",
"buf",
".",
"WriteRune",
"(",
"']'",
")",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // followCursor follows the cursor of the given response and returns
// all elements of every batch returned by the database. | [
"followCursor",
"follows",
"the",
"cursor",
"of",
"the",
"given",
"response",
"and",
"returns",
"all",
"elements",
"of",
"every",
"batch",
"returned",
"by",
"the",
"database",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/database.go#L225-L255 |
12,194 | solher/arangolite | log.go | newLoggingSender | func newLoggingSender(sender sender, logger Logger, verbosity LogVerbosity) sender {
return &loggingSender{
sender: sender,
logger: logger,
verbosity: verbosity,
}
} | go | func newLoggingSender(sender sender, logger Logger, verbosity LogVerbosity) sender {
return &loggingSender{
sender: sender,
logger: logger,
verbosity: verbosity,
}
} | [
"func",
"newLoggingSender",
"(",
"sender",
"sender",
",",
"logger",
"Logger",
",",
"verbosity",
"LogVerbosity",
")",
"sender",
"{",
"return",
"&",
"loggingSender",
"{",
"sender",
":",
"sender",
",",
"logger",
":",
"logger",
",",
"verbosity",
":",
"verbosity",
",",
"}",
"\n",
"}"
] | // newLoggingSender returns a logging wrapper around a sender. | [
"newLoggingSender",
"returns",
"a",
"logging",
"wrapper",
"around",
"a",
"sender",
"."
] | 5ed3a6d253e00039c5cb13370ac73e1410b8d99d | https://github.com/solher/arangolite/blob/5ed3a6d253e00039c5cb13370ac73e1410b8d99d/log.go#L30-L36 |
12,195 | mattheath/base62 | base62.go | Option | func (e *Encoding) Option(opts ...option) *Encoding {
for _, opt := range opts {
opt(e)
}
// Return the encoding to allow chaining
return e
} | go | func (e *Encoding) Option(opts ...option) *Encoding {
for _, opt := range opts {
opt(e)
}
// Return the encoding to allow chaining
return e
} | [
"func",
"(",
"e",
"*",
"Encoding",
")",
"Option",
"(",
"opts",
"...",
"option",
")",
"*",
"Encoding",
"{",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"e",
")",
"\n",
"}",
"\n\n",
"// Return the encoding to allow chaining",
"return",
"e",
"\n",
"}"
] | // Option sets a number of optional parameters on the encoding | [
"Option",
"sets",
"a",
"number",
"of",
"optional",
"parameters",
"on",
"the",
"encoding"
] | b80cdc656a7a61702f293555d54777d6ff617eb7 | https://github.com/mattheath/base62/blob/b80cdc656a7a61702f293555d54777d6ff617eb7/base62.go#L20-L27 |
12,196 | mattheath/base62 | base62.go | EncodeInt64 | func (e *Encoding) EncodeInt64(n int64) string {
var (
b = make([]byte, 0)
rem int64
)
// Progressively divide by base, store remainder each time
// Prepend as an additional character is the higher power
for n > 0 {
rem = n % base
n = n / base
b = append([]byte{e.encode[rem]}, b...)
}
s := string(b)
if e.padding > 0 {
s = e.pad(s, e.padding)
}
return s
} | go | func (e *Encoding) EncodeInt64(n int64) string {
var (
b = make([]byte, 0)
rem int64
)
// Progressively divide by base, store remainder each time
// Prepend as an additional character is the higher power
for n > 0 {
rem = n % base
n = n / base
b = append([]byte{e.encode[rem]}, b...)
}
s := string(b)
if e.padding > 0 {
s = e.pad(s, e.padding)
}
return s
} | [
"func",
"(",
"e",
"*",
"Encoding",
")",
"EncodeInt64",
"(",
"n",
"int64",
")",
"string",
"{",
"var",
"(",
"b",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
"\n",
"rem",
"int64",
"\n",
")",
"\n\n",
"// Progressively divide by base, store remainder each time",
"// Prepend as an additional character is the higher power",
"for",
"n",
">",
"0",
"{",
"rem",
"=",
"n",
"%",
"base",
"\n",
"n",
"=",
"n",
"/",
"base",
"\n",
"b",
"=",
"append",
"(",
"[",
"]",
"byte",
"{",
"e",
".",
"encode",
"[",
"rem",
"]",
"}",
",",
"b",
"...",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"string",
"(",
"b",
")",
"\n",
"if",
"e",
".",
"padding",
">",
"0",
"{",
"s",
"=",
"e",
".",
"pad",
"(",
"s",
",",
"e",
".",
"padding",
")",
"\n",
"}",
"\n\n",
"return",
"s",
"\n",
"}"
] | // EncodeInt64 returns the base62 encoding of n | [
"EncodeInt64",
"returns",
"the",
"base62",
"encoding",
"of",
"n"
] | b80cdc656a7a61702f293555d54777d6ff617eb7 | https://github.com/mattheath/base62/blob/b80cdc656a7a61702f293555d54777d6ff617eb7/base62.go#L73-L93 |
12,197 | mattheath/base62 | base62.go | EncodeBigInt | func (e *Encoding) EncodeBigInt(n *big.Int) string {
var (
b = make([]byte, 0)
rem = new(big.Int)
bse = new(big.Int)
zero = new(big.Int)
)
bse.SetInt64(base)
zero.SetInt64(0)
// Progressively divide by base, until we hit zero
// store remainder each time
// Prepend as an additional character is the higher power
for n.Cmp(zero) == 1 {
n, rem = n.DivMod(n, bse, rem)
b = append([]byte{e.encode[rem.Int64()]}, b...)
}
s := string(b)
if e.padding > 0 {
s = e.pad(s, e.padding)
}
return s
} | go | func (e *Encoding) EncodeBigInt(n *big.Int) string {
var (
b = make([]byte, 0)
rem = new(big.Int)
bse = new(big.Int)
zero = new(big.Int)
)
bse.SetInt64(base)
zero.SetInt64(0)
// Progressively divide by base, until we hit zero
// store remainder each time
// Prepend as an additional character is the higher power
for n.Cmp(zero) == 1 {
n, rem = n.DivMod(n, bse, rem)
b = append([]byte{e.encode[rem.Int64()]}, b...)
}
s := string(b)
if e.padding > 0 {
s = e.pad(s, e.padding)
}
return s
} | [
"func",
"(",
"e",
"*",
"Encoding",
")",
"EncodeBigInt",
"(",
"n",
"*",
"big",
".",
"Int",
")",
"string",
"{",
"var",
"(",
"b",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
"\n",
"rem",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"bse",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"zero",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
")",
"\n",
"bse",
".",
"SetInt64",
"(",
"base",
")",
"\n",
"zero",
".",
"SetInt64",
"(",
"0",
")",
"\n\n",
"// Progressively divide by base, until we hit zero",
"// store remainder each time",
"// Prepend as an additional character is the higher power",
"for",
"n",
".",
"Cmp",
"(",
"zero",
")",
"==",
"1",
"{",
"n",
",",
"rem",
"=",
"n",
".",
"DivMod",
"(",
"n",
",",
"bse",
",",
"rem",
")",
"\n",
"b",
"=",
"append",
"(",
"[",
"]",
"byte",
"{",
"e",
".",
"encode",
"[",
"rem",
".",
"Int64",
"(",
")",
"]",
"}",
",",
"b",
"...",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"string",
"(",
"b",
")",
"\n",
"if",
"e",
".",
"padding",
">",
"0",
"{",
"s",
"=",
"e",
".",
"pad",
"(",
"s",
",",
"e",
".",
"padding",
")",
"\n",
"}",
"\n\n",
"return",
"s",
"\n",
"}"
] | // EncodeBigInt returns the base62 encoding of an arbitrary precision integer | [
"EncodeBigInt",
"returns",
"the",
"base62",
"encoding",
"of",
"an",
"arbitrary",
"precision",
"integer"
] | b80cdc656a7a61702f293555d54777d6ff617eb7 | https://github.com/mattheath/base62/blob/b80cdc656a7a61702f293555d54777d6ff617eb7/base62.go#L96-L120 |
12,198 | mattheath/base62 | base62.go | DecodeToInt64 | func (e *Encoding) DecodeToInt64(s string) int64 {
var (
n int64
c int64
idx int
power int
)
for i, v := range s {
idx = strings.IndexRune(e.encode, v)
// Work downwards through powers of our base
power = len(s) - (i + 1)
// Calculate value at this position and add
c = int64(idx) * int64(math.Pow(float64(base), float64(power)))
n = n + c
}
return int64(n)
} | go | func (e *Encoding) DecodeToInt64(s string) int64 {
var (
n int64
c int64
idx int
power int
)
for i, v := range s {
idx = strings.IndexRune(e.encode, v)
// Work downwards through powers of our base
power = len(s) - (i + 1)
// Calculate value at this position and add
c = int64(idx) * int64(math.Pow(float64(base), float64(power)))
n = n + c
}
return int64(n)
} | [
"func",
"(",
"e",
"*",
"Encoding",
")",
"DecodeToInt64",
"(",
"s",
"string",
")",
"int64",
"{",
"var",
"(",
"n",
"int64",
"\n",
"c",
"int64",
"\n",
"idx",
"int",
"\n",
"power",
"int",
"\n",
")",
"\n\n",
"for",
"i",
",",
"v",
":=",
"range",
"s",
"{",
"idx",
"=",
"strings",
".",
"IndexRune",
"(",
"e",
".",
"encode",
",",
"v",
")",
"\n\n",
"// Work downwards through powers of our base",
"power",
"=",
"len",
"(",
"s",
")",
"-",
"(",
"i",
"+",
"1",
")",
"\n\n",
"// Calculate value at this position and add",
"c",
"=",
"int64",
"(",
"idx",
")",
"*",
"int64",
"(",
"math",
".",
"Pow",
"(",
"float64",
"(",
"base",
")",
",",
"float64",
"(",
"power",
")",
")",
")",
"\n",
"n",
"=",
"n",
"+",
"c",
"\n",
"}",
"\n\n",
"return",
"int64",
"(",
"n",
")",
"\n",
"}"
] | // DecodeToInt64 decodes a base62 encoded string | [
"DecodeToInt64",
"decodes",
"a",
"base62",
"encoded",
"string"
] | b80cdc656a7a61702f293555d54777d6ff617eb7 | https://github.com/mattheath/base62/blob/b80cdc656a7a61702f293555d54777d6ff617eb7/base62.go#L138-L158 |
12,199 | mattheath/base62 | base62.go | DecodeToBigInt | func (e *Encoding) DecodeToBigInt(s string) *big.Int {
var (
n = new(big.Int)
c = new(big.Int)
idx = new(big.Int)
power = new(big.Int)
exp = new(big.Int)
bse = new(big.Int)
)
bse.SetInt64(base)
// Run through each character to decode
for i, v := range s {
// Get index/position of the rune as a big int
idx.SetInt64(int64(strings.IndexRune(e.encode, v)))
// Work downwards through exponents
exp.SetInt64(int64(len(s) - (i + 1)))
// Calculate power for this exponent
power.Exp(bse, exp, nil)
// Multiplied by our index, gives us the value for this character
c = c.Mul(idx, power)
// Finally add to running total
n.Add(n, c)
}
return n
} | go | func (e *Encoding) DecodeToBigInt(s string) *big.Int {
var (
n = new(big.Int)
c = new(big.Int)
idx = new(big.Int)
power = new(big.Int)
exp = new(big.Int)
bse = new(big.Int)
)
bse.SetInt64(base)
// Run through each character to decode
for i, v := range s {
// Get index/position of the rune as a big int
idx.SetInt64(int64(strings.IndexRune(e.encode, v)))
// Work downwards through exponents
exp.SetInt64(int64(len(s) - (i + 1)))
// Calculate power for this exponent
power.Exp(bse, exp, nil)
// Multiplied by our index, gives us the value for this character
c = c.Mul(idx, power)
// Finally add to running total
n.Add(n, c)
}
return n
} | [
"func",
"(",
"e",
"*",
"Encoding",
")",
"DecodeToBigInt",
"(",
"s",
"string",
")",
"*",
"big",
".",
"Int",
"{",
"var",
"(",
"n",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n\n",
"c",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"idx",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"power",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"exp",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"bse",
"=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
")",
"\n",
"bse",
".",
"SetInt64",
"(",
"base",
")",
"\n\n",
"// Run through each character to decode",
"for",
"i",
",",
"v",
":=",
"range",
"s",
"{",
"// Get index/position of the rune as a big int",
"idx",
".",
"SetInt64",
"(",
"int64",
"(",
"strings",
".",
"IndexRune",
"(",
"e",
".",
"encode",
",",
"v",
")",
")",
")",
"\n\n",
"// Work downwards through exponents",
"exp",
".",
"SetInt64",
"(",
"int64",
"(",
"len",
"(",
"s",
")",
"-",
"(",
"i",
"+",
"1",
")",
")",
")",
"\n\n",
"// Calculate power for this exponent",
"power",
".",
"Exp",
"(",
"bse",
",",
"exp",
",",
"nil",
")",
"\n\n",
"// Multiplied by our index, gives us the value for this character",
"c",
"=",
"c",
".",
"Mul",
"(",
"idx",
",",
"power",
")",
"\n\n",
"// Finally add to running total",
"n",
".",
"Add",
"(",
"n",
",",
"c",
")",
"\n",
"}",
"\n\n",
"return",
"n",
"\n",
"}"
] | // DecodeToBigInt returns an arbitrary precision integer from the base62 encoded string | [
"DecodeToBigInt",
"returns",
"an",
"arbitrary",
"precision",
"integer",
"from",
"the",
"base62",
"encoded",
"string"
] | b80cdc656a7a61702f293555d54777d6ff617eb7 | https://github.com/mattheath/base62/blob/b80cdc656a7a61702f293555d54777d6ff617eb7/base62.go#L161-L192 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.