Golang 如何跳过证书认证连接云搜索服务

Go
问题描述

使用go-elasticsearch连接云搜索服务,报错如下: alt

问题分析

通过https协议访问云搜索服务的时候,证书颁发的IP SANS中并没有包含云搜索服务对外暴露的IP地址111.xxx.xxx.xxx

解决方案

通过跳过证书认证,使用https协议连接与云搜索服务通信。具体示例代码如下:

1.编写go.mod文件导入go-elasticsearch依赖包。

[root@iv-a8j78jje1ylrx9p4t93t my-elasticsearch-app]# cat go.mod
module my-elasticsearch-app
go 1.16
require github.com/elastic/go-elasticsearch/v7 v7.16.0

2.编写main.go文件实现连接测试连接。

package main

import (

"crypto/tls"

"crypto/x509"

"flag"

"fmt"

"github.com/elastic/go-elasticsearch/v7"

"io/ioutil"

"log"

"net"

"net/http"

"time"

)

func main() {

var err error

//insecure := flag.Bool("insecure-ssl", false, "Accept/Ignore all server SSL certificates")

flag.Parse()

// Get the SystemCertPool, continue with an empty pool on error

rootCAs, _ := x509.SystemCertPool()

if rootCAs == nil {

rootCAs = x509.NewCertPool()

}

certs, err := ioutil.ReadFile("/etc/logstash/es_ca.cer")   // /etc/logstash/es_ca.cer为服务页面中下载的ca文件

if err != nil {

log.Fatalf("Failed to append %q to RootCAs: %v", certs, err)

}

if ok := rootCAs.AppendCertsFromPEM(certs); !ok {

log.Println("No certs appended, using system certs only")

}

cfg := elasticsearch.Config{

Addresses: []string{

"https://100.xxx.xxx.xxx:9200",      //地址为云搜索服务访问的内网或者外网地址

},

Username: "admin",

Password: " 密码",

Transport: &http.Transport{

MaxIdleConnsPerHost: 10,

ResponseHeaderTimeout: time.Second,

DialContext: (&net.Dialer{

Timeout: 30 * time.Second,

KeepAlive: 30 * time.Second,

}).DialContext,

TLSClientConfig: &tls.Config{

InsecureSkipVerify: true,    //跳过证书认证

RootCAs: rootCAs,

},

},

}

client, err := elasticsearch.NewClient(cfg)

if err != nil {

log.Fatal(err)

}

fmt.Println(client.Info())

}

3.查看输出结果如下:

[root@iv-a8j78jje1ylrx9p4t93t my-elasticsearch-app]# go run main.go
[200 OK] {
  "name" : "es-master-s6avp377dc08jgct-2",
  "cluster_name" : "s6avp377dc08jgct",
  "cluster_uuid" : "Zsa3tv2LSU-jIwJrXMidGA",
  "version" : {
    "number" : "7.10.2",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "747e1cc71def077253878a59143c1f785afa92b9",
    "build_date" : "2021-01-13T00:42:12.435326Z",
    "build_snapshot" : false,
    "lucene_version" : "8.7.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
 <nil>

参考文档

[1] https://github.com/elastic/go-elasticsearch

如果您有其他问题,欢迎您联系火山引擎技术支持服务

231
0
0
0
相关产品
评论
未登录
看完啦,登录分享一下感受吧~
暂无评论