去意想不到的字符串文字

时间:2015-03-21 20:45:25

标签: string go literals

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

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

1 个答案:

答案 0 :(得分:1)

您的示例中有一些小错字。修复后,您的示例在没有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))