Implimenting the ContextDialer interface

Im working with the go.mongodb.org/mongo-driver/mongo" driver, and i need to implement a tls handshake using the tls.Dial function so the client can dial to the server with the certificates passed. The only issue is i dont know how to put the pieces together. Here is my attempt of a type that implements the ContextDialer interface

dialer := func(context.Context, string, string) (net.Conn, error){
    return tls.Dial("tcp", "addr", &tls.Config{
          RootCAs:        rootCerts,
           Certificates: clientCerts,
     })
}

And then the client should be able to set a dialer like this for example

clientOpts := options.Client().ApplyURI("mongodb://localhost:27017")
clientOpts.SetDialer(dialer)

the SetDialer() takes in this interface
Unfortunately, here my dialer doesnt implement the ContextDialer interface. How can i implement it?

You’re dialer is a function but it should be, for example, a struct with DialContext implementation. Example:

type myDialer struct {}

func (d myDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
     return tls.Dial("tcp", "addr", &tls.Config{
          RootCAs:        rootCerts,
           Certificates: clientCerts,
     })
}

// later...
dialer := myDialer{}
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017")
clientOpts.SetDialer(dialer)

Yeah, but i then need to call the method to pass in my certificates like this -

type myDialer struct {
rootcerts *x509.CertPool
clientCerts []tls.Certificate
}

func (d myDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
     return tls.Dial("tcp", "addr", &tls.Config{
          RootCAs:        d.rootCerts,
           Certificates:  d.clientCerts,
     })
}

// later...
dialer := myDialer{}
conn, err := dialer.DialContext(ctx, "tcp", addr)

is it okay to ignore what our DialContext returns? Read the docs and it seems we need to use the conn returned somewhere. Just not sure where

clientOpts := options.Client().ApplyURI("mongodb://localhost:27017")
clientOpts.SetDialer(dialer)

Thats why in the beginning, i tried making a function that implements the interface, and easily pass that function when the interface is needed

Actually that works. Ignoring what method returns is okay…

here you need to assign values to the struct fields first

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.