4.01 课后复习-Server

本节课工程结构:

(base) yanglei@yuanhong v4-rc % tree ./
./

0 directories, 0 files

PART1. Server

1.1 接口定义

serverInterface.go:

package v4_rc

import "net/http"

// ServerInterface 服务器实体接口
// 用于定义服务器实体的行为
type ServerInterface interface {
	// Handler 组合http.Handler接口
	http.Handler
	// Start 启动服务器
	Start(addr string) error
}

这里组合http.Handler,是为了最终调用http.Serve(),使得该方法的第2个参数是我们自己实现的http.Handler接口的实现.这一点我当时整理笔记时其实是不理解的,我复习时也发现我解释不清楚这件事.故补充.

1.2 实现接口的Start()方法

1.2.1 实现Start()方法

server.go:

net.Listen()http.Serve()之间做框架的操作,例如生命周期回调.

1.2.2 测试

server_test.go:

1.3 定义注册路由的方法addRoute()

1.3.1 定义Context

context.go:

这里其实是为了定义HandleFunc,而定义HandleFunc是为了定义AddRoute().

1.3.2 定义HandleFunc

handle_func.go

1.3.3 在接口上定义addRoute()

server_interface.go:

1.3.4 在实现上定义addRoute()

server.go:

1.3.5 定义addRoute()的衍生方法

或者也可以说是暴露给使用者的方法

server.go:

PART2. 完成Server时的工程结构

附录

1. 可以魔改的点

  • 将addr作为Server的一个成员属性

  • 我看原生的http.Server结构体为了支持HTTPS,组合了一个*tls.Config,可以尝试

Last updated