Standard library / net/http
http.Post()
Send a POST request using the default client. Check HTTP status separately and close the response body. Expected stdout: '200 "go"\n'.
Formal Syntax & Structure
go syntaxgo
func Post(url, contentType string, body io.Reader) (resp *Response, err error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| url | string | Destination URL string. |
| contentType | string | Media type of the request body. |
| body | io.Reader | Optional 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(http.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) }}