Standard library / net/http

http.Client.Post()

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

Formal Syntax & Structure

go syntaxgo
func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)

Parameters & Attributes

NameTypeDescription
urlstringDestination URL string.
contentTypestringMedia type of the request body.
bodyio.ReaderOptional reader containing the request body.

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"  "strings")
func main() {  s := fixture()  defer s.Close()  r := must(s.Client().Post(s.URL, "text/plain", strings.NewReader("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