Golang API 的 HTTPS

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

HTTPS for Golang API

问题

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

以下是你要翻译的内容:

我对Golang还不熟悉,但我已经在我们的VPS上设置了一个Golang API的“Hello World!”测试消息。它在http://www.example.com:8080/hello上正常工作。然而,我想切换到HTTPS。

有人可以逐步告诉我如何将Golang API从HTTP切换到HTTPS吗?谢谢!

如果Golang代码有问题的话:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. )
  7. func main() {
  8. http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
  9. fmt.Fprintf(w, "Hello, World")
  10. })
  11. fmt.Println("Server Started On Port 8080")
  12. log.Fatal(http.ListenAndServe(":8080", nil))
  13. }
英文:

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:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. )
  7. func main() {
  8. http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
  9. fmt.Fprintf(w, "Hello, World")
  10. })
  11. fmt.Println("Server Started On Port 8080")
  12. log.Fatal(http.ListenAndServe(":8080", nil))
  13. }

答案1

得分: 2

使用http.ListenAndServeTLS代替

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

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. )
  7. func main() {
  8. http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
  9. fmt.Fprintf(w, "Hello, World")
  10. })
  11. fmt.Println("Server Started On Port 8080")
  12. err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil)
  13. log.Fatal(err)
  14. }

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

英文:

Use http.ListenAndServeTLS Instead

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

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. )
  7. func main() {
  8. http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
  9. fmt.Fprintf(w, "Hello, World")
  10. })
  11. fmt.Println("Server Started On Port 8080")
  12. err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil)
  13. log.Fatal(err)
  14. }

答案2

得分: 1

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

  1. Listen 80
  2. <IfModule ssl_module>
  3. Listen 443
  4. Listen 8443
  5. </IfModule>

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

  1. <VirtualHost *:8443>
  2. ServerAdmin admin@example.com
  3. ServerName www.example.com
  4. ServerAlias example.com
  5. ProxyRequests Off
  6. <Proxy *>
  7. Order deny,allow
  8. Allow from all
  9. </Proxy>
  10. ProxyPass / http://localhost:8080/
  11. ProxyPassReverse / http://localhost:8080/
  12. ErrorLog ${APACHE_LOG_DIR}/error.log
  13. CustomLog ${APACHE_LOG_DIR}/access.log combined
  14. Include /etc/letsencrypt/options-ssl-apache.conf
  15. SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
  16. SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
  17. </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:

  1. Listen 80
  2. &lt;IfModule ssl_module&gt;
  3. Listen 443
  4. Listen 8443
  5. &lt;/IfModule&gt;

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

  1. &lt;VirtualHost *:8443&gt;
  2. ServerAdmin admin@example.com
  3. ServerName www.example.com
  4. ServerAlias example.com
  5. ProxyRequests Off
  6. &lt;Proxy *&gt;
  7. Order deny,allow
  8. Allow from all
  9. &lt;/Proxy&gt;
  10. ProxyPass / http://localhost:8080/
  11. ProxyPassReverse / http://localhost:8080/
  12. ErrorLog ${APACHE_LOG_DIR}/error.log
  13. CustomLog ${APACHE_LOG_DIR}/access.log combined
  14. Include /etc/letsencrypt/options-ssl-apache.conf
  15. SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
  16. SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
  17. &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的答案上。这是一个稍微复杂一些的实现,但可以让你进行更多的配置。

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

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

创建tls配置:

  1. cfg := &tls.Config{
  2. Certificates: certs,
  3. MinVersion: tls.VersionTLS12,
  4. }
  5. cfg.BuildNameToCertificate()
  6. server := &http.Server{
  7. Addr: ":8080",
  8. TLSConfig: cfg,
  9. IdleTimeout: 30 * time.Second,
  10. }

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

  1. http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
  2. fmt.Fprintf(w, "Hello, World")
  3. })
  4. err := server.ListenAndServeTLS("", "") // 如果在上面的tls配置中提供了一组证书,则此处不要提供文件名
  5. if err != nil {
  6. return err
  7. }
英文:

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

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

Create tls config

  1. cfg := &amp;tls.Config {
  2. Certificates: certs,
  3. MinVersion: tls.VersionTLS12,
  4. }
  5. cfg.BuildNameToCertificate()
  6. server := &amp;http.Server{
  7. Addr: &quot;:8080&quot;,
  8. TLSConfig: cfg,
  9. IdleTimeout: 30 * time.Second,
  10. }

Add handler and start server

  1. http.HandleFunc(&quot;/hello&quot;, func(w http.ResponseWriter, r *http.Request) {
  2. fmt.Fprintf(w, &quot;Hello, World&quot;)
  3. })
  4. err := server.ListenAndServeTLS(&quot;&quot;, &quot;&quot;) // Dont give filename here if giving set of certs in tls config above
  5. if err != nil {
  6. return err
  7. }

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:

确定