我是 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))
}
uj5u.com熱心網友回復:
改用 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)
}
uj5u.com熱心網友回復:
感謝 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 [email protected]
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 proxyand加載模塊 proxy 和 proxy_http e2enmod proxy_http。重新加載 apache 后,可以在https://www.example.com:8443/hello呼叫 API 。
uj5u.com熱心網友回復:
添加到@Dan 的答案。更復雜的實作,但使您能夠對其進行更多配置。
如果您想使用超過 1 組證書
certs := []tls.Certificate{}
for _, cert := range []{"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("", "") // Dont give filename here if giving set of certs in tls config above
if err != nil {
return err
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465401.html
