我正在查看使用GO创建REST API的教程。我正在尝试构建一个Web服务器并提供一个简单的json响应:
package main
import(
"encoding/json"
"fmt"
"net/http"
)
type Payload struct {
Stuff Data
}
type Data struct {
Fruit Fruits
Veggies Vegetables
}
type Fruits map[string]int
type Vegetables map[string]int
func serveRest(w http.ResponseWriter, r *http.Request) {
response, err := getJsonResponse()
if err != nil {
panic(err)
}
fmt.Fprintf(w, string(response))
}
func main() {
http.HandleFunc("/", serveRest)
http.ListenAndServe("localhost:7200", nil)
}
func getJsonResponse() ([]byte, error){
fruits := make(map[string]int)
fruits["Apples"] = 25
fruits["Oranges"] = 11
vegetables := make(map[string]int)
vegetables["Carrots"] = 21
vegetables["Peppers"] = 0
d := Data(fruits, vegetables)
p := Payload(d)
return json.MarshalIndent(p, "", " ")
}
当我运行此代码时,我收到错误:
too many arguments to conversion to Data: Data(fruits, vegetables)
我不明白为什么它抛出那个错误,因为它期待2个参数而且我传递了2个参数。这是我尝试GO的第一天,所以也许我错过了一些概念或什么。