猿问

Golang API 的 HTTPS

我是 Golang 的新手,我确实设置了一个“hello world!” 在我们的 VPS 上测试 Golang API 的消息。它在http://www.example.com:8080/hello上工作得很好。不过,我想转到 HTTPS。


有人可以逐步告诉我从 HTTP 到 HTTPS 的 golang API 的正确程序吗?谢谢!


如果 golang 代码有问题:


package main


import (

        "fmt"

        "log"

        "net/http"

)


func main() {

        http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {

                fmt.Fprintf(w, "Hello, World")

        })


        fmt.Println("Server Started On Port 8080")

        log.Fatal(http.ListenAndServe(":8080", nil))

}


慕尼黑的夜晚无繁华
浏览 112回答 2
2回答

蝴蝶不菲

使用 http.ListenAndServeTLS 代替https://pkg.go.dev/net/http#ListenAndServeTLS    package mainimport (        "fmt"        "log"        "net/http")func main() {        http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {                fmt.Fprintf(w, "Hello, World")        })        fmt.Println("Server Started On Port 8080")        err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil)        log.Fatal(err)}

慕桂英546537

感谢约翰·汉利 (John Hanley) 的支持,导致了这个答案。首先,我确实通过编辑 /etc/apache2/ports.conf 为 https 设置了端口 8443:Listen 80<IfModule ssl_module>&nbsp; &nbsp; &nbsp; &nbsp; Listen 443&nbsp; &nbsp; &nbsp; &nbsp; Listen 8443</IfModule>然后我在 example.com 域的配置中添加了一个 VirtualHost,以便端口 8443 充当代理:<VirtualHost *:8443>&nbsp; &nbsp; &nbsp; &nbsp; ServerAdmin admin@example.com&nbsp; &nbsp; &nbsp; &nbsp; ServerName www.example.com&nbsp; &nbsp; &nbsp; &nbsp; ServerAlias example.com&nbsp; &nbsp; &nbsp; &nbsp; ProxyRequests Off&nbsp; &nbsp; &nbsp; &nbsp; <Proxy *>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Order deny,allow&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Allow from all&nbsp; &nbsp; &nbsp; &nbsp; </Proxy>&nbsp; &nbsp; &nbsp; &nbsp; ProxyPass / http://localhost:8080/&nbsp; &nbsp; &nbsp; &nbsp; ProxyPassReverse / http://localhost:8080/&nbsp; &nbsp; &nbsp; &nbsp; ErrorLog ${APACHE_LOG_DIR}/error.log&nbsp; &nbsp; &nbsp; &nbsp; CustomLog ${APACHE_LOG_DIR}/access.log combined&nbsp; &nbsp; &nbsp; &nbsp;Include /etc/letsencrypt/options-ssl-apache.conf&nbsp; &nbsp; &nbsp; &nbsp;SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem&nbsp; &nbsp; &nbsp; &nbsp;SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem</VirtualHost>并且您需要使用e2enmod proxy和加载模块 proxy 和 proxy_http e2enmod proxy_http。重新加载 apache 后,可以在https://www.example.com:8443/hello调用 API 。
随时随地看视频慕课网APP

相关分类

Go
我要回答