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.
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}