GO学习之网络通信(Net/Http)

113 阅读1分钟

在Go语言中,通过 net/http包实现网络通信和HTTP操作非常方便。以下是关于网络通信和HTTP的简要介绍:

  1. 导入包:  首先,你需要导入 net/http包来使用其中的函数和结构体。

    import (
        "net/http"
    )
    
  2. 创建HTTP服务器:  你可以使用 http.ListenAndServe函数来创建一个HTTP服务器,监听指定的端口。

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })
    
    http.ListenAndServe(":8080", nil)
    

    上面的代码创建了一个简单的HTTP服务器,当访问根路径时,返回 "Hello, World!"。

  3. 发送HTTP请求:  使用 http.Get函数可以发送GET请求到指定的URL,并获取响应。

    response, err := http.Get("https://example.com")
    if err != nil {
        // 处理错误
    }
    defer response.Body.Close()
    
    // 读取响应内容
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        // 处理错误
    }
    
    // 打印响应内容
    fmt.Println(string(body))
    

    上述代码发送GET请求到 "example.com" 并输出响应内容。

  4. 自定义HTTP请求:  你可以使用 http.NewRequest函数创建自定义的HTTP请求,并发送到指定的URL。

    request, err := http.NewRequest("POST", "https://example.com", nil)
    if err != nil {
        // 处理错误
    }
    
    // 设置请求头
    request.Header.Set("Content-Type", "application/json")
    
    // 发送请求
    client := &http.Client{}
    response, err := client.Do(request)
    if err != nil {
        // 处理错误
    }
    defer response.Body.Close()
    
    // 处理响应
    // ...
    

通过 net/http包,Go语言提供了强大且简洁的方式来进行网络通信和HTTP操作。你可以根据需求创建HTTP服务器、发送HTTP请求以及处理响应。


香港五网CN2网络云服务器链接:www.tsyvps.com

蓝易云香港五网CN2 GIA/GT精品网络服务器。拒绝绕路,拒绝不稳定。