Go (Golang) / Networking and APIs in Go

Making HTTP Requests with Go’s net/http Package

This tutorial will guide you on how to make HTTP requests using Go's net/http package. The net/http package provides a set of functions and methods that allow for easy sending and…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers HTTP requests, RESTful APIs, and working with web services in Go.

Introduction

This tutorial aims to guide you through making HTTP requests using Go's net/http package. By the end of this tutorial, you will learn how to send and receive HTTP requests and responses using Go.

Prerequisites:
- Basic knowledge of Go programming language
- Go installed on your system

Step-by-Step Guide

The net/http package in Go provides functions to send and receive HTTP requests. Here, we will focus on making requests using the 'http.Get', 'http.Post', and 'http.NewRequest' functions.

http.Get

The http.Get function makes a GET request to a URL and returns a Response and an error. The Response contains the server's response to the request.

http.Post

The http.Post function sends a POST request to a URL. It includes a payload (data) to send to the server. It also returns a Response and an error.

http.NewRequest

The http.NewRequest function is used when you need more flexibility with your HTTP request – for example, adding headers or changing the method (GET, POST, PUT, DELETE, etc.) It returns a Request and an error.

Code Examples

Example 1: Making a GET request

package main

import (
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    res, err := http.Get("http://example.com")
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("%s", body)
}

In this example, we make a GET request to http://example.com using http.Get. The response from the server is read and logged to the console.

Example 2: Making a POST request

package main

import (
    "log"
    "net/http"
    "strings"
)

func main() {
    res, err := http.Post(
        "http://example.com/form",
        "application/x-www-form-urlencoded",
        strings.NewReader("name=test"),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer res.Body.Close()
    log.Printf("Response status: %s", res.Status)
}

In this example, we send a POST request to http://example.com/form with a data payload of "name=test". The server's response status is logged to the console.

Summary

This tutorial covered how to make HTTP requests using the net/http package in Go. You learned how to send GET and POST requests, and read the server's response.

Next steps:
- Explore other methods available in the net/http package
- Learn how to handle errors and status codes in HTTP responses

Additional resources:
- Go net/http package documentation

Practice Exercises

  1. Write a program to send a GET request to your favorite website and log the response body.
  2. Write a program to send a POST request with some data to a test server (like http://httpbin.org/post), and log the response status.
  3. Write a program to send a GET request to a non-existing URL, handle the error, and log a friendly message.

Solutions and tips will vary depending on the server used and the data sent in the requests. Remember to handle errors and close response bodies to prevent memory leaks.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

File Size Checker

Check the size of uploaded files.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help