【问题标题】:Passing a string to a handler function in Go将字符串传递给 Go 中的处理函数
【发布时间】:2022-01-09 22:12:04
【问题描述】:

我有一个通用的网络服务器,我想在不同的域/服务器上使用它。 为了设置每个服务器,我只需读取一个包含所有必要信息的 JSON 配置文件。例如,一种是重定向所有到达端口 80 的流量并将其转发到 TLS 服务。因为我不想使配置对象成为全局对象。如何将 inputFromConfigFile 中的内容传递给 redirectTLS 函数?

这是一个例子:

func main(){
  var inputFromConfigFile = "https://www.example.com:443"


  go func() {
    if err := http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)); err != nil {
      log.Fatalf("ListenAndServe error: %v", err)
    }
  }()
}

//Pass the above string to this function:

func redirectTLS(w http.ResponseWriter, r *http.Request) {
  http.Redirect(w, r, "https://www.example.com:443"+r.RequestURI,http.StatusMovedPermanently)
}

【问题讨论】:

  • 如果是 JSON 配置文件,你应该解析一次并将对象/映射传递给处理程序,而不是传递字符串,这样每个处理程序都必须重复解析它
  • 这是我真正想做的。为了简单起见,我只是在示例中使用了一个字符串……

标签: http go redirect


【解决方案1】:

你可以定义一个自定义的Handler(可以实现为一个结构体),只要它匹配http.Handler接口即可。配置可以作为结构字段保存在 Handler 中。

type Handler struct {
  // config goes here
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  // anything that handler needs to do here
}

示例:https://pkg.go.dev/net/http#example-Handle

【讨论】:

    【解决方案2】:

    你可以直接在main中将redirectTLS定义为内联闭包函数:

    var inputFromConfigFile = "https://www.example.com:443"
    
    go func() {
        err := http.ListenAndServe(":80", func(w http.ResponseWriter, r *http.Request) {
            http.Redirect(w, r, inputFromConfigFile+r.RequestURI, http.StatusMovedPermanently)
        })
    
        if err != nil {
            log.Fatalf("ListenAndServe error: %v", err)
        }
    }()
    

    【讨论】:

      【解决方案3】:

      我会让配置对象全局化。

      否则,您可以定义一个接受配置作为参数的函数,并返回一个关闭配置对象的处理函数:

      
      var inputFromConfigFile = "https://www.example.com:443"
      
      http.ListenAndServe(":80", createHandler(inputFromConfigFile))
      
      // ...
      
      func createHandler(config string) http.HandlerFunc {
        return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
          http.Redirect(w, r, config+r.RequestURI,http.StatusMovedPermanently)
        })
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-21
        • 2016-01-28
        • 2013-12-11
        • 1970-01-01
        相关资源
        最近更新 更多