英文:
Creating a simple Json response GO
问题
我正在查看一个使用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,所以可能我漏掉了一些概念或其他东西。
英文:
I'm looking at a tutorial for creating REST API's with GO. I'm trying to build a web server and serve up a simple json response:
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, "", " ")
}
When I run this code I get the error:
too many arguments to conversion to Data: Data(fruits, vegetables)
I don't understand why its throwing that error since its expecting 2 arguments and I'm passing in 2 arguments. This is my first day trying GO so maybe I'm missing some concept or something.
答案1
得分: 3
我发现了我的错误,我传递了一个函数而不是一个对象给我创建的类型:
d := Data(fruits, vegetables)
p := Payload(d)
应该改为:
d := Data{fruits, vegetables}
p := Payload{d}
英文:
I found my error I passed in a function instead of an object to the types I created:
d := Data(fruits, vegetables)
p := Payload(d)
should be:
d := Data{fruits, vegetables}
p := Payload{d}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论