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) using Golang?

WBOY
WBOYOriginal
2024-06-03 12:09:571077browse

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.

如何使用 Golang 设置 HTTP 安全传输协议(SSL/TLS)?

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:

  1. 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
  2. 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")
    }
  3. Run the server:

    go run server.go
  4. Access your server in your browser using the secure HTTPS protocol (e.g. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn