【问题标题】:Golang: Right way to serve both http & https from Go web app with Goji?Golang:使用 Goji 从 Go Web 应用程序同时提供 http 和 https 的正确方法?
【发布时间】:2015-02-18 11:30:36
【问题描述】:

对于单个 Go Web 应用程序(使用 Goji)处理 http 和 https 流量,这是正确的方法吗?

package main

import (
    "fmt"
    "net/http"
    "github.com/zenazn/goji/graceful"
    "github.com/zenazn/goji/web"
)

func main() {
    r := web.New()
    //https://127.0.0.1:8000/r
    r.Get("/r", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %s!", "r")
    })

    go graceful.ListenAndServeTLS(":8000", "cert.pem", "key.pem", r)

    r1 := web.New()
    //  http://127.0.0.1:8001/r1
    r1.Get("/r1", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %s!", "r1")
    })

    graceful.ListenAndServe(":8001", r1)
}

或者,让单个 Go Web 应用同时监听端口 8000 和 8001 的最佳方法是什么?

【问题讨论】:

  • 另外,您可以使用 nginx 终止 HTTP 和 HTTPS (TLS) 连接,将它们反向代理到侦听(例如)端口 8000 的单个 Go 服务器。这里有一个示例,您可以利用:@ 987654321@

标签: https go goji


【解决方案1】:

您不需要创建新对象,只需将r 传递给graceful.ListenAndServe(":8001", r),当然除非您执行依赖于https 的不同操作。

【讨论】:

  • 好吧,在我的情况下,SSL证书在某些路径上是有效的,而在某些路径上则不是。那么……我该怎么办呢?
  • 那么你正在做的就很好了。您可以在某处定义常用函数并将它们添加到您的rr1
  • 好的,谢谢,我刚刚开始使用 Go。将第一个作为 goroutine 而第二个不作为 goroutine 是否正确?
  • 是的,否则它会阻塞,您可能需要执行runtime.GOMAXPROCS(runtime.NumCPU()) 以使用所有处理器内核来处理请求。
  • 感谢您的帮助!
猜你喜欢
  • 2014-12-06
  • 2011-10-30
  • 2018-11-15
  • 1970-01-01
  • 2016-03-15
  • 2017-08-16
  • 2016-06-03
  • 2014-04-20
  • 1970-01-01
相关资源
最近更新 更多