golang,go,博客,开源,编程

golang每日一库之net/http

Published on with 0 views and 0 comments

Go 的 net/http 包是标准库中用于处理 HTTP 请求和响应的核心库之一,广泛应用于 Web 服务、API 服务器以及客户端实现。这个包非常高效且易用,提供了大量功能,帮助开发者在 Go 中构建 HTTP 服务或客户端。

1. 概述

net/http 包提供了 HTTP 客户端和服务器的功能。它实现了 HTTP 协议的相关功能,支持从发送请求、接收响应到处理 HTTP 服务器中的请求和响应等操作。

  • HTTP 客户端:你可以用它发起 HTTP 请求,处理响应。
  • HTTP 服务器:你可以用它构建一个 HTTP 服务器,接收并响应 HTTP 请求。

2. 常见功能概述

  • HTTP 请求发送:发起 GET、POST、PUT、DELETE 等请求。
  • HTTP 服务器:创建一个 Web 服务器,处理客户端请求。
  • URL 解析:对 URL 进行解析和处理。
  • 请求处理:解析请求头、请求体、查询参数等。

3. 创建一个 HTTP 服务器

创建一个简单的 HTTP 服务器,处理请求并返回响应是 net/http 包的一个常见用法。以下是一个最简单的例子:

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 服务器,监听在 8080 端口
    http.ListenAndServe(":8080", nil)
}

3.1 http.HandleFunc

  • http.HandleFunc 将一个 URL 路径(如 /)与一个处理函数(如 handler)绑定。每当该路径上的请求到来时,处理函数就会被调用。
  • handler 函数的两个参数分别是:
    • whttp.ResponseWriter 用于构造响应。
    • r*http.Request 用于获取请求的信息(如请求头、请求体等)。

3.2 http.ListenAndServe

  • http.ListenAndServe(":8080", nil) 启动一个 HTTP 服务器并监听在 8080 端口,第二个参数 nil 表示使用默认的 ServeMux
  • 该函数是一个阻塞操作,直到服务器关闭。

4. HTTP 请求

在 HTTP 客户端中,使用 net/http 包发送请求并处理响应非常简单。以下是如何发送 GET 请求的示例:

package main

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

func main() {
    // 发起 GET 请求
    resp, err := http.Get("https://www.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 reading body:", err)
        return
    }

    // 打印响应内容
    fmt.Println("Response:", string(body))
}

4.1 常见 HTTP 方法

  • http.Get(url string):发送一个 GET 请求,返回一个 http.Response
  • http.Post(url string, contentType string, body io.Reader):发送一个 POST 请求,提交数据到服务器。
  • http.Head(url string):发送一个 HEAD 请求,获取响应头,不返回响应体。
  • http.PostForm(url string, data url.Values):发送一个 POST 请求,使用 application/x-www-form-urlencoded 编码提交表单数据。
  • http.NewRequest(method, url string, body io.Reader):创建一个 HTTP 请求,你可以用它构建自定义的 HTTP 请求(包括设置请求头等)。

5. 自定义 HTTP 请求

对于一些需要更多自定义的 HTTP 请求(如设置头、使用 PUT 方法等),可以使用 http.NewRequest 创建一个新的请求对象:

package main

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

func main() {
    // 创建一个新的 POST 请求
    req, err := http.NewRequest("POST", "https://www.example.com", bytes.NewBuffer([]byte(`{"name": "test"}`)))
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    // 设置请求头
    req.Header.Set("Content-Type", "application/json")

    // 创建 HTTP 客户端并发送请求
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error sending request:", err)
        return
    }
    defer resp.Body.Close()

    // 读取响应体
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error reading response:", err)
        return
    }

    // 输出响应内容
    fmt.Println("Response:", string(body))
}

6. HTTP 响应处理

每个 HTTP 响应都包含以下信息:

  • 状态码http.Response 中的 StatusCode 字段。
  • 响应体Body 字段,它是一个 io.ReadCloser,通常需要读取内容。
  • 头信息:通过 Header 字段获取响应头。

6.1 获取响应状态码

status := resp.StatusCode

6.2 获取响应头

contentType := resp.Header.Get("Content-Type")

7. 路由与请求多路复用

Go 中的 HTTP 服务器默认使用 http.ServeMux 作为多路复用器来管理 URL 路由。你可以使用 http.HandleFunc 注册 URL 路由和处理函数,但如果需要更多灵活性,可以使用 http.NewServeMux 创建一个新的路由器:

mux := http.NewServeMux()
mux.HandleFunc("/", handler)
mux.HandleFunc("/about", aboutHandler)
http.ListenAndServe(":8080", mux)

8. 中间件

Go 的 net/http 包本身没有内建的中间件机制,但你可以轻松地手动实现。中间件可以用于请求的预处理、身份验证、日志记录等:

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Request received:", r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", handler)
    mux.HandleFunc("/about", aboutHandler)

    // 使用中间件
    http.ListenAndServe(":8080", loggingMiddleware(mux))
}

9. HTTP 服务器的高级功能

  • TLS/SSL 支持:通过 http.ListenAndServeTLS 启动一个支持 HTTPS 的服务器。
    http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
    
  • 请求超时设置:可以使用 http.Client 设置请求超时,防止客户端在网络不通或服务器迟缓时无限期等待。
    client := &http.Client{
        Timeout: time.Second * 10, // 设置 10 秒超时
    }
    
  • 自定义 http.Server:可以使用 http.Server 对象来精确控制服务器的行为,如设置读取/写入超时、最大连接数等。
    server := &http.Server{
        Addr: ":8080",
        Handler: mux,
        ReadTimeout: time.Second * 5,
        WriteTimeout: time.Second * 10,
    }
    server.ListenAndServe()
    

10. 总结

net/http 是 Go 中实现 HTTP 服务和客户端的核心包,功能强大且灵活。它支持常见的 HTTP 请求和响应处理、路由、多路复用、TLS 加密、客户端自定义等功能。无论是构建一个简单的 Web 服务器,还是开发一个高性能的 HTTP 客户端,net/http 都提供了极其简洁且高效的 API。通过本包,Go 程序员可以轻松地处理 HTTP 相关的工作,并灵活地应对不同的场景。


标题:golang每日一库之net/http
作者:mooncakeee
地址:http://blog.dd95828.com/articles/2025/02/07/1738889655516.html
联系:scotttu@163.com