I'm trying to write simple http server, that will serve requests to API. This is a code:
type Config struct {
ListenPort int `json:"listenPort"`
Requests []struct {
Request string `json:"request"`
ResponceFile string `json:"responceFile"`
} `json:"requests"`
}
...
func main() {
...
startServer(config)
}
func startServer(config Config) {
http.HandleFunc(apiPrefix+config.Requests[0].Request,
func(w http.ResponseWriter, r *http.Request) {
var dataStruct interface{}
err := loadJSON(config.Requests[0].ResponseFile, &dataStruct)
if err != nil {
w.Write([]byte("Oops! Something was wrong"))
}
data, _ := json.Marshal(dataStruct)
w.Header().Set("Content-Type", "application/json")
w.Write(data)
})
http.HandleFunc(apiPrefix+config.Requests[1].Request,
func(w http.ResponseWriter, r *http.Request) {
var dataStruct interface{}
err := loadJSON(config.Requests[1].ResponseFile, &dataStruct)
if err != nil {
w.Write([]byte("Oops! Something was wrong"))
}
data, _ := json.Marshal(dataStruct)
w.Header().Set("Content-Type", "application/json")
w.Write(data)
})
http.HandleFunc("/", http.NotFound)
port := ""
if config.ListenPort != 0 {
port = fmt.Sprintf(":%v", config.ListenPort)
} else {
port = ":8080"
}
fmt.Printf("Started @%v
", port)
log.Fatal(http.ListenAndServe(port, nil))
}
func loadJSON(filePath string, retStruct interface{}) error {
fmt.Println(filePath)
fileJSON, err := ioutil.ReadFile(filePath)
json.Unmarshal(fileJSON, retStruct)
return err
}
And this is config, where files that should be returned via specific requests are described:
{
"listenPort": 8080,
"requests": [
{
"request": "switches/brocade",
"responseFile": "switches.json"
},
{
"request": "smth",
"responseFile": "smth.json"
}
]
}
So question is: why this code is not the same as code atop? It returns only last response file, described in config.json on all requests from this file? Or what is correct way to write dynamically-defined handlers?
func startServer(config Config) {
for _, req := config.Requests {
http.HandleFunc(apiPrefix+req.Request,
func(w http.ResponseWriter, r *http.Request) {
var dataStruct interface{}
err := loadJSON(req.ResponseFile, &dataStruct)
if err != nil {
w.Write([]byte("Oops! Something was wrong"))
}
data, _ := json.Marshal(dataStruct)
w.Header().Set("Content-Type", "application/json")
w.Write(data)
})
}
http.HandleFunc("/", http.NotFound)