zoukankan      html  css  js  c++  java
  • 简析 Golang net/http 包

    net/http 包涵盖了与 HTTP 请求发送和处理的相关代码。虽然包中定义了大量类型、函数,但最重要、最基础的概念只有两个:ServeMux 和 Handler。

    ServeMux 是 HTTP 请求多路复用器(即路由器,HTTP request router),记录着请求路由表。对于每一个到来的请求,它都会比较请求路径和路由表中定义的 URL 路径,并调用指定的 handler 来处理请求。

    Handler 的任务是返回一个 response 消息,并把 header 和 body 写入消息中。任何对象只要实现了 http.Handler 接口的接口方法 ServeHTTP 就可以成为 handler。ServeHTTP 的方法签名是:ServeHTTP(ResponseWriter, *Request)。

    我们先通过以下代码,快速了解它们的功能:

    package main
    
    import (
    	"io"
    	"log"
    	"net/http"
    )
    
    type myHandler struct{}
    
    func (h *myHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
    	io.WriteString(w, "Hello world!
    ")
    }
    
    func main() {
    	mux := http.NewServeMux()
    
    	h := new(myHandler)
    	mux.Handle("/foo", h)
    
    	log.Println("Listening...")
    	http.ListenAndServe(":3000", mux)
    }
    

    代码拆解如下:

    1. 首先,使用 http.NewServeMux 方法生成一个 HTTP 请求路由器。该方法内部逻辑其实是 return new(ServeMux);
    2. 然后我们创建了一个自定义 handler,功能是返回 Hello world! 文本;
    3. 接着,通过 mux.Handle 函数,将该 handler 注册到新创建的 ServeMux 对象中。这样 handler 就可以和 URL 路径 /foo 关联了;
    4. 最后,我们创建一个 server 并在 3000 端口监听请求。这里 ListenAndServe 的方法签名是 ListenAndServe(addr string, handler Handler),我们之所以可以 ServeMux 作为第二个参数,是因为 ServeMux 实现了 ServeHTTP 接口方法。

    掌握了这两个概念,基本上其他概念 比如 Server,Client 类型、HandleFunc 函数作为 handler 等, 就都很好理解了。另外, 如果你对包中 HTTP 相关的概念不是很清楚的话,比如 TCP keep-alive、proxy、redirect、cookie、TLS,建议阅读《 HTTP: The Definitive Guide 》补充知识。

    参考文献:A Recap of Request Handling in Go

  • 相关阅读:
    批归一化(Batch Normalization)
    NLP | 文本风格迁移 总结
    LeetCode: Word Ladder
    LeetCode: Longest Consecutive Sequence
    LeetCode: Sum Root to Leaf Numbers
    LeetCode: Surrounded Regions
    LeetCode: Palindrome Partition
    LeetCode: Clone Graph
    LeetCode: Gas Station
    LeetCode: Candy
  • 原文地址:https://www.cnblogs.com/huanggze/p/11409999.html
Copyright © 2011-2022 走看看