Home > Article > Backend Development > How to set up HTTP Secure Transport Protocol (SSL/TLS) using Golang?
How to set up HTTP Secure Transport Protocol (SSL/TLS) in Golang to generate a self-signed certificate. Configure the TLS configuration of the Golang HTTP server, including certificates and keys. Create an HTTP server with TLS configuration.
How to set up HTTP Secure Transport Protocol (SSL/TLS) in Golang
Introduction
Protecting web traffic from eavesdropping and tampering is critical, and SSL/TLS is a key technology to achieve this goal. This tutorial will guide you on how to set up SSL/TLS in Golang to secure your HTTP connections.
Generate a self-signed certificate
Since certificates issued by a Certificate Authority (CA) require payment, generating a self-signed certificate is a viable option for development and testing purposes. . A self-signed certificate can be generated using the following command:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365
Remember that self-signed certificates are only trusted within your own domain or environment and are therefore not suitable for production environments.
Configure Golang HTTP Server
After creating the self-signed certificate, you can configure SSL/TLS in the Golang HTTP server:
package main import ( "crypto/tls" "fmt" "net/http" ) func main() { // 创建 TLS 配置 tlsConfig := &tls.Config{ Certificates: []tls.Certificate{ { // 读取生成的证书和密钥 Certificate: []byte("cert.pem"), PrivateKey: []byte("key.pem"), }, }, } // 使用 TLS 配置创建一个 HTTP 服务器 server := &http.Server{ Addr: ":443", TLSConfig: tlsConfig, } fmt.Println("正在启动 TLS HTTP 服务器...") server.ListenAndServeTLS("", "") }
Practical case
Let us run a simple Golang HTTP server to demonstrate how SSL/TLS works:
Run the following command in the terminal to generate a self-signature Certificate:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365
Create a Go file named server.go
with the following code:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, HTTPS!") }) fmt.Println("正在启动 HTTPS 服务器...") http.ListenAndServeTLS(":443", "cert.pem", "key.pem") }
Run the server:
go run server.go
https://localhost:443
). If set up correctly, you should see the "Hello, HTTPS!" message. The above is the detailed content of How to set up HTTP Secure Transport Protocol (SSL/TLS) using Golang?. For more information, please follow other related articles on the PHP Chinese website!