去意外的字符串文字

这是我在 Go 中的代码,我猜一切都是正确的......


package main


import(

"fmt"

"encoding/json"

"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 *httpRequest){

    response , err := getJsonResponse()

    if err != nil{

        panic(err)

    }

    fmt.println(w, string(response))


}







func main(){


http.HandleFucn("/", serveRest)

http.ListenAndServe("localhost:1337",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, "", "  ")


}

这是我得到的错误


API_Sushant.go:31: syntax error: unexpected string literal, expecting semicolon or newline or }

谁能告诉我错误是什么请....


心有法竹
浏览 244回答 1
1回答

繁花不似锦

您的示例中有一些小错误。修复这些之后,您的示例为我运行而没有unexpected string literal错误。此外,如果要将 JSON 写入http.ResponseWriter,则应更改fmt.Println为fmt.Fprintln如下面的第 2 部分所示。(1) 轻微错别字# Error 1: undefined: httpRequestfunc serveRest(w http.ResponseWriter, r *httpRequest){# Fixed:func serveRest(w http.ResponseWriter, r *http.Request){# Error 2: cannot refer to unexported name fmt.printlnfmt.println(w, string(response))# Fixed to remove error. Use Fprintln to write to 'w' http.ResponseWriterfmt.Println(w, string(response))# Error 3: undefined: http.HandleFucnhttp.HandleFucn("/", serveRest)# Fixedhttp.HandleFunc("/", serveRest)(2) HTTP Response 中返回 JSON因为fmt.Println写入标准输出并fmt.Fprintln写入提供的 io.Writer,要在 HTTP 响应中返回 JSON,请使用以下内容:fmt.Fprintln(w, string(response))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go