Go中 net/http 使用

转载请注明出处:

  net/http是Go语言标准库中的一个包,提供了实现HTTP客户端和服务器的功能。它使得编写基于HTTP协议的Web应用程序变得简单和方便。

  net/http包的主要用途包括:

  1. 实现HTTP客户端:可以发送HTTP请求并接收服务器的响应。

  2. 实现HTTP服务器:可以创建一个HTTP服务器,接受客户端的请求并返回响应

1.实现HTTP客户端

1.1发送GET请求:

package main  import (     "fmt"     "io/ioutil"     "net/http" )  func main() {     // 发送GET请求     resp, err := http.Get("https://www.baidu.com")     if err != nil {         fmt.Println("请求失败:", err)         return     }     defer resp.Body.Close()      // 读取响应内容     body, err := ioutil.ReadAll(resp.Body)     if err != nil {         fmt.Println("读取响应失败:", err)         return     }      fmt.Println("响应内容:", string(body)) }

  上面使用http.Client创建了一个HTTP客户端对象,并通过其Get方法发送了一个GET请求。然后通过ioutil.ReadAll方法读取响应的内容,并打印出来。

  其运行之后结果如下:

            Go中 net/http 使用

 1.2 发送POST请求

package main  import (     "fmt"     "io/ioutil"     "net/http"     "strings" )  func main() {     // POST请求数据     payload := strings.NewReader("name=John&age=30")      // 发送POST请求     resp, err := http.Post("https://api.example.com/submit", "application/x-www-form-urlencoded", payload)     if err != nil {         fmt.Println("请求失败:", err)         return     }     defer resp.Body.Close()      // 读取响应内容     body, err := ioutil.ReadAll(resp.Body)     if err != nil {         fmt.Println("读取响应失败:", err)         return     }      fmt.Println("响应内容:", string(body)) }

  通过http.Post方法发送了一个POST请求,并从响应中读取了内容。需要注意的是,第二个参数指定了请求的Content-Type为application/x-www-form-urlencoded,并且通过strings.NewReader创建了请求体。

1.3自定义请求

package main  import (     "fmt"     "io/ioutil"     "net/http" )  func main() {     // 创建一个自定义请求     req, err := http.NewRequest("GET", "https://api.example.com/data", nil)     if err != nil {         fmt.Println("创建请求失败:", err)         return     }      // 可以设置请求头部信息     req.Header.Add("Authorization", "Bearer token123")      // 发送自定义请求     client := &http.Client{}     resp, err := client.Do(req)     if err != nil {         fmt.Println("请求失败:", err)         return     }     defer resp.Body.Close()      // 读取响应内容     body, err := ioutil.ReadAll(resp.Body)     if err != nil {         fmt.Println("读取响应失败:", err)         return     }      fmt.Println("响应内容:", string(body)) }

  上面首先使用http.NewRequest方法创建了一个自定义的GET请求,然后可以通过req.Header.Add方法设置请求头部信息。最后使用client.Do方法发送自定义请求,并从响应中读取内容。

2.HTTP服务器

2.1创建HTTP服务器:

// 定义处理器函数 func helloHandler(w http.ResponseWriter, r *http.Request) {     fmt.Fprint(w, "Hello, World!") }  // 注册处理器函数 http.HandleFunc("/", helloHandler)  // 启动HTTP服务器 err := http.ListenAndServe(":8080", nil) if err != nil {     fmt.Println("Server error:", err) }

  上面定义了一个处理器函数helloHandler,该函数对所有的HTTP请求都返回"Hello, World!"。使用http.HandleFunc方法将处理器函数注册到根路径"/"上。然后通过http.ListenAndServe方法启动了一个监听在端口8080的HTTP服务器。

  当有客户端请求到达时,服务器会调用相应的处理器函数来处理请求并返回响应。

2.2 实现路由

  net/http中,路由是指根据不同的URL路径来匹配和执行相应的处理函数。通过路由,我们可以将不同的URL请求映射到不同的处理逻辑上。

  net/http包提供了http.HandleFunchttp.Handle两个方法用于注册路由处理函数。

  1. http.HandleFunc方法:

    http.HandleFunc方法允许我们直接指定一个处理函数来处理特定的URL路径。示例代码如下:

// 定义处理函数 func helloHandler(w http.ResponseWriter, r *http.Request) {     fmt.Fprint(w, "Hello, World!") }  // 注册处理函数 http.HandleFunc("/hello", helloHandler)

  上面定义了一个处理函数helloHandler,当客户端请求路径为"/hello"时,服务器会调用该函数进行处理并返回"Hello, World!"。

  2. http.Handle方法:

  http.Handle方法允许我们使用自定义的处理器类型来实现更灵活的路由功能。示例代码如下:

// 定义自定义处理器类型 type MyHandler struct{}  // 实现处理器接口的ServeHTTP方法 func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {     fmt.Fprint(w, "Custom Handler") }  // 创建自定义处理器对象 myHandler := &MyHandler{}  // 注册处理器 http.Handle("/custom", myHandler)

  上面定义了一个自定义处理器类型MyHandler,并在该类型上实现了ServeHTTP方法。当客户端请求路径为"/custom"时,服务器会调用ServeHTTP方法来处理请求并返回"Custom Handler"。

 

发表评论

评论已关闭。

相关文章