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

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

相关推荐
艾莉丝努力练剑14 分钟前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
清源妙木真菌21 分钟前
应用层协议——HTTP
网络·网络协议·http
CHEN5_0229 分钟前
【Java基础面试题】Java基础概念
java·开发语言
杜子不疼.2 小时前
《Python学习之字典(一):基础操作与核心用法》
开发语言·python·学习
落霞的思绪2 小时前
Java设计模式详细解读
java·开发语言·设计模式
阿巴~阿巴~2 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
java1234_小锋3 小时前
一周学会Matplotlib3 Python 数据可视化-绘制自相关图
开发语言·python·信息可视化·matplotlib·matplotlib3
甄超锋3 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
凢en4 小时前
Perl——qw()函数
开发语言·perl
郝学胜-神的一滴4 小时前
基于C++的词法分析器:使用正则表达式的实现
开发语言·c++·程序人生·正则表达式·stl