Simple example of Go support HTTPS protocol

Source: Internet
Author: User
Tags function prototype openssl

We know that in addition to HTTP access to Web pages, there is an encrypted way of HTTPS. The Net/http package in the Go language includes support for this HTTPS page access method. The LISTENANDSERVETLS in the Net/http package is provided for this function. 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 2048
OpenSSL req-new-x509-key key.pem-out cert.pem-days 3650
Then we will copy the Cert.key and Key.pem to a directory Https_demo below, then create a simple_https.go file under this directory, the code is as follows:

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 to access Https://localhost:8080/hello can see the results.

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



Related Article

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.