Reputation: 3268
Trying to accomplish a HTTP Post in Go:
Posting to: apiUrl
Payload/Post Body (expected as a json string): postBody
Here is the error I'm getting:
cannot use postBodyJson (type []byte) as type io.Reader in argument to http.Post:
[]byte does not implement io.Reader (missing Read method)
What am I doing wrong?
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
var postBody = []string{
"http://google.com",
"http://facebook.com",
"http://youtube.com",
"http://yahoo.com",
"http://twitter.com",
"http://live.com",
}
requestUrl := "http://lsapi.seomoz.com/linkscape/url-metrics"
postBodyJson, _ := json.Marshal(postBody)
resp, err := http.Post(requestUrl, "application/json", postBodyJson)
fmt.Println(resp)
}
Upvotes: 0
Views: 1184
Reputation: 1996
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
var postBody = []string{
"http://google.com",
"http://facebook.com",
"http://youtube.com",
"http://yahoo.com",
"http://twitter.com",
"http://live.com",
}
apiUrl := "http://lsapi.seomoz.com/linkscape/url-metrics"
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
err := enc.Encode(postBody)
if err != nil {
log.Fatal(err)
}
resp, err := http.Post(apiUrl, "application/json", buf)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp)
}
Something like this might work. But as I already said in the comments, you should familiarize yourself with the language a little more. When you post code, make sure it compiles.
Upvotes: 3