mirror of
https://github.com/DefectingCat/DefectingCat.github.io
synced 2025-07-16 01:01:38 +00:00
update test 更新文章 1. 测试新主题 挖坑 挖坑 update config 更新文章 1. 简易FaaS平台 更新文章 1. 修复错误 更新文章:Promise信任问题 update theme 1. 合并js post: update notedly fix: update faas feature: change theme * fix: comment * feature: pgp * fix: delete local file post: update darkmode update: update dependencies fix: navbar in post incorrect height * pre code adapt to dark mode update new post useCallback update dependencies new post tiny router * add static files update vue tiny router 添加备案 * 更新依赖 add post Add ignore file
32 lines
694 B
Markdown
32 lines
694 B
Markdown
## 处理请求
|
||
|
||
每进来一个 HTTP 请求,Handler 都会为其创建一个 goroutine。默认 Handler `http.DefaulServeMux`。
|
||
|
||
`http.ListenAndServe(":4000", nil)` 第二个参数就是 Handler,为 nil 时,就是 `DefaulServeMux`。
|
||
|
||
`DefaulServeMux` 是一个 multiplexer。
|
||
|
||
### 编写 Handler
|
||
|
||
Handler 是一个 struct,它需要实现一个 `ServeHTTP()` 方法。
|
||
|
||
```go
|
||
type myHandler struct {
|
||
}
|
||
|
||
func (m *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||
_, err := w.Write([]byte("Hello world"))
|
||
if err != nil {
|
||
return
|
||
}
|
||
}
|
||
```
|
||
|
||
注册一个 Handler 到 multiplexer 需要使用 `http.Handle`
|
||
|
||
```go
|
||
http.Handle("/hello", &mh)
|
||
http.Handle("/about", &a)
|
||
```
|
||
|