【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 响应。

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

相关推荐
AKA__Zas5 分钟前
初识多线程(3.0)
java·开发语言·学习方法
小杍随笔12 分钟前
【Rust 工具链管理工具再升级!rust-verse v1.3.1 ~ v1.3.5 最新更新深度解析】
开发语言·后端·rust
姚不倒20 分钟前
从零实现一个基于 Ollama + Go + MySQL 的 Text-to-SQL 智能体(M1 实战)
sql·mysql·云原生·golang
大数据三康30 分钟前
在spyder进行的遗传算法练习
开发语言·python·算法
Vallelonga34 分钟前
Rust 从结构体中取字段的引用
开发语言·rust
社交怪人1 小时前
【球体体积】信息学奥赛一本通C语言解法(题号1030)
c语言·开发语言
froginwe111 小时前
Foundation 顶部导航栏详解
开发语言
沐知全栈开发1 小时前
MySQL 运算符详解
开发语言
java修仙传1 小时前
Java 实习日记:断面分析基态限额为空问题的排查与修复
java·开发语言·bug·实习
njsgcs1 小时前
我仓库内cad python 有哪些应用到聚类的方法
开发语言·python·聚类