Sushant Ubale Patil
Sushant Ubale Patil

Reputation: 39

Go unexpected string literal

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 ....

Upvotes: 0

Views: 7285

Answers (1)

Grokify
Grokify

Reputation: 16324

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

Upvotes: 2

Related Questions