简单的GoLang SSL示例

huangapple go评论77阅读模式
英文:

Simple GoLang SSL example

问题

刚刚开始使用Go,有Python背景。

我需要与一个使用自签名证书的服务器建立SSL(HTTP GET和POST)连接,并暂时忽略安全错误。

在Python中这很简单,但我似乎找不到一个简单的示例。

有人可以提供一个真正简单的示例吗?

更新:

好的,这是它的工作原理,只需要找出如何暂时禁用证书检查!

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"os"
)

func main() {
	response, err := http.Get("https://golang.com/")
	if err != nil {
		fmt.Printf("%s", err)
		os.Exit(1)
	} else {
		defer response.Body.Close()
		contents, err := ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
		}
		fmt.Printf("%s\n", string(contents))
	}
}
英文:

Just started out with go with a Python background.

I need to make an SSL (HTTP GET and POST) connection to server with a self signed certificate and ignore (for now) the security errors.

This is dead easy in Python, but I can't seem to find a simple example.

Can somebody provide a really simple example.

UPDATE:

OK, so this is how it works, just need to work out how to disable the cert checking for now!

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
    "os"
)

func main() {
    response, err := http.Get( "https://golang.com/")
    if err != nil {
	    fmt.Printf("%s", err)
	    os.Exit(1)
    } else {
	    defer response.Body.Close()
	    contents, err := ioutil.ReadAll(response.Body)
	    if err != nil {
		    fmt.Printf("%s", err)
		    os.Exit(1)
	    }
	    fmt.Printf("%s\n", string(contents))
    }
}

答案1

得分: 4

好的,以下是翻译好的代码:

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"os"
	"crypto/tls"
)

func main() {

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify : true},
	}

	client := &http.Client{Transport: tr}

	response, err := client.Get("https://80.84.50.156/VEDsdk/")
	if err != nil {
		fmt.Printf("%s", err)
		os.Exit(1)
	} else {
		defer response.Body.Close()
		contents, err := ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
		}
		fmt.Printf("%s\n", string(contents))
	}
}

希望对你有帮助!

英文:

OK Sorted, here's what I did:

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"os"
	"crypto/tls"
)

func main() {

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify : true},
	}

	client := &http.Client{Transport: tr}

	response, err := client.Get( "https://80.84.50.156/VEDsdk/")
	if err != nil {
		fmt.Printf("%s", err)
		os.Exit(1)
	} else {
		defer response.Body.Close()
		contents, err := ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
		}
		fmt.Printf("%s\n", string(contents))
	}
}

huangapple
  • 本文由 发表于 2014年9月12日 19:25:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/25807204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定