0
type requestNodeType struct {
// edited: added the last part
    urls    []string  `json:"urls"` 
}

... some more code ... then a part where I set the gin router context ... c ->>> *gin.Context

and then ...

x, _ := ioutil.ReadAll(c.Request.Body)
fmt.Printf("crb2 = %s\n", string(x))
uList := requestNodeType{}
json.Unmarshal(x, &uList)
// edited: updated prints for clarity 
fmt.Printf("json1 = %+v, %T - %p\n", uList, uList, uList )
fmt.Printf("json2 = %+v, %T - %p\n", uList.urls, uList.urls, uList.urls )
fmt.Printf("json3 = %+v, %T - %p\n", uList.urls[0], uList.urls[0], uList.urls[0] )

gives me an output of:

crb2 = {"urls":["http://www.indeed.com/viewjob?jk=9388f66529358f6a", "http://www.indeed.com/viewjob?jk=53e937ef73c0c808"]}
json1 = {urls:[]}, main.requestNodeType - %!p(main.requestNodeType={[]})
json2 = [], []string - 0x0
2016/02/20 09:10:39 Panic recovery -> runtime error: index out of range

How can I represent this structure properly or fix my code?

Or even better, an idea to get c.BindJSON(&uList) to work for Gin ...?

codeaperature
  • 1,089
  • 2
  • 10
  • 25

1 Answers1

1

Your JSON is invalid if it is really equal to

{["http://www.jobs.com/job?jk=9388f66529358f6a","http://www.job.com/job?jk=53e937ef73c0c808"]}

So your uList.URIs is empty. You could check for parsing error json.Unmarshal result.

Proper JSON for your model should look like

["http://www.jobs.com/job?jk=9388f66529358f6a","http://www.job.com/job?jk=53e937ef73c0c808"]

with struct like

type URLs []string

or

{"URLs": ["http://www.jobs.com/job?jk=9388f66529358f6a","http://www.job.com/job?jk=53e937ef73c0c808"]}

with struct like

type requestNodeType struct {
    URLs []string `json:"URLs"`
}

Also you can replace json.Unmarshal([]byte(string(x)), &uList) with json.Unmarshal(x, &uList) as x is already []byte.

CrazyCrow
  • 4,125
  • 1
  • 28
  • 39
  • I believe you don't need `json:"URLs"` because the field name is already exported and the same. But to make it more readable sure. – ahmy Feb 20 '16 at 11:51
  • The changes suggested by bearburger were implemented. The results are similar. I am using the suggested structure and I am now using `$ curl -H "Content-Type: application/json" -X POST -d '{"urls":["http://www.indeed.com/viewjob?jk=9388f66529358f6a", "http://www.indeed.com/viewjob?jk=53e937ef73c0c808"]}' http://localhost:8888/post` for my request. For ahmy's comment, I reqlize I probably don't need to add `json:"urls"` - I'm adding this in case I decide to change to 'unmatched and not the same names'. – codeaperature Feb 20 '16 at 17:28
  • @StephanWarren `urls []string` should be `Urls []string` to be properly parsed as JSON. Here is example http://play.golang.org/p/tP4FE8Gf3x [Here](http://stackoverflow.com/questions/21825322/why-golang-cannot-generate-json-from-struct-with-front-lowercase-character) you can read explaination why you should use upper-case for field names. – CrazyCrow Feb 20 '16 at 17:48