I'm very new to Go so please forgive me if this is stupid obvious.
I'm trying to post a form to a REST API written in Go using gorest. I've successfully done this using GET, but I can't get the POST data to parse into a map. Here is my Go code
gotest.go:
package main
import (
"code.google.com/p/gorest"
"net/http"
"fmt"
)
func main() {
gorest.RegisterService(new(HelloService)) //Register our service
http.Handle("/",gorest.Handle())
http.ListenAndServe(":8787",nil)
}
//Service Definition
type HelloService struct {
gorest.RestService `root:"/api/"`
save gorest.EndPoint `method:"POST" path:"/save/" output:"string" postdata:"map[string]string"`
}
func(serv HelloService) Save(PostData map[string]string) {
fmt.Println(PostData)
}
And my awesome html form:
<form method="POST" action="http://127.0.0.1:8787/api/save/">
key: <input type="text" name="key" /><br />
json: <input type="text" name="json" /><br />
<input type="submit" />
</form>
I would think that would turn my post data into a nice map that I could access. I fill out the form, hit submit, and it returns an error:
Error Unmarshalling data using application/json. Client sent incompetible data format in entity. (invalid character 'k' looking for beginning of value)
EDIT: As greggory.hz points out, the program seems to think that the post data is a json. This error is because a json has to start with a brace, bracket or quote.
If map[string]string
with string
it prints the following to the bash terminal where I am running this:
key=arst&json=%7B%27arst%27%3A%27arst%27%7D
In the go rest documentation the only example of this that I could find is:
posted gorest.EndPoint method:"POST" path:"/post/" postdata:"User"
func(serv HelloService) Posted(posted User)
But my attempts at creating a custom struct have also fails with the same unmarshalling error seen above.
type MyStruct struct {
key,json string
}
Can someone please tell me what data type I should be using?
You are trying to post an html form to a service expecting a json body. But your browser isn't going to format the post as application/json. It will instead format it as a urlencoded body. The problem isn't in your go server code it's in the html form. You probably want to use javascript to package up and send your post instead of a standard html form.
<div>
<input type="hidden" name="endpont" value="http://127.0.0.1:8787/api/save/" />
key: <input type="text" name="key" /><br /> <!-- this should be used in your post url -->
json: <input type="text" name="json" /><br /> <!-- this will get sent by your javascript as the post body -->
<input type="button" onclick="send_using_ajax();" />
</div>