Home > Software design >  Passing a string to a handler function in Go
Passing a string to a handler function in Go

Time:12-03

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

CodePudding user response:

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

CodePudding user response:

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)
    }
}()
  • Related