Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Go Index

🌐 net/http — HTTP client and server

The most powerful package in Go's standard library for web development. Provides both an HTTP/HTTPS client and a production-ready HTTP server — no framework needed for many use cases. Handles routing, headers, cookies, TLS, and streaming.

Import: import "net/http" | Docs: pkg.go.dev/net/http

📋 Functions, Types & Constants

NameSignature / ValueDescription
http.Getfunc Get(url string) (resp *Response, err error)Issue HTTP GET request
http.Postfunc Post(url, contentType string, body io.Reader) (*Response, error)Issue HTTP POST request
http.PostFormfunc PostForm(url string, data url.Values) (*Response, error)POST form data
http.NewRequestfunc NewRequest(method, url string, body io.Reader) (*Request, error)Build custom HTTP request
http.DefaultClientvar DefaultClient = &Client{}Package-level HTTP client
client.Dofunc (c *Client) Do(req *Request) (*Response, error)Execute a custom request
resp.Bodyio.ReadCloserResponse body — always defer resp.Body.Close()
resp.StatusCodeintHTTP status code (200, 404, 500 etc.)
resp.HeaderHeaderResponse headers map
http.ListenAndServefunc ListenAndServe(addr string, handler Handler) errorStart HTTP server on addr
http.ListenAndServeTLSfunc ListenAndServeTLS(addr, cert, key string, h Handler) errorStart HTTPS server
http.HandleFuncfunc HandleFunc(pattern string, handler func(ResponseWriter, *Request))Register URL pattern handler
http.Handlefunc Handle(pattern string, handler Handler)Register Handler interface
http.NewServeMuxfunc NewServeMux() *ServeMuxCreate new HTTP request multiplexer
http.ResponseWriterinterfaceInterface for writing HTTP responses
w.WriteHeaderfunc (w ResponseWriter) WriteHeader(statusCode int)Set HTTP status code
w.Header().Setfunc (h Header) Set(key, value string)Set response header
r.URL.Queryfunc (u *URL) Query() ValuesParse URL query string
r.FormValuefunc (r *Request) FormValue(key string) stringGet form or query parameter
r.MethodstringHTTP method (GET, POST etc.)
r.Header.Getfunc (h Header) Get(key string) stringGet request header value
http.StatusOKconst = 200HTTP 200 OK
http.StatusNotFoundconst = 404HTTP 404 Not Found
http.StatusInternalServerErrorconst = 500HTTP 500 Internal Server Error
http.StatusCreatedconst = 201HTTP 201 Created
http.Redirectfunc Redirect(w ResponseWriter, r *Request, url string, code int)Send redirect response
http.Errorfunc Error(w ResponseWriter, error string, code int)Send error response
http.ServeFilefunc ServeFile(w ResponseWriter, r *Request, name string)Serve a file
http.FileServerfunc FileServer(root FileSystem) HandlerHTTP handler for static files
http.StripPrefixfunc StripPrefix(prefix string, h Handler) HandlerStrip URL prefix before passing to handler

💡 Example Program

Save as main.go inside any directory and run with go run main.go. No extra packages to install — all standard library.

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "time"
)

// --- Handler functions ---
func homeHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    name := r.URL.Query().Get("name")
    if name == "" {
        name = "World"
    }
    fmt.Fprintf(w, "<h1>Hello, %s!</h1><p>Method: %s</p>", name, r.Method)
}

func apiHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, `{"status":"ok","time":"%s"}`, time.Now().Format(time.RFC3339))
}

// --- HTTP client ---
func fetchURL(url string) {
    resp, err := http.Get(url)
    if err != nil {
        log.Println("GET error:", err)
        return
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    fmt.Printf("Status: %d  Body: %s\n", resp.StatusCode, string(body)[:80])
}

func main() {
    // --- Server ---
    mux := http.NewServeMux()
    mux.HandleFunc("/",    homeHandler)
    mux.HandleFunc("/api", apiHandler)

    // Serve static files
    fs := http.FileServer(http.Dir("./static"))
    mux.Handle("/static/", http.StripPrefix("/static/", fs))

    server := &http.Server{
        Addr:         ":8080",
        Handler:      mux,
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }

    fmt.Println("Server starting on http://localhost:8080")
    fmt.Println("Try: http://localhost:8080/?name=MyWebUniversity")
    fmt.Println("Try: http://localhost:8080/api")
    log.Fatal(server.ListenAndServe())
}
// go run main.go
// curl http://localhost:8080/api

← time  |  🏠 Index  |  sync →