Golang API 的 HTTPS

huangapple go评论95阅读模式
英文:

HTTPS for Golang API

问题

我对Golang还不熟悉,但我可以帮你翻译一下你的问题和代码。

以下是你要翻译的内容:

我对Golang还不熟悉,但我已经在我们的VPS上设置了一个Golang API的“Hello World!”测试消息。它在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))
}
英文:

I am new to Golang and I did set up a "hello world!" test message for a Golang API on our VPS. It works just fine at http://www.example.com:8080/hello. I would like however to move to HTTPS.

Could someone tell me step by step the right procedure to go from HTTP to HTTPS for a golang API? Thank you!

In case there is an issue with the golang code:

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

答案1

得分: 2

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

请注意,这是一个Go语言的示例代码,用于在端口8080上启动一个使用TLS的HTTP服务器。你需要将cert.pemkey.pem替换为你自己的TLS证书和私钥文件。

英文:

Use http.ListenAndServeTLS Instead

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

答案2

得分: 1

感谢John Hanley的支持,帮助我得出这个答案。
首先,我通过编辑/etc/apache2/ports.conf文件将端口8443设置为https:

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>

你需要使用a2enmod proxya2enmod proxy_http命令加载proxy和proxy_http模块。
重新加载apache之后,可以通过https://www.example.com:8443/hello调用API。

英文:

Thanks to John Hanley for support that lead to this answer.
First of all I did set the port 8443 for https by editing /etc/apache2/ports.conf:

Listen 80

&lt;IfModule ssl_module&gt;
        Listen 443
        Listen 8443
&lt;/IfModule&gt;

Then I added a VirtualHost in the config of the example.com domain so that port 8443 acts as a proxy:

&lt;VirtualHost *:8443&gt;
        ServerAdmin admin@example.com
        ServerName www.example.com
        ServerAlias example.com

        ProxyRequests Off
        &lt;Proxy *&gt;
                Order deny,allow
                Allow from all
        &lt;/Proxy&gt;
        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
&lt;/VirtualHost&gt;

and you need to load the modules proxy and proxy_http using e2enmod proxy and e2enmod proxy_http.
After reloading apache, the API can be called at https://www.example.com:8443/hello.

答案3

得分: 0

添加到@Dan的答案上。这是一个稍微复杂一些的实现,但可以让你进行更多的配置。

如果你想使用多个证书集合:

certs := []tls.Certificate{}
for _, cert := range []string{"cert1", "cert2"} {
    certSet, err := tls.LoadX509KeyPair(cert+".pem", cert+".key")
    if err != nil {
        return err
    }
    certs = append(certs, certSet)
}

创建tls配置:

cfg := &tls.Config{
    Certificates: certs,
    MinVersion:   tls.VersionTLS12,
}
cfg.BuildNameToCertificate()
server := &http.Server{
    Addr:        ":8080",
    TLSConfig:   cfg,
    IdleTimeout: 30 * time.Second,
}

添加处理程序并启动服务器:

http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World")
})

err := server.ListenAndServeTLS("", "") // 如果在上面的tls配置中提供了一组证书,则此处不要提供文件名
if err != nil {
    return err
}
英文:

Adding on to @Dan 's answer. A little more complex implementation but enables you to configure it more.

If you want to use more than 1 set of certs

certs := []tls.Certificate{}
for _, cert := range []{&quot;cert1&quot;, &quot;cert2&quot;} {
    certSet, err := tls.LoadX509KeyPair(cert+&quot;.pem&quot;, cert+&quot;.key&quot;)
    if err != nil {
        return err
    }
    certs = append(certs, certSet)
}

Create tls config

cfg := &amp;tls.Config {
    Certificates: certs,
    MinVersion:   tls.VersionTLS12,
}
cfg.BuildNameToCertificate()
server := &amp;http.Server{
    Addr:        &quot;:8080&quot;,
    TLSConfig:   cfg,
    IdleTimeout: 30 * time.Second,
}

Add handler and start server

http.HandleFunc(&quot;/hello&quot;, func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, &quot;Hello, World&quot;)
})

err := server.ListenAndServeTLS(&quot;&quot;, &quot;&quot;) // Dont give filename here if giving set of certs in tls config above
if err != nil {
    return err
}

huangapple
  • 本文由 发表于 2022年4月22日 01:33:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/71958629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定