Golang能够用很短的代码实现HTTP和HTTPS服务html
HTTP是基于传输层TCP协议的。安全
package main import ( "net/http" "fmt" "log" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){ fmt.Fprint(w, "Hello world") }) log.Fatal(http.ListenAndServe(":5001", nil)) }
HTTPS服务不一样于HTTP服务,HTTPS是HTTP over SSL或HTTP over TLS。post
SSL是“Secure Sockets Layer”的缩写,中文叫作“安全套接层”。它是在上世纪90年代中期,由NetScape公司设计的。为啥要发明 SSL 这个协议捏?由于原先互联网上使用的 HTTP 协议是明文的,存在不少缺点——好比传输内容会被偷窥(嗅探)和篡改。发明 SSL 协议,就是为了解决这些问题。
到了1999年,SSL 由于应用普遍,已经成为互联网上的事实标准。IETF 就在那年把 SSL 标准化。标准化以后的名称改成 TLS是“Transport Layer Security”的缩写,中文叫作“传输层安全协议”。
不少相关的文章都把这二者并列称呼(SSL/TLS),由于这二者能够视做同一个东西的不一样阶段。 参考
要启用HTTPS首先须要建立私钥和证书。设计
有两种方式生成私钥和证书:code
openssl genrsa -out key.pem 2048 openssl req -new -x509 -key key.pem -out cert.pem -days 3650
go run $GOROOT/src/crypto/tls/generate_cert.go --host localhost
将生成的key.pem、cert.pem和如下代码放在同一目录下server
package main import ( "log" "net/http" ) func handler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("This is an example server.\n")) } func main() { http.HandleFunc("/", handler) log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/") // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem. // ListenAndServeTLS always returns a non-nil error. err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil) log.Fatal(err) }
(END)htm