如何在 Go 中使用 TLS 连接 MongoDB

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

内容简介:通常我们的数据库都配置为内网访问,但由于业务部署架构的不同,有时也需要通过公网访问 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 实例,当连接上后,其数据库的操作和内网连接一致。


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

查看所有标签

猜你喜欢:

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

Writing Apache Modules with Perl and C

Writing Apache Modules with Perl and C

Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95

Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具