golang http

函数 说明
http.ServeMux 是 Go 语言标准库中的一个多路复用器(multiplexer)。它用于路由和处理 HTTP 请求,将请求分发到相应的处理器函数。
http.HandleFunc 是 Go 语言标准库中的一个函数,用于注册处理器函数来处理 HTTP 请求。它是对 http.ServeMux 的简化封装,方便快速实现路由功能。
http.Handler 接口定义了一个方法 ServeHTTP,该方法接收两个参数:ResponseWriter 和 Request。它用于处理传入的 HTTP 请求并生成相应的 HTTP 响应。
http.ListenAndServe 是 Go 语言标准库中的一个函数,用于启动一个 HTTP 服务器并开始监听指定的地址和端口,以接收和处理传入的 HTTP 请求。

一、使用 http.ServeMux 的一些基本操作:

1、创建一个新的 ServeMux:

cpp 复制代码
mux := http.NewServeMux()

2、注册处理器函数并指定 URL 路径:

cpp 复制代码
mux.HandleFunc("/hello", helloHandler)
mux.HandleFunc("/foo", fooHandler)
//在上面的例子中,当 /hello 路径接收到请求时,helloHandler 函数将被调用;当 /foo 路径接收到请求时,fooHandler 函数将被调用。

3、创建一个 HTTP 服务器并指定 ServeMux 作为处理器:

cpp 复制代码
server := &http.Server{
    Addr:    ":8080",
    Handler: mux,
}
//创建了一个监听 8080 端口的 HTTP 服务器,并将 mux 作为处理器。

4、启动服务器:

cpp 复制代码
err := server.ListenAndServe()
if err != nil {
    panic(err)
}
//这会开始监听指定的端口,并开始接受和处理请求。

完整示例:

cpp 复制代码
package main

import (
	"net/http"
	"time"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)

	server := &http.Server{
		Addr:         ":8080",
		Handler:      http.TimeoutHandler(mux, 2*time.Second, "Timeout"),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	err := server.ListenAndServe()
	if err != nil {
		panic(err)
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	time.Sleep(3 * time.Second) // 模拟长时间处理的操作

	w.Write([]byte("Hello, World!"))
}
cpp 复制代码
package main

import (
	"net/http"
	"time"
)

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8081", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello, World!"))
}

-------------end

相关推荐
我不会插花弄玉21 小时前
5.应⽤层协议HTTP【由浅入深-网络】
http
如夏倾城2 天前
QUIC——HTTP/3 的唯一底层传输协议 及 0-RTT恢复
网络·网络协议·tcp/ip·安全·http
程序员Query2 天前
day01-认识Go语言 + golang环境的安装
开发语言·后端·golang
Thanks_ks3 天前
HTTPS:浏览器地址栏那把锁的工作原理
http·网络安全·https·tls·加密算法·数字证书·中间人攻击
喵了几个咪3 天前
GoWind Flow 拆解:一个 Go 工作流引擎与它的双模式设计器
开发语言·人工智能·后端·golang
codeejun3 天前
每日一Go·MySQL-14、慢 SQL 产生原因全解
sql·mysql·golang
杨凯凡3 天前
Spring Boot 大文件下载如何实现断点续传?HTTP Range、206 与 416 实战
spring boot·后端·http
FungLeo4 天前
成为全栈·Vue 管理后台篇·用 fetch 建一层可控的请求内核
前端·javascript·vue.js·http·fetch·formdata·接口封装
wuyk5554 天前
Spider-第03讲-HTTP速通与读懂响应
网络·爬虫·网络协议·http
杨凯凡5 天前
Spring Framework 7 HTTP Interface 实战:声明式 RestClient、超时与测试
java·spring·http