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

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

相关推荐
工具人55554 小时前
python 环境问题
开发语言·python
小年糕是糕手4 小时前
【C++】string类(二)
开发语言·数据结构·c++·程序人生·算法·leetcode·数字货币
小鸡吃米…4 小时前
Python编程语言面试问题三
开发语言·python·面试
周杰伦_Jay4 小时前
【Go语言面试题核心详细解析】基础语法、并发编程、内存管理、接口、错误处理
开发语言·后端·golang
福尔摩斯张4 小时前
Linux Kernel 设计思路与原理详解:从“一切皆文件“到模块化架构(超详细)
java·linux·运维·开发语言·jvm·c++·架构
smile_Iris4 小时前
Day 41 早停策略和模型权重的保存
开发语言·python
傅里叶的耶4 小时前
C++ Primer Plus(第6版):第四章 复合类型
开发语言·c++
MediaTea4 小时前
Python:接口隔离原则(ISP)
开发语言·网络·python·接口隔离原则
Clarence Liu4 小时前
Golang slice 深度原理与面试指南
开发语言·后端·golang
moxiaoran57534 小时前
Go语言中的切片
golang