【go从零单排】HTTP客户端和服务端

🌈Don't worry , just coding!
内耗与overthinking只会削弱你的精力,虚度你的光阴,每天迈出一小步,回头时发现已经走了很远。

📗概念

在 Go 语言中,net/http 包提供了强大的 HTTP 客户端和服务器功能。

💻代码

HTTP 客户端

go 复制代码
package main

import (
	//bufio:用于缓冲 I/O 操作,提供了扫描输入的功能。
	//fmt:用于格式化输入输出。
	//net/http:提供 HTTP 客户端和服务器的功能。
	"bufio"
	"fmt"
	"net/http"
)

func main() {
	//使用 http.Get 方法发送 GET 请求到指定的 URL
	//返回一个 HTTP 响应和一个错误对象。
	resp, err := http.Get("https://www.baidu.com")
	if err != nil {
		panic(err)
	}
	//使用 defer 关键字确保在 main 函数结束时关闭响应体,释放资源。
	defer resp.Body.Close()
	//打印响应的状态码resp.Status
	fmt.Println("Response status:", resp.Status)
	//创建一个新的扫描器,用于逐行读取响应体的内容。
	scanner := bufio.NewScanner(resp.Body)
	//使用循环读取响应的前五行内容。scanner.Scan() 方法返回 true 表示还有更多的内容可供读取,scanner.Text() 返回当前行的文本。
	for i := 0; scanner.Scan() && i < 5; i++ {
		fmt.Println(scanner.Text())
	}
	//检查扫描过程中是否发生错误。如果有错误,终止程序并输出错误信息。
	if err := scanner.Err(); err != nil {
		panic(err)
	}
}

HTTP 服务端

c 复制代码
package main

import (
	"fmt"
	//net/http:提供 HTTP 客户端和服务器的功能。
	"net/http"
)

// 定义了一个名为 hello 的处理函数,它接受两个参数:
// w http.ResponseWriter:用于构建 HTTP 响应。
// req *http.Request:包含了 HTTP 请求的信息。
func hello(w http.ResponseWriter, req *http.Request) {
	//使用 fmt.Fprintf 向响应写入字符串 "hello"。
	fmt.Fprintf(w, "hello\n")
}

// 定义了一个名为 headers 的处理函数,功能是输出请求的所有 HTTP 头:
func headers(w http.ResponseWriter, req *http.Request) {
	//使用 req.Header 获取请求头的键值对。
	for name, headers := range req.Header {
		//遍历每个头的名称和对应的值,并将其写入响应中。
		for _, h := range headers {
			fmt.Fprintf(w, "%v: %v\n", name, h)
		}
	}
}

func main() {
	//在 main 函数中,使用 http.HandleFunc 注册了两个路由:
	///hello 路由会调用 hello 函数。
	///headers 路由会调用 headers 函数。

	http.HandleFunc("/hello", hello)
	http.HandleFunc("/headers", headers)
	//启动 HTTP 服务器,监听在端口 8090。nil 表示使用默认的多路复用器。
	http.ListenAndServe(":8090", nil)
}

路由和多路复用

c 复制代码
mux := http.NewServeMux()
mux.HandleFunc("/hello", helloHandler)
mux.HandleFunc("/goodbye", goodbyeHandler)
http.ListenAndServe(":8080", mux)

中间件

c 复制代码
func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Request received:", r.Method, r.URL)
        next.ServeHTTP(w, r)
    })
}

JSON处理

c 复制代码
package main

import (
    "encoding/json"
    "net/http"
)

type Message struct {
    Text string `json:"text"`
}

func jsonHandler(w http.ResponseWriter, r *http.Request) {
    msg := Message{Text: "Hello, JSON!"}
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(msg)
}

🔍理解

  • 使用 http.ListenAndServe 启动服务器。
  • 使用 http.Get、http.Post 等函数可以轻松发送 HTTP 请求。
  • http.Request 对象包含了请求的信息,例如请求方法、URL、头信息等。
  • http.ResponseWriter 用于构建和发送 HTTP 响应。

💪无人扶我青云志,我自踏雪至山巅。

相关推荐
风逸hhh1 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮1 小时前
Python训练第四十三天
开发语言·python
ascarl20102 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc3 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗3 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长3 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao4 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码4 小时前
STL解析——list的使用
开发语言·c++
SoFlu软件机器人4 小时前
智能生成完整 Java 后端架构,告别手动编写 ControllerServiceDao
java·开发语言·架构
英英_4 小时前
视频爬虫的Python库
开发语言·python·音视频