去意外的字符串文字

Go unexpected string literal

这是我在 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 }

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

您的示例中有一些小错别字。修复这些问题后,您的示例 运行 对我来说没有 unexpected string literal 错误。此外,如果您想将 JSON 写入 http.ResponseWriter,您应该将 fmt.Println 更改为 fmt.Fprintln,如下面的第 2 部分所示。

(1) 个小错别字

# Error 1: undefined: httpRequest
func serveRest(w http.ResponseWriter, r *httpRequest){
# Fixed:
func serveRest(w http.ResponseWriter, r *http.Request){

# Error 2: cannot refer to unexported name fmt.println
fmt.println(w, string(response))
# Fixed to remove error. Use Fprintln to write to 'w' http.ResponseWriter
fmt.Println(w, string(response))

# Error 3: undefined: http.HandleFucn
http.HandleFucn("/", serveRest)
# Fixed
http.HandleFunc("/", serveRest)

(2) 在 HTTP 响应

中返回 JSON

因为 fmt.Println 写入标准输出并且 fmt.Fprintln 写入提供的 io.Writer,return HTTP 响应中的 JSON,使用以下:

fmt.Fprintln(w, string(response))