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.