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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9,600 | mindprince/gonvml | bindings.go | DecoderUtilization | func (d Device) DecoderUtilization() (uint, uint, error) {
if C.nvmlHandle == nil {
return 0, 0, errLibraryNotLoaded
}
var n C.uint
var sp C.uint
r := C.nvmlDeviceGetDecoderUtilization(d.dev, &n, &sp)
return uint(n), uint(sp), errorString(r)
} | go | func (d Device) DecoderUtilization() (uint, uint, error) {
if C.nvmlHandle == nil {
return 0, 0, errLibraryNotLoaded
}
var n C.uint
var sp C.uint
r := C.nvmlDeviceGetDecoderUtilization(d.dev, &n, &sp)
return uint(n), uint(sp), errorString(r)
} | [
"func",
"(",
"d",
"Device",
")",
"DecoderUtilization",
"(",
")",
"(",
"uint",
",",
"uint",
",",
"error",
")",
"{",
"if",
"C",
".",
"nvmlHandle",
"==",
"nil",
"{",
"return",
"0",
",",
"0",
",",
"errLibraryNotLoaded",
"\n",
"}",
"\n",
"var",
"n",
"C"... | // DecoderUtilization returns the percent of time over the last sample period during which the GPU video decoder was being used.
// The sampling period is variable and is returned in the second return argument in microseconds. | [
"DecoderUtilization",
"returns",
"the",
"percent",
"of",
"time",
"over",
"the",
"last",
"sample",
"period",
"during",
"which",
"the",
"GPU",
"video",
"decoder",
"was",
"being",
"used",
".",
"The",
"sampling",
"period",
"is",
"variable",
"and",
"is",
"returned"... | b364b296c7320f5d3dc084aa536a3dba33b68f90 | https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L516-L524 |
9,601 | libp2p/go-libp2p-host | match.go | MultistreamSemverMatcher | func MultistreamSemverMatcher(base protocol.ID) (func(string) bool, error) {
parts := strings.Split(string(base), "/")
vers, err := semver.NewVersion(parts[len(parts)-1])
if err != nil {
return nil, err
}
return func(check string) bool {
chparts := strings.Split(check, "/")
if len(chparts) != len(parts) {
return false
}
for i, v := range chparts[:len(chparts)-1] {
if parts[i] != v {
return false
}
}
chvers, err := semver.NewVersion(chparts[len(chparts)-1])
if err != nil {
return false
}
return vers.Major == chvers.Major && vers.Minor >= chvers.Minor
}, nil
} | go | func MultistreamSemverMatcher(base protocol.ID) (func(string) bool, error) {
parts := strings.Split(string(base), "/")
vers, err := semver.NewVersion(parts[len(parts)-1])
if err != nil {
return nil, err
}
return func(check string) bool {
chparts := strings.Split(check, "/")
if len(chparts) != len(parts) {
return false
}
for i, v := range chparts[:len(chparts)-1] {
if parts[i] != v {
return false
}
}
chvers, err := semver.NewVersion(chparts[len(chparts)-1])
if err != nil {
return false
}
return vers.Major == chvers.Major && vers.Minor >= chvers.Minor
}, nil
} | [
"func",
"MultistreamSemverMatcher",
"(",
"base",
"protocol",
".",
"ID",
")",
"(",
"func",
"(",
"string",
")",
"bool",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"string",
"(",
"base",
")",
",",
"\"",
"\"",
")",
"\n",
"vers",... | // MultistreamSemverMatcher returns a matcher function for a given base protocol.
// The matcher function will return a boolean indicating whether a protocol ID
// matches the base protocol. A given protocol ID matches the base protocol if
// the IDs are the same and if the semantic version of the base protocol is the
// same or higher than that of the protocol ID provided. | [
"MultistreamSemverMatcher",
"returns",
"a",
"matcher",
"function",
"for",
"a",
"given",
"base",
"protocol",
".",
"The",
"matcher",
"function",
"will",
"return",
"a",
"boolean",
"indicating",
"whether",
"a",
"protocol",
"ID",
"matches",
"the",
"base",
"protocol",
... | 3f45e8092ec195e802044313971709e913f92329 | https://github.com/libp2p/go-libp2p-host/blob/3f45e8092ec195e802044313971709e913f92329/match.go#L15-L41 |
9,602 | libp2p/go-libp2p-host | helpers.go | PeerInfoFromHost | func PeerInfoFromHost(h Host) *pstore.PeerInfo {
return &pstore.PeerInfo{
ID: h.ID(),
Addrs: h.Addrs(),
}
} | go | func PeerInfoFromHost(h Host) *pstore.PeerInfo {
return &pstore.PeerInfo{
ID: h.ID(),
Addrs: h.Addrs(),
}
} | [
"func",
"PeerInfoFromHost",
"(",
"h",
"Host",
")",
"*",
"pstore",
".",
"PeerInfo",
"{",
"return",
"&",
"pstore",
".",
"PeerInfo",
"{",
"ID",
":",
"h",
".",
"ID",
"(",
")",
",",
"Addrs",
":",
"h",
".",
"Addrs",
"(",
")",
",",
"}",
"\n",
"}"
] | // PeerInfoFromHost returns a PeerInfo struct with the Host's ID and all of its Addrs. | [
"PeerInfoFromHost",
"returns",
"a",
"PeerInfo",
"struct",
"with",
"the",
"Host",
"s",
"ID",
"and",
"all",
"of",
"its",
"Addrs",
"."
] | 3f45e8092ec195e802044313971709e913f92329 | https://github.com/libp2p/go-libp2p-host/blob/3f45e8092ec195e802044313971709e913f92329/helpers.go#L6-L11 |
9,603 | vjeantet/ldapserver | route.go | ServeLDAP | func (h *RouteMux) ServeLDAP(w ResponseWriter, r *Message) {
//find a matching Route
for _, route := range h.routes {
//if the route don't match, skip it
if route.Match(r) == false {
continue
}
if route.label != "" {
Logger.Printf("")
Logger.Printf(" ROUTE MATCH ; %s", route.label)
Logger.Printf("")
// Logger.Printf(" ROUTE MATCH ; %s", runtime.FuncForPC(reflect.ValueOf(route.handler).Pointer()).Name())
}
route.handler(w, r)
return
}
// Catch a AbandonRequest not handled by user
switch v := r.ProtocolOp().(type) {
case ldap.AbandonRequest:
// retreive the request to abandon, and send a abort signal to it
if requestToAbandon, ok := r.Client.GetMessageByID(int(v)); ok {
requestToAbandon.Abandon()
}
}
if h.notFoundRoute != nil {
h.notFoundRoute.handler(w, r)
} else {
res := NewResponse(LDAPResultUnwillingToPerform)
res.SetDiagnosticMessage("Operation not implemented by server")
w.Write(res)
}
} | go | func (h *RouteMux) ServeLDAP(w ResponseWriter, r *Message) {
//find a matching Route
for _, route := range h.routes {
//if the route don't match, skip it
if route.Match(r) == false {
continue
}
if route.label != "" {
Logger.Printf("")
Logger.Printf(" ROUTE MATCH ; %s", route.label)
Logger.Printf("")
// Logger.Printf(" ROUTE MATCH ; %s", runtime.FuncForPC(reflect.ValueOf(route.handler).Pointer()).Name())
}
route.handler(w, r)
return
}
// Catch a AbandonRequest not handled by user
switch v := r.ProtocolOp().(type) {
case ldap.AbandonRequest:
// retreive the request to abandon, and send a abort signal to it
if requestToAbandon, ok := r.Client.GetMessageByID(int(v)); ok {
requestToAbandon.Abandon()
}
}
if h.notFoundRoute != nil {
h.notFoundRoute.handler(w, r)
} else {
res := NewResponse(LDAPResultUnwillingToPerform)
res.SetDiagnosticMessage("Operation not implemented by server")
w.Write(res)
}
} | [
"func",
"(",
"h",
"*",
"RouteMux",
")",
"ServeLDAP",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Message",
")",
"{",
"//find a matching Route",
"for",
"_",
",",
"route",
":=",
"range",
"h",
".",
"routes",
"{",
"//if the route don't match, skip it",
"if",
"ro... | // ServeLDAP dispatches the request to the handler whose
// pattern most closely matches the request request Message. | [
"ServeLDAP",
"dispatches",
"the",
"request",
"to",
"the",
"handler",
"whose",
"pattern",
"most",
"closely",
"matches",
"the",
"request",
"request",
"Message",
"."
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/route.go#L140-L177 |
9,604 | vjeantet/ldapserver | examples/ssl/main.go | getTLSconfig | func getTLSconfig() (*tls.Config, error) {
cert, err := tls.X509KeyPair(localhostCert, localhostKey)
if err != nil {
return &tls.Config{}, err
}
return &tls.Config{
MinVersion: tls.VersionSSL30,
MaxVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
ServerName: "127.0.0.1",
}, nil
} | go | func getTLSconfig() (*tls.Config, error) {
cert, err := tls.X509KeyPair(localhostCert, localhostKey)
if err != nil {
return &tls.Config{}, err
}
return &tls.Config{
MinVersion: tls.VersionSSL30,
MaxVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
ServerName: "127.0.0.1",
}, nil
} | [
"func",
"getTLSconfig",
"(",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"cert",
",",
"err",
":=",
"tls",
".",
"X509KeyPair",
"(",
"localhostCert",
",",
"localhostKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"tls",
... | // getTLSconfig returns a tls configuration used
// to build a TLSlistener for TLS or StartTLS | [
"getTLSconfig",
"returns",
"a",
"tls",
"configuration",
"used",
"to",
"build",
"a",
"TLSlistener",
"for",
"TLS",
"or",
"StartTLS"
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/examples/ssl/main.go#L41-L53 |
9,605 | vjeantet/ldapserver | packet.go | readLdapMessageBytes | func readLdapMessageBytes(br *bufio.Reader) (ret *[]byte, err error) {
var bytes []byte
var tagAndLength ldap.TagAndLength
tagAndLength, err = readTagAndLength(br, &bytes)
if err != nil {
return
}
readBytes(br, &bytes, tagAndLength.Length)
return &bytes, err
} | go | func readLdapMessageBytes(br *bufio.Reader) (ret *[]byte, err error) {
var bytes []byte
var tagAndLength ldap.TagAndLength
tagAndLength, err = readTagAndLength(br, &bytes)
if err != nil {
return
}
readBytes(br, &bytes, tagAndLength.Length)
return &bytes, err
} | [
"func",
"readLdapMessageBytes",
"(",
"br",
"*",
"bufio",
".",
"Reader",
")",
"(",
"ret",
"*",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"var",
"bytes",
"[",
"]",
"byte",
"\n",
"var",
"tagAndLength",
"ldap",
".",
"TagAndLength",
"\n",
"tagAndLeng... | // BELLOW SHOULD BE IN ROOX PACKAGE | [
"BELLOW",
"SHOULD",
"BE",
"IN",
"ROOX",
"PACKAGE"
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/packet.go#L51-L60 |
9,606 | vjeantet/ldapserver | packet.go | readBytes | func readBytes(conn *bufio.Reader, bytes *[]byte, length int) (b byte, err error) {
newbytes := make([]byte, length)
n, err := conn.Read(newbytes)
if n != length {
fmt.Errorf("%d bytes read instead of %d", n, length)
} else if err != nil {
return
}
*bytes = append(*bytes, newbytes...)
b = (*bytes)[len(*bytes)-1]
return
} | go | func readBytes(conn *bufio.Reader, bytes *[]byte, length int) (b byte, err error) {
newbytes := make([]byte, length)
n, err := conn.Read(newbytes)
if n != length {
fmt.Errorf("%d bytes read instead of %d", n, length)
} else if err != nil {
return
}
*bytes = append(*bytes, newbytes...)
b = (*bytes)[len(*bytes)-1]
return
} | [
"func",
"readBytes",
"(",
"conn",
"*",
"bufio",
".",
"Reader",
",",
"bytes",
"*",
"[",
"]",
"byte",
",",
"length",
"int",
")",
"(",
"b",
"byte",
",",
"err",
"error",
")",
"{",
"newbytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"length",
")",
... | // Read "length" bytes from the connection
// Append the read bytes to "bytes"
// Return the last read byte | [
"Read",
"length",
"bytes",
"from",
"the",
"connection",
"Append",
"the",
"read",
"bytes",
"to",
"bytes",
"Return",
"the",
"last",
"read",
"byte"
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/packet.go#L137-L148 |
9,607 | vjeantet/ldapserver | examples/simple/main.go | handleBind | func handleBind(w ldap.ResponseWriter, m *ldap.Message) {
r := m.GetBindRequest()
res := ldap.NewBindResponse(ldap.LDAPResultSuccess)
if string(r.Name()) == "login" {
// w.Write(res)
return
}
log.Printf("Bind failed User=%s, Pass=%s", string(r.Name()), string(r.AuthenticationSimple()))
res.SetResultCode(ldap.LDAPResultInvalidCredentials)
res.SetDiagnosticMessage("invalid credentials")
w.Write(res)
} | go | func handleBind(w ldap.ResponseWriter, m *ldap.Message) {
r := m.GetBindRequest()
res := ldap.NewBindResponse(ldap.LDAPResultSuccess)
if string(r.Name()) == "login" {
// w.Write(res)
return
}
log.Printf("Bind failed User=%s, Pass=%s", string(r.Name()), string(r.AuthenticationSimple()))
res.SetResultCode(ldap.LDAPResultInvalidCredentials)
res.SetDiagnosticMessage("invalid credentials")
w.Write(res)
} | [
"func",
"handleBind",
"(",
"w",
"ldap",
".",
"ResponseWriter",
",",
"m",
"*",
"ldap",
".",
"Message",
")",
"{",
"r",
":=",
"m",
".",
"GetBindRequest",
"(",
")",
"\n",
"res",
":=",
"ldap",
".",
"NewBindResponse",
"(",
"ldap",
".",
"LDAPResultSuccess",
"... | // handleBind return Success if login == mysql | [
"handleBind",
"return",
"Success",
"if",
"login",
"==",
"mysql"
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/examples/simple/main.go#L40-L53 |
9,608 | vjeantet/ldapserver | server.go | Handle | func (s *Server) Handle(h Handler) {
if s.Handler != nil {
panic("LDAP: multiple Handler registrations")
}
s.Handler = h
} | go | func (s *Server) Handle(h Handler) {
if s.Handler != nil {
panic("LDAP: multiple Handler registrations")
}
s.Handler = h
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Handle",
"(",
"h",
"Handler",
")",
"{",
"if",
"s",
".",
"Handler",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"s",
".",
"Handler",
"=",
"h",
"\n",
"}"
] | // Handle registers the handler for the server.
// If a handler already exists for pattern, Handle panics | [
"Handle",
"registers",
"the",
"handler",
"for",
"the",
"server",
".",
"If",
"a",
"handler",
"already",
"exists",
"for",
"pattern",
"Handle",
"panics"
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/server.go#L36-L41 |
9,609 | vjeantet/ldapserver | server.go | serve | func (s *Server) serve() error {
defer s.Listener.Close()
if s.Handler == nil {
Logger.Panicln("No LDAP Request Handler defined")
}
i := 0
for {
select {
case <-s.chDone:
Logger.Print("Stopping server")
s.Listener.Close()
return nil
default:
}
rw, err := s.Listener.Accept()
if s.ReadTimeout != 0 {
rw.SetReadDeadline(time.Now().Add(s.ReadTimeout))
}
if s.WriteTimeout != 0 {
rw.SetWriteDeadline(time.Now().Add(s.WriteTimeout))
}
if nil != err {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
Logger.Println(err)
}
cli, err := s.newClient(rw)
if err != nil {
continue
}
i = i + 1
cli.Numero = i
Logger.Printf("Connection client [%d] from %s accepted", cli.Numero, cli.rwc.RemoteAddr().String())
s.wg.Add(1)
go cli.serve()
}
return nil
} | go | func (s *Server) serve() error {
defer s.Listener.Close()
if s.Handler == nil {
Logger.Panicln("No LDAP Request Handler defined")
}
i := 0
for {
select {
case <-s.chDone:
Logger.Print("Stopping server")
s.Listener.Close()
return nil
default:
}
rw, err := s.Listener.Accept()
if s.ReadTimeout != 0 {
rw.SetReadDeadline(time.Now().Add(s.ReadTimeout))
}
if s.WriteTimeout != 0 {
rw.SetWriteDeadline(time.Now().Add(s.WriteTimeout))
}
if nil != err {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
Logger.Println(err)
}
cli, err := s.newClient(rw)
if err != nil {
continue
}
i = i + 1
cli.Numero = i
Logger.Printf("Connection client [%d] from %s accepted", cli.Numero, cli.rwc.RemoteAddr().String())
s.wg.Add(1)
go cli.serve()
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"serve",
"(",
")",
"error",
"{",
"defer",
"s",
".",
"Listener",
".",
"Close",
"(",
")",
"\n\n",
"if",
"s",
".",
"Handler",
"==",
"nil",
"{",
"Logger",
".",
"Panicln",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n"... | // Handle requests messages on the ln listener | [
"Handle",
"requests",
"messages",
"on",
"the",
"ln",
"listener"
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/server.go#L67-L114 |
9,610 | vjeantet/ldapserver | server.go | newClient | func (s *Server) newClient(rwc net.Conn) (c *client, err error) {
c = &client{
srv: s,
rwc: rwc,
br: bufio.NewReader(rwc),
bw: bufio.NewWriter(rwc),
}
return c, nil
} | go | func (s *Server) newClient(rwc net.Conn) (c *client, err error) {
c = &client{
srv: s,
rwc: rwc,
br: bufio.NewReader(rwc),
bw: bufio.NewWriter(rwc),
}
return c, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"newClient",
"(",
"rwc",
"net",
".",
"Conn",
")",
"(",
"c",
"*",
"client",
",",
"err",
"error",
")",
"{",
"c",
"=",
"&",
"client",
"{",
"srv",
":",
"s",
",",
"rwc",
":",
"rwc",
",",
"br",
":",
"bufio",
... | // Return a new session with the connection
// client has a writer and reader buffer | [
"Return",
"a",
"new",
"session",
"with",
"the",
"connection",
"client",
"has",
"a",
"writer",
"and",
"reader",
"buffer"
] | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/server.go#L118-L126 |
9,611 | vjeantet/ldapserver | server.go | Stop | func (s *Server) Stop() {
close(s.chDone)
Logger.Print("gracefully closing client connections...")
s.wg.Wait()
Logger.Print("all clients connection closed")
} | go | func (s *Server) Stop() {
close(s.chDone)
Logger.Print("gracefully closing client connections...")
s.wg.Wait()
Logger.Print("all clients connection closed")
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Stop",
"(",
")",
"{",
"close",
"(",
"s",
".",
"chDone",
")",
"\n",
"Logger",
".",
"Print",
"(",
"\"",
"\"",
")",
"\n",
"s",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"Logger",
".",
"Print",
"(",
"\"",
"\... | // Termination of the LDAP session is initiated by the server sending a
// Notice of Disconnection. In this case, each
// protocol peer gracefully terminates the LDAP session by ceasing
// exchanges at the LDAP message layer, tearing down any SASL layer,
// tearing down any TLS layer, and closing the transport connection.
// A protocol peer may determine that the continuation of any
// communication would be pernicious, and in this case, it may abruptly
// terminate the session by ceasing communication and closing the
// transport connection.
// In either case, when the LDAP session is terminated. | [
"Termination",
"of",
"the",
"LDAP",
"session",
"is",
"initiated",
"by",
"the",
"server",
"sending",
"a",
"Notice",
"of",
"Disconnection",
".",
"In",
"this",
"case",
"each",
"protocol",
"peer",
"gracefully",
"terminates",
"the",
"LDAP",
"session",
"by",
"ceasin... | 479fece7c5f15b209e2e3ba082a89d18cd2a8207 | https://github.com/vjeantet/ldapserver/blob/479fece7c5f15b209e2e3ba082a89d18cd2a8207/server.go#L138-L143 |
9,612 | libp2p/go-libp2p-secio | rw.go | NewETMWriter | func NewETMWriter(w io.Writer, s cipher.Stream, mac HMAC) msgio.WriteCloser {
return &etmWriter{w: w, str: s, mac: mac}
} | go | func NewETMWriter(w io.Writer, s cipher.Stream, mac HMAC) msgio.WriteCloser {
return &etmWriter{w: w, str: s, mac: mac}
} | [
"func",
"NewETMWriter",
"(",
"w",
"io",
".",
"Writer",
",",
"s",
"cipher",
".",
"Stream",
",",
"mac",
"HMAC",
")",
"msgio",
".",
"WriteCloser",
"{",
"return",
"&",
"etmWriter",
"{",
"w",
":",
"w",
",",
"str",
":",
"s",
",",
"mac",
":",
"mac",
"}"... | // NewETMWriter Encrypt-Then-MAC | [
"NewETMWriter",
"Encrypt",
"-",
"Then",
"-",
"MAC"
] | 3175340d7c342f07587c89ef4c14c9324f1f9f40 | https://github.com/libp2p/go-libp2p-secio/blob/3175340d7c342f07587c89ef4c14c9324f1f9f40/rw.go#L28-L30 |
9,613 | libp2p/go-libp2p-secio | rw.go | Write | func (w *etmWriter) Write(b []byte) (int, error) {
if err := w.WriteMsg(b); err != nil {
return 0, err
}
return len(b), nil
} | go | func (w *etmWriter) Write(b []byte) (int, error) {
if err := w.WriteMsg(b); err != nil {
return 0, err
}
return len(b), nil
} | [
"func",
"(",
"w",
"*",
"etmWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"err",
":=",
"w",
".",
"WriteMsg",
"(",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}... | // Write writes passed in buffer as a single message. | [
"Write",
"writes",
"passed",
"in",
"buffer",
"as",
"a",
"single",
"message",
"."
] | 3175340d7c342f07587c89ef4c14c9324f1f9f40 | https://github.com/libp2p/go-libp2p-secio/blob/3175340d7c342f07587c89ef4c14c9324f1f9f40/rw.go#L33-L38 |
9,614 | libp2p/go-libp2p-secio | rw.go | WriteMsg | func (w *etmWriter) WriteMsg(b []byte) error {
w.Lock()
defer w.Unlock()
// encrypt.
buf := pool.Get(4 + len(b) + w.mac.Size())
defer pool.Put(buf)
data := buf[4 : 4+len(b)]
w.str.XORKeyStream(data, b)
// log.Debugf("ENC plaintext (%d): %s %v", len(b), b, b)
// log.Debugf("ENC ciphertext (%d): %s %v", len(data), data, data)
// then, mac.
if _, err := w.mac.Write(data); err != nil {
return err
}
// Sum appends.
data = w.mac.Sum(data)
w.mac.Reset()
binary.BigEndian.PutUint32(buf[:4], uint32(len(data)))
_, err := w.w.Write(buf)
return err
} | go | func (w *etmWriter) WriteMsg(b []byte) error {
w.Lock()
defer w.Unlock()
// encrypt.
buf := pool.Get(4 + len(b) + w.mac.Size())
defer pool.Put(buf)
data := buf[4 : 4+len(b)]
w.str.XORKeyStream(data, b)
// log.Debugf("ENC plaintext (%d): %s %v", len(b), b, b)
// log.Debugf("ENC ciphertext (%d): %s %v", len(data), data, data)
// then, mac.
if _, err := w.mac.Write(data); err != nil {
return err
}
// Sum appends.
data = w.mac.Sum(data)
w.mac.Reset()
binary.BigEndian.PutUint32(buf[:4], uint32(len(data)))
_, err := w.w.Write(buf)
return err
} | [
"func",
"(",
"w",
"*",
"etmWriter",
")",
"WriteMsg",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"w",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"Unlock",
"(",
")",
"\n\n",
"// encrypt.",
"buf",
":=",
"pool",
".",
"Get",
"(",
"4",
"+",
... | // WriteMsg writes the msg in the passed in buffer. | [
"WriteMsg",
"writes",
"the",
"msg",
"in",
"the",
"passed",
"in",
"buffer",
"."
] | 3175340d7c342f07587c89ef4c14c9324f1f9f40 | https://github.com/libp2p/go-libp2p-secio/blob/3175340d7c342f07587c89ef4c14c9324f1f9f40/rw.go#L41-L66 |
9,615 | libp2p/go-libp2p-secio | rw.go | NewETMReader | func NewETMReader(r io.Reader, s cipher.Stream, mac HMAC) msgio.ReadCloser {
return &etmReader{msg: msgio.NewReader(r), str: s, mac: mac}
} | go | func NewETMReader(r io.Reader, s cipher.Stream, mac HMAC) msgio.ReadCloser {
return &etmReader{msg: msgio.NewReader(r), str: s, mac: mac}
} | [
"func",
"NewETMReader",
"(",
"r",
"io",
".",
"Reader",
",",
"s",
"cipher",
".",
"Stream",
",",
"mac",
"HMAC",
")",
"msgio",
".",
"ReadCloser",
"{",
"return",
"&",
"etmReader",
"{",
"msg",
":",
"msgio",
".",
"NewReader",
"(",
"r",
")",
",",
"str",
"... | // NewETMReader Encrypt-Then-MAC | [
"NewETMReader",
"Encrypt",
"-",
"Then",
"-",
"MAC"
] | 3175340d7c342f07587c89ef4c14c9324f1f9f40 | https://github.com/libp2p/go-libp2p-secio/blob/3175340d7c342f07587c89ef4c14c9324f1f9f40/rw.go#L99-L101 |
9,616 | libp2p/go-libp2p-secio | rw.go | readWriteMsg | func readWriteMsg(c msgio.ReadWriter, out []byte) ([]byte, error) {
wresult := make(chan error)
go func() {
wresult <- c.WriteMsg(out)
}()
msg, err1 := c.ReadMsg()
// Always wait for the read to finish.
err2 := <-wresult
if err1 != nil {
return nil, err1
}
if err2 != nil {
c.ReleaseMsg(msg)
return nil, err2
}
return msg, nil
} | go | func readWriteMsg(c msgio.ReadWriter, out []byte) ([]byte, error) {
wresult := make(chan error)
go func() {
wresult <- c.WriteMsg(out)
}()
msg, err1 := c.ReadMsg()
// Always wait for the read to finish.
err2 := <-wresult
if err1 != nil {
return nil, err1
}
if err2 != nil {
c.ReleaseMsg(msg)
return nil, err2
}
return msg, nil
} | [
"func",
"readWriteMsg",
"(",
"c",
"msgio",
".",
"ReadWriter",
",",
"out",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"wresult",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"wresult",
"<-"... | // read and write a message at the same time. | [
"read",
"and",
"write",
"a",
"message",
"at",
"the",
"same",
"time",
"."
] | 3175340d7c342f07587c89ef4c14c9324f1f9f40 | https://github.com/libp2p/go-libp2p-secio/blob/3175340d7c342f07587c89ef4c14c9324f1f9f40/rw.go#L249-L268 |
9,617 | phayes/permbits | permbits.go | Stat | func Stat(filepath string) (PermissionBits, error) {
fi, err := os.Stat(filepath)
if err != nil {
return 0, err
}
return FileMode(fi.Mode()), nil
} | go | func Stat(filepath string) (PermissionBits, error) {
fi, err := os.Stat(filepath)
if err != nil {
return 0, err
}
return FileMode(fi.Mode()), nil
} | [
"func",
"Stat",
"(",
"filepath",
"string",
")",
"(",
"PermissionBits",
",",
"error",
")",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"filepath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"retu... | // Given a filepath, get it's permission bits | [
"Given",
"a",
"filepath",
"get",
"it",
"s",
"permission",
"bits"
] | 1efae4548023f60d7a172fead76cccf194cf45de | https://github.com/phayes/permbits/blob/1efae4548023f60d7a172fead76cccf194cf45de/permbits.go#L26-L32 |
9,618 | phayes/permbits | permbits.go | FileMode | func FileMode(fm os.FileMode) PermissionBits {
perm := PermissionBits(fm.Perm())
if fm&os.ModeSetuid != 0 {
perm.SetSetuid(true)
}
if fm&os.ModeSetgid != 0 {
perm.SetSetgid(true)
}
if fm&os.ModeSticky != 0 {
perm.SetSticky(true)
}
return perm
} | go | func FileMode(fm os.FileMode) PermissionBits {
perm := PermissionBits(fm.Perm())
if fm&os.ModeSetuid != 0 {
perm.SetSetuid(true)
}
if fm&os.ModeSetgid != 0 {
perm.SetSetgid(true)
}
if fm&os.ModeSticky != 0 {
perm.SetSticky(true)
}
return perm
} | [
"func",
"FileMode",
"(",
"fm",
"os",
".",
"FileMode",
")",
"PermissionBits",
"{",
"perm",
":=",
"PermissionBits",
"(",
"fm",
".",
"Perm",
"(",
")",
")",
"\n\n",
"if",
"fm",
"&",
"os",
".",
"ModeSetuid",
"!=",
"0",
"{",
"perm",
".",
"SetSetuid",
"(",
... | // Given a FileMode from the os package, get it's permission bits | [
"Given",
"a",
"FileMode",
"from",
"the",
"os",
"package",
"get",
"it",
"s",
"permission",
"bits"
] | 1efae4548023f60d7a172fead76cccf194cf45de | https://github.com/phayes/permbits/blob/1efae4548023f60d7a172fead76cccf194cf45de/permbits.go#L35-L48 |
9,619 | phayes/permbits | permbits.go | Chmod | func Chmod(filepath string, b PermissionBits) error {
if e := syscall.Chmod(filepath, syscallMode(b)); e != nil {
return &os.PathError{"chmod", filepath, e}
}
return nil
} | go | func Chmod(filepath string, b PermissionBits) error {
if e := syscall.Chmod(filepath, syscallMode(b)); e != nil {
return &os.PathError{"chmod", filepath, e}
}
return nil
} | [
"func",
"Chmod",
"(",
"filepath",
"string",
",",
"b",
"PermissionBits",
")",
"error",
"{",
"if",
"e",
":=",
"syscall",
".",
"Chmod",
"(",
"filepath",
",",
"syscallMode",
"(",
"b",
")",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"&",
"os",
".",
"Pat... | // Given a filepath, set it's permission bits directly | [
"Given",
"a",
"filepath",
"set",
"it",
"s",
"permission",
"bits",
"directly"
] | 1efae4548023f60d7a172fead76cccf194cf45de | https://github.com/phayes/permbits/blob/1efae4548023f60d7a172fead76cccf194cf45de/permbits.go#L51-L56 |
9,620 | phayes/permbits | permbits.go | UpdateFileMode | func UpdateFileMode(fm *os.FileMode, b PermissionBits) {
// Setuid, Setgid, and Sticky bits are not in the same position in the two bitmaks
// So we need to set their values manually
if b.Setuid() {
*fm |= os.ModeSetuid
} else {
*fm &^= os.ModeSetuid
}
if b.Setgid() {
*fm |= os.ModeSetgid
} else {
*fm &^= os.ModeSetgid
}
if b.Sticky() {
*fm |= os.ModeSticky
} else {
*fm &^= os.ModeSticky
}
// unset bit-values that don't map to the same position in FileMode
b.SetSetgid(false)
b.SetSetuid(false)
b.SetSticky(false)
// Clear the permission bitss
*fm &^= 0777
// Set the permission bits
*fm |= os.FileMode(b)
} | go | func UpdateFileMode(fm *os.FileMode, b PermissionBits) {
// Setuid, Setgid, and Sticky bits are not in the same position in the two bitmaks
// So we need to set their values manually
if b.Setuid() {
*fm |= os.ModeSetuid
} else {
*fm &^= os.ModeSetuid
}
if b.Setgid() {
*fm |= os.ModeSetgid
} else {
*fm &^= os.ModeSetgid
}
if b.Sticky() {
*fm |= os.ModeSticky
} else {
*fm &^= os.ModeSticky
}
// unset bit-values that don't map to the same position in FileMode
b.SetSetgid(false)
b.SetSetuid(false)
b.SetSticky(false)
// Clear the permission bitss
*fm &^= 0777
// Set the permission bits
*fm |= os.FileMode(b)
} | [
"func",
"UpdateFileMode",
"(",
"fm",
"*",
"os",
".",
"FileMode",
",",
"b",
"PermissionBits",
")",
"{",
"// Setuid, Setgid, and Sticky bits are not in the same position in the two bitmaks",
"// So we need to set their values manually",
"if",
"b",
".",
"Setuid",
"(",
")",
"{"... | // Given an os.FileMode object, update it's permissions | [
"Given",
"an",
"os",
".",
"FileMode",
"object",
"update",
"it",
"s",
"permissions"
] | 1efae4548023f60d7a172fead76cccf194cf45de | https://github.com/phayes/permbits/blob/1efae4548023f60d7a172fead76cccf194cf45de/permbits.go#L59-L88 |
9,621 | phayes/permbits | permbits.go | syscallMode | func syscallMode(p PermissionBits) (o uint32) {
o |= uint32(p)
if p.Setuid() {
o |= syscall.S_ISUID
}
if p.Setgid() {
o |= syscall.S_ISGID
}
if p.Sticky() {
o |= syscall.S_ISVTX
}
return
} | go | func syscallMode(p PermissionBits) (o uint32) {
o |= uint32(p)
if p.Setuid() {
o |= syscall.S_ISUID
}
if p.Setgid() {
o |= syscall.S_ISGID
}
if p.Sticky() {
o |= syscall.S_ISVTX
}
return
} | [
"func",
"syscallMode",
"(",
"p",
"PermissionBits",
")",
"(",
"o",
"uint32",
")",
"{",
"o",
"|=",
"uint32",
"(",
"p",
")",
"\n\n",
"if",
"p",
".",
"Setuid",
"(",
")",
"{",
"o",
"|=",
"syscall",
".",
"S_ISUID",
"\n",
"}",
"\n",
"if",
"p",
".",
"S... | // syscallMode returns the syscall-specific mode bits from PermissionBits bit positions | [
"syscallMode",
"returns",
"the",
"syscall",
"-",
"specific",
"mode",
"bits",
"from",
"PermissionBits",
"bit",
"positions"
] | 1efae4548023f60d7a172fead76cccf194cf45de | https://github.com/phayes/permbits/blob/1efae4548023f60d7a172fead76cccf194cf45de/permbits.go#L251-L264 |
9,622 | itchyny/base58-go | base58.go | New | func New(alphabet []byte) *Encoding {
enc := &Encoding{}
copy(enc.alphabet[:], alphabet[:])
for i := range enc.decodeMap {
enc.decodeMap[i] = -1
}
for i, b := range enc.alphabet {
enc.decodeMap[b] = int64(i)
}
return enc
} | go | func New(alphabet []byte) *Encoding {
enc := &Encoding{}
copy(enc.alphabet[:], alphabet[:])
for i := range enc.decodeMap {
enc.decodeMap[i] = -1
}
for i, b := range enc.alphabet {
enc.decodeMap[b] = int64(i)
}
return enc
} | [
"func",
"New",
"(",
"alphabet",
"[",
"]",
"byte",
")",
"*",
"Encoding",
"{",
"enc",
":=",
"&",
"Encoding",
"{",
"}",
"\n",
"copy",
"(",
"enc",
".",
"alphabet",
"[",
":",
"]",
",",
"alphabet",
"[",
":",
"]",
")",
"\n",
"for",
"i",
":=",
"range",... | // New creates a new base58 encoding. | [
"New",
"creates",
"a",
"new",
"base58",
"encoding",
"."
] | 4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f | https://github.com/itchyny/base58-go/blob/4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f/base58.go#L15-L25 |
9,623 | itchyny/base58-go | base58.go | Encode | func (enc *Encoding) Encode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
n, ok := new(big.Int).SetString(string(src), 10)
if !ok {
return nil, fmt.Errorf("expecting a number but got %q", src)
}
bytes := make([]byte, 0, len(src))
for _, c := range src {
if c == '0' {
bytes = append(bytes, enc.alphabet[0])
} else {
break
}
}
zerocnt := len(bytes)
mod := new(big.Int)
zero := big.NewInt(0)
for {
switch n.Cmp(zero) {
case 1:
n.DivMod(n, radix, mod)
bytes = append(bytes, enc.alphabet[mod.Int64()])
case 0:
reverse(bytes[zerocnt:])
return bytes, nil
default:
return nil, fmt.Errorf("expecting a non-negative number in base58 encoding but got %s", n)
}
}
} | go | func (enc *Encoding) Encode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
n, ok := new(big.Int).SetString(string(src), 10)
if !ok {
return nil, fmt.Errorf("expecting a number but got %q", src)
}
bytes := make([]byte, 0, len(src))
for _, c := range src {
if c == '0' {
bytes = append(bytes, enc.alphabet[0])
} else {
break
}
}
zerocnt := len(bytes)
mod := new(big.Int)
zero := big.NewInt(0)
for {
switch n.Cmp(zero) {
case 1:
n.DivMod(n, radix, mod)
bytes = append(bytes, enc.alphabet[mod.Int64()])
case 0:
reverse(bytes[zerocnt:])
return bytes, nil
default:
return nil, fmt.Errorf("expecting a non-negative number in base58 encoding but got %s", n)
}
}
} | [
"func",
"(",
"enc",
"*",
"Encoding",
")",
"Encode",
"(",
"src",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"src",
")",
"==",
"0",
"{",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"nil",
"\n",
"}",... | // Encode encodes the number represented in the byte array base 10. | [
"Encode",
"encodes",
"the",
"number",
"represented",
"in",
"the",
"byte",
"array",
"base",
"10",
"."
] | 4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f | https://github.com/itchyny/base58-go/blob/4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f/base58.go#L45-L76 |
9,624 | itchyny/base58-go | base58.go | Decode | func (enc *Encoding) Decode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
var zeros []byte
for i, c := range src {
if c == enc.alphabet[0] && i < len(src)-1 {
zeros = append(zeros, '0')
} else {
break
}
}
n := new(big.Int)
var i int64
for _, c := range src {
if i = enc.decodeMap[c]; i < 0 {
return nil, fmt.Errorf("invalid character '%c' in decoding a base58 string \"%s\"", c, src)
}
n.Add(n.Mul(n, radix), big.NewInt(i))
}
return n.Append(zeros, 10), nil
} | go | func (enc *Encoding) Decode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
var zeros []byte
for i, c := range src {
if c == enc.alphabet[0] && i < len(src)-1 {
zeros = append(zeros, '0')
} else {
break
}
}
n := new(big.Int)
var i int64
for _, c := range src {
if i = enc.decodeMap[c]; i < 0 {
return nil, fmt.Errorf("invalid character '%c' in decoding a base58 string \"%s\"", c, src)
}
n.Add(n.Mul(n, radix), big.NewInt(i))
}
return n.Append(zeros, 10), nil
} | [
"func",
"(",
"enc",
"*",
"Encoding",
")",
"Decode",
"(",
"src",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"src",
")",
"==",
"0",
"{",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"nil",
"\n",
"}",... | // Decode decodes the base58 encoded bytes. | [
"Decode",
"decodes",
"the",
"base58",
"encoded",
"bytes",
"."
] | 4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f | https://github.com/itchyny/base58-go/blob/4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f/base58.go#L79-L100 |
9,625 | itchyny/base58-go | base58.go | UnmarshalFlag | func (enc *Encoding) UnmarshalFlag(value string) error {
switch value {
case "flickr":
*enc = *FlickrEncoding
case "ripple":
*enc = *RippleEncoding
case "bitcoin":
*enc = *BitcoinEncoding
default:
return fmt.Errorf("unknown encoding: %s", value)
}
return nil
} | go | func (enc *Encoding) UnmarshalFlag(value string) error {
switch value {
case "flickr":
*enc = *FlickrEncoding
case "ripple":
*enc = *RippleEncoding
case "bitcoin":
*enc = *BitcoinEncoding
default:
return fmt.Errorf("unknown encoding: %s", value)
}
return nil
} | [
"func",
"(",
"enc",
"*",
"Encoding",
")",
"UnmarshalFlag",
"(",
"value",
"string",
")",
"error",
"{",
"switch",
"value",
"{",
"case",
"\"",
"\"",
":",
"*",
"enc",
"=",
"*",
"FlickrEncoding",
"\n",
"case",
"\"",
"\"",
":",
"*",
"enc",
"=",
"*",
"Rip... | // UnmarshalFlag implements flags.Unmarshaler | [
"UnmarshalFlag",
"implements",
"flags",
".",
"Unmarshaler"
] | 4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f | https://github.com/itchyny/base58-go/blob/4ff5679a8f9daefa3b889eadf0d6c4b9c8c24c3f/base58.go#L103-L115 |
9,626 | bifurcation/mint | cookie-protector.go | NewDefaultCookieProtector | func NewDefaultCookieProtector() (CookieProtector, error) {
secret := make([]byte, cookieSecretSize)
if _, err := rand.Read(secret); err != nil {
return nil, err
}
return &DefaultCookieProtector{secret: secret}, nil
} | go | func NewDefaultCookieProtector() (CookieProtector, error) {
secret := make([]byte, cookieSecretSize)
if _, err := rand.Read(secret); err != nil {
return nil, err
}
return &DefaultCookieProtector{secret: secret}, nil
} | [
"func",
"NewDefaultCookieProtector",
"(",
")",
"(",
"CookieProtector",
",",
"error",
")",
"{",
"secret",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"cookieSecretSize",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"secret",
")",
";",... | // NewDefaultCookieProtector creates a source for source address tokens | [
"NewDefaultCookieProtector",
"creates",
"a",
"source",
"for",
"source",
"address",
"tokens"
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/cookie-protector.go#L33-L39 |
9,627 | bifurcation/mint | cookie-protector.go | NewToken | func (s *DefaultCookieProtector) NewToken(data []byte) ([]byte, error) {
nonce := make([]byte, cookieNonceSize)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
aead, aeadNonce, err := s.createAEAD(nonce)
if err != nil {
return nil, err
}
return append(nonce, aead.Seal(nil, aeadNonce, data, nil)...), nil
} | go | func (s *DefaultCookieProtector) NewToken(data []byte) ([]byte, error) {
nonce := make([]byte, cookieNonceSize)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
aead, aeadNonce, err := s.createAEAD(nonce)
if err != nil {
return nil, err
}
return append(nonce, aead.Seal(nil, aeadNonce, data, nil)...), nil
} | [
"func",
"(",
"s",
"*",
"DefaultCookieProtector",
")",
"NewToken",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"nonce",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"cookieNonceSize",
")",
"\n",
"if",
"_",
",",
... | // NewToken encodes data into a new token. | [
"NewToken",
"encodes",
"data",
"into",
"a",
"new",
"token",
"."
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/cookie-protector.go#L42-L52 |
9,628 | bifurcation/mint | cookie-protector.go | DecodeToken | func (s *DefaultCookieProtector) DecodeToken(p []byte) ([]byte, error) {
if len(p) < cookieNonceSize {
return nil, fmt.Errorf("Token too short: %d", len(p))
}
nonce := p[:cookieNonceSize]
aead, aeadNonce, err := s.createAEAD(nonce)
if err != nil {
return nil, err
}
return aead.Open(nil, aeadNonce, p[cookieNonceSize:], nil)
} | go | func (s *DefaultCookieProtector) DecodeToken(p []byte) ([]byte, error) {
if len(p) < cookieNonceSize {
return nil, fmt.Errorf("Token too short: %d", len(p))
}
nonce := p[:cookieNonceSize]
aead, aeadNonce, err := s.createAEAD(nonce)
if err != nil {
return nil, err
}
return aead.Open(nil, aeadNonce, p[cookieNonceSize:], nil)
} | [
"func",
"(",
"s",
"*",
"DefaultCookieProtector",
")",
"DecodeToken",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"p",
")",
"<",
"cookieNonceSize",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf"... | // DecodeToken decodes a token. | [
"DecodeToken",
"decodes",
"a",
"token",
"."
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/cookie-protector.go#L55-L65 |
9,629 | bifurcation/mint | state-machine.go | Next | func (state stateConnected) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
return state, nil, AlertNoAlert
} | go | func (state stateConnected) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
return state, nil, AlertNoAlert
} | [
"func",
"(",
"state",
"stateConnected",
")",
"Next",
"(",
"hr",
"handshakeMessageReader",
")",
"(",
"HandshakeState",
",",
"[",
"]",
"HandshakeAction",
",",
"Alert",
")",
"{",
"return",
"state",
",",
"nil",
",",
"AlertNoAlert",
"\n",
"}"
] | // Next does nothing for this state. | [
"Next",
"does",
"nothing",
"for",
"this",
"state",
"."
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/state-machine.go#L181-L183 |
9,630 | bifurcation/mint | timer.go | remaining | func (ts *timerSet) remaining() (bool, time.Duration) {
for _, t := range ts.ts {
if t.cb != nil {
return true, time.Until(t.deadline)
}
}
return false, time.Duration(0)
} | go | func (ts *timerSet) remaining() (bool, time.Duration) {
for _, t := range ts.ts {
if t.cb != nil {
return true, time.Until(t.deadline)
}
}
return false, time.Duration(0)
} | [
"func",
"(",
"ts",
"*",
"timerSet",
")",
"remaining",
"(",
")",
"(",
"bool",
",",
"time",
".",
"Duration",
")",
"{",
"for",
"_",
",",
"t",
":=",
"range",
"ts",
".",
"ts",
"{",
"if",
"t",
".",
"cb",
"!=",
"nil",
"{",
"return",
"true",
",",
"ti... | // Returns the next time any of the timers would fire. | [
"Returns",
"the",
"next",
"time",
"any",
"of",
"the",
"timers",
"would",
"fire",
"."
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/timer.go#L79-L87 |
9,631 | bifurcation/mint | handshake-layer.go | sendAlert | func (h *HandshakeLayer) sendAlert(err Alert) error {
tmp := make([]byte, 2)
tmp[0] = AlertLevelError
tmp[1] = byte(err)
h.conn.WriteRecord(&TLSPlaintext{
contentType: RecordTypeAlert,
fragment: tmp},
)
// closeNotify is a special case in that it isn't an error:
if err != AlertCloseNotify {
return &net.OpError{Op: "local error", Err: err}
}
return nil
} | go | func (h *HandshakeLayer) sendAlert(err Alert) error {
tmp := make([]byte, 2)
tmp[0] = AlertLevelError
tmp[1] = byte(err)
h.conn.WriteRecord(&TLSPlaintext{
contentType: RecordTypeAlert,
fragment: tmp},
)
// closeNotify is a special case in that it isn't an error:
if err != AlertCloseNotify {
return &net.OpError{Op: "local error", Err: err}
}
return nil
} | [
"func",
"(",
"h",
"*",
"HandshakeLayer",
")",
"sendAlert",
"(",
"err",
"Alert",
")",
"error",
"{",
"tmp",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"2",
")",
"\n",
"tmp",
"[",
"0",
"]",
"=",
"AlertLevelError",
"\n",
"tmp",
"[",
"1",
"]",
"=",
"... | // sendAlert sends a TLS alert message. | [
"sendAlert",
"sends",
"a",
"TLS",
"alert",
"message",
"."
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/handshake-layer.go#L232-L246 |
9,632 | bifurcation/mint | conn.go | Clone | func (c *Config) Clone() *Config {
c.mutex.Lock()
defer c.mutex.Unlock()
return &Config{
ServerName: c.ServerName,
SendSessionTickets: c.SendSessionTickets,
TicketLifetime: c.TicketLifetime,
TicketLen: c.TicketLen,
EarlyDataLifetime: c.EarlyDataLifetime,
AllowEarlyData: c.AllowEarlyData,
RequireCookie: c.RequireCookie,
CookieHandler: c.CookieHandler,
CookieProtector: c.CookieProtector,
ExtensionHandler: c.ExtensionHandler,
RequireClientAuth: c.RequireClientAuth,
Time: c.Time,
RootCAs: c.RootCAs,
InsecureSkipVerify: c.InsecureSkipVerify,
Certificates: c.Certificates,
VerifyPeerCertificate: c.VerifyPeerCertificate,
CipherSuites: c.CipherSuites,
Groups: c.Groups,
SignatureSchemes: c.SignatureSchemes,
NextProtos: c.NextProtos,
PSKs: c.PSKs,
PSKModes: c.PSKModes,
NonBlocking: c.NonBlocking,
UseDTLS: c.UseDTLS,
}
} | go | func (c *Config) Clone() *Config {
c.mutex.Lock()
defer c.mutex.Unlock()
return &Config{
ServerName: c.ServerName,
SendSessionTickets: c.SendSessionTickets,
TicketLifetime: c.TicketLifetime,
TicketLen: c.TicketLen,
EarlyDataLifetime: c.EarlyDataLifetime,
AllowEarlyData: c.AllowEarlyData,
RequireCookie: c.RequireCookie,
CookieHandler: c.CookieHandler,
CookieProtector: c.CookieProtector,
ExtensionHandler: c.ExtensionHandler,
RequireClientAuth: c.RequireClientAuth,
Time: c.Time,
RootCAs: c.RootCAs,
InsecureSkipVerify: c.InsecureSkipVerify,
Certificates: c.Certificates,
VerifyPeerCertificate: c.VerifyPeerCertificate,
CipherSuites: c.CipherSuites,
Groups: c.Groups,
SignatureSchemes: c.SignatureSchemes,
NextProtos: c.NextProtos,
PSKs: c.PSKs,
PSKModes: c.PSKModes,
NonBlocking: c.NonBlocking,
UseDTLS: c.UseDTLS,
}
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Clone",
"(",
")",
"*",
"Config",
"{",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"&",
"Config",
"{",
"ServerName",
":",
"c",
".",... | // Clone returns a shallow clone of c. It is safe to clone a Config that is
// being used concurrently by a TLS client or server. | [
"Clone",
"returns",
"a",
"shallow",
"clone",
"of",
"c",
".",
"It",
"is",
"safe",
"to",
"clone",
"a",
"Config",
"that",
"is",
"being",
"used",
"concurrently",
"by",
"a",
"TLS",
"client",
"or",
"server",
"."
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/conn.go#L141-L173 |
9,633 | bifurcation/mint | conn.go | Read | func (c *Conn) Read(buffer []byte) (int, error) {
if _, connected := c.hState.(stateConnected); !connected {
// Clients can't call Read prior to handshake completion.
if c.isClient {
return 0, errors.New("Read called before the handshake completed")
}
// Neither can servers that don't allow early data.
if !c.config.AllowEarlyData {
return 0, errors.New("Read called before the handshake completed")
}
// If there's no early data, then return WouldBlock
if len(c.hsCtx.earlyData) == 0 {
return 0, AlertWouldBlock
}
return readPartial(&c.hsCtx.earlyData, buffer), nil
}
// The handshake is now connected.
logf(logTypeHandshake, "conn.Read with buffer = %d", len(buffer))
if alert := c.Handshake(); alert != AlertNoAlert {
return 0, alert
}
if len(buffer) == 0 {
return 0, nil
}
// Run our timers.
if c.config.UseDTLS {
if err := c.hsCtx.timers.check(time.Now()); err != nil {
return 0, AlertInternalError
}
}
// Lock the input channel
c.in.Lock()
defer c.in.Unlock()
for len(c.readBuffer) == 0 {
err := c.consumeRecord()
// err can be nil if consumeRecord processed a non app-data
// record.
if err != nil {
if c.config.NonBlocking || err != AlertWouldBlock {
logf(logTypeIO, "conn.Read returns err=%v", err)
return 0, err
}
}
}
return readPartial(&c.readBuffer, buffer), nil
} | go | func (c *Conn) Read(buffer []byte) (int, error) {
if _, connected := c.hState.(stateConnected); !connected {
// Clients can't call Read prior to handshake completion.
if c.isClient {
return 0, errors.New("Read called before the handshake completed")
}
// Neither can servers that don't allow early data.
if !c.config.AllowEarlyData {
return 0, errors.New("Read called before the handshake completed")
}
// If there's no early data, then return WouldBlock
if len(c.hsCtx.earlyData) == 0 {
return 0, AlertWouldBlock
}
return readPartial(&c.hsCtx.earlyData, buffer), nil
}
// The handshake is now connected.
logf(logTypeHandshake, "conn.Read with buffer = %d", len(buffer))
if alert := c.Handshake(); alert != AlertNoAlert {
return 0, alert
}
if len(buffer) == 0 {
return 0, nil
}
// Run our timers.
if c.config.UseDTLS {
if err := c.hsCtx.timers.check(time.Now()); err != nil {
return 0, AlertInternalError
}
}
// Lock the input channel
c.in.Lock()
defer c.in.Unlock()
for len(c.readBuffer) == 0 {
err := c.consumeRecord()
// err can be nil if consumeRecord processed a non app-data
// record.
if err != nil {
if c.config.NonBlocking || err != AlertWouldBlock {
logf(logTypeIO, "conn.Read returns err=%v", err)
return 0, err
}
}
}
return readPartial(&c.readBuffer, buffer), nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Read",
"(",
"buffer",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"_",
",",
"connected",
":=",
"c",
".",
"hState",
".",
"(",
"stateConnected",
")",
";",
"!",
"connected",
"{",
"// Clients ... | // Read application data up to the size of buffer. Handshake and alert records
// are consumed by the Conn object directly. | [
"Read",
"application",
"data",
"up",
"to",
"the",
"size",
"of",
"buffer",
".",
"Handshake",
"and",
"alert",
"records",
"are",
"consumed",
"by",
"the",
"Conn",
"object",
"directly",
"."
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/conn.go#L414-L468 |
9,634 | bifurcation/mint | conn.go | Write | func (c *Conn) Write(buffer []byte) (int, error) {
// Lock the output channel
c.out.Lock()
defer c.out.Unlock()
if !c.Writable() {
return 0, errors.New("Write called before the handshake completed (and early data not in use)")
}
// Send full-size fragments
var start int
sent := 0
for start = 0; len(buffer)-start >= maxFragmentLen; start += maxFragmentLen {
err := c.out.WriteRecord(&TLSPlaintext{
contentType: RecordTypeApplicationData,
fragment: buffer[start : start+maxFragmentLen],
})
if err != nil {
return sent, err
}
sent += maxFragmentLen
}
// Send a final partial fragment if necessary
if start < len(buffer) {
err := c.out.WriteRecord(&TLSPlaintext{
contentType: RecordTypeApplicationData,
fragment: buffer[start:],
})
if err != nil {
return sent, err
}
sent += len(buffer[start:])
}
return sent, nil
} | go | func (c *Conn) Write(buffer []byte) (int, error) {
// Lock the output channel
c.out.Lock()
defer c.out.Unlock()
if !c.Writable() {
return 0, errors.New("Write called before the handshake completed (and early data not in use)")
}
// Send full-size fragments
var start int
sent := 0
for start = 0; len(buffer)-start >= maxFragmentLen; start += maxFragmentLen {
err := c.out.WriteRecord(&TLSPlaintext{
contentType: RecordTypeApplicationData,
fragment: buffer[start : start+maxFragmentLen],
})
if err != nil {
return sent, err
}
sent += maxFragmentLen
}
// Send a final partial fragment if necessary
if start < len(buffer) {
err := c.out.WriteRecord(&TLSPlaintext{
contentType: RecordTypeApplicationData,
fragment: buffer[start:],
})
if err != nil {
return sent, err
}
sent += len(buffer[start:])
}
return sent, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Write",
"(",
"buffer",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"// Lock the output channel",
"c",
".",
"out",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"out",
".",
"Unlock",
"(",
")",
... | // Write application data | [
"Write",
"application",
"data"
] | 83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88 | https://github.com/bifurcation/mint/blob/83ba9bc2ead9cdf8b0c8bd94e8a41243e5f6ed88/conn.go#L471-L508 |
9,635 | fernet/fernet-go | fernet.go | encodedLen | func encodedLen(n int) int {
const k = aes.BlockSize
return n/k*k + k + overhead
} | go | func encodedLen(n int) int {
const k = aes.BlockSize
return n/k*k + k + overhead
} | [
"func",
"encodedLen",
"(",
"n",
"int",
")",
"int",
"{",
"const",
"k",
"=",
"aes",
".",
"BlockSize",
"\n",
"return",
"n",
"/",
"k",
"*",
"k",
"+",
"k",
"+",
"overhead",
"\n",
"}"
] | // token length for input msg of length n, not including base64 | [
"token",
"length",
"for",
"input",
"msg",
"of",
"length",
"n",
"not",
"including",
"base64"
] | 9eac43b88a5efb8651d24de9b68e87567e029736 | https://github.com/fernet/fernet-go/blob/9eac43b88a5efb8651d24de9b68e87567e029736/fernet.go#L53-L56 |
9,636 | fernet/fernet-go | fernet.go | verify | func verify(msg, tok []byte, ttl time.Duration, now time.Time, k *Key) []byte {
if len(tok) < 1 || tok[0] != version {
return nil
}
ts := time.Unix(int64(binary.BigEndian.Uint64(tok[1:])), 0)
if ttl > 0 && (now.After(ts.Add(ttl)) || ts.After(now.Add(maxClockSkew))) {
return nil
}
n := len(tok) - sha256.Size
var hmac [sha256.Size]byte
genhmac(hmac[:0], tok[:n], k.signBytes())
if subtle.ConstantTimeCompare(tok[n:], hmac[:]) != 1 {
return nil
}
pay := tok[payOffset : len(tok)-sha256.Size]
if len(pay)%aes.BlockSize != 0 {
return nil
}
if msg != nil {
copy(msg, pay)
pay = msg
}
bc, _ := aes.NewCipher(k.cryptBytes())
iv := tok[9:][:aes.BlockSize]
cipher.NewCBCDecrypter(bc, iv).CryptBlocks(pay, pay)
return unpad(pay)
} | go | func verify(msg, tok []byte, ttl time.Duration, now time.Time, k *Key) []byte {
if len(tok) < 1 || tok[0] != version {
return nil
}
ts := time.Unix(int64(binary.BigEndian.Uint64(tok[1:])), 0)
if ttl > 0 && (now.After(ts.Add(ttl)) || ts.After(now.Add(maxClockSkew))) {
return nil
}
n := len(tok) - sha256.Size
var hmac [sha256.Size]byte
genhmac(hmac[:0], tok[:n], k.signBytes())
if subtle.ConstantTimeCompare(tok[n:], hmac[:]) != 1 {
return nil
}
pay := tok[payOffset : len(tok)-sha256.Size]
if len(pay)%aes.BlockSize != 0 {
return nil
}
if msg != nil {
copy(msg, pay)
pay = msg
}
bc, _ := aes.NewCipher(k.cryptBytes())
iv := tok[9:][:aes.BlockSize]
cipher.NewCBCDecrypter(bc, iv).CryptBlocks(pay, pay)
return unpad(pay)
} | [
"func",
"verify",
"(",
"msg",
",",
"tok",
"[",
"]",
"byte",
",",
"ttl",
"time",
".",
"Duration",
",",
"now",
"time",
".",
"Time",
",",
"k",
"*",
"Key",
")",
"[",
"]",
"byte",
"{",
"if",
"len",
"(",
"tok",
")",
"<",
"1",
"||",
"tok",
"[",
"0... | // if msg is nil, decrypts in place and returns a slice of tok. | [
"if",
"msg",
"is",
"nil",
"decrypts",
"in",
"place",
"and",
"returns",
"a",
"slice",
"of",
"tok",
"."
] | 9eac43b88a5efb8651d24de9b68e87567e029736 | https://github.com/fernet/fernet-go/blob/9eac43b88a5efb8651d24de9b68e87567e029736/fernet.go#L65-L91 |
9,637 | fernet/fernet-go | fernet.go | EncryptAndSign | func EncryptAndSign(msg []byte, k *Key) (tok []byte, err error) {
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
b := make([]byte, encodedLen(len(msg)))
n := gen(b, msg, iv, time.Now(), k)
tok = make([]byte, encoding.EncodedLen(n))
encoding.Encode(tok, b[:n])
return tok, nil
} | go | func EncryptAndSign(msg []byte, k *Key) (tok []byte, err error) {
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
b := make([]byte, encodedLen(len(msg)))
n := gen(b, msg, iv, time.Now(), k)
tok = make([]byte, encoding.EncodedLen(n))
encoding.Encode(tok, b[:n])
return tok, nil
} | [
"func",
"EncryptAndSign",
"(",
"msg",
"[",
"]",
"byte",
",",
"k",
"*",
"Key",
")",
"(",
"tok",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"iv",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"aes",
".",
"BlockSize",
")",
"\n",
"if",
"_",
","... | // EncryptAndSign encrypts and signs msg with key k and returns the resulting
// fernet token. If msg contains text, the text should be encoded
// with UTF-8 to follow fernet convention. | [
"EncryptAndSign",
"encrypts",
"and",
"signs",
"msg",
"with",
"key",
"k",
"and",
"returns",
"the",
"resulting",
"fernet",
"token",
".",
"If",
"msg",
"contains",
"text",
"the",
"text",
"should",
"be",
"encoded",
"with",
"UTF",
"-",
"8",
"to",
"follow",
"fern... | 9eac43b88a5efb8651d24de9b68e87567e029736 | https://github.com/fernet/fernet-go/blob/9eac43b88a5efb8651d24de9b68e87567e029736/fernet.go#L143-L153 |
9,638 | fernet/fernet-go | fernet.go | VerifyAndDecrypt | func VerifyAndDecrypt(tok []byte, ttl time.Duration, k []*Key) (msg []byte) {
b := make([]byte, encoding.DecodedLen(len(tok)))
n, _ := encoding.Decode(b, tok)
for _, k1 := range k {
msg = verify(nil, b[:n], ttl, time.Now(), k1)
if msg != nil {
return msg
}
}
return nil
} | go | func VerifyAndDecrypt(tok []byte, ttl time.Duration, k []*Key) (msg []byte) {
b := make([]byte, encoding.DecodedLen(len(tok)))
n, _ := encoding.Decode(b, tok)
for _, k1 := range k {
msg = verify(nil, b[:n], ttl, time.Now(), k1)
if msg != nil {
return msg
}
}
return nil
} | [
"func",
"VerifyAndDecrypt",
"(",
"tok",
"[",
"]",
"byte",
",",
"ttl",
"time",
".",
"Duration",
",",
"k",
"[",
"]",
"*",
"Key",
")",
"(",
"msg",
"[",
"]",
"byte",
")",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"encoding",
".",
"Decoded... | // VerifyAndDecrypt verifies that tok is a valid fernet token that was signed
// with a key in k at most ttl time ago only if ttl is greater than zero.
// Returns the message contained in tok if tok is valid, otherwise nil. | [
"VerifyAndDecrypt",
"verifies",
"that",
"tok",
"is",
"a",
"valid",
"fernet",
"token",
"that",
"was",
"signed",
"with",
"a",
"key",
"in",
"k",
"at",
"most",
"ttl",
"time",
"ago",
"only",
"if",
"ttl",
"is",
"greater",
"than",
"zero",
".",
"Returns",
"the",... | 9eac43b88a5efb8651d24de9b68e87567e029736 | https://github.com/fernet/fernet-go/blob/9eac43b88a5efb8651d24de9b68e87567e029736/fernet.go#L158-L168 |
9,639 | fernet/fernet-go | key.go | DecodeKey | func DecodeKey(s string) (*Key, error) {
var b []byte
var err error
if s == "" {
return nil, errors.New("empty key")
}
if len(s) == hex.EncodedLen(len(Key{})) {
b, err = hex.DecodeString(s)
} else {
b, err = base64.StdEncoding.DecodeString(s)
if err != nil {
b, err = base64.URLEncoding.DecodeString(s)
}
}
if err != nil {
return nil, err
}
if len(b) != len(Key{}) {
return nil, errKeyLen
}
k := new(Key)
copy(k[:], b)
return k, nil
} | go | func DecodeKey(s string) (*Key, error) {
var b []byte
var err error
if s == "" {
return nil, errors.New("empty key")
}
if len(s) == hex.EncodedLen(len(Key{})) {
b, err = hex.DecodeString(s)
} else {
b, err = base64.StdEncoding.DecodeString(s)
if err != nil {
b, err = base64.URLEncoding.DecodeString(s)
}
}
if err != nil {
return nil, err
}
if len(b) != len(Key{}) {
return nil, errKeyLen
}
k := new(Key)
copy(k[:], b)
return k, nil
} | [
"func",
"DecodeKey",
"(",
"s",
"string",
")",
"(",
"*",
"Key",
",",
"error",
")",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"... | // DecodeKey decodes a key from s and returns it. The key can be in
// hexadecimal, standard base64, or URL-safe base64. | [
"DecodeKey",
"decodes",
"a",
"key",
"from",
"s",
"and",
"returns",
"it",
".",
"The",
"key",
"can",
"be",
"in",
"hexadecimal",
"standard",
"base64",
"or",
"URL",
"-",
"safe",
"base64",
"."
] | 9eac43b88a5efb8651d24de9b68e87567e029736 | https://github.com/fernet/fernet-go/blob/9eac43b88a5efb8651d24de9b68e87567e029736/key.go#L40-L63 |
9,640 | fernet/fernet-go | key.go | DecodeKeys | func DecodeKeys(a ...string) ([]*Key, error) {
if len(a) == 0 {
return nil, errNoKeys
}
var err error
ks := make([]*Key, len(a))
for i, s := range a {
ks[i], err = DecodeKey(s)
if err != nil {
return nil, err
}
}
return ks, nil
} | go | func DecodeKeys(a ...string) ([]*Key, error) {
if len(a) == 0 {
return nil, errNoKeys
}
var err error
ks := make([]*Key, len(a))
for i, s := range a {
ks[i], err = DecodeKey(s)
if err != nil {
return nil, err
}
}
return ks, nil
} | [
"func",
"DecodeKeys",
"(",
"a",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"Key",
",",
"error",
")",
"{",
"if",
"len",
"(",
"a",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errNoKeys",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"ks",
":=",
... | // DecodeKeys decodes each element of a using DecodeKey and returns the
// resulting keys. Requires at least one key. | [
"DecodeKeys",
"decodes",
"each",
"element",
"of",
"a",
"using",
"DecodeKey",
"and",
"returns",
"the",
"resulting",
"keys",
".",
"Requires",
"at",
"least",
"one",
"key",
"."
] | 9eac43b88a5efb8651d24de9b68e87567e029736 | https://github.com/fernet/fernet-go/blob/9eac43b88a5efb8651d24de9b68e87567e029736/key.go#L67-L80 |
9,641 | fernet/fernet-go | key.go | MustDecodeKeys | func MustDecodeKeys(a ...string) []*Key {
k, err := DecodeKeys(a...)
if err != nil {
panic(err)
}
return k
} | go | func MustDecodeKeys(a ...string) []*Key {
k, err := DecodeKeys(a...)
if err != nil {
panic(err)
}
return k
} | [
"func",
"MustDecodeKeys",
"(",
"a",
"...",
"string",
")",
"[",
"]",
"*",
"Key",
"{",
"k",
",",
"err",
":=",
"DecodeKeys",
"(",
"a",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"k",
"\n",... | // MustDecodeKeys is like DecodeKeys, but panics if an error occurs.
// It simplifies safe initialization of global variables holding
// keys. | [
"MustDecodeKeys",
"is",
"like",
"DecodeKeys",
"but",
"panics",
"if",
"an",
"error",
"occurs",
".",
"It",
"simplifies",
"safe",
"initialization",
"of",
"global",
"variables",
"holding",
"keys",
"."
] | 9eac43b88a5efb8651d24de9b68e87567e029736 | https://github.com/fernet/fernet-go/blob/9eac43b88a5efb8651d24de9b68e87567e029736/key.go#L85-L91 |
9,642 | opentracing/basictracer-go | examples/dapperish/trivialrecorder.go | NewTrivialRecorder | func NewTrivialRecorder(processName string) *TrivialRecorder {
return &TrivialRecorder{
processName: processName,
tags: make(map[string]string),
}
} | go | func NewTrivialRecorder(processName string) *TrivialRecorder {
return &TrivialRecorder{
processName: processName,
tags: make(map[string]string),
}
} | [
"func",
"NewTrivialRecorder",
"(",
"processName",
"string",
")",
"*",
"TrivialRecorder",
"{",
"return",
"&",
"TrivialRecorder",
"{",
"processName",
":",
"processName",
",",
"tags",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"}",
"\n",
... | // NewTrivialRecorder returns a TrivialRecorder for the given `processName`. | [
"NewTrivialRecorder",
"returns",
"a",
"TrivialRecorder",
"for",
"the",
"given",
"processName",
"."
] | 98b91394c2def4a44acff5e100538b4812f2f694 | https://github.com/opentracing/basictracer-go/blob/98b91394c2def4a44acff5e100538b4812f2f694/examples/dapperish/trivialrecorder.go#L16-L21 |
9,643 | opentracing/basictracer-go | examples/dapperish/trivialrecorder.go | SetTag | func (t *TrivialRecorder) SetTag(key string, val interface{}) *TrivialRecorder {
t.tags[key] = fmt.Sprint(val)
return t
} | go | func (t *TrivialRecorder) SetTag(key string, val interface{}) *TrivialRecorder {
t.tags[key] = fmt.Sprint(val)
return t
} | [
"func",
"(",
"t",
"*",
"TrivialRecorder",
")",
"SetTag",
"(",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
")",
"*",
"TrivialRecorder",
"{",
"t",
".",
"tags",
"[",
"key",
"]",
"=",
"fmt",
".",
"Sprint",
"(",
"val",
")",
"\n",
"return",
"t",
... | // SetTag sets a tag. | [
"SetTag",
"sets",
"a",
"tag",
"."
] | 98b91394c2def4a44acff5e100538b4812f2f694 | https://github.com/opentracing/basictracer-go/blob/98b91394c2def4a44acff5e100538b4812f2f694/examples/dapperish/trivialrecorder.go#L27-L30 |
9,644 | opentracing/basictracer-go | examples/dapperish/trivialrecorder.go | RecordSpan | func (t *TrivialRecorder) RecordSpan(span basictracer.RawSpan) {
fmt.Printf(
"RecordSpan: %v[%v, %v us] --> %v logs. context: %v; baggage: %v\n",
span.Operation, span.Start, span.Duration, len(span.Logs),
span.Context, span.Context.Baggage)
for i, l := range span.Logs {
fmt.Printf(
" log %v @ %v: %v\n", i, l.Timestamp, l.Fields)
}
} | go | func (t *TrivialRecorder) RecordSpan(span basictracer.RawSpan) {
fmt.Printf(
"RecordSpan: %v[%v, %v us] --> %v logs. context: %v; baggage: %v\n",
span.Operation, span.Start, span.Duration, len(span.Logs),
span.Context, span.Context.Baggage)
for i, l := range span.Logs {
fmt.Printf(
" log %v @ %v: %v\n", i, l.Timestamp, l.Fields)
}
} | [
"func",
"(",
"t",
"*",
"TrivialRecorder",
")",
"RecordSpan",
"(",
"span",
"basictracer",
".",
"RawSpan",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"span",
".",
"Operation",
",",
"span",
".",
"Start",
",",
"span",
".",
"Duration",
"... | // RecordSpan complies with the basictracer.Recorder interface. | [
"RecordSpan",
"complies",
"with",
"the",
"basictracer",
".",
"Recorder",
"interface",
"."
] | 98b91394c2def4a44acff5e100538b4812f2f694 | https://github.com/opentracing/basictracer-go/blob/98b91394c2def4a44acff5e100538b4812f2f694/examples/dapperish/trivialrecorder.go#L33-L42 |
9,645 | remind101/pkg | httpx/errors/errors.go | WithInfo | func WithInfo(ctx context.Context, key string, value interface{}) context.Context {
ctx = withInfo(ctx)
i, _ := infoFromContext(ctx)
i.data[key] = value
return ctx
} | go | func WithInfo(ctx context.Context, key string, value interface{}) context.Context {
ctx = withInfo(ctx)
i, _ := infoFromContext(ctx)
i.data[key] = value
return ctx
} | [
"func",
"WithInfo",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"context",
".",
"Context",
"{",
"ctx",
"=",
"withInfo",
"(",
"ctx",
")",
"\n",
"i",
",",
"_",
":=",
"infoFromContext",
"(",
"ct... | // WithInfo adds contextual information to the info object in the context. | [
"WithInfo",
"adds",
"contextual",
"information",
"to",
"the",
"info",
"object",
"in",
"the",
"context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/errors/errors.go#L34-L39 |
9,646 | remind101/pkg | httpx/errors/errors.go | WithRequest | func WithRequest(ctx context.Context, req *http.Request) context.Context {
ctx = withInfo(ctx)
i, _ := infoFromContext(ctx)
i.request = safeCloneRequest(req)
return ctx
} | go | func WithRequest(ctx context.Context, req *http.Request) context.Context {
ctx = withInfo(ctx)
i, _ := infoFromContext(ctx)
i.request = safeCloneRequest(req)
return ctx
} | [
"func",
"WithRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"http",
".",
"Request",
")",
"context",
".",
"Context",
"{",
"ctx",
"=",
"withInfo",
"(",
"ctx",
")",
"\n",
"i",
",",
"_",
":=",
"infoFromContext",
"(",
"ctx",
")",
"\n",
... | // WithRequest adds information from an http.Request to the info object in the context. | [
"WithRequest",
"adds",
"information",
"from",
"an",
"http",
".",
"Request",
"to",
"the",
"info",
"object",
"in",
"the",
"context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/errors/errors.go#L42-L47 |
9,647 | remind101/pkg | httpx/errors/errors.go | New | func New(ctx context.Context, err error, skip int) *Error {
if e, ok := err.(*Error); ok {
return e
}
return new(err, skip+1).WithContext(ctx)
} | go | func New(ctx context.Context, err error, skip int) *Error {
if e, ok := err.(*Error); ok {
return e
}
return new(err, skip+1).WithContext(ctx)
} | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"err",
"error",
",",
"skip",
"int",
")",
"*",
"Error",
"{",
"if",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"Error",
")",
";",
"ok",
"{",
"return",
"e",
"\n",
"}",
"\n",
"return",
"... | // New returns a new Error instance. If err is already an Error instance,
// it will be returned, otherwise err will be wrapped with Error. | [
"New",
"returns",
"a",
"new",
"Error",
"instance",
".",
"If",
"err",
"is",
"already",
"an",
"Error",
"instance",
"it",
"will",
"be",
"returned",
"otherwise",
"err",
"will",
"be",
"wrapped",
"with",
"Error",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/errors/errors.go#L82-L87 |
9,648 | remind101/pkg | httpx/errors/errors.go | new | func new(err error, skip int) *Error {
return &Error{
Err: err,
stackTrace: stacktrace(err, skip+1),
info: map[string]interface{}{},
}
} | go | func new(err error, skip int) *Error {
return &Error{
Err: err,
stackTrace: stacktrace(err, skip+1),
info: map[string]interface{}{},
}
} | [
"func",
"new",
"(",
"err",
"error",
",",
"skip",
"int",
")",
"*",
"Error",
"{",
"return",
"&",
"Error",
"{",
"Err",
":",
"err",
",",
"stackTrace",
":",
"stacktrace",
"(",
"err",
",",
"skip",
"+",
"1",
")",
",",
"info",
":",
"map",
"[",
"string",
... | // new wraps err as an Error and generates a stack trace pointing at the
// caller of this function. | [
"new",
"wraps",
"err",
"as",
"an",
"Error",
"and",
"generates",
"a",
"stack",
"trace",
"pointing",
"at",
"the",
"caller",
"of",
"this",
"function",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/errors/errors.go#L91-L97 |
9,649 | remind101/pkg | httpx/errors/errors.go | WithContext | func (e *Error) WithContext(ctx context.Context) *Error {
if i, ok := infoFromContext(ctx); ok {
e.info = i.data
e.request = i.request
}
return e
} | go | func (e *Error) WithContext(ctx context.Context) *Error {
if i, ok := infoFromContext(ctx); ok {
e.info = i.data
e.request = i.request
}
return e
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"WithContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"Error",
"{",
"if",
"i",
",",
"ok",
":=",
"infoFromContext",
"(",
"ctx",
")",
";",
"ok",
"{",
"e",
".",
"info",
"=",
"i",
".",
"data",
"\n",
"e... | // WithContext returns a new Error with contextual information added. | [
"WithContext",
"returns",
"a",
"new",
"Error",
"with",
"contextual",
"information",
"added",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/errors/errors.go#L125-L131 |
9,650 | remind101/pkg | httpx/errors/errors.go | genStacktrace | func genStacktrace(err error, skip int) errors.StackTrace {
var stack errors.StackTrace
errWithStack := errors.WithStack(err)
stack = errWithStack.(stackTracer).StackTrace()
skip++
// if it is recovering from a panic() call,
// reset the stack trace at that point
for index, frame := range stack {
file := fmt.Sprintf("%s", frame)
if file == "panic.go" {
skip = index + 1
break
}
}
return stack[skip:]
} | go | func genStacktrace(err error, skip int) errors.StackTrace {
var stack errors.StackTrace
errWithStack := errors.WithStack(err)
stack = errWithStack.(stackTracer).StackTrace()
skip++
// if it is recovering from a panic() call,
// reset the stack trace at that point
for index, frame := range stack {
file := fmt.Sprintf("%s", frame)
if file == "panic.go" {
skip = index + 1
break
}
}
return stack[skip:]
} | [
"func",
"genStacktrace",
"(",
"err",
"error",
",",
"skip",
"int",
")",
"errors",
".",
"StackTrace",
"{",
"var",
"stack",
"errors",
".",
"StackTrace",
"\n",
"errWithStack",
":=",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"stack",
"=",
"errWithStack... | // It generates a brand new stack trace given an error and
// the number of frames that should be skipped,
// from innermost to outermost frames. | [
"It",
"generates",
"a",
"brand",
"new",
"stack",
"trace",
"given",
"an",
"error",
"and",
"the",
"number",
"of",
"frames",
"that",
"should",
"be",
"skipped",
"from",
"innermost",
"to",
"outermost",
"frames",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/errors/errors.go#L144-L161 |
9,651 | remind101/pkg | httpx/middleware/request_id.go | ServeHTTPContext | func (h *RequestID) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
e := h.Extractor
if e == nil {
e = DefaultRequestIDExtractor
}
requestID := e(r)
ctx = httpx.WithRequestID(ctx, requestID)
r = r.WithContext(ctx)
return h.handler.ServeHTTPContext(ctx, w, r)
} | go | func (h *RequestID) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
e := h.Extractor
if e == nil {
e = DefaultRequestIDExtractor
}
requestID := e(r)
ctx = httpx.WithRequestID(ctx, requestID)
r = r.WithContext(ctx)
return h.handler.ServeHTTPContext(ctx, w, r)
} | [
"func",
"(",
"h",
"*",
"RequestID",
")",
"ServeHTTPContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"e",
":=",
"h",
".",
"Extractor",
"\n",
"if",
"e",
... | // ServeHTTPContext implements the httpx.Handler interface. It extracts a
// request id from the headers and inserts it into the context. | [
"ServeHTTPContext",
"implements",
"the",
"httpx",
".",
"Handler",
"interface",
".",
"It",
"extracts",
"a",
"request",
"id",
"from",
"the",
"headers",
"and",
"inserts",
"it",
"into",
"the",
"context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/middleware/request_id.go#L35-L46 |
9,652 | remind101/pkg | httpx/middleware/error.go | HandleError | func HandleError(h httpx.Handler, f ErrorHandlerFunc) *Error {
e := NewError(h)
e.ErrorHandler = f
return e
} | go | func HandleError(h httpx.Handler, f ErrorHandlerFunc) *Error {
e := NewError(h)
e.ErrorHandler = f
return e
} | [
"func",
"HandleError",
"(",
"h",
"httpx",
".",
"Handler",
",",
"f",
"ErrorHandlerFunc",
")",
"*",
"Error",
"{",
"e",
":=",
"NewError",
"(",
"h",
")",
"\n",
"e",
".",
"ErrorHandler",
"=",
"f",
"\n",
"return",
"e",
"\n",
"}"
] | // HandleError returns a new Error middleware that uses f as the ErrorHandler. | [
"HandleError",
"returns",
"a",
"new",
"Error",
"middleware",
"that",
"uses",
"f",
"as",
"the",
"ErrorHandler",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/middleware/error.go#L50-L54 |
9,653 | remind101/pkg | httpx/middleware/error.go | ServeHTTPContext | func (h *Error) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
err := h.handler.ServeHTTPContext(ctx, w, r)
if err != nil {
f := h.ErrorHandler
if f == nil {
f = DefaultErrorHandler
}
f(ctx, err, w, r)
}
// Pass the error up for any other middleware to use.
return err
} | go | func (h *Error) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
err := h.handler.ServeHTTPContext(ctx, w, r)
if err != nil {
f := h.ErrorHandler
if f == nil {
f = DefaultErrorHandler
}
f(ctx, err, w, r)
}
// Pass the error up for any other middleware to use.
return err
} | [
"func",
"(",
"h",
"*",
"Error",
")",
"ServeHTTPContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"err",
":=",
"h",
".",
"handler",
".",
"ServeHTTPContext"... | // ServeHTTPContext implements the httpx.Handler interface. | [
"ServeHTTPContext",
"implements",
"the",
"httpx",
".",
"Handler",
"interface",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/middleware/error.go#L57-L71 |
9,654 | remind101/pkg | reporter/hb2/hb2.go | NewReporter | func NewReporter(cfg Config) *HbReporter {
hbCfg := honeybadger.Configuration{}
hbCfg.APIKey = cfg.ApiKey
hbCfg.Env = cfg.Environment
hbCfg.Endpoint = cfg.Endpoint
return &HbReporter{honeybadger.New(hbCfg)}
} | go | func NewReporter(cfg Config) *HbReporter {
hbCfg := honeybadger.Configuration{}
hbCfg.APIKey = cfg.ApiKey
hbCfg.Env = cfg.Environment
hbCfg.Endpoint = cfg.Endpoint
return &HbReporter{honeybadger.New(hbCfg)}
} | [
"func",
"NewReporter",
"(",
"cfg",
"Config",
")",
"*",
"HbReporter",
"{",
"hbCfg",
":=",
"honeybadger",
".",
"Configuration",
"{",
"}",
"\n",
"hbCfg",
".",
"APIKey",
"=",
"cfg",
".",
"ApiKey",
"\n",
"hbCfg",
".",
"Env",
"=",
"cfg",
".",
"Environment",
... | // NewReporter returns a new Reporter instance. | [
"NewReporter",
"returns",
"a",
"new",
"Reporter",
"instance",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/hb2.go#L33-L40 |
9,655 | remind101/pkg | reporter/hb2/hb2.go | ReportWithLevel | func (r *HbReporter) ReportWithLevel(ctx context.Context, level string, err error) error {
extras := []interface{}{}
if e, ok := err.(util.Contexter); ok {
extras = append(extras, getContextData(e))
}
if e, ok := err.(util.Requester); ok {
if r := e.Request(); r != nil {
extras = append(extras, honeybadger.Params(r.Form), getRequestData(r), *r.URL)
}
}
err = makeHoneybadgerError(err)
_, clientErr := r.client.Notify(err, extras...)
return clientErr
} | go | func (r *HbReporter) ReportWithLevel(ctx context.Context, level string, err error) error {
extras := []interface{}{}
if e, ok := err.(util.Contexter); ok {
extras = append(extras, getContextData(e))
}
if e, ok := err.(util.Requester); ok {
if r := e.Request(); r != nil {
extras = append(extras, honeybadger.Params(r.Form), getRequestData(r), *r.URL)
}
}
err = makeHoneybadgerError(err)
_, clientErr := r.client.Notify(err, extras...)
return clientErr
} | [
"func",
"(",
"r",
"*",
"HbReporter",
")",
"ReportWithLevel",
"(",
"ctx",
"context",
".",
"Context",
",",
"level",
"string",
",",
"err",
"error",
")",
"error",
"{",
"extras",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n\n",
"if",
"e",
",",
"... | // Report reports the error to honeybadger. | [
"Report",
"reports",
"the",
"error",
"to",
"honeybadger",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/hb2.go#L48-L65 |
9,656 | remind101/pkg | client/client.go | Timeout | func Timeout(t time.Duration) ClientOpt {
return func(c *Client) {
c.HTTPClient.Timeout = t
}
} | go | func Timeout(t time.Duration) ClientOpt {
return func(c *Client) {
c.HTTPClient.Timeout = t
}
} | [
"func",
"Timeout",
"(",
"t",
"time",
".",
"Duration",
")",
"ClientOpt",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"HTTPClient",
".",
"Timeout",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // Timeout specifies a time limit for requests made by this Client. | [
"Timeout",
"specifies",
"a",
"time",
"limit",
"for",
"requests",
"made",
"by",
"this",
"Client",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/client.go#L45-L49 |
9,657 | remind101/pkg | client/client.go | RoundTripper | func RoundTripper(r http.RoundTripper) ClientOpt {
return func(c *Client) {
c.HTTPClient.Transport = r
}
} | go | func RoundTripper(r http.RoundTripper) ClientOpt {
return func(c *Client) {
c.HTTPClient.Transport = r
}
} | [
"func",
"RoundTripper",
"(",
"r",
"http",
".",
"RoundTripper",
")",
"ClientOpt",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"HTTPClient",
".",
"Transport",
"=",
"r",
"\n",
"}",
"\n",
"}"
] | // RoundTripper sets a custom transport on the underlying http Client. | [
"RoundTripper",
"sets",
"a",
"custom",
"transport",
"on",
"the",
"underlying",
"http",
"Client",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/client.go#L52-L56 |
9,658 | remind101/pkg | client/client.go | BasicAuth | func BasicAuth(username, password string) ClientOpt {
return func(c *Client) {
c.Handlers.Build.Append(request.BasicAuther(username, password))
}
} | go | func BasicAuth(username, password string) ClientOpt {
return func(c *Client) {
c.Handlers.Build.Append(request.BasicAuther(username, password))
}
} | [
"func",
"BasicAuth",
"(",
"username",
",",
"password",
"string",
")",
"ClientOpt",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"Handlers",
".",
"Build",
".",
"Append",
"(",
"request",
".",
"BasicAuther",
"(",
"username",
",",
"p... | // BasicAuth adds basic auth to every request made by this client. | [
"BasicAuth",
"adds",
"basic",
"auth",
"to",
"every",
"request",
"made",
"by",
"this",
"client",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/client.go#L59-L63 |
9,659 | remind101/pkg | client/client.go | RequestSigning | func RequestSigning(id, key string) ClientOpt {
return func(c *Client) {
c.Handlers.Sign.Append(request.RequestSigner(id, key))
}
} | go | func RequestSigning(id, key string) ClientOpt {
return func(c *Client) {
c.Handlers.Sign.Append(request.RequestSigner(id, key))
}
} | [
"func",
"RequestSigning",
"(",
"id",
",",
"key",
"string",
")",
"ClientOpt",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"Handlers",
".",
"Sign",
".",
"Append",
"(",
"request",
".",
"RequestSigner",
"(",
"id",
",",
"key",
")",... | // RequestSigning adds a handler to sign requests. | [
"RequestSigning",
"adds",
"a",
"handler",
"to",
"sign",
"requests",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/client.go#L66-L70 |
9,660 | remind101/pkg | client/client.go | DebugLogging | func DebugLogging(c *Client) {
c.Handlers.Send.Prepend(request.RequestLogger)
c.Handlers.Send.Append(request.ResponseLogger)
} | go | func DebugLogging(c *Client) {
c.Handlers.Send.Prepend(request.RequestLogger)
c.Handlers.Send.Append(request.ResponseLogger)
} | [
"func",
"DebugLogging",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"Handlers",
".",
"Send",
".",
"Prepend",
"(",
"request",
".",
"RequestLogger",
")",
"\n",
"c",
".",
"Handlers",
".",
"Send",
".",
"Append",
"(",
"request",
".",
"ResponseLogger",
")",... | // DebugLogging adds logging of the enitre request and response. | [
"DebugLogging",
"adds",
"logging",
"of",
"the",
"enitre",
"request",
"and",
"response",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/client.go#L73-L76 |
9,661 | remind101/pkg | client/client.go | New | func New(info metadata.ClientInfo, options ...ClientOpt) *Client {
c := &Client{
Info: info,
Handlers: request.DefaultHandlers(),
HTTPClient: &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 1 * time.Second,
KeepAlive: 90 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 8,
IdleConnTimeout: 90 * time.Second,
},
},
}
// Apply options
for _, option := range options {
option(c)
}
return c
} | go | func New(info metadata.ClientInfo, options ...ClientOpt) *Client {
c := &Client{
Info: info,
Handlers: request.DefaultHandlers(),
HTTPClient: &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 1 * time.Second,
KeepAlive: 90 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 8,
IdleConnTimeout: 90 * time.Second,
},
},
}
// Apply options
for _, option := range options {
option(c)
}
return c
} | [
"func",
"New",
"(",
"info",
"metadata",
".",
"ClientInfo",
",",
"options",
"...",
"ClientOpt",
")",
"*",
"Client",
"{",
"c",
":=",
"&",
"Client",
"{",
"Info",
":",
"info",
",",
"Handlers",
":",
"request",
".",
"DefaultHandlers",
"(",
")",
",",
"HTTPCli... | // New returns a new client with default Handlers and http client. | [
"New",
"returns",
"a",
"new",
"client",
"with",
"default",
"Handlers",
"and",
"http",
"client",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/client.go#L79-L105 |
9,662 | remind101/pkg | client/client.go | NewRequest | func (c *Client) NewRequest(ctx context.Context, method, path string, params interface{}, data interface{}) *request.Request {
httpReq, _ := http.NewRequest(method, path, nil)
httpReq = httpReq.WithContext(ctx)
httpReq.URL, _ = url.Parse(c.Info.Endpoint + path)
r := request.New(httpReq, c.Info, c.Handlers.Copy(), params, data)
r.HTTPClient = c.HTTPClient
return r
} | go | func (c *Client) NewRequest(ctx context.Context, method, path string, params interface{}, data interface{}) *request.Request {
httpReq, _ := http.NewRequest(method, path, nil)
httpReq = httpReq.WithContext(ctx)
httpReq.URL, _ = url.Parse(c.Info.Endpoint + path)
r := request.New(httpReq, c.Info, c.Handlers.Copy(), params, data)
r.HTTPClient = c.HTTPClient
return r
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"NewRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"method",
",",
"path",
"string",
",",
"params",
"interface",
"{",
"}",
",",
"data",
"interface",
"{",
"}",
")",
"*",
"request",
".",
"Request",
"{",
"http... | // NewRequest builds a request from the client configuration.
// An http.Request will be initialized with the given context, method and path.
// A request.Request will be initialized with the http.Request, Handlers,
// params and data. | [
"NewRequest",
"builds",
"a",
"request",
"from",
"the",
"client",
"configuration",
".",
"An",
"http",
".",
"Request",
"will",
"be",
"initialized",
"with",
"the",
"given",
"context",
"method",
"and",
"path",
".",
"A",
"request",
".",
"Request",
"will",
"be",
... | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/client.go#L111-L119 |
9,663 | remind101/pkg | httpx/middleware/header.go | HeaderExtractor | func HeaderExtractor(headers []string) func(*http.Request) string {
return func(r *http.Request) string {
for _, h := range headers {
v := r.Header.Get(h)
if v != "" {
return v
}
}
return ""
}
} | go | func HeaderExtractor(headers []string) func(*http.Request) string {
return func(r *http.Request) string {
for _, h := range headers {
v := r.Header.Get(h)
if v != "" {
return v
}
}
return ""
}
} | [
"func",
"HeaderExtractor",
"(",
"headers",
"[",
"]",
"string",
")",
"func",
"(",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"return",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"for",
"_",
",",
"h",
":=",
"range",
"hea... | // HeaderExtractor returns a function that can extract a value from a list
// of headers. | [
"HeaderExtractor",
"returns",
"a",
"function",
"that",
"can",
"extract",
"a",
"value",
"from",
"a",
"list",
"of",
"headers",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/middleware/header.go#L38-L49 |
9,664 | remind101/pkg | reporter/hb2/internal/honeybadger-go/client.go | BeforeNotify | func (client *Client) BeforeNotify(handler func(notice *Notice) error) {
client.beforeNotifyHandlers = append(client.beforeNotifyHandlers, handler)
} | go | func (client *Client) BeforeNotify(handler func(notice *Notice) error) {
client.beforeNotifyHandlers = append(client.beforeNotifyHandlers, handler)
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"BeforeNotify",
"(",
"handler",
"func",
"(",
"notice",
"*",
"Notice",
")",
"error",
")",
"{",
"client",
".",
"beforeNotifyHandlers",
"=",
"append",
"(",
"client",
".",
"beforeNotifyHandlers",
",",
"handler",
")",
... | // BeforeNotify adds a callback function which is run before a notice is
// reported to Honeybadger. If any function returns an error the notification
// will be skipped, otherwise it will be sent. | [
"BeforeNotify",
"adds",
"a",
"callback",
"function",
"which",
"is",
"run",
"before",
"a",
"notice",
"is",
"reported",
"to",
"Honeybadger",
".",
"If",
"any",
"function",
"returns",
"an",
"error",
"the",
"notification",
"will",
"be",
"skipped",
"otherwise",
"it"... | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/internal/honeybadger-go/client.go#L50-L52 |
9,665 | remind101/pkg | reporter/hb2/internal/honeybadger-go/client.go | Notify | func (client *Client) Notify(err interface{}, extra ...interface{}) (string, error) {
extra = append([]interface{}{*client.context}, extra...)
notice := newNotice(client.Config, newError(err, 2), extra...)
for _, handler := range client.beforeNotifyHandlers {
if err := handler(notice); err != nil {
return "", err
}
}
workerErr := client.worker.Push(func() error {
if err := client.Config.Backend.Notify(Notices, notice); err != nil {
return err
}
return nil
})
if workerErr != nil {
client.Config.Logger.Printf("worker error: %v\n", workerErr)
return "", workerErr
}
return notice.Token, nil
} | go | func (client *Client) Notify(err interface{}, extra ...interface{}) (string, error) {
extra = append([]interface{}{*client.context}, extra...)
notice := newNotice(client.Config, newError(err, 2), extra...)
for _, handler := range client.beforeNotifyHandlers {
if err := handler(notice); err != nil {
return "", err
}
}
workerErr := client.worker.Push(func() error {
if err := client.Config.Backend.Notify(Notices, notice); err != nil {
return err
}
return nil
})
if workerErr != nil {
client.Config.Logger.Printf("worker error: %v\n", workerErr)
return "", workerErr
}
return notice.Token, nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"Notify",
"(",
"err",
"interface",
"{",
"}",
",",
"extra",
"...",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"extra",
"=",
"append",
"(",
"[",
"]",
"interface",
"{",
"}",
"{",
"*"... | // Notify reports the error err to the Honeybadger service. | [
"Notify",
"reports",
"the",
"error",
"err",
"to",
"the",
"Honeybadger",
"service",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/internal/honeybadger-go/client.go#L55-L74 |
9,666 | remind101/pkg | reporter/hb2/internal/honeybadger-go/client.go | Monitor | func (client *Client) Monitor() {
if err := recover(); err != nil {
client.Notify(newError(err, 2))
panic(err)
}
} | go | func (client *Client) Monitor() {
if err := recover(); err != nil {
client.Notify(newError(err, 2))
panic(err)
}
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"Monitor",
"(",
")",
"{",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"client",
".",
"Notify",
"(",
"newError",
"(",
"err",
",",
"2",
")",
")",
"\n",
"panic",
"(",
"err",
")",... | // Monitor automatically reports panics which occur in the function it's called
// from. Must be deferred. | [
"Monitor",
"automatically",
"reports",
"panics",
"which",
"occur",
"in",
"the",
"function",
"it",
"s",
"called",
"from",
".",
"Must",
"be",
"deferred",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/internal/honeybadger-go/client.go#L78-L83 |
9,667 | remind101/pkg | reporter/hb2/internal/honeybadger-go/client.go | Handler | func (client *Client) Handler(h http.Handler) http.Handler {
if h == nil {
h = http.DefaultServeMux
}
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
client.Notify(newError(err, 2), Params(r.Form), getCGIData(r), *r.URL)
panic(err)
}
}()
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
} | go | func (client *Client) Handler(h http.Handler) http.Handler {
if h == nil {
h = http.DefaultServeMux
}
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
client.Notify(newError(err, 2), Params(r.Form), getCGIData(r), *r.URL)
panic(err)
}
}()
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"Handler",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"if",
"h",
"==",
"nil",
"{",
"h",
"=",
"http",
".",
"DefaultServeMux",
"\n",
"}",
"\n",
"fn",
":=",
"func",
"(",
"w",
"http"... | // Handler returns an http.Handler function which automatically reports panics
// to Honeybadger and then re-panics. | [
"Handler",
"returns",
"an",
"http",
".",
"Handler",
"function",
"which",
"automatically",
"reports",
"panics",
"to",
"Honeybadger",
"and",
"then",
"re",
"-",
"panics",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/internal/honeybadger-go/client.go#L87-L101 |
9,668 | remind101/pkg | reporter/hb2/internal/honeybadger-go/client.go | MetricsHandler | func (client *Client) MetricsHandler(h http.Handler) http.Handler {
client.Config.Logger.Printf("DEPRECATION WARNING: honeybadger.MetricsHandler() has no effect and will be removed.")
if h == nil {
h = http.DefaultServeMux
}
fn := func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
} | go | func (client *Client) MetricsHandler(h http.Handler) http.Handler {
client.Config.Logger.Printf("DEPRECATION WARNING: honeybadger.MetricsHandler() has no effect and will be removed.")
if h == nil {
h = http.DefaultServeMux
}
fn := func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"MetricsHandler",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"client",
".",
"Config",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"if",
"h",
"==",
"nil",
"{",
"h",
... | // MetricsHandler is deprecated. | [
"MetricsHandler",
"is",
"deprecated",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/internal/honeybadger-go/client.go#L104-L113 |
9,669 | remind101/pkg | reporter/hb2/internal/honeybadger-go/client.go | Increment | func (client *Client) Increment(metric string, value int) {
client.Config.Logger.Printf("DEPRECATION WARNING: honeybadger.Increment() has no effect and will be removed.")
} | go | func (client *Client) Increment(metric string, value int) {
client.Config.Logger.Printf("DEPRECATION WARNING: honeybadger.Increment() has no effect and will be removed.")
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"Increment",
"(",
"metric",
"string",
",",
"value",
"int",
")",
"{",
"client",
".",
"Config",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Increment is deprecated. | [
"Increment",
"is",
"deprecated",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/internal/honeybadger-go/client.go#L116-L118 |
9,670 | remind101/pkg | httpx/context/copy.go | Copy | func Copy(ctx context.Context) context.Context {
return CopyToContext(context.Background(), ctx)
} | go | func Copy(ctx context.Context) context.Context {
return CopyToContext(context.Background(), ctx)
} | [
"func",
"Copy",
"(",
"ctx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"return",
"CopyToContext",
"(",
"context",
".",
"Background",
"(",
")",
",",
"ctx",
")",
"\n",
"}"
] | // Copy copies common httpx values injected into a request context to another
// context.
//
// This is useful when performing work outside of the request lifecycle that was
// a result of a request. For instance, the request id and tracing spans are useful
// but the deadline of the request context does not apply. | [
"Copy",
"copies",
"common",
"httpx",
"values",
"injected",
"into",
"a",
"request",
"context",
"to",
"another",
"context",
".",
"This",
"is",
"useful",
"when",
"performing",
"work",
"outside",
"of",
"the",
"request",
"lifecycle",
"that",
"was",
"a",
"result",
... | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/context/copy.go#L18-L20 |
9,671 | remind101/pkg | client/request/handlers.go | DefaultHandlers | func DefaultHandlers() Handlers {
return Handlers{
Build: NewHandlerList(JSONBuilder),
Sign: NewHandlerList(),
Send: NewHandlerList(WithTracing(BaseSender)),
ValidateResponse: NewHandlerList(),
Decode: NewHandlerList(JSONDecoder),
DecodeError: NewHandlerList(),
Complete: NewHandlerList(),
}
} | go | func DefaultHandlers() Handlers {
return Handlers{
Build: NewHandlerList(JSONBuilder),
Sign: NewHandlerList(),
Send: NewHandlerList(WithTracing(BaseSender)),
ValidateResponse: NewHandlerList(),
Decode: NewHandlerList(JSONDecoder),
DecodeError: NewHandlerList(),
Complete: NewHandlerList(),
}
} | [
"func",
"DefaultHandlers",
"(",
")",
"Handlers",
"{",
"return",
"Handlers",
"{",
"Build",
":",
"NewHandlerList",
"(",
"JSONBuilder",
")",
",",
"Sign",
":",
"NewHandlerList",
"(",
")",
",",
"Send",
":",
"NewHandlerList",
"(",
"WithTracing",
"(",
"BaseSender",
... | // DefaultHandlers defines a basic request configuration that assumes JSON
// requests and responses. | [
"DefaultHandlers",
"defines",
"a",
"basic",
"request",
"configuration",
"that",
"assumes",
"JSON",
"requests",
"and",
"responses",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L36-L46 |
9,672 | remind101/pkg | client/request/handlers.go | Copy | func (h Handlers) Copy() Handlers {
return Handlers{
Build: h.Build.copy(),
Sign: h.Sign.copy(),
Send: h.Send.copy(),
ValidateResponse: h.ValidateResponse.copy(),
Decode: h.Decode.copy(),
DecodeError: h.DecodeError.copy(),
Complete: h.Complete.copy(),
}
} | go | func (h Handlers) Copy() Handlers {
return Handlers{
Build: h.Build.copy(),
Sign: h.Sign.copy(),
Send: h.Send.copy(),
ValidateResponse: h.ValidateResponse.copy(),
Decode: h.Decode.copy(),
DecodeError: h.DecodeError.copy(),
Complete: h.Complete.copy(),
}
} | [
"func",
"(",
"h",
"Handlers",
")",
"Copy",
"(",
")",
"Handlers",
"{",
"return",
"Handlers",
"{",
"Build",
":",
"h",
".",
"Build",
".",
"copy",
"(",
")",
",",
"Sign",
":",
"h",
".",
"Sign",
".",
"copy",
"(",
")",
",",
"Send",
":",
"h",
".",
"S... | // Copy returns a copy of a Handlers instance. | [
"Copy",
"returns",
"a",
"copy",
"of",
"a",
"Handlers",
"instance",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L49-L59 |
9,673 | remind101/pkg | client/request/handlers.go | Run | func (hl *HandlerList) Run(r *Request) {
for _, h := range hl.list {
h.Fn(r)
}
} | go | func (hl *HandlerList) Run(r *Request) {
for _, h := range hl.list {
h.Fn(r)
}
} | [
"func",
"(",
"hl",
"*",
"HandlerList",
")",
"Run",
"(",
"r",
"*",
"Request",
")",
"{",
"for",
"_",
",",
"h",
":=",
"range",
"hl",
".",
"list",
"{",
"h",
".",
"Fn",
"(",
"r",
")",
"\n",
"}",
"\n",
"}"
] | // Run calls each request handler in order. | [
"Run",
"calls",
"each",
"request",
"handler",
"in",
"order",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L74-L78 |
9,674 | remind101/pkg | client/request/handlers.go | Append | func (hl *HandlerList) Append(h Handler) {
hl.list = append(hl.list, h)
} | go | func (hl *HandlerList) Append(h Handler) {
hl.list = append(hl.list, h)
} | [
"func",
"(",
"hl",
"*",
"HandlerList",
")",
"Append",
"(",
"h",
"Handler",
")",
"{",
"hl",
".",
"list",
"=",
"append",
"(",
"hl",
".",
"list",
",",
"h",
")",
"\n",
"}"
] | // Append adds a handler to the end of the list. | [
"Append",
"adds",
"a",
"handler",
"to",
"the",
"end",
"of",
"the",
"list",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L81-L83 |
9,675 | remind101/pkg | client/request/handlers.go | Prepend | func (hl *HandlerList) Prepend(h Handler) {
hl.list = append([]Handler{h}, hl.list...)
} | go | func (hl *HandlerList) Prepend(h Handler) {
hl.list = append([]Handler{h}, hl.list...)
} | [
"func",
"(",
"hl",
"*",
"HandlerList",
")",
"Prepend",
"(",
"h",
"Handler",
")",
"{",
"hl",
".",
"list",
"=",
"append",
"(",
"[",
"]",
"Handler",
"{",
"h",
"}",
",",
"hl",
".",
"list",
"...",
")",
"\n",
"}"
] | // Prepend adds a handler to the front of the list. | [
"Prepend",
"adds",
"a",
"handler",
"to",
"the",
"front",
"of",
"the",
"list",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L86-L88 |
9,676 | remind101/pkg | client/request/handlers.go | RequestSigner | func RequestSigner(id, key string) Handler {
return Handler{
Name: "RequestSigner",
Fn: func(r *Request) {
r.Error = httpsignatures.DefaultSha256Signer.SignRequest(id, key, r.HTTPRequest)
},
}
} | go | func RequestSigner(id, key string) Handler {
return Handler{
Name: "RequestSigner",
Fn: func(r *Request) {
r.Error = httpsignatures.DefaultSha256Signer.SignRequest(id, key, r.HTTPRequest)
},
}
} | [
"func",
"RequestSigner",
"(",
"id",
",",
"key",
"string",
")",
"Handler",
"{",
"return",
"Handler",
"{",
"Name",
":",
"\"",
"\"",
",",
"Fn",
":",
"func",
"(",
"r",
"*",
"Request",
")",
"{",
"r",
".",
"Error",
"=",
"httpsignatures",
".",
"DefaultSha25... | // RequestSigner signs requests. | [
"RequestSigner",
"signs",
"requests",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L200-L207 |
9,677 | remind101/pkg | client/request/handlers.go | BasicAuther | func BasicAuther(username, password string) Handler {
return Handler{
Name: "BasicAuther",
Fn: func(r *Request) {
r.HTTPRequest.SetBasicAuth(username, password)
},
}
} | go | func BasicAuther(username, password string) Handler {
return Handler{
Name: "BasicAuther",
Fn: func(r *Request) {
r.HTTPRequest.SetBasicAuth(username, password)
},
}
} | [
"func",
"BasicAuther",
"(",
"username",
",",
"password",
"string",
")",
"Handler",
"{",
"return",
"Handler",
"{",
"Name",
":",
"\"",
"\"",
",",
"Fn",
":",
"func",
"(",
"r",
"*",
"Request",
")",
"{",
"r",
".",
"HTTPRequest",
".",
"SetBasicAuth",
"(",
... | // BasicAuther sets basic auth on a request. | [
"BasicAuther",
"sets",
"basic",
"auth",
"on",
"a",
"request",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L210-L217 |
9,678 | remind101/pkg | client/request/handlers.go | HeadersFromContext | func HeadersFromContext(headers ...string) Handler {
return Handler{
Name: "HeadersFromContext",
Fn: func(r *Request) {
for _, header := range headers {
r.HTTPRequest.Header.Add(header, httpx.Header(r.HTTPRequest.Context(), header))
}
},
}
} | go | func HeadersFromContext(headers ...string) Handler {
return Handler{
Name: "HeadersFromContext",
Fn: func(r *Request) {
for _, header := range headers {
r.HTTPRequest.Header.Add(header, httpx.Header(r.HTTPRequest.Context(), header))
}
},
}
} | [
"func",
"HeadersFromContext",
"(",
"headers",
"...",
"string",
")",
"Handler",
"{",
"return",
"Handler",
"{",
"Name",
":",
"\"",
"\"",
",",
"Fn",
":",
"func",
"(",
"r",
"*",
"Request",
")",
"{",
"for",
"_",
",",
"header",
":=",
"range",
"headers",
"{... | // HeadersFromContext adds headers with values from the request context.
// This is useful for forwarding headers to upstream services. | [
"HeadersFromContext",
"adds",
"headers",
"with",
"values",
"from",
"the",
"request",
"context",
".",
"This",
"is",
"useful",
"for",
"forwarding",
"headers",
"to",
"upstream",
"services",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L221-L230 |
9,679 | remind101/pkg | client/request/handlers.go | WithTracing | func WithTracing(h Handler) Handler {
return Handler{
Name: "TracedSender",
Fn: func(r *Request) {
span, ctx := opentracing.StartSpanFromContext(r.HTTPRequest.Context(), "client.request")
opentracing.GlobalTracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.HTTPRequest.Header),
)
defer span.Finish()
r.HTTPRequest = r.HTTPRequest.WithContext(ctx)
span.SetTag(ext.ResourceName, r.ClientInfo.ServiceName)
span.SetTag("http.method", r.HTTPRequest.Method)
span.SetTag("http.url", r.HTTPRequest.URL.Hostname()+r.HTTPRequest.URL.EscapedPath())
span.SetTag("out.host", r.HTTPRequest.URL.Hostname())
span.SetTag("out.port", r.HTTPRequest.URL.Port())
h.Fn(r)
if r.HTTPResponse != nil {
span.SetTag("http.status_code", r.HTTPResponse.StatusCode)
}
if r.Error != nil {
span.SetTag(ext.Error, r.Error)
}
},
}
} | go | func WithTracing(h Handler) Handler {
return Handler{
Name: "TracedSender",
Fn: func(r *Request) {
span, ctx := opentracing.StartSpanFromContext(r.HTTPRequest.Context(), "client.request")
opentracing.GlobalTracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.HTTPRequest.Header),
)
defer span.Finish()
r.HTTPRequest = r.HTTPRequest.WithContext(ctx)
span.SetTag(ext.ResourceName, r.ClientInfo.ServiceName)
span.SetTag("http.method", r.HTTPRequest.Method)
span.SetTag("http.url", r.HTTPRequest.URL.Hostname()+r.HTTPRequest.URL.EscapedPath())
span.SetTag("out.host", r.HTTPRequest.URL.Hostname())
span.SetTag("out.port", r.HTTPRequest.URL.Port())
h.Fn(r)
if r.HTTPResponse != nil {
span.SetTag("http.status_code", r.HTTPResponse.StatusCode)
}
if r.Error != nil {
span.SetTag(ext.Error, r.Error)
}
},
}
} | [
"func",
"WithTracing",
"(",
"h",
"Handler",
")",
"Handler",
"{",
"return",
"Handler",
"{",
"Name",
":",
"\"",
"\"",
",",
"Fn",
":",
"func",
"(",
"r",
"*",
"Request",
")",
"{",
"span",
",",
"ctx",
":=",
"opentracing",
".",
"StartSpanFromContext",
"(",
... | // WithTracing returns a Send Handler that wraps another Send Handler in a trace
// span. | [
"WithTracing",
"returns",
"a",
"Send",
"Handler",
"that",
"wraps",
"another",
"Send",
"Handler",
"in",
"a",
"trace",
"span",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/client/request/handlers.go#L260-L290 |
9,680 | remind101/pkg | tracing/contrib/redigo/redis/redis.go | Do | func (tc Conn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
var (
ctx context.Context
ok bool
)
if n := len(args); n > 0 {
ctx, ok = args[n-1].(context.Context)
if ok {
args = args[:n-1]
}
}
if ctx == nil {
ctx = context.Background()
}
span := tc.newChildSpan(ctx)
defer func() {
if err != nil {
span.SetTag(ext.Error, err)
}
span.Finish()
}()
span.SetTag("redis.args_length", strconv.Itoa(len(args)))
if len(commandName) > 0 {
span.SetTag(ext.ResourceName, commandName)
} else {
// When the command argument to the Do method is "", then the Do method will flush the output buffer
// See https://godoc.org/github.com/garyburd/redigo/redis#hdr-Pipelining
span.SetTag(ext.ResourceName, "conn.flush")
}
var b bytes.Buffer
b.WriteString(commandName)
for _, arg := range args {
b.WriteString(" ")
switch arg := arg.(type) {
case string:
b.WriteString(arg)
case int:
b.WriteString(strconv.Itoa(arg))
case int32:
b.WriteString(strconv.FormatInt(int64(arg), 10))
case int64:
b.WriteString(strconv.FormatInt(arg, 10))
case fmt.Stringer:
b.WriteString(arg.String())
}
}
span.SetTag("redis.command", b.String())
return tc.Conn.Do(commandName, args...)
} | go | func (tc Conn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
var (
ctx context.Context
ok bool
)
if n := len(args); n > 0 {
ctx, ok = args[n-1].(context.Context)
if ok {
args = args[:n-1]
}
}
if ctx == nil {
ctx = context.Background()
}
span := tc.newChildSpan(ctx)
defer func() {
if err != nil {
span.SetTag(ext.Error, err)
}
span.Finish()
}()
span.SetTag("redis.args_length", strconv.Itoa(len(args)))
if len(commandName) > 0 {
span.SetTag(ext.ResourceName, commandName)
} else {
// When the command argument to the Do method is "", then the Do method will flush the output buffer
// See https://godoc.org/github.com/garyburd/redigo/redis#hdr-Pipelining
span.SetTag(ext.ResourceName, "conn.flush")
}
var b bytes.Buffer
b.WriteString(commandName)
for _, arg := range args {
b.WriteString(" ")
switch arg := arg.(type) {
case string:
b.WriteString(arg)
case int:
b.WriteString(strconv.Itoa(arg))
case int32:
b.WriteString(strconv.FormatInt(int64(arg), 10))
case int64:
b.WriteString(strconv.FormatInt(arg, 10))
case fmt.Stringer:
b.WriteString(arg.String())
}
}
span.SetTag("redis.command", b.String())
return tc.Conn.Do(commandName, args...)
} | [
"func",
"(",
"tc",
"Conn",
")",
"Do",
"(",
"commandName",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"reply",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"var",
"(",
"ctx",
"context",
".",
"Context",
"\n",
"ok",
"bool"... | // Do wraps redis.Conn.Do. It sends a command to the Redis server and returns the received reply.
// In the process it emits a span containing key information about the command sent.
// When passed a context.Context as the final argument, Do will ensure that any span created
// inherits from this context. The rest of the arguments are passed through to the Redis server unchanged. | [
"Do",
"wraps",
"redis",
".",
"Conn",
".",
"Do",
".",
"It",
"sends",
"a",
"command",
"to",
"the",
"Redis",
"server",
"and",
"returns",
"the",
"received",
"reply",
".",
"In",
"the",
"process",
"it",
"emits",
"a",
"span",
"containing",
"key",
"information",... | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/tracing/contrib/redigo/redis/redis.go#L62-L114 |
9,681 | remind101/pkg | tracing/contrib/redigo/redis/redis.go | newChildSpan | func (tc Conn) newChildSpan(ctx context.Context) opentracing.Span {
p := tc.params
span, _ := opentracing.StartSpanFromContext(ctx, "redis.command")
span.SetTag(ext.ServiceName, p.config.serviceName)
span.SetTag(ext.SpanType, "cache")
span.SetTag("out.network", p.network)
span.SetTag("out.port", p.port)
span.SetTag("out.host", p.host)
return span
} | go | func (tc Conn) newChildSpan(ctx context.Context) opentracing.Span {
p := tc.params
span, _ := opentracing.StartSpanFromContext(ctx, "redis.command")
span.SetTag(ext.ServiceName, p.config.serviceName)
span.SetTag(ext.SpanType, "cache")
span.SetTag("out.network", p.network)
span.SetTag("out.port", p.port)
span.SetTag("out.host", p.host)
return span
} | [
"func",
"(",
"tc",
"Conn",
")",
"newChildSpan",
"(",
"ctx",
"context",
".",
"Context",
")",
"opentracing",
".",
"Span",
"{",
"p",
":=",
"tc",
".",
"params",
"\n",
"span",
",",
"_",
":=",
"opentracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\""... | // newChildSpan creates a span inheriting from the given context. It adds to the span useful metadata about the traced Redis connection | [
"newChildSpan",
"creates",
"a",
"span",
"inheriting",
"from",
"the",
"given",
"context",
".",
"It",
"adds",
"to",
"the",
"span",
"useful",
"metadata",
"about",
"the",
"traced",
"Redis",
"connection"
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/tracing/contrib/redigo/redis/redis.go#L117-L127 |
9,682 | remind101/pkg | reporter/hb2/internal/honeybadger-go/context.go | Update | func (context Context) Update(other Context) {
for k, v := range other {
context[k] = v
}
} | go | func (context Context) Update(other Context) {
for k, v := range other {
context[k] = v
}
} | [
"func",
"(",
"context",
"Context",
")",
"Update",
"(",
"other",
"Context",
")",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"other",
"{",
"context",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}"
] | // Update applies the values in other Context to context. | [
"Update",
"applies",
"the",
"values",
"in",
"other",
"Context",
"to",
"context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/hb2/internal/honeybadger-go/context.go#L7-L11 |
9,683 | remind101/pkg | reporter/reporter.go | ReportWithLevel | func (f ReporterFunc) ReportWithLevel(ctx context.Context, level string, err error) error {
return f(ctx, level, err)
} | go | func (f ReporterFunc) ReportWithLevel(ctx context.Context, level string, err error) error {
return f(ctx, level, err)
} | [
"func",
"(",
"f",
"ReporterFunc",
")",
"ReportWithLevel",
"(",
"ctx",
"context",
".",
"Context",
",",
"level",
"string",
",",
"err",
"error",
")",
"error",
"{",
"return",
"f",
"(",
"ctx",
",",
"level",
",",
"err",
")",
"\n",
"}"
] | // Report implements the Reporter interface. | [
"Report",
"implements",
"the",
"Reporter",
"interface",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/reporter.go#L38-L40 |
9,684 | remind101/pkg | reporter/reporter.go | FromContext | func FromContext(ctx context.Context) (Reporter, bool) {
h, ok := ctx.Value(reporterKey).(Reporter)
return h, ok
} | go | func FromContext(ctx context.Context) (Reporter, bool) {
h, ok := ctx.Value(reporterKey).(Reporter)
return h, ok
} | [
"func",
"FromContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"Reporter",
",",
"bool",
")",
"{",
"h",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"reporterKey",
")",
".",
"(",
"Reporter",
")",
"\n",
"return",
"h",
",",
"ok",
"\n",
"}"
] | // FromContext extracts a Reporter from a context.Context. | [
"FromContext",
"extracts",
"a",
"Reporter",
"from",
"a",
"context",
".",
"Context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/reporter.go#L43-L46 |
9,685 | remind101/pkg | reporter/reporter.go | WithReporter | func WithReporter(ctx context.Context, r Reporter) context.Context {
return context.WithValue(ctx, reporterKey, r)
} | go | func WithReporter(ctx context.Context, r Reporter) context.Context {
return context.WithValue(ctx, reporterKey, r)
} | [
"func",
"WithReporter",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"Reporter",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"reporterKey",
",",
"r",
")",
"\n",
"}"
] | // WithReporter inserts a Reporter into the context.Context. | [
"WithReporter",
"inserts",
"a",
"Reporter",
"into",
"the",
"context",
".",
"Context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/reporter.go#L49-L51 |
9,686 | remind101/pkg | reporter/reporter.go | Error | func (e *MultiError) Error() string {
var m []string
for _, err := range e.Errors {
m = append(m, err.Error())
}
return strings.Join(m, ", ")
} | go | func (e *MultiError) Error() string {
var m []string
for _, err := range e.Errors {
m = append(m, err.Error())
}
return strings.Join(m, ", ")
} | [
"func",
"(",
"e",
"*",
"MultiError",
")",
"Error",
"(",
")",
"string",
"{",
"var",
"m",
"[",
"]",
"string",
"\n\n",
"for",
"_",
",",
"err",
":=",
"range",
"e",
".",
"Errors",
"{",
"m",
"=",
"append",
"(",
"m",
",",
"err",
".",
"Error",
"(",
"... | // Error implements the error interface. It simply joins all of the individual
// error messages with a comma. | [
"Error",
"implements",
"the",
"error",
"interface",
".",
"It",
"simply",
"joins",
"all",
"of",
"the",
"individual",
"error",
"messages",
"with",
"a",
"comma",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/reporter.go#L60-L68 |
9,687 | remind101/pkg | reporter/reporter.go | ReportWithLevel | func ReportWithLevel(ctx context.Context, level string, err error) error {
e := errors.New(ctx, err, 1)
return reportWithLevel(ctx, level, e)
} | go | func ReportWithLevel(ctx context.Context, level string, err error) error {
e := errors.New(ctx, err, 1)
return reportWithLevel(ctx, level, e)
} | [
"func",
"ReportWithLevel",
"(",
"ctx",
"context",
".",
"Context",
",",
"level",
"string",
",",
"err",
"error",
")",
"error",
"{",
"e",
":=",
"errors",
".",
"New",
"(",
"ctx",
",",
"err",
",",
"1",
")",
"\n",
"return",
"reportWithLevel",
"(",
"ctx",
"... | // ReportWithLevel wraps the err as an Error and reports it the the Reporter embedded
// within the context.Context. | [
"ReportWithLevel",
"wraps",
"the",
"err",
"as",
"an",
"Error",
"and",
"reports",
"it",
"the",
"the",
"Reporter",
"embedded",
"within",
"the",
"context",
".",
"Context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/reporter.go#L72-L75 |
9,688 | remind101/pkg | reporter/reporter.go | Report | func Report(ctx context.Context, err error) error {
e := errors.New(ctx, err, 1)
return reportWithLevel(ctx, DefaultLevel, e)
} | go | func Report(ctx context.Context, err error) error {
e := errors.New(ctx, err, 1)
return reportWithLevel(ctx, DefaultLevel, e)
} | [
"func",
"Report",
"(",
"ctx",
"context",
".",
"Context",
",",
"err",
"error",
")",
"error",
"{",
"e",
":=",
"errors",
".",
"New",
"(",
"ctx",
",",
"err",
",",
"1",
")",
"\n",
"return",
"reportWithLevel",
"(",
"ctx",
",",
"DefaultLevel",
",",
"e",
"... | // Report wraps the err as an Error and reports it the the Reporter embedded
// within the context.Context. | [
"Report",
"wraps",
"the",
"err",
"as",
"an",
"Error",
"and",
"reports",
"it",
"the",
"the",
"Reporter",
"embedded",
"within",
"the",
"context",
".",
"Context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/reporter.go#L79-L82 |
9,689 | remind101/pkg | reporter/reporter.go | Flush | func Flush(ctx context.Context) {
if r, ok := FromContext(ctx); ok {
if f, ok := r.(flusher); ok {
f.Flush()
}
}
} | go | func Flush(ctx context.Context) {
if r, ok := FromContext(ctx); ok {
if f, ok := r.(flusher); ok {
f.Flush()
}
}
} | [
"func",
"Flush",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"if",
"r",
",",
"ok",
":=",
"FromContext",
"(",
"ctx",
")",
";",
"ok",
"{",
"if",
"f",
",",
"ok",
":=",
"r",
".",
"(",
"flusher",
")",
";",
"ok",
"{",
"f",
".",
"Flush",
"(",
... | // Flush the Reporter embedded within the context.Context | [
"Flush",
"the",
"Reporter",
"embedded",
"within",
"the",
"context",
".",
"Context"
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/reporter/reporter.go#L85-L91 |
9,690 | remind101/pkg | httpx/http_service.go | NewClient | func NewClient(c *http.Client) *Client {
return &Client{Transport: &Transport{Client: c}}
} | go | func NewClient(c *http.Client) *Client {
return &Client{Transport: &Transport{Client: c}}
} | [
"func",
"NewClient",
"(",
"c",
"*",
"http",
".",
"Client",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"Transport",
":",
"&",
"Transport",
"{",
"Client",
":",
"c",
"}",
"}",
"\n",
"}"
] | // NewClient returns a new Client instance that will use the given http.Client
// to perform round trips | [
"NewClient",
"returns",
"a",
"new",
"Client",
"instance",
"that",
"will",
"use",
"the",
"given",
"http",
".",
"Client",
"to",
"perform",
"round",
"trips"
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/http_service.go#L47-L49 |
9,691 | remind101/pkg | httpx/http_service.go | Do | func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error) {
return c.Transport.RoundTrip(ctx, req)
} | go | func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error) {
return c.Transport.RoundTrip(ctx, req)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Do",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"return",
"c",
".",
"Transport",
".",
"RoundTrip",
"(",
"c... | // Do performs the request and returns the response. | [
"Do",
"performs",
"the",
"request",
"and",
"returns",
"the",
"response",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/http_service.go#L76-L78 |
9,692 | remind101/pkg | httpx/http_service.go | NewJSONRequest | func NewJSONRequest(method, path string, v interface{}) (*http.Request, error) {
var r io.Reader
if v != nil {
raw, err := json.Marshal(v)
if err != nil {
return nil, err
}
r = bytes.NewReader(raw)
}
req, err := http.NewRequest(method, path, r)
if err != nil {
return nil, err
}
if v != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
} | go | func NewJSONRequest(method, path string, v interface{}) (*http.Request, error) {
var r io.Reader
if v != nil {
raw, err := json.Marshal(v)
if err != nil {
return nil, err
}
r = bytes.NewReader(raw)
}
req, err := http.NewRequest(method, path, r)
if err != nil {
return nil, err
}
if v != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
} | [
"func",
"NewJSONRequest",
"(",
"method",
",",
"path",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"var",
"r",
"io",
".",
"Reader",
"\n",
"if",
"v",
"!=",
"nil",
"{",
"raw",
",",
"err",... | // NewJSONRequest generates a new http.Request with the body set to the json
// encoding of v. | [
"NewJSONRequest",
"generates",
"a",
"new",
"http",
".",
"Request",
"with",
"the",
"body",
"set",
"to",
"the",
"json",
"encoding",
"of",
"v",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/http_service.go#L153-L171 |
9,693 | remind101/pkg | httpx/http_service.go | URLWithoutCreds | func URLWithoutCreds(u url.URL) string {
u.User = nil
return u.String()
} | go | func URLWithoutCreds(u url.URL) string {
u.User = nil
return u.String()
} | [
"func",
"URLWithoutCreds",
"(",
"u",
"url",
".",
"URL",
")",
"string",
"{",
"u",
".",
"User",
"=",
"nil",
"\n",
"return",
"u",
".",
"String",
"(",
")",
"\n",
"}"
] | // Shows the URL without information about the current username and password | [
"Shows",
"the",
"URL",
"without",
"information",
"about",
"the",
"current",
"username",
"and",
"password"
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/http_service.go#L179-L182 |
9,694 | remind101/pkg | tracing/contrib/aws/handlers.go | WithTracing | func WithTracing(s *session.Session) {
// After adding these handlers, the "Send" handler list will look
// something like:
//
// opentracing.Start -> opentracing.RequestInfo -> opentracing.DynamoDBInfo -> core.ValidateReqSigHandler -> core.SendHandler
s.Handlers.Send.PushFrontNamed(DynamoDBInfoHandler)
s.Handlers.Send.PushFrontNamed(RequestInfoHandler)
s.Handlers.Send.PushFrontNamed(StartHandler)
s.Handlers.Complete.PushBackNamed(FinishHandler)
} | go | func WithTracing(s *session.Session) {
// After adding these handlers, the "Send" handler list will look
// something like:
//
// opentracing.Start -> opentracing.RequestInfo -> opentracing.DynamoDBInfo -> core.ValidateReqSigHandler -> core.SendHandler
s.Handlers.Send.PushFrontNamed(DynamoDBInfoHandler)
s.Handlers.Send.PushFrontNamed(RequestInfoHandler)
s.Handlers.Send.PushFrontNamed(StartHandler)
s.Handlers.Complete.PushBackNamed(FinishHandler)
} | [
"func",
"WithTracing",
"(",
"s",
"*",
"session",
".",
"Session",
")",
"{",
"// After adding these handlers, the \"Send\" handler list will look",
"// something like:",
"//",
"//\topentracing.Start -> opentracing.RequestInfo -> opentracing.DynamoDBInfo -> core.ValidateReqSigHandler -> core.... | // WithTracing adds the necessary request handlers to an AWS session.Session
// object to enable tracing with opentracing. | [
"WithTracing",
"adds",
"the",
"necessary",
"request",
"handlers",
"to",
"an",
"AWS",
"session",
".",
"Session",
"object",
"to",
"enable",
"tracing",
"with",
"opentracing",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/tracing/contrib/aws/handlers.go#L85-L95 |
9,695 | remind101/pkg | tracing/contrib/aws/handlers.go | dynamoDBTableName | func dynamoDBTableName(r *request.Request) *string {
// All DynamoDB requests that operate on a table.
switch v := r.Params.(type) {
case *dynamodb.QueryInput:
return v.TableName
case *dynamodb.ScanInput:
return v.TableName
case *dynamodb.PutItemInput:
return v.TableName
case *dynamodb.GetItemInput:
return v.TableName
case *dynamodb.UpdateItemInput:
return v.TableName
case *dynamodb.DeleteItemInput:
return v.TableName
case *dynamodb.CreateTableInput:
return v.TableName
case *dynamodb.UpdateTableInput:
return v.TableName
case *dynamodb.DeleteTableInput:
return v.TableName
case *dynamodb.CreateBackupInput:
return v.TableName
case *dynamodb.ListBackupsInput:
return v.TableName
case *dynamodb.DescribeContinuousBackupsInput:
return v.TableName
case *dynamodb.UpdateContinuousBackupsInput:
return v.TableName
case *dynamodb.DescribeTableInput:
return v.TableName
case *dynamodb.DescribeTimeToLiveInput:
return v.TableName
default:
return nil
}
} | go | func dynamoDBTableName(r *request.Request) *string {
// All DynamoDB requests that operate on a table.
switch v := r.Params.(type) {
case *dynamodb.QueryInput:
return v.TableName
case *dynamodb.ScanInput:
return v.TableName
case *dynamodb.PutItemInput:
return v.TableName
case *dynamodb.GetItemInput:
return v.TableName
case *dynamodb.UpdateItemInput:
return v.TableName
case *dynamodb.DeleteItemInput:
return v.TableName
case *dynamodb.CreateTableInput:
return v.TableName
case *dynamodb.UpdateTableInput:
return v.TableName
case *dynamodb.DeleteTableInput:
return v.TableName
case *dynamodb.CreateBackupInput:
return v.TableName
case *dynamodb.ListBackupsInput:
return v.TableName
case *dynamodb.DescribeContinuousBackupsInput:
return v.TableName
case *dynamodb.UpdateContinuousBackupsInput:
return v.TableName
case *dynamodb.DescribeTableInput:
return v.TableName
case *dynamodb.DescribeTimeToLiveInput:
return v.TableName
default:
return nil
}
} | [
"func",
"dynamoDBTableName",
"(",
"r",
"*",
"request",
".",
"Request",
")",
"*",
"string",
"{",
"// All DynamoDB requests that operate on a table.",
"switch",
"v",
":=",
"r",
".",
"Params",
".",
"(",
"type",
")",
"{",
"case",
"*",
"dynamodb",
".",
"QueryInput"... | // dynamoDBTableName attempts to return the name of the DynamoDB table that this
// request is operating on. | [
"dynamoDBTableName",
"attempts",
"to",
"return",
"the",
"name",
"of",
"the",
"DynamoDB",
"table",
"that",
"this",
"request",
"is",
"operating",
"on",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/tracing/contrib/aws/handlers.go#L99-L139 |
9,696 | remind101/pkg | example/main.go | ip | func ip(ctx context.Context) (string, error) {
req, err := http.NewRequest("GET", "http://api.ipify.org?format=text", nil)
if err != nil {
return "", err
}
req.Header.Set("X-Request-ID", httpx.RequestID(ctx))
retrier := retry.NewRetrier("ip", retry.DefaultBackOffOpts, retry.RetryOnAnyError)
val, err := retrier.Retry(func() (interface{}, error) { return http.DefaultClient.Do(req) })
if err != nil {
return "", err
}
resp := val.(*http.Response)
defer resp.Body.Close()
raw, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(raw), nil
} | go | func ip(ctx context.Context) (string, error) {
req, err := http.NewRequest("GET", "http://api.ipify.org?format=text", nil)
if err != nil {
return "", err
}
req.Header.Set("X-Request-ID", httpx.RequestID(ctx))
retrier := retry.NewRetrier("ip", retry.DefaultBackOffOpts, retry.RetryOnAnyError)
val, err := retrier.Retry(func() (interface{}, error) { return http.DefaultClient.Do(req) })
if err != nil {
return "", err
}
resp := val.(*http.Response)
defer resp.Body.Close()
raw, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(raw), nil
} | [
"func",
"ip",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"string",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return... | // ip returns your ip. | [
"ip",
"returns",
"your",
"ip",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/example/main.go#L103-L124 |
9,697 | remind101/pkg | httpx/request_id.go | WithRequestID | func WithRequestID(ctx context.Context, requestID string) context.Context {
return context.WithValue(ctx, requestIDKey, requestID)
} | go | func WithRequestID(ctx context.Context, requestID string) context.Context {
return context.WithValue(ctx, requestIDKey, requestID)
} | [
"func",
"WithRequestID",
"(",
"ctx",
"context",
".",
"Context",
",",
"requestID",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"requestIDKey",
",",
"requestID",
")",
"\n",
"}"
] | // WithRequestID inserts a RequestID into the context. | [
"WithRequestID",
"inserts",
"a",
"RequestID",
"into",
"the",
"context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/request_id.go#L6-L8 |
9,698 | remind101/pkg | httpx/request_id.go | RequestID | func RequestID(ctx context.Context) string {
requestID, _ := ctx.Value(requestIDKey).(string)
return requestID
} | go | func RequestID(ctx context.Context) string {
requestID, _ := ctx.Value(requestIDKey).(string)
return requestID
} | [
"func",
"RequestID",
"(",
"ctx",
"context",
".",
"Context",
")",
"string",
"{",
"requestID",
",",
"_",
":=",
"ctx",
".",
"Value",
"(",
"requestIDKey",
")",
".",
"(",
"string",
")",
"\n",
"return",
"requestID",
"\n",
"}"
] | // RequestID extracts a RequestID from a context. | [
"RequestID",
"extracts",
"a",
"RequestID",
"from",
"a",
"context",
"."
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/httpx/request_id.go#L11-L14 |
9,699 | remind101/pkg | retry/retry.go | New | func New(name string,
backOffOpts *BackOffOpts, shouldRetryFunc func(error) bool) *Retrier {
return &Retrier{
Name: newName(name),
backOffOpts: backOffOpts,
shouldRetryFunc: shouldRetryFunc,
notifyRetryFuncs: []RetryNotifier{},
notifyGaveUpFuncs: []RetryNotifier{},
notifyShouldNotRetryFuncs: []RetryNotifier{}}
} | go | func New(name string,
backOffOpts *BackOffOpts, shouldRetryFunc func(error) bool) *Retrier {
return &Retrier{
Name: newName(name),
backOffOpts: backOffOpts,
shouldRetryFunc: shouldRetryFunc,
notifyRetryFuncs: []RetryNotifier{},
notifyGaveUpFuncs: []RetryNotifier{},
notifyShouldNotRetryFuncs: []RetryNotifier{}}
} | [
"func",
"New",
"(",
"name",
"string",
",",
"backOffOpts",
"*",
"BackOffOpts",
",",
"shouldRetryFunc",
"func",
"(",
"error",
")",
"bool",
")",
"*",
"Retrier",
"{",
"return",
"&",
"Retrier",
"{",
"Name",
":",
"newName",
"(",
"name",
")",
",",
"backOffOpts"... | // Retrier without logging functions included as defaults for notify funcs | [
"Retrier",
"without",
"logging",
"functions",
"included",
"as",
"defaults",
"for",
"notify",
"funcs"
] | 6c8f1a7b080e58f5c69a857536d9989fc9356841 | https://github.com/remind101/pkg/blob/6c8f1a7b080e58f5c69a857536d9989fc9356841/retry/retry.go#L56-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.