L
L
levisl2015-11-09 21:28:17
go
levisl, 2015-11-09 21:28:17

How to use NewRequest in golang?

Hello!
There is such a code

package main

import (
  "fmt"
  //	"net"
  "net/http"
)

func main() {
  client := &http.Client{}
  fmt.Println("Hello, playground")
  req, err := http.NewRequest("POST", "http://example.com", nil)
  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("If-None-Match", `W/"wyzzy"`)
  req.Form.Add("username", "a")
  req.Form.Add("password", "b")
  resp, err := client.Do(req)
  //k:=resp.Body
  fmt.Printf("%+v\n", resp)
}

req.Header.Add("If-None-Match", `W/"wyzzy"`) - works
req.Form.Add("password", "b") - doesn't work - panic. like I don’t have a map at all, in which I write.
I don't understand how. Header and url.Values ​​are the same. fully. And the methods are the same.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill, 2015-11-09
@kshvakov

buffer := new(bytes.Buffer)
params := url.Values{}
params.Set("username", "a")
params.Set("password", "b")
buffer.WriteString(params.Encode())
req, _ := http.NewRequest("POST", "", buffer)
req.Header.Set("content-type", "application/x-www-form-urlencoded")

req.Form is the "incoming" request and after request .ParseForm

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question