登录
首页 >  Golang >  Go问答

使用Https的Golang API

来源:stackoverflow

时间:2024-02-13 08:03:23 247浏览 收藏

你在学习Golang相关的知识吗?本文《使用Https的Golang API》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我是 golang 新手,我确实设置了一个“hello world!”在我们的 vps 上测试 golang api 的消息。它在 http://www.example.com:8080/hello 上运行得很好。不过,我想迁移到 https。

有人可以一步步告诉我 golang api 从 http 到 https 的正确过程吗?谢谢!

如果 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))
}

正确答案


感谢约翰·汉利 (john hanley) 的支持,才得出了这个答案。 首先,我通过编辑 /etc/apache2/ports.conf 为 https 设置了端口 8443:

listen 80


        listen 443
        listen 8443

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


        serveradmin [email protected]
        servername www.example.com
        serveralias example.com

        proxyrequests off
        
                order deny,allow
                allow from all
        
        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

并且您需要使用 e2enmod proxye2enmod proxy_http 加载模块 proxy 和 proxy_http。 重新加载apache后,可以在https://www.example.com:8443/hello调用api。

改用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)
}

终于介绍完啦!小伙伴们,这篇关于《使用Https的Golang API》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>