我有viper在config.yml&中提供以下值附上其余的配置:
servers:
- projectname: test
directory: D:\playgroud\test
port: 1029
- projectname: test1
directory: D:\playground\test1
port: 1030
Coniguration.go包含
package config
import ()
type Configuration struct {
Servers []ServerConfiguration
}
package main
import (
"config"
"github.com/spf13/viper"
"log"
"net/http"
)
Server.go
package config
type ServerConfiguration struct {
ProjectName string
Directory string
Port string
}
Main.go
func main() {
viper.SetConfigName("config")
viper.AddConfigPath(".")
var configuration config.Configuration
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading config file, %s", err)
}
err := viper.Unmarshal(&configuration)
if err != nil {
log.Fatalf("unable to decode into struct, %v", err)
}
counter := 0
finish := make(chan bool)
for _, h := range configuration.Servers {
counter = counter +1
log.Println(counter)
counter := http.NewServeMux()
counter.HandleFunc("/"+h.ProjectName, foo8001 )
go func() {
http.ListenAndServe(":"+h.Port, counter)
}()
}
<-finish
}
func foo8001(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Listening on 8001: foo "))
}
但是,当我运行服务器时,我只看到一个服务于1030和1029似乎该过程已经结束。
这是输出:
2018/02/25 03:53:30 1
2018/02/25 03:53:30 2
我在这里做错了什么,不胜感激任何更好的理解,也会感激任何想法或建议。
提前致谢!
答案 0 :(得分:1)
这可能是因为你的端口在开始最安全的方式之前在循环中改变是将参数传递给goroutine并将所有调用移动到h
参数到goroutine。这样的事情应该有效
for _, h := range configuration.Servers {
counter = counter + 1
log.Println(counter)
go func(h ServerConfiguration) {
server := http.NewServeMux()
server.HandleFunc("/"+h.ProjectName, foo8001)
http.ListenAndServe(":"+h.Port, server)
}(h)
}