意外的字符串文字

问题描述 投票:0回答:1

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

任何人都可以告诉我错误是什么吗....

string go literals
1个回答
2
投票

您的示例中有一些小错别字。修复这些问题后,您的示例为我运行,没有出现

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,要在 HTTP 响应中返回 JSON,请使用以下命令:

fmt.Fprintln(w, string(response))
© www.soinside.com 2019 - 2024. All rights reserved.