在Go语言中将字符串传递给处理函数的方法是:

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

Passing a string to a handler function in Go

问题

我有一个通用的Web服务器,我想在不同的域名/服务器上使用它。
为了设置每个服务器,我只需读取一个包含所有必要信息的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)
    }
  }()
}

//将上述字符串传递给此函数:

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

I have a generic Webserver which I want to use on different domains / servers.
For setting up each server I simply read a JSON config file with all necessary information. One would be for example the redirect for all traffic which reaches port 80 and forward it to a TLS service. Since I don't want to make the config object global. How can I pass the content from my inputFromConfigFile to the redirectTLS function?

Here is an example:

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

答案1

得分: 3

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

type Handler struct {
  // 配置放在这里
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  // 处理程序需要执行的任何操作
}

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

英文:

You can define a custom Handler (could be implemented as a struct) as long as it matches the http.Handler interface. The config could be saved inside the Handler as a struct field.

type Handler struct {
  // config goes here
}

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

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

答案2

得分: 1

你可以直接在主函数中定义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)
    }
}()

这段代码的作用是在主函数中定义一个闭包函数redirectTLS,然后使用http.ListenAndServe函数监听端口80,并在接收到请求时进行重定向。重定向的目标地址是从配置文件中获取的inputFromConfigFile加上当前请求的URI。如果监听过程中出现错误,会使用log.Fatalf函数输出错误信息并终止程序的执行。

英文:

You can define redirectTLS as an inline closure function directly in main:

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

得分: 0

我会将配置对象设为全局变量。

否则,你可以定义一个接受配置作为参数并返回一个闭包函数的函数:

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)
  })
}
英文:

I would make the config object global.

Otherwise, you can define a function that accepts the config as an argument, and returns a handler function that closes over the configuration object:


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

huangapple
  • 本文由 发表于 2021年12月3日 22:40:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/70216062.html
匿名

发表评论

匿名网友

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

确定