codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐹

Go (Golang)

30 / 72 topics
27Standard Library Overview28IO Package29Net Package30HTTP Package31JSON Package32XML Package33Time Package34OS Package35Fmt Package36Math Package37Regexp Package38Log Package39Flag Package40Context Package41Embed Package
Tutorials/Go (Golang)/HTTP Package
🐹Go (Golang)

HTTP Package

Updated 2026-05-15
10 min read

HTTP Package

Introduction

The net/http package in Go is a fundamental part of the language's standard library, providing tools for building both HTTP servers and clients. Whether you're creating a web application or interacting with external APIs, understanding how to use this package is essential.

In this tutorial, we'll explore how to build basic HTTP servers and clients using the net/http package. We'll cover everything from setting up a server to handling requests and responses, as well as making HTTP requests to other services.

Concept

Building an HTTP Server

To create an HTTP server in Go, you need to import the net/http package and define a handler function that will process incoming requests. The http.HandleFunc function is used to associate URLs with handler functions.

Here's a simple example of how to set up an HTTP server:

Go
1package main
2
3import (
4 "fmt"
5 "log"
6 "net/http"
7)
8
9func helloHandler(w http.ResponseWriter, r *http.Request) {
10 fmt.Fprintf(w, "Hello, World!")
11}
12
13func main() {
14 http.HandleFunc("/", helloHandler)
15 log.Println("Starting server at port 8080")
16 if err := http.ListenAndServe(":8080", nil); err != nil {
17 log.Fatal(err)
18 }
19}

In this example:

  • We define a helloHandler function that writes "Hello, World!" to the response.
  • We use http.HandleFunc to map the root URL ("/") to our handler function.
  • Finally, we start the server on port 8080 using http.ListenAndServe.

Handling Requests and Responses

The http.ResponseWriter interface is used to send responses back to the client. The *http.Request struct contains information about the incoming request, such as the URL, headers, and body.

Here's an example of how to handle different HTTP methods:

Go
1package main
2
3import (
4 "fmt"
5 "log"
6 "net/http"
7)
8
9func methodHandler(w http.ResponseWriter, r *http.Request) {
10 switch r.Method {
11 case "GET":
12 fmt.Fprintf(w, "Received a GET request")
13 case "POST":
14 fmt.Fprintf(w, "Received a POST request")
15 default:
16 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
17 }
18}
19
20func main() {
21 http.HandleFunc("/", methodHandler)
22 log.Println("Starting server at port 8080")
23 if err := http.ListenAndServe(":8080", nil); err != nil {
24 log.Fatal(err)
25 }
26}

In this example:

  • We define a methodHandler function that checks the HTTP method of the request.
  • Depending on the method, it sends a different response back to the client.

Building an HTTP Client

To make HTTP requests in Go, you can use the http.Client struct. This allows you to send GET, POST, and other types of requests to external services.

Here's an example of how to make a GET request:

Go
1package main
2
3import (
4 "fmt"
5 "io/ioutil"
6 "log"
7 "net/http"
8)
9
10func fetchExample() {
11 resp, err := http.Get("https://example.com")
12 if err != nil {
13 log.Fatal(err)
14 }
15 defer resp.Body.Close()
16
17 body, err := ioutil.ReadAll(resp.Body)
18 if err != nil {
19 log.Fatal(err)
20 }
21
22 fmt.Println(string(body))
23}
24
25func main() {
26 fetchExample()
27}

In this example:

  • We use http.Get to make a GET request to "https://example.com".
  • We read the response body using ioutil.ReadAll.
  • Finally, we print the response body as a string.

Examples

Example 1: Simple HTTP Server

Let's create a simple HTTP server that responds with different messages based on the URL path:

Go
1package main
2
3import (
4 "fmt"
5 "log"
6 "net/http"
7)
8
9func homeHandler(w http.ResponseWriter, r *http.Request) {
10 fmt.Fprintf(w, "Welcome to the homepage!")
11}
12
13func aboutHandler(w http.ResponseWriter, r *http.Request) {
14 fmt.Fprintf(w, "About us page")
15}
16
17func main() {
18 http.HandleFunc("/", homeHandler)
19 http.HandleFunc("/about", aboutHandler)
20 log.Println("Starting server at port 8080")
21 if err := http.ListenAndServe(":8080", nil); err != nil {
22 log.Fatal(err)
23 }
24}

In this example:

  • We define two handler functions: homeHandler and aboutHandler.
  • We map the root URL ("/") to homeHandler and /about to aboutHandler.

Example 2: HTTP Client with POST Request

Let's create an HTTP client that sends a POST request with some JSON data:

Go
1package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io/ioutil"
8 "log"
9 "net/http"
10)
11
12type Payload struct {
13 Name string `json:"name"`
14 Email string `json:"email"`
15}
16
17func postExample() {
18 payload := Payload{
19 Name: "John Doe",
20 Email: "john.doe@example.com",
21 }
22
23 jsonPayload, err := json.Marshal(payload)
24 if err != nil {
25 log.Fatal(err)
26 }
27
28 req, err := http.NewRequest("POST", "https://example.com/api/users", bytes.NewBuffer(jsonPayload))
29 if err != nil {
30 log.Fatal(err)
31 }
32 req.Header.Set("Content-Type", "application/json")
33
34 client := &http.Client{}
35 resp, err := client.Do(req)
36 if err != nil {
37 log.Fatal(err)
38 }
39 defer resp.Body.Close()
40
41 body, err := ioutil.ReadAll(resp.Body)
42 if err != nil {
43 log.Fatal(err)
44 }
45
46 fmt.Println(string(body))
47}
48
49func main() {
50 postExample()
51}

In this example:

  • We define a Payload struct to represent the JSON data.
  • We marshal the struct into JSON and create an HTTP POST request with it.
  • We set the Content-Type header to application/json.
  • Finally, we send the request using an http.Client and print the response body.

What's Next?

In the next section, we'll explore the encoding/json package, which is essential for working with JSON data in Go. This will be particularly useful when interacting with APIs or handling JSON responses from HTTP requests.

Stay tuned!


PreviousNet PackageNext JSON Package

Recommended Gear

Net PackageJSON Package