Standard library / net/http

http.Client.PostForm()

Send a POSTFORM request using this client. Check HTTP status separately and close the response body. Expected stdout: '200 "q=go"\n'.

Formal Syntax & Structure

go syntaxgo
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

Parameters & Attributes

NameTypeDescription
urlstringDestination URL string.
dataurl.ValuesInput bytes or form values, as declared.

Return Value

(resp *Response, err error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "fmt"  "io"  "net/http"  "net/http/httptest"  "net/url")
func main() {  s := fixture()  defer s.Close()  r := must(s.Client().PostForm(s.URL, url.Values{"q": {"go"}}))  defer r.Body.Close()  fmt.Printf("%d %q\n", r.StatusCode, string(must(io.ReadAll(r.Body))))}func fixture() *httptest.Server {  return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {    w.Header().Set("X-Demo", "yes")    if r.Method == "POST" {      b, e := io.ReadAll(io.LimitReader(r.Body, 1025))      check(e)      if len(b) > 1024 {        w.WriteHeader(413)        return      }      fmt.Fprint(w, string(b))      return    }    fmt.Fprint(w, "hello")  }))}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference