Simple example of Go support HTTPS protocol

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

we know that in addition to HTTP access to Web pages, there is an encrypted way of HTTPS. The Go languagenet/httpThe package contains support for how this HTTPS page is accessed. net/httpin the packageListenAndServeTLSis to provide this functionality. We can look at the prototype of this function first.

Func listenandservetls (addr string, CertFile string, keyfile string, handler handler) error

From the above function prototype, we can see that the difference between the HTTP method and the need to provide a pair of public key file CertFile and the private key file keyfile.

We can use the following command to generate the public and private key files for a pair of tests under Linux.

OpenSSL genrsa-out key.pem 2048openssl req-new-x509-key key.pem-out cert.pem-days 3650

then we put cert.key and the key.pem to copy to a directory https_demo below, and then in this directory create a simple_https.go file with the following code:

Package main import (    "io"    "log" "    net/http") func Hellohandler (w http. Responsewriter, R *http. Request) {    io. WriteString (w, "Hello world!")} Func Main () {    http. Handlefunc ("/hello", Hellohandler)    err: = http. Listenandservetls (": 8080", "Cert.pem", "Key.pem", nil)    if err! = Nil {        log. Fatal ("Listenandservetls:", err.) Error ())    }}
Run:
Go Run https.go

At this point, listen to local port 8080, open the browser access https://localhost:8080/hello to see the results.

In fact, compared with normal HTTP, there is a couple of public and private keys.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.