Golang(Handler入门)

我该如何对的起这句话呢?
熟练使用 Golang 进行 HTTP 服务开发,具备基础接口设计与健康检查实现经验

什么是HTTP?

这个我们都不陌生。TCP/UDP也知道吧。但是它们是如何实现的呢?

Gin用的太久了,很多底层的东西,我几乎不知道。

http服务,监听,处理。 监听路径,处理。

一个URL对应一个请求的处理器,构成了http请求的核心。

这就是http.Handle()的两个参数。

go 复制代码
func Handle(pattern string, handler Handler)

http.Handle是一切的起点。

pattern 是string,handler 的是Handler。

作为数据类型,string我们很好理解。但是Handler是什么呢?

我们来查看源码

go 复制代码
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

显然,Handler 是一个接口。任何一个实现了ServeHTTP(ResponseWriter, *Request)方法且无返回值的数据type,都可以作为Handler 来使用。

这就是第一种做法。

go 复制代码
package main

import (
	"net/http"
)

type my_handler struct{}

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

func main() {
	http.Handle("/", my_handler{})
	http.ListenAndServe("0.0.0.0:8080", nil)
}

同时,如果我们只需要写对应的处理逻辑,而不需要一个具体的结构体,再实现ServeHTTP呢?

这就出来了第2种方法:

go 复制代码
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// [Handler] that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

由于HandlerFunc 的特殊设计,导致我们可以将我们的具体的代码逻辑写成一个普通的函数,当然这个普通函数的函数签名和返回值与ServeHTTP一样。然后这个函数就可以作为HandlerFunc 的参数构建一个实例,这个实例就可以作为Handler 来使用。

go 复制代码
package main

import (
	"net/http"
)

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

func main() {
	http.Handle("/", http.HandlerFunc(rootHandler))
	http.ListenAndServe("0.0.0.0:8080", nil)
}

当然也可以直接写匿名函数:

go 复制代码
package main

import (
	"net/http"
)

func main() {
	http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello World"))
	}))
	http.ListenAndServe("0.0.0.0:8080", nil)
}

难道我们不能直接将普通函数作为参数传入吗?能不能再多封装一点方便我们做开发?

那就是第3种方法:

go 复制代码
package main

import (
	"net/http"
)

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

func main() {
	http.HandleFunc("/", rootHandler)
	http.ListenAndServe("0.0.0.0:8080", nil)
}

当然,我们也可以写匿名函数:

go 复制代码
package main

import (
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello World"))
	})
	http.ListenAndServe("0.0.0.0:8080", nil)
}
相关推荐
choke2331 小时前
[特殊字符] Python异常处理
开发语言·python
云中飞鸿1 小时前
linux中qt安装
开发语言·qt
少控科技2 小时前
QT第6个程序 - 网页内容摘取
开发语言·qt
darkb1rd2 小时前
八、PHP SAPI与运行环境差异
开发语言·网络安全·php·webshell
历程里程碑2 小时前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法
郝学胜-神的一滴2 小时前
深入浅出:使用Linux系统函数构建高性能TCP服务器
linux·服务器·开发语言·网络·c++·tcp/ip·程序人生
承渊政道2 小时前
Linux系统学习【Linux系统的进度条实现、版本控制器git和调试器gdb介绍】
linux·开发语言·笔记·git·学习·gitee
JQLvopkk2 小时前
C# 轻量级工业温湿度监控系统(含数据库与源码)
开发语言·数据库·c#
玄同7652 小时前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
czy87874752 小时前
深入了解 C++ 中的 `std::bind` 函数
开发语言·c++