Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. http.Get() / Post()

http.Get() / Post()

The standard library's net/http package makes it easy to send HTTP requests from Go. Use http.Get() for GET requests and http.Post() for POST requests.

Syntax

// Send a GET request
resp, err := http.Get("URL")

// Send a POST request (specify Content-Type and body)
resp, err := http.Post("URL", "application/json", body)

// Read the response body (always call Close)
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)

Function list

Function / FieldDescription
http.Get(url)Sends a GET request to the specified URL and returns the response.
http.Post(url, contentType, body)Sends a POST request to the specified URL. Pass an io.Reader as the body.
http.PostForm(url, values)POSTs form data as url.Values.
resp.StatusCodeReturns the HTTP status code (e.g., 200, 404) as an integer.
resp.BodyThe response body as an io.ReadCloser. You must call Close() after reading it.
io.ReadAll(r)Reads all content from an io.Reader and returns it as a byte slice.

Sample code

package main

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

func main() {
	// Send a GET request
	resp, err := http.Get("https://httpbin.org/get")
	if err != nil {
		fmt.Println("GET error:", err)
		return
	}
	defer resp.Body.Close()

	fmt.Println("Status:", resp.StatusCode)

	// Read and display the response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Read error:", err)
		return
	}
	// Only show the first 100 characters since the response can be long
	fmt.Println("Response (first 100 chars):", string(body[:100]))

	// Send a POST request with a JSON body
	jsonBody := `{"name":"Gopher","lang":"Go"}`
	resp2, err := http.Post(
		"https://httpbin.org/post",
		"application/json",
		strings.NewReader(jsonBody),
	)
	if err != nil {
		fmt.Println("POST error:", err)
		return
	}
	defer resp2.Body.Close()
	fmt.Println("POST status:", resp2.StatusCode)
}

Notes

http.Get() and http.Post() are convenient for simple use cases, but if you need timeout control or custom headers, combine http.Client with http.NewRequest() instead.

Forgetting to call resp.Body.Close() will cause a connection leak. Always write defer resp.Body.Close() immediately after receiving the response. Additionally, always check for errors — if a network request fails, err will be non-nil.

If you find any errors or copyright issues, please .