How can I record and replay MongoDB requests in Go?

I’m writing integration tests for a Go program that queries a MongoDB cluster using Mongo Go Driver. I’d like to record those requests and later replay them in the tests.

Is there a library that I could use? I’m currently familiar with 2 similar libraries, but those are used for different purposes:

I’ve already tried overriding HTTP client using SetHTTPClient option, but it seems like the driver doesn’t use the HTTP client at all (I’ve set the transport to log a string to see if that gets used, but it doesn’t).

Any help would be appreciated. Thank you.

@Aleksandar_Jelic thanks for the question! AFAIK there’s no plug-and-play library that can record and/or replay requests with the MongoDB Go Driver. The best way to capture all data sent/received is by implementing a net.Conn that captures data and then providing a custom connection dialer that returns the capturing conn via SetDialer.

Example of how to implement net.Conn and ContextDialer wrappers:

type myConn struct {
	net.Conn
}

func (mc *myConn) Read(b []byte) (n int, err error) {
	// Capture data read here.
	return mc.Conn.Read(b)
}

func (mc *myConn) Write(b []byte) (n int, err error) {
	// Capture data written here.
	return mc.Conn.Write(b)
}

type myDialer struct {
	dialer *net.Dialer
}

func (md *myDialer) DialContext(ctx context.Context, net, addr string) (net.Conn, error) {
	conn, err := md.dialer.DialContext(ctx, network, address)
	if err != nil {
		return nil, err
	}
	return &myConn{Conn: conn}, nil
}

func main() {
	client, err := mongo.Connect(
		context.Background(),
		options.Client().
			ApplyURI("my URI").
			SetDialer(myDialer{dialer: &net.Dialer{}}))
	// ...

P.S. As you discovered, the HTTP client that you can configure with SetHTTPClient is not used for database communication. It is only used for OCSP TLS certificate revocation checks.