为了账号安全,请及时绑定邮箱和手机立即绑定

Golang API 的 HTTPS

Golang API 的 HTTPS

Go
慕尼黑的夜晚无繁华 2022-12-05 16:41:43
我是 Golang 的新手,我确实设置了一个“hello world!” 在我们的 VPS 上测试 Golang API 的消息。它在http://www.example.com:8080/hello上工作得很好。不过,我想转到 HTTPS。有人可以逐步告诉我从 HTTP 到 HTTPS 的 golang API 的正确程序吗?谢谢!如果 golang 代码有问题: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")        log.Fatal(http.ListenAndServe(":8080", nil))}
查看完整描述

2 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

使用 http.ListenAndServeTLS 代替


https://pkg.go.dev/net/http#ListenAndServeTLS


    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")

        err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil)

        log.Fatal(err)

}


查看完整回答
反对 回复 2022-12-05
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

感谢约翰·汉利 (John Hanley) 的支持,导致了这个答案。首先,我确实通过编辑 /etc/apache2/ports.conf 为 https 设置了端口 8443:


Listen 80


<IfModule ssl_module>

        Listen 443

        Listen 8443

</IfModule>

然后我在 example.com 域的配置中添加了一个 VirtualHost,以便端口 8443 充当代理:


<VirtualHost *:8443>

        ServerAdmin admin@example.com

        ServerName www.example.com

        ServerAlias example.com


        ProxyRequests Off

        <Proxy *>

                Order deny,allow

                Allow from all

        </Proxy>

        ProxyPass / http://localhost:8080/

        ProxyPassReverse / http://localhost:8080/


        ErrorLog ${APACHE_LOG_DIR}/error.log

        CustomLog ${APACHE_LOG_DIR}/access.log combined


       Include /etc/letsencrypt/options-ssl-apache.conf

       SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem

       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 。


查看完整回答
反对 回复 2022-12-05
  • 2 回答
  • 0 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号