Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

HTTP Package in Go Programming

Introduction

The HTTP package in Go provides HTTP client and server implementations. It's a powerful tool for network communication. This tutorial will guide you through the basics and some advanced features of the HTTP package.

Setting Up

First, ensure you have Go installed. You can download it from the official website. Verify your installation by running:

go version

Basic HTTP Server

Let's start by creating a simple HTTP server. Create a new file main.go and add the following code:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Run the server using the command:

go run main.go

Open your browser and navigate to http://localhost:8080 to see the output.

HTTP Client

Now, let's create a simple HTTP client to make a GET request. Add the following code to your main.go:

package main

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

func main() {
    resp, err := http.Get("http://example.com")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(string(body))
}

Run the client using the command:

go run main.go

You should see the HTML content of http://example.com printed in your terminal.

Handling POST Requests

To handle POST requests, modify your server code as follows:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        r.ParseForm()
        fmt.Fprintf(w, "POST request received:\n")
        fmt.Fprintf(w, "Form data: %v\n", r.Form)
    } else {
        fmt.Fprintf(w, "Hello, World!")
    }
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Use the following client code to make a POST request:

package main

import (
    "bytes"
    "fmt"
    "net/http"
)

func main() {
    data := []byte(`{"name":"John"}`)
    resp, err := http.Post("http://localhost:8080", "application/json", bytes.NewBuffer(data))
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

Advanced Features

Go's HTTP package offers more advanced features like custom HTTP clients, setting headers, and handling cookies. Here's an example of setting custom headers:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, `{"message": "Hello, World!"}`)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

When you access http://localhost:8080, the response will have a JSON content type.

Conclusion

In this tutorial, we've covered the basics of the HTTP package in Go, including setting up a server and client, handling GET and POST requests, and using some advanced features. The HTTP package is a powerful tool for building networked applications in Go.