dtlh12053 2015-03-21 20:45
浏览 4
已采纳

去意外的字符串文字

This is my code in Go and everything is right I guess....

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, "", "  ")

}

And this is the error I am getting

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

Can anybody tell me whats the error plz ....

  • 写回答

1条回答 默认 最新

  • douxing9641 2015-03-21 20:55
    关注

    There are a few minor typos in your example. After fixing those, your example ran for me without the unexpected string literal error. Also, if you want to write the JSON to the http.ResponseWriter, you should change fmt.Println to fmt.Fprintln as shown in part 2 below.

    (1) Minor Typos

    # 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) Returning JSON in HTTP Response

    Because fmt.Println writes to standard output and fmt.Fprintln writes to supplied io.Writer, to return the JSON in the HTTP response, use the following:

    fmt.Fprintln(w, string(response))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算