Getting Started with Go's net/http Package

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating a Simple HTTP Server
  5. Handling HTTP Requests
  6. Sending HTTP Requests
  7. Conclusion

Introduction

Go is a powerful programming language that provides excellent support for network and web programming. The net/http package is part of the standard library in Go and offers a straightforward way to create HTTP servers and clients. In this tutorial, we will explore the basics of net/http package and see how to create a simple HTTP server and handle HTTP requests.

By the end of this tutorial, you will understand the fundamentals of the net/http package and be able to create your own HTTP server or client using Go.

Prerequisites

Before getting started, make sure you have the following prerequisites:

  • Basic understanding of the Go programming language
  • Go installed on your machine

Setup

To get started, open your favorite text editor or IDE and create a new file called main.go.

Inside the main.go file, import the net/http package:

package main

import (
    "net/http"
)

Now that we have set up our project, let’s dive into creating a simple HTTP server.

Creating a Simple HTTP Server

To create an HTTP server, we need to define a handler function that will be called whenever an HTTP request is received.

In Go, a handler is any object that implements the http.Handler interface. The http.HandlerFunc type is a convenient way to create a handler function that satisfies the http.Handler interface.

Here’s an example of a simple handler function that returns “Hello, World!” as the response:

func helloHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, World!"))
}

Now, let’s create the HTTP server and register our handler function to handle all incoming requests:

func main() {
    http.HandleFunc("/", helloHandler)

    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

In the code above, we register our helloHandler function to handle all requests for the root path (“/”). We then start the HTTP server on port 8080 using the http.ListenAndServe function.

To start the server, open a terminal or command prompt, navigate to the directory containing the main.go file, and run the following command:

go run main.go

You should see the HTTP server start successfully.

Now, if you open your web browser and visit http://localhost:8080, you should see the message “Hello, World!” displayed on the page.

Congratulations! You have created a simple HTTP server using the net/http package.

Handling HTTP Requests

In addition to creating an HTTP server, the net/http package allows us to handle different types of HTTP requests.

Let’s modify our previous example to handle different paths and HTTP methods.

func helloHandler(w http.ResponseWriter, r *http.Request) {
    switch r.URL.Path {
    case "/":
        w.Write([]byte("Hello, World!"))
    case "/about":
        w.Write([]byte("About"))
    default:
        http.NotFound(w, r)
    }
}

In the updated helloHandler function, we use a switch statement to determine the requested path (r.URL.Path). If the path is “/”, we return “Hello, World!”. If the path is “/about”, we return “About”. Otherwise, we use the http.NotFound function to indicate that the requested path is not found.

Now, if you visit http://localhost:8080/about, you should see the message “About” displayed on the page. If you visit any other path, you will see a “404 - Not Found” error.

You can add more complex logic to handle different paths, query parameters, headers, and request bodies based on your application’s requirements.

Sending HTTP Requests

The net/http package also provides functionality to send HTTP requests from your Go code.

Let’s see an example of sending an HTTP GET request to an external API and displaying the response.

func main() {
    response, err := http.Get("https://api.example.com/users")
    if err != nil {
        panic(err)
    }
    defer response.Body.Close()

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(body))
}

In the code above, we use the http.Get function to send an HTTP GET request to the URL “https://api.example.com/users”. We then read the response body and print it to the console.

Make sure to import the necessary packages:

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

By running the modified program, you will see the response from the API displayed in your console.

Conclusion

In this tutorial, we have covered the basics of Go’s net/http package. We learned how to create a simple HTTP server, handle different types of HTTP requests, and send HTTP requests to external APIs.

By understanding these concepts, you can build powerful web applications or create robust HTTP clients using Go.

Feel free to experiment with the examples provided and explore more features offered by the net/http package.