1.监听一个端口的普通http
func listenServer() {
http.Handle("/", http.HandlerFunc(lServe))
http.ListenAndServe(":3002", nil)
}
func lServe(w http.ResponseWriter, r *http.Request) {
log.Println("listen serve")
}
2.自定义路由器,监听多个端口
func muxServer() {
mx := http.NewServeMux()
mx.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Println("this is 3002")
})
go http.ListenAndServe(":3002", mx)//注意这里,不开协程直接就监听阻塞了
mt := http.NewServeMux()
mt.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Println("there is 3003")
})
http.ListenAndServe(":3003", mt)//这里开启第二个端口监听
}
3.使用tcp自定义监听多个端口,带上中间件
func sever() {
mx := http.NewServeMux()
l, err := net.Listen("tcp", ":3001")
if err != nil {
log.Println(err)
return
}
mx.HandleFunc("/aa", test)
mx.HandleFunc("/bb", test2)
http.Serve(l, middle(mx))
}
func test(w http.ResponseWriter, r *http.Request) {
log.Println("aa")
}
func test2(w http.ResponseWriter, r *http.Request) {
log.Println("bb")
}
func middle(next http.Handler) http.Handler {
return next
//这里可以写入条件,符合的直接反馈next,继续执行,如果有其他逻辑按下面的方法进行逻辑处理
// return http.HandlerFunc(
// func(w http.ResponseWriter, r *http.Request) {
// log.Println("123")
// },
// )
}
有疑问加站长微信联系(非本文作者)