我正在尝试启动多个 http 服务器侦听同一包中的不同端口。在我的测试 HandleFunc 函数中,我需要打印我们的主机和服务请求的 http 服务器的信息端口。我该怎么做?
这是我的示例代码:
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"os"
"github.com/dineshgowda24/lb/backendserver/config"
)
func main() {
c := flag.String("c", "config/config.json", "Please specify conf.json")
flag.Parse()
file, err := os.Open(*c)
if err != nil {
log.Fatal("Unable to open config file")
}
defer file.Close()
decoder := json.NewDecoder(file)
config := bconfig.BackendConfiguration{}
err = decoder.Decode(&config)
if err != nil {
log.Fatal("Unable to decode conf.json file")
}
http.HandleFunc("/", handle)
for _, s := range config.Servers {
log.Printf("Started server at : %s : %s ", s.Host, s.Port)
go func(host, port string) {
if err := http.ListenAndServe(host+":"+port, nil); err != nil {
log.Printf("Unable to start server at : %s : %s ", host, port)
}
}(s.Host, s.Port)
}
select {}
}
//How to get info of the server which served the request ??
func handle(w http.ResponseWriter, r *http.Request) {
response := "I came from " //need to get server info
w.Write([]byte(response))
w.WriteHeader(http.StatusOK)
}