_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q11000 | Decode | train | func (m AttributeMap) Decode(dst interface{}, opts ...mapdecode.Option) error {
return DecodeInto(dst, m, opts...)
} | go | {
"resource": ""
} |
q11001 | Run | train | func Run(t crossdock.T) {
fatals := crossdock.Fatals(t)
server := t.Param(serverParam)
fatals.NotEmpty(server, "apachethriftserver is required")
httpTransport := http.NewTransport()
url := fmt.Sprintf("http://%v:%v", server, serverPort)
thriftOutbound := httpTransport.NewSingleOutbound(url + "/thrift/ThriftTest")
secondOutbound := httpTransport.NewSingleOutbound(url + "/thrift/SecondService")
multiplexOutbound := httpTransport.NewSingleOutbound(url + "/thrift/multiplexed")
dispatcher := yarpc.NewDispatcher(yarpc.Config{
Name: "apache-thrift-client",
Outbounds: yarpc.Outbounds{
"ThriftTest": {
Unary: thriftOutbound,
Oneway: thriftOutbound,
},
"SecondService": {
Unary: secondOutbound,
},
"Multiplexed": {
Unary: multiplexOutbound,
Oneway: multiplexOutbound,
},
},
})
fatals.NoError(dispatcher.Start(), "could not start Dispatcher")
defer dispatcher.Stop()
// We can just run all the gauntlet tests against each URL because
// tests for undefined methods are skipped.
tests := []struct {
ServerName string
Services gauntlet.ServiceSet
Options []thrift.ClientOption
}{
{
ServerName: "ThriftTest",
Services: gauntlet.ThriftTest,
},
{
ServerName: "SecondService",
Services: gauntlet.SecondService,
},
{
ServerName: "Multiplexed",
Services: gauntlet.AllServices,
Options: []thrift.ClientOption{thrift.Multiplexed},
},
}
for _, tt := range tests {
t.Tag("outbound", tt.ServerName)
gauntlet.RunGauntlet(t, gauntlet.Config{
Dispatcher: dispatcher,
ServerName: tt.ServerName,
Envelope: true,
Services: tt.Services,
ClientOptions: tt.Options,
})
}
} | go | {
"resource": ""
} |
q11002 | Add | train | func (fc *FakeClock) Add(d time.Duration) {
fc.Lock()
// Calculate the final time.
end := fc.now.Add(d)
fc.flush(end)
if fc.now.Before(end) {
fc.now = end
}
fc.Unlock()
nap()
} | go | {
"resource": ""
} |
q11003 | Set | train | func (fc *FakeClock) Set(end time.Time) {
fc.Lock()
fc.flush(end)
if fc.now.Before(end) {
fc.now = end
}
fc.Unlock()
nap()
} | go | {
"resource": ""
} |
q11004 | FakeTimer | train | func (fc *FakeClock) FakeTimer(d time.Duration) *FakeTimer {
fc.Lock()
defer fc.Unlock()
c := make(chan time.Time, 1)
t := &FakeTimer{
c: c,
clock: fc,
time: fc.now.Add(d),
}
fc.addTimer(t)
return t
} | go | {
"resource": ""
} |
q11005 | FakeAfterFunc | train | func (fc *FakeClock) FakeAfterFunc(d time.Duration, f func()) *FakeTimer {
t := fc.FakeTimer(d)
go func() {
<-t.c
f()
}()
nap()
return t
} | go | {
"resource": ""
} |
q11006 | Now | train | func (fc *FakeClock) Now() time.Time {
fc.Lock()
defer fc.Unlock()
return fc.now
} | go | {
"resource": ""
} |
q11007 | Reset | train | func (t *FakeTimer) Reset(d time.Duration) bool {
t.time = t.clock.now.Add(d)
// Empty the channel if already filled.
select {
case <-t.c:
default:
}
if t.index >= 0 {
heap.Fix(&t.clock.timers, t.index)
return true
}
heap.Push(&t.clock.timers, t)
return false
} | go | {
"resource": ""
} |
q11008 | Stop | train | func (t *FakeTimer) Stop() bool {
if t.index < 0 {
return false
}
// Empty the channel if already filled.
select {
case <-t.c:
default:
}
t.clock.timers.Swap(t.index, len(t.clock.timers)-1)
t.clock.timers.Pop()
heap.Fix(&t.clock.timers, t.index)
return true
} | go | {
"resource": ""
} |
q11009 | NewHelloYARPCClient | train | func NewHelloYARPCClient(clientConfig transport.ClientConfig, options ...protobuf.ClientOption) HelloYARPCClient {
return &_HelloYARPCCaller{protobuf.NewStreamClient(
protobuf.ClientParams{
ServiceName: "uber.yarpc.internal.examples.streaming.Hello",
ClientConfig: clientConfig,
Options: options,
},
)}
} | go | {
"resource": ""
} |
q11010 | BuildHelloYARPCProcedures | train | func BuildHelloYARPCProcedures(server HelloYARPCServer) []transport.Procedure {
handler := &_HelloYARPCHandler{server}
return protobuf.BuildProcedures(
protobuf.BuildProceduresParams{
ServiceName: "uber.yarpc.internal.examples.streaming.Hello",
UnaryHandlerParams: []protobuf.BuildProceduresUnaryHandlerParams{
{
MethodName: "HelloUnary",
Handler: protobuf.NewUnaryHandler(
protobuf.UnaryHandlerParams{
Handle: handler.HelloUnary,
NewRequest: newHelloServiceHelloUnaryYARPCRequest,
},
),
},
},
OnewayHandlerParams: []protobuf.BuildProceduresOnewayHandlerParams{},
StreamHandlerParams: []protobuf.BuildProceduresStreamHandlerParams{
{
MethodName: "HelloThere",
Handler: protobuf.NewStreamHandler(
protobuf.StreamHandlerParams{
Handle: handler.HelloThere,
},
),
},
{
MethodName: "HelloInStream",
Handler: protobuf.NewStreamHandler(
protobuf.StreamHandlerParams{
Handle: handler.HelloInStream,
},
),
},
{
MethodName: "HelloOutStream",
Handler: protobuf.NewStreamHandler(
protobuf.StreamHandlerParams{
Handle: handler.HelloOutStream,
},
),
},
},
},
)
} | go | {
"resource": ""
} |
q11011 | StartTransports | train | func (s *PhasedStarter) StartTransports() error {
if s.transportsStartInitiated.Swap(true) {
return errors.New("already began starting transports")
}
defer s.transportsStarted.Store(true)
s.log.Info("starting transports")
wait := errorsync.ErrorWaiter{}
for _, t := range s.dispatcher.transports {
wait.Submit(s.start(t))
}
if errs := wait.Wait(); len(errs) != 0 {
return s.abort(errs)
}
s.log.Debug("started transports")
return nil
} | go | {
"resource": ""
} |
q11012 | StartOutbounds | train | func (s *PhasedStarter) StartOutbounds() error {
if !s.transportsStarted.Load() {
return errors.New("must start outbounds after transports")
}
if s.outboundsStartInitiated.Swap(true) {
return errors.New("already began starting outbounds")
}
defer s.outboundsStarted.Store(true)
s.log.Info("starting outbounds")
wait := errorsync.ErrorWaiter{}
for _, o := range s.dispatcher.outbounds {
wait.Submit(s.start(o.Unary))
wait.Submit(s.start(o.Oneway))
wait.Submit(s.start(o.Stream))
}
if errs := wait.Wait(); len(errs) != 0 {
return s.abort(errs)
}
s.log.Debug("started outbounds")
return nil
} | go | {
"resource": ""
} |
q11013 | StartInbounds | train | func (s *PhasedStarter) StartInbounds() error {
if !s.transportsStarted.Load() || !s.outboundsStarted.Load() {
return errors.New("must start inbounds after transports and outbounds")
}
if s.inboundsStartInitiated.Swap(true) {
return errors.New("already began starting inbounds")
}
s.log.Info("starting inbounds")
wait := errorsync.ErrorWaiter{}
for _, i := range s.dispatcher.inbounds {
wait.Submit(s.start(i))
}
if errs := wait.Wait(); len(errs) != 0 {
return s.abort(errs)
}
s.log.Debug("started inbounds")
return nil
} | go | {
"resource": ""
} |
q11014 | StopInbounds | train | func (s *PhasedStopper) StopInbounds() error {
if s.inboundsStopInitiated.Swap(true) {
return errors.New("already began stopping inbounds")
}
defer s.inboundsStopped.Store(true)
s.log.Debug("stopping inbounds")
wait := errorsync.ErrorWaiter{}
for _, ib := range s.dispatcher.inbounds {
wait.Submit(ib.Stop)
}
if errs := wait.Wait(); len(errs) > 0 {
return multierr.Combine(errs...)
}
s.log.Debug("stopped inbounds")
return nil
} | go | {
"resource": ""
} |
q11015 | StopOutbounds | train | func (s *PhasedStopper) StopOutbounds() error {
if !s.inboundsStopped.Load() {
return errors.New("must stop inbounds first")
}
if s.outboundsStopInitiated.Swap(true) {
return errors.New("already began stopping outbounds")
}
defer s.outboundsStopped.Store(true)
s.log.Debug("stopping outbounds")
wait := errorsync.ErrorWaiter{}
for _, o := range s.dispatcher.outbounds {
if o.Unary != nil {
wait.Submit(o.Unary.Stop)
}
if o.Oneway != nil {
wait.Submit(o.Oneway.Stop)
}
if o.Stream != nil {
wait.Submit(o.Stream.Stop)
}
}
if errs := wait.Wait(); len(errs) > 0 {
return multierr.Combine(errs...)
}
s.log.Debug("stopped outbounds")
return nil
} | go | {
"resource": ""
} |
q11016 | StopTransports | train | func (s *PhasedStopper) StopTransports() error {
if !s.inboundsStopped.Load() || !s.outboundsStopped.Load() {
return errors.New("must stop inbounds and outbounds first")
}
if s.transportsStopInitiated.Swap(true) {
return errors.New("already began stopping transports")
}
s.log.Debug("stopping transports")
wait := errorsync.ErrorWaiter{}
for _, t := range s.dispatcher.transports {
wait.Submit(t.Stop)
}
if errs := wait.Wait(); len(errs) > 0 {
return multierr.Combine(errs...)
}
s.log.Debug("stopped transports")
s.log.Debug("stopping metrics push loop, if any")
s.dispatcher.stopMeter()
s.log.Debug("stopped metrics push loop, if any")
return nil
} | go | {
"resource": ""
} |
q11017 | Mux | train | func Mux(pattern string, mux *http.ServeMux) InboundOption {
return func(i *Inbound) {
i.mux = mux
i.muxPattern = pattern
}
} | go | {
"resource": ""
} |
q11018 | Interceptor | train | func Interceptor(interceptor func(yarpcHandler http.Handler) http.Handler) InboundOption {
return func(i *Inbound) {
i.interceptor = interceptor
}
} | go | {
"resource": ""
} |
q11019 | ShutdownTimeout | train | func ShutdownTimeout(timeout time.Duration) InboundOption {
return func(i *Inbound) {
i.shutdownTimeout = timeout
}
} | go | {
"resource": ""
} |
q11020 | NewInbound | train | func (t *Transport) NewInbound(addr string, opts ...InboundOption) *Inbound {
i := &Inbound{
once: lifecycle.NewOnce(),
addr: addr,
shutdownTimeout: defaultShutdownTimeout,
tracer: t.tracer,
logger: t.logger,
transport: t,
grabHeaders: make(map[string]struct{}),
bothResponseError: true,
}
for _, opt := range opts {
opt(i)
}
return i
} | go | {
"resource": ""
} |
q11021 | Tracer | train | func (i *Inbound) Tracer(tracer opentracing.Tracer) *Inbound {
i.tracer = tracer
return i
} | go | {
"resource": ""
} |
q11022 | Stop | train | func (i *Inbound) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), i.shutdownTimeout)
defer cancel()
return i.shutdown(ctx)
} | go | {
"resource": ""
} |
q11023 | shutdown | train | func (i *Inbound) shutdown(ctx context.Context) error {
return i.once.Stop(func() error {
if i.server == nil {
return nil
}
return i.server.Shutdown(ctx)
})
} | go | {
"resource": ""
} |
q11024 | Addr | train | func (i *Inbound) Addr() net.Addr {
if i.server == nil {
return nil
}
listener := i.server.Listener()
if listener == nil {
return nil
}
return listener.Addr()
} | go | {
"resource": ""
} |
q11025 | Swap | train | func (ph *pendingHeap) Swap(i, j int) {
p1 := ph.peers[i]
p2 := ph.peers[j]
ph.peers[i], ph.peers[j] = ph.peers[j], ph.peers[i]
p1.index = j
p2.index = i
} | go | {
"resource": ""
} |
q11026 | Push | train | func (ph *pendingHeap) Push(x interface{}) {
ps := x.(*peerScore)
ps.index = len(ph.peers)
ph.peers = append(ph.peers, ps)
} | go | {
"resource": ""
} |
q11027 | Pop | train | func (ph *pendingHeap) Pop() interface{} {
lastIndex := len(ph.peers) - 1
last := ph.peers[lastIndex]
ph.peers = ph.peers[:lastIndex]
return last
} | go | {
"resource": ""
} |
q11028 | delete | train | func (ph *pendingHeap) delete(ps *peerScore) {
if ps.index < 0 {
return
}
index := ps.index
// Swap the element we want to delete with the last element, then pop it off.
ph.Swap(index, ph.Len()-1)
ph.Pop()
// If the original index still exists in the list, it contains a different
// element so update the heap.
if index < ph.Len() {
ph.update(index)
}
// Set the index to negative so we do not try to delete it again.
ps.index = -1
} | go | {
"resource": ""
} |
q11029 | pushPeerRandom | train | func (ph *pendingHeap) pushPeerRandom(ps *peerScore) {
ph.next++
ps.last = ph.next
random := ph.nextRand(len(ph.peers) + 1)
if random < len(ph.peers) {
randPeer := ph.peers[random]
ps.last, randPeer.last = randPeer.last, ps.last
heap.Fix(ph, random)
}
heap.Push(ph, ps)
} | go | {
"resource": ""
} |
q11030 | Sink | train | func (h *helloHandler) Sink(ctx context.Context, snk *sink.SinkRequest) error {
log.Println("received message:", snk.Message)
return nil
} | go | {
"resource": ""
} |
q11031 | UnaryChain | train | func UnaryChain(mw ...middleware.UnaryInbound) middleware.UnaryInbound {
unchained := make([]middleware.UnaryInbound, 0, len(mw))
for _, m := range mw {
if m == nil {
continue
}
if c, ok := m.(unaryChain); ok {
unchained = append(unchained, c...)
continue
}
unchained = append(unchained, m)
}
switch len(unchained) {
case 0:
return middleware.NopUnaryInbound
case 1:
return unchained[0]
default:
return unaryChain(unchained)
}
} | go | {
"resource": ""
} |
q11032 | OnewayChain | train | func OnewayChain(mw ...middleware.OnewayInbound) middleware.OnewayInbound {
unchained := make([]middleware.OnewayInbound, 0, len(mw))
for _, m := range mw {
if m == nil {
continue
}
if c, ok := m.(onewayChain); ok {
unchained = append(unchained, c...)
continue
}
unchained = append(unchained, m)
}
switch len(unchained) {
case 0:
return middleware.NopOnewayInbound
case 1:
return unchained[0]
default:
return onewayChain(unchained)
}
} | go | {
"resource": ""
} |
q11033 | StreamChain | train | func StreamChain(mw ...middleware.StreamInbound) middleware.StreamInbound {
unchained := make([]middleware.StreamInbound, 0, len(mw))
for _, m := range mw {
if m == nil {
continue
}
if c, ok := m.(streamChain); ok {
unchained = append(unchained, c...)
continue
}
unchained = append(unchained, m)
}
switch len(unchained) {
case 0:
return middleware.NopStreamInbound
case 1:
return unchained[0]
default:
return streamChain(unchained)
}
} | go | {
"resource": ""
} |
q11034 | Start | train | func Start() {
// We expose the following endpoints:
// /thrift/ThriftTest:
// Thrift service using TBinaryProtocol
// /thrift/SecondService
// Thrift service using TBinaryProtocol
// /thrift/mutliplexed
// Thrift service using TBinaryProtocol with TMultiplexedProtocol,
// serving both, ThriftTest and SecondService
pfactory := thrift.NewTBinaryProtocolFactoryDefault()
thriftTest := gauntlet_apache.NewThriftTestProcessor(thriftTestHandler{})
secondService := gauntlet_apache.NewSecondServiceProcessor(secondServiceHandler{})
multiplexed := thrift.NewTMultiplexedProcessor()
multiplexed.RegisterProcessor("ThriftTest", thriftTest)
multiplexed.RegisterProcessor("SecondService", secondService)
mux := http.NewServeMux()
mux.HandleFunc("/thrift/ThriftTest", newThriftHandlerFunc(thriftTest, pfactory, pfactory))
mux.HandleFunc("/thrift/SecondService", newThriftHandlerFunc(secondService, pfactory, pfactory))
mux.HandleFunc("/thrift/multiplexed", newThriftHandlerFunc(multiplexed, pfactory, pfactory))
server = net.NewHTTPServer(&http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
})
if err := server.ListenAndServe(); err != nil {
log.Fatalf("failed to start Apache Thrift server: %v", err)
}
} | go | {
"resource": ""
} |
q11035 | transportRequestToMetadata | train | func transportRequestToMetadata(request *transport.Request) (metadata.MD, error) {
md := metadata.New(nil)
if err := multierr.Combine(
addToMetadata(md, CallerHeader, request.Caller),
addToMetadata(md, ServiceHeader, request.Service),
addToMetadata(md, ShardKeyHeader, request.ShardKey),
addToMetadata(md, RoutingKeyHeader, request.RoutingKey),
addToMetadata(md, RoutingDelegateHeader, request.RoutingDelegate),
addToMetadata(md, EncodingHeader, string(request.Encoding)),
); err != nil {
return md, err
}
return md, addApplicationHeaders(md, request.Headers)
} | go | {
"resource": ""
} |
q11036 | metadataToTransportRequest | train | func metadataToTransportRequest(md metadata.MD) (*transport.Request, error) {
request := &transport.Request{
Headers: transport.NewHeadersWithCapacity(md.Len()),
}
for header, values := range md {
var value string
switch len(values) {
case 0:
continue
case 1:
value = values[0]
default:
return nil, yarpcerrors.InvalidArgumentErrorf("header has more than one value: %s", header)
}
header = transport.CanonicalizeHeaderKey(header)
switch header {
case CallerHeader:
request.Caller = value
case ServiceHeader:
request.Service = value
case ShardKeyHeader:
request.ShardKey = value
case RoutingKeyHeader:
request.RoutingKey = value
case RoutingDelegateHeader:
request.RoutingDelegate = value
case EncodingHeader:
request.Encoding = transport.Encoding(value)
case contentTypeHeader:
// if request.Encoding was set, do not parse content-type
// this results in EncodingHeader overriding content-type
if request.Encoding == "" {
request.Encoding = transport.Encoding(getContentSubtype(value))
}
default:
request.Headers = request.Headers.With(header, value)
}
}
return request, nil
} | go | {
"resource": ""
} |
q11037 | addApplicationHeaders | train | func addApplicationHeaders(md metadata.MD, headers transport.Headers) error {
for header, value := range headers.Items() {
header = transport.CanonicalizeHeaderKey(header)
if isReserved(header) {
return yarpcerrors.InvalidArgumentErrorf("cannot use reserved header in application headers: %s", header)
}
if err := addToMetadata(md, header, value); err != nil {
return err
}
}
return nil
} | go | {
"resource": ""
} |
q11038 | getApplicationHeaders | train | func getApplicationHeaders(md metadata.MD) (transport.Headers, error) {
if len(md) == 0 {
return transport.Headers{}, nil
}
headers := transport.NewHeadersWithCapacity(md.Len())
for header, values := range md {
header = transport.CanonicalizeHeaderKey(header)
if isReserved(header) {
continue
}
var value string
switch len(values) {
case 0:
continue
case 1:
value = values[0]
default:
return headers, yarpcerrors.InvalidArgumentErrorf("header has more than one value: %s", header)
}
headers = headers.With(header, value)
}
return headers, nil
} | go | {
"resource": ""
} |
q11039 | addToMetadata | train | func addToMetadata(md metadata.MD, key string, value string) error {
if value == "" {
return nil
}
if _, ok := md[key]; ok {
return yarpcerrors.InvalidArgumentErrorf("duplicate key: %s", key)
}
md[key] = []string{value}
return nil
} | go | {
"resource": ""
} |
q11040 | getContentSubtype | train | func getContentSubtype(contentType string) string {
if !strings.HasPrefix(contentType, baseContentType) || len(contentType) == len(baseContentType) {
return ""
}
switch contentType[len(baseContentType)] {
case '+', ';':
return contentType[len(baseContentType)+1:]
default:
return ""
}
} | go | {
"resource": ""
} |
q11041 | ForeachKey | train | func (md mdReadWriter) ForeachKey(handler func(string, string) error) error {
for key, values := range md {
for _, value := range values {
if err := handler(key, value); err != nil {
return err
}
}
}
return nil
} | go | {
"resource": ""
} |
q11042 | Set | train | func (md mdReadWriter) Set(key string, value string) {
key = strings.ToLower(key)
md[key] = []string{value}
} | go | {
"resource": ""
} |
q11043 | DecodeInto | train | func DecodeInto(dst interface{}, src interface{}, opts ...mapdecode.Option) error {
opts = append(opts, mapdecode.TagName(_tagName))
return mapdecode.Decode(dst, src, opts...)
} | go | {
"resource": ""
} |
q11044 | InterpolateWith | train | func InterpolateWith(resolver interpolate.VariableResolver) mapdecode.Option {
return mapdecode.FieldHook(func(dest reflect.StructField, srcData reflect.Value) (reflect.Value, error) {
shouldInterpolate := false
options := strings.Split(dest.Tag.Get(_tagName), ",")[1:]
for _, option := range options {
if option == _interpolateOption {
shouldInterpolate = true
break
}
}
if !shouldInterpolate {
return srcData, nil
}
// Use Interface().(string) so that we handle the case where data is an
// interface{} holding a string.
v, ok := srcData.Interface().(string)
if !ok {
// Cannot interpolate non-string type. This shouldn't be an error
// because an integer field may be marked as interpolatable and may
// have received an integer as expected.
return srcData, nil
}
s, err := interpolate.Parse(v)
if err != nil {
return srcData, fmt.Errorf("failed to parse %q for interpolation: %v", v, err)
}
newV, err := s.Render(resolver)
if err != nil {
return srcData, fmt.Errorf("failed to render %q with environment variables: %v", v, err)
}
return reflect.ValueOf(newV), nil
})
} | go | {
"resource": ""
} |
q11045 | readLengthEncodedString | train | func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
// Get length
num, isNull, n := readLengthEncodedInteger(b)
if num < 1 {
return b[n:n], isNull, n, nil
}
n += int(num)
// Check data length
if len(b) >= n {
return b[n-int(num) : n], false, n, nil
}
return nil, false, n, io.EOF
} | go | {
"resource": ""
} |
q11046 | readLengthEncodedInteger | train | func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
// See issue #349
if len(b) == 0 {
return 0, true, 1
}
switch b[0] {
// 251: NULL
case 0xfb:
return 0, true, 1
// 252: value of following 2
case 0xfc:
return uint64(b[1]) | uint64(b[2])<<8, false, 3
// 253: value of following 3
case 0xfd:
return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
// 254: value of following 8
case 0xfe:
return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
uint64(b[7])<<48 | uint64(b[8])<<56,
false, 9
}
// 0-250: value of first byte
return uint64(b[0]), false, 1
} | go | {
"resource": ""
} |
q11047 | ReadPacket | train | func (pr *PacketResponse) ReadPacket() (*ber.Packet, error) {
if (pr == nil) || (pr.Packet == nil && pr.Error == nil) {
return nil, NewError(ErrorNetwork, errors.New("ldap: could not retrieve response"))
}
return pr.Packet, pr.Error
} | go | {
"resource": ""
} |
q11048 | Dial | train | func Dial(network, addr string, timeout time.Duration) (*Conn, error) {
c, err := net.DialTimeout(network, addr, timeout)
if err != nil {
return nil, NewError(ErrorNetwork, err)
}
conn := NewConn(c, false)
conn.Start()
return conn, nil
} | go | {
"resource": ""
} |
q11049 | DialTLS | train | func DialTLS(network, addr string, config *tls.Config) (*Conn, error) {
dc, err := net.DialTimeout(network, addr, DefaultTimeout)
if err != nil {
return nil, NewError(ErrorNetwork, err)
}
c := tls.Client(dc, config)
err = c.Handshake()
if err != nil {
// Handshake error, close the established connection before we return an error
dc.Close()
return nil, NewError(ErrorNetwork, err)
}
conn := NewConn(c, true)
conn.Start()
return conn, nil
} | go | {
"resource": ""
} |
q11050 | Start | train | func (l *Conn) Start() {
go l.reader()
go l.processMessages()
l.wgClose.Add(1)
} | go | {
"resource": ""
} |
q11051 | SetTimeout | train | func (l *Conn) SetTimeout(timeout time.Duration) {
if timeout > 0 {
l.requestTimeout = timeout
}
} | go | {
"resource": ""
} |
q11052 | nextMessageID | train | func (l *Conn) nextMessageID() int64 {
if l.chanMessageID != nil {
if messageID, ok := <-l.chanMessageID; ok {
return messageID
}
}
return 0
} | go | {
"resource": ""
} |
q11053 | StartTLS | train | func (l *Conn) StartTLS(config *tls.Config) error {
if l.isTLS {
return NewError(ErrorNetwork, errors.New("ldap: already encrypted"))
}
packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Start TLS")
request.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, "1.3.6.1.4.1.1466.20037", "TLS Extended Command"))
packet.AppendChild(request)
l.Debug.PrintPacket(packet)
msgCtx, err := l.sendMessageWithFlags(packet, startTLS)
if err != nil {
return err
}
defer l.finishMessage(msgCtx)
l.Debug.Printf("%d: waiting for response", msgCtx.id)
packetResponse, ok := <-msgCtx.responses
if !ok {
return NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
}
packet, err = packetResponse.ReadPacket()
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
if err != nil {
return err
}
if l.Debug {
if err := addLDAPDescriptions(packet); err != nil {
l.Close()
return err
}
ber.PrintPacket(packet)
}
if resultCode, message := getLDAPResultCode(packet); resultCode == LDAPResultSuccess {
conn := tls.Client(l.conn, config)
if err := conn.Handshake(); err != nil {
l.Close()
return NewError(ErrorNetwork, fmt.Errorf("TLS handshake failed (%v)", err))
}
l.isTLS = true
l.conn = conn
} else {
return NewError(resultCode, fmt.Errorf("ldap: cannot StartTLS (%s)", message))
}
go l.reader()
return nil
} | go | {
"resource": ""
} |
q11054 | TLSConnectionState | train | func (l *Conn) TLSConnectionState() (*tls.ConnectionState, error) {
if !l.isTLS {
return nil, errors.New("ldap: Cannot get TLS Connection State for non-TLS connection")
}
state := l.conn.(*tls.Conn).ConnectionState()
return &state, nil
} | go | {
"resource": ""
} |
q11055 | Value | train | func (a ByteaArray) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// There will be at least two curly brackets, 2*N bytes of quotes,
// 3*N bytes of hex formatting, and N-1 bytes of delimiters.
size := 1 + 6*n
for _, x := range a {
size += hex.EncodedLen(len(x))
}
b := make([]byte, size)
for i, s := 0, b; i < n; i++ {
o := copy(s, `,"\\x`)
o += hex.Encode(s[o:], a[i])
s[o] = '"'
s = s[o+1:]
}
b[0] = '{'
b[size-1] = '}'
return string(b), nil
}
return "{}", nil
} | go | {
"resource": ""
} |
q11056 | appendArray | train | func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) {
var del string
var err error
b = append(b, '{')
if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil {
return b, del, err
}
for i := 1; i < n; i++ {
b = append(b, del...)
if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil {
return b, del, err
}
}
return append(b, '}'), del, nil
} | go | {
"resource": ""
} |
q11057 | Attribute | train | func (a *AddRequest) Attribute(attrType string, attrVals []string) {
a.Attributes = append(a.Attributes, Attribute{Type: attrType, Vals: attrVals})
} | go | {
"resource": ""
} |
q11058 | decodeUUIDBinary | train | func decodeUUIDBinary(src []byte) ([]byte, error) {
if len(src) != 16 {
return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src))
}
dst := make([]byte, 36)
dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-'
hex.Encode(dst[0:], src[0:4])
hex.Encode(dst[9:], src[4:6])
hex.Encode(dst[14:], src[6:8])
hex.Encode(dst[19:], src[8:10])
hex.Encode(dst[24:], src[10:16])
return dst, nil
} | go | {
"resource": ""
} |
q11059 | NewEntry | train | func NewEntry(dn string, attributes map[string][]string) *Entry {
var attributeNames []string
for attributeName := range attributes {
attributeNames = append(attributeNames, attributeName)
}
sort.Strings(attributeNames)
var encodedAttributes []*EntryAttribute
for _, attributeName := range attributeNames {
encodedAttributes = append(encodedAttributes, NewEntryAttribute(attributeName, attributes[attributeName]))
}
return &Entry{
DN: dn,
Attributes: encodedAttributes,
}
} | go | {
"resource": ""
} |
q11060 | GetAttributeValues | train | func (e *Entry) GetAttributeValues(attribute string) []string {
for _, attr := range e.Attributes {
if attr.Name == attribute {
return attr.Values
}
}
return []string{}
} | go | {
"resource": ""
} |
q11061 | GetRawAttributeValues | train | func (e *Entry) GetRawAttributeValues(attribute string) [][]byte {
for _, attr := range e.Attributes {
if attr.Name == attribute {
return attr.ByteValues
}
}
return [][]byte{}
} | go | {
"resource": ""
} |
q11062 | GetAttributeValue | train | func (e *Entry) GetAttributeValue(attribute string) string {
values := e.GetAttributeValues(attribute)
if len(values) == 0 {
return ""
}
return values[0]
} | go | {
"resource": ""
} |
q11063 | GetRawAttributeValue | train | func (e *Entry) GetRawAttributeValue(attribute string) []byte {
values := e.GetRawAttributeValues(attribute)
if len(values) == 0 {
return []byte{}
}
return values[0]
} | go | {
"resource": ""
} |
q11064 | Print | train | func (e *Entry) Print() {
fmt.Printf("DN: %s\n", e.DN)
for _, attr := range e.Attributes {
attr.Print()
}
} | go | {
"resource": ""
} |
q11065 | PrettyPrint | train | func (e *Entry) PrettyPrint(indent int) {
fmt.Printf("%sDN: %s\n", strings.Repeat(" ", indent), e.DN)
for _, attr := range e.Attributes {
attr.PrettyPrint(indent + 2)
}
} | go | {
"resource": ""
} |
q11066 | NewEntryAttribute | train | func NewEntryAttribute(name string, values []string) *EntryAttribute {
var bytes [][]byte
for _, value := range values {
bytes = append(bytes, []byte(value))
}
return &EntryAttribute{
Name: name,
Values: values,
ByteValues: bytes,
}
} | go | {
"resource": ""
} |
q11067 | NewSearchRequest | train | func NewSearchRequest(
BaseDN string,
Scope, DerefAliases, SizeLimit, TimeLimit int,
TypesOnly bool,
Filter string,
Attributes []string,
Controls []Control,
) *SearchRequest {
return &SearchRequest{
BaseDN: BaseDN,
Scope: Scope,
DerefAliases: DerefAliases,
SizeLimit: SizeLimit,
TimeLimit: TimeLimit,
TypesOnly: TypesOnly,
Filter: Filter,
Attributes: Attributes,
Controls: Controls,
}
} | go | {
"resource": ""
} |
q11068 | Get | train | func (err *Error) Get(k byte) (v string) {
switch k {
case 'S':
return err.Severity
case 'C':
return string(err.Code)
case 'M':
return err.Message
case 'D':
return err.Detail
case 'H':
return err.Hint
case 'P':
return err.Position
case 'p':
return err.InternalPosition
case 'q':
return err.InternalQuery
case 'W':
return err.Where
case 's':
return err.Schema
case 't':
return err.Table
case 'c':
return err.Column
case 'd':
return err.DataTypeName
case 'n':
return err.Constraint
case 'F':
return err.File
case 'L':
return err.Line
case 'R':
return err.Routine
}
return ""
} | go | {
"resource": ""
} |
q11069 | Equal | train | func (a *AttributeTypeAndValue) Equal(other *AttributeTypeAndValue) bool {
return strings.EqualFold(a.Type, other.Type) && a.Value == other.Value
} | go | {
"resource": ""
} |
q11070 | PasswordModify | train | func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*PasswordModifyResult, error) {
packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
encodedPasswordModifyRequest, err := passwordModifyRequest.encode()
if err != nil {
return nil, err
}
packet.AppendChild(encodedPasswordModifyRequest)
l.Debug.PrintPacket(packet)
msgCtx, err := l.sendMessage(packet)
if err != nil {
return nil, err
}
defer l.finishMessage(msgCtx)
result := &PasswordModifyResult{}
l.Debug.Printf("%d: waiting for response", msgCtx.id)
packetResponse, ok := <-msgCtx.responses
if !ok {
return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
}
packet, err = packetResponse.ReadPacket()
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
if err != nil {
return nil, err
}
if packet == nil {
return nil, NewError(ErrorNetwork, errors.New("ldap: could not retrieve message"))
}
if l.Debug {
if err := addLDAPDescriptions(packet); err != nil {
return nil, err
}
ber.PrintPacket(packet)
}
if packet.Children[1].Tag == ApplicationExtendedResponse {
resultCode, resultDescription := getLDAPResultCode(packet)
if resultCode != 0 {
return nil, NewError(resultCode, errors.New(resultDescription))
}
} else {
return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("Unexpected Response: %d", packet.Children[1].Tag))
}
extendedResponse := packet.Children[1]
for _, child := range extendedResponse.Children {
if child.Tag == 11 {
passwordModifyReponseValue := ber.DecodePacket(child.Data.Bytes())
if len(passwordModifyReponseValue.Children) == 1 {
if passwordModifyReponseValue.Children[0].Tag == 0 {
result.GeneratedPassword = ber.DecodeString(passwordModifyReponseValue.Children[0].Data.Bytes())
}
}
}
}
return result, nil
} | go | {
"resource": ""
} |
q11071 | EncodeX509ToJSON | train | func EncodeX509ToJSON(cert *x509.Certificate) []byte {
out := createSimpleCertificate("", cert)
raw, err := json.Marshal(out)
if err != nil {
panic(err)
}
return raw
} | go | {
"resource": ""
} |
q11072 | EncodeX509ToText | train | func EncodeX509ToText(cert *x509.Certificate, terminalWidth int, verbose bool) []byte {
c := createSimpleCertificate("", cert)
c.Width = terminalWidth - 8 /* Need some margin for tab */
return displayCert(c, verbose)
} | go | {
"resource": ""
} |
q11073 | timeString | train | func timeString(t time.Time, c *color.Color) string {
return c.SprintfFunc()(t.Format("2006-01-02 15:04 MST"))
} | go | {
"resource": ""
} |
q11074 | certStart | train | func certStart(start time.Time) string {
now := time.Now()
day, _ := time.ParseDuration("24h")
threshold := start.Add(day)
if now.After(threshold) {
return timeString(start, green)
} else if now.After(start) {
return timeString(start, yellow)
} else {
return timeString(start, red)
}
} | go | {
"resource": ""
} |
q11075 | certEnd | train | func certEnd(end time.Time) string {
now := time.Now()
month, _ := time.ParseDuration("720h")
threshold := now.Add(month)
if threshold.Before(end) {
return timeString(end, green)
} else if now.Before(end) {
return timeString(end, yellow)
} else {
return timeString(end, red)
}
} | go | {
"resource": ""
} |
q11076 | PrintCommonName | train | func PrintCommonName(name pkix.Name) (out string) {
if name.CommonName != "" {
return fmt.Sprintf("CN=%s", name.CommonName)
}
return PrintShortName(name)
} | go | {
"resource": ""
} |
q11077 | PrintShortName | train | func PrintShortName(name pkix.Name) (out string) {
printed := false
for _, name := range name.Names {
short := oidShort(name.Type)
if short != "" {
if printed {
out += ", "
}
out += fmt.Sprintf("%s=%v", short, name.Value)
printed = true
}
}
return
} | go | {
"resource": ""
} |
q11078 | handleDriverSettings | train | func (c *conn) handleDriverSettings(o values) (err error) {
boolSetting := func(key string, val *bool) error {
if value := o.Get(key); value != "" {
if value == "yes" {
*val = true
} else if value == "no" {
*val = false
} else {
return fmt.Errorf("unrecognized value %q for %s", value, key)
}
}
return nil
}
err = boolSetting("disable_prepared_binary_result", &c.disablePreparedBinaryResult)
if err != nil {
return err
}
err = boolSetting("binary_parameters", &c.binaryParameters)
if err != nil {
return err
}
return nil
} | go | {
"resource": ""
} |
q11079 | decideColumnFormats | train | func decideColumnFormats(colTyps []oid.Oid, forceText bool) (colFmts []format, colFmtData []byte) {
if len(colTyps) == 0 {
return nil, colFmtDataAllText
}
colFmts = make([]format, len(colTyps))
if forceText {
return colFmts, colFmtDataAllText
}
allBinary := true
allText := true
for i, o := range colTyps {
switch o {
// This is the list of types to use binary mode for when receiving them
// through a prepared statement. If a type appears in this list, it
// must also be implemented in binaryDecode in encode.go.
case oid.T_bytea:
fallthrough
case oid.T_int8:
fallthrough
case oid.T_int4:
fallthrough
case oid.T_int2:
fallthrough
case oid.T_uuid:
colFmts[i] = formatBinary
allText = false
default:
allBinary = false
}
}
if allBinary {
return colFmts, colFmtDataAllBinary
} else if allText {
return colFmts, colFmtDataAllText
} else {
colFmtData = make([]byte, 2+len(colFmts)*2)
binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts)))
for i, v := range colFmts {
binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v))
}
return colFmts, colFmtData
}
} | go | {
"resource": ""
} |
q11080 | Query | train | func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) {
return cn.query(query, args)
} | go | {
"resource": ""
} |
q11081 | sendSimpleMessage | train | func (cn *conn) sendSimpleMessage(typ byte) (err error) {
_, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'})
return err
} | go | {
"resource": ""
} |
q11082 | recvMessage | train | func (cn *conn) recvMessage(r *readBuf) (byte, error) {
// workaround for a QueryRow bug, see exec
if cn.saveMessageType != 0 {
t := cn.saveMessageType
*r = cn.saveMessageBuffer
cn.saveMessageType = 0
cn.saveMessageBuffer = nil
return t, nil
}
x := cn.scratch[:5]
_, err := io.ReadFull(cn.buf, x)
if err != nil {
return 0, err
}
// read the type and length of the message that follows
t := x[0]
n := int(binary.BigEndian.Uint32(x[1:])) - 4
var y []byte
if n <= len(cn.scratch) {
y = cn.scratch[:n]
} else {
y = make([]byte, n)
}
_, err = io.ReadFull(cn.buf, y)
if err != nil {
return 0, err
}
*r = y
return t, nil
} | go | {
"resource": ""
} |
q11083 | recv | train | func (cn *conn) recv() (t byte, r *readBuf) {
for {
var err error
r = &readBuf{}
t, err = cn.recvMessage(r)
if err != nil {
panic(err)
}
switch t {
case 'E':
panic(parseError(r))
case 'N':
// ignore
default:
return
}
}
} | go | {
"resource": ""
} |
q11084 | recv1Buf | train | func (cn *conn) recv1Buf(r *readBuf) byte {
for {
t, err := cn.recvMessage(r)
if err != nil {
panic(err)
}
switch t {
case 'A', 'N':
// ignore
case 'S':
cn.processParameterStatus(r)
default:
return t
}
}
} | go | {
"resource": ""
} |
q11085 | recv1 | train | func (cn *conn) recv1() (t byte, r *readBuf) {
r = &readBuf{}
t = cn.recv1Buf(r)
return t, r
} | go | {
"resource": ""
} |
q11086 | isDriverSetting | train | func isDriverSetting(key string) bool {
switch key {
case "host", "port":
return true
case "password":
return true
case "sslmode", "sslcert", "sslkey", "sslrootcert":
return true
case "fallback_application_name":
return true
case "connect_timeout":
return true
case "disable_prepared_binary_result":
return true
case "binary_parameters":
return true
default:
return false
}
} | go | {
"resource": ""
} |
q11087 | isUTF8 | train | func isUTF8(name string) bool {
// Recognize all sorts of silly things as "UTF-8", like Postgres does
s := strings.Map(alnumLowerASCII, name)
return s == "utf8" || s == "unicode"
} | go | {
"resource": ""
} |
q11088 | Add | train | func (m *ModifyRequest) Add(attrType string, attrVals []string) {
m.AddAttributes = append(m.AddAttributes, PartialAttribute{Type: attrType, Vals: attrVals})
} | go | {
"resource": ""
} |
q11089 | Delete | train | func (m *ModifyRequest) Delete(attrType string, attrVals []string) {
m.DeleteAttributes = append(m.DeleteAttributes, PartialAttribute{Type: attrType, Vals: attrVals})
} | go | {
"resource": ""
} |
q11090 | Replace | train | func (m *ModifyRequest) Replace(attrType string, attrVals []string) {
m.ReplaceAttributes = append(m.ReplaceAttributes, PartialAttribute{Type: attrType, Vals: attrVals})
} | go | {
"resource": ""
} |
q11091 | Modify | train | func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
packet.AppendChild(modifyRequest.encode())
l.Debug.PrintPacket(packet)
msgCtx, err := l.sendMessage(packet)
if err != nil {
return err
}
defer l.finishMessage(msgCtx)
l.Debug.Printf("%d: waiting for response", msgCtx.id)
packetResponse, ok := <-msgCtx.responses
if !ok {
return NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
}
packet, err = packetResponse.ReadPacket()
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
if err != nil {
return err
}
if l.Debug {
if err := addLDAPDescriptions(packet); err != nil {
return err
}
ber.PrintPacket(packet)
}
if packet.Children[1].Tag == ApplicationModifyResponse {
resultCode, resultDescription := getLDAPResultCode(packet)
if resultCode != 0 {
return NewError(resultCode, errors.New(resultDescription))
}
} else {
log.Printf("Unexpected Response: %d", packet.Children[1].Tag)
}
l.Debug.Printf("%d: returning", msgCtx.id)
return nil
} | go | {
"resource": ""
} |
q11092 | Compare | train | func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationCompareRequest, nil, "Compare Request")
request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, dn, "DN"))
ava := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "AttributeValueAssertion")
ava.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute, "AttributeDesc"))
ava.AppendChild(ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagOctetString, value, "AssertionValue"))
request.AppendChild(ava)
packet.AppendChild(request)
l.Debug.PrintPacket(packet)
msgCtx, err := l.sendMessage(packet)
if err != nil {
return false, err
}
defer l.finishMessage(msgCtx)
l.Debug.Printf("%d: waiting for response", msgCtx.id)
packetResponse, ok := <-msgCtx.responses
if !ok {
return false, NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
}
packet, err = packetResponse.ReadPacket()
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
if err != nil {
return false, err
}
if l.Debug {
if err := addLDAPDescriptions(packet); err != nil {
return false, err
}
ber.PrintPacket(packet)
}
if packet.Children[1].Tag == ApplicationCompareResponse {
resultCode, resultDescription := getLDAPResultCode(packet)
if resultCode == LDAPResultCompareTrue {
return true, nil
} else if resultCode == LDAPResultCompareFalse {
return false, nil
} else {
return false, NewError(resultCode, errors.New(resultDescription))
}
}
return false, fmt.Errorf("Unexpected Response: %d", packet.Children[1].Tag)
} | go | {
"resource": ""
} |
q11093 | NewListenerConn | train | func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) {
return newDialListenerConn(defaultDialer{}, name, notificationChan)
} | go | {
"resource": ""
} |
q11094 | acquireSenderLock | train | func (l *ListenerConn) acquireSenderLock() error {
// we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery
l.senderLock.Lock()
l.connectionLock.Lock()
err := l.err
l.connectionLock.Unlock()
if err != nil {
l.senderLock.Unlock()
return err
}
return nil
} | go | {
"resource": ""
} |
q11095 | setState | train | func (l *ListenerConn) setState(newState int32) bool {
var expectedState int32
switch newState {
case connStateIdle:
expectedState = connStateExpectReadyForQuery
case connStateExpectResponse:
expectedState = connStateIdle
case connStateExpectReadyForQuery:
expectedState = connStateExpectResponse
default:
panic(fmt.Sprintf("unexpected listenerConnState %d", newState))
}
return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState)
} | go | {
"resource": ""
} |
q11096 | listenerConnMain | train | func (l *ListenerConn) listenerConnMain() {
err := l.listenerConnLoop()
// listenerConnLoop terminated; we're done, but we still have to clean up.
// Make sure nobody tries to start any new queries by making sure the err
// pointer is set. It is important that we do not overwrite its value; a
// connection could be closed by either this goroutine or one sending on
// the connection -- whoever closes the connection is assumed to have the
// more meaningful error message (as the other one will probably get
// net.errClosed), so that goroutine sets the error we expose while the
// other error is discarded. If the connection is lost while two
// goroutines are operating on the socket, it probably doesn't matter which
// error we expose so we don't try to do anything more complex.
l.connectionLock.Lock()
if l.err == nil {
l.err = err
}
l.cn.Close()
l.connectionLock.Unlock()
// There might be a query in-flight; make sure nobody's waiting for a
// response to it, since there's not going to be one.
close(l.replyChan)
// let the listener know we're done
close(l.notificationChan)
// this ListenerConn is done
} | go | {
"resource": ""
} |
q11097 | Listen | train | func (l *ListenerConn) Listen(channel string) (bool, error) {
return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel))
} | go | {
"resource": ""
} |
q11098 | Ping | train | func (l *ListenerConn) Ping() error {
sent, err := l.ExecSimpleQuery("")
if !sent {
return err
}
if err != nil {
// shouldn't happen
panic(err)
}
return nil
} | go | {
"resource": ""
} |
q11099 | NewDialListener | train | func NewDialListener(d Dialer,
name string,
minReconnectInterval time.Duration,
maxReconnectInterval time.Duration,
eventCallback EventCallbackType) *Listener {
l := &Listener{
name: name,
minReconnectInterval: minReconnectInterval,
maxReconnectInterval: maxReconnectInterval,
dialer: d,
eventCallback: eventCallback,
channels: make(map[string]struct{}),
Notify: make(chan *Notification, 32),
}
l.reconnectCond = sync.NewCond(&l.lock)
go l.listenerMain()
return l
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.