net/http

Package http

The http package implements a client and server for the HTTP protocol. It provides convenient interfaces for common HTTP tasks, allowing developers to easily send HTTP requests, handle responses, and build web servers.

Import Path:
net/http
Version:
Go 1.21.4 Latest
Authors:
Rob Pike, Ken Thompson, Robert Griesemer

Overview

The net/http package is a cornerstone of Go's networking capabilities. It offers a high-level API that abstracts away much of the complexity of HTTP, while still providing access to lower-level details when needed.

Key features include:

Getting Started

To send a simple HTTP GET request:

package main

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

func main() {
	resp, err := http.Get("https://golang.org/")
	if err != nil {
		fmt.Printf("Error making request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response body: %v\n", err)
		return
	}

	fmt.Printf("Status Code: %d\n", resp.StatusCode)
	fmt.Printf("Response Body (first 100 chars): %s\n", string(body)[:100])
}

To start a simple HTTP server:

package main

import (
	"fmt"
	"net/http"
)

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

func main() {
	http.HandleFunc("/", helloHandler)
	fmt.Println("Server starting on :8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Printf("Server error: %v\n", err)
	}
}

Core Components

Further Reading