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.