如何在 Go 中使用 TLS 连接 MongoDB

栏目: Go · 发布时间: 7年前

内容简介:通常我们的数据库都配置为内网访问,但由于业务部署架构的不同,有时也需要通过公网访问 MongoDB 数据库,此时为了防止被端口扫描和脱库,MongoDB 需要配置为 TLS 访问,那在 Go 中应该如何实现呢?通过以上代码,我们就能通过公网连接 tls 的 MongoDB 实例,当连接上后,其数据库的操作和内网连接一致。

通常我们的数据库都配置为内网访问,但由于业务部署架构的不同,有时也需要通过公网访问 MongoDB 数据库,此时为了防止被端口扫描和脱库,MongoDB 需要配置为 TLS 访问,那在 Go 中应该如何实现呢?

依赖

  • 配置了 TLS 公网访问的 MongoDB 实例
  • Go 的 MongoDB 驱动 globalsign/mgo

Go 实现代码:

package model

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"github.com/globalsign/mgo"
	"io/ioutil"
	"log"
	"net"
)

func main() {
	dsn := "mongodb://user:password@host/database"

	dialInfo, err := mgo.ParseURL(dsn)
	if err != nil {
		log.Panic(err)
	}

	// read pemfile data
	pemData, err := ioutil.ReadFile("./pemfile")
	if err != nil {
		log.Panic(err)
	}

	roots := x509.NewCertPool()
	if !roots.AppendCertsFromPEM(pemData) {
		log.Panic(errors.New("failed to parse root certificate"))
	}

	// set tls config
	tlsConfig := &tls.Config{
		RootCAs:            roots,
		InsecureSkipVerify: true,
	}

	// update dialserver with tls Dial
	dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
		conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
		if err != nil {
			log.Println(err)
		}
		return conn, err
	}

	session, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		log.Panic(err.Error())
	}
	// db operation with session
}

通过以上代码,我们就能通过公网连接 tls 的 MongoDB 实例,当连接上后,其数据库的操作和内网连接一致。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Security Testing Cookbook

Web Security Testing Cookbook

Paco Hope、Ben Walther / O'Reilly Media / 2008-10-24 / USD 39.99

Among the tests you perform on web applications, security testing is perhaps the most important, yet it's often the most neglected. The recipes in the Web Security Testing Cookbook demonstrate how dev......一起来看看 《Web Security Testing Cookbook》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码