package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
)
type HandlerStruct struct {
content string
}
//HandlerStruct Handler对象
func (handler *HandlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, handler.content)
}
func Handler(w http.ResponseWriter, req *http.Request) {
// 判断请求类型
if req.Method != "GET" {
w.WriteHeader(500)
fmt.Fprintf(w, "requrie get method")
return
}
if req.URL.Path == "handleFunc" {
w.WriteHeader(200)
//
fmt.Fprintf(w, "Hello word")
return
} else {
w.WriteHeader(200)
//
fmt.Fprintf(w, "muxHandleFunc hello word")
return
}
}
func main() {
//1. 路由,func(w http.ResponseWriter, r *http.Requests)
//http.HandleFunc("/handleFunc", Handler)
//2. 路由,ServeHTTP(ResponseWriter, *Request) 实现http.Handler接口的类型的实例
//http.Handle("/handle", &HandlerStruct{content: "Hello word"})
// ListenAndServe监听TCP网络地址addr,然后调用handler,
//handler来处理传入连接的请求,没handler,默认用DefaultServeMux,ListenAndServe总是返回一个非nil错误
//已接受的连接被配置为启用TCP保持连接。
// HandlerFunc实际上是将handler函数做了一个类型转换
//http.ListenAndServe(":8080", nil)
// DefaultServeMux是service使用的默认ServeMux
// DefaultServeMux.Handle(pattern, handler) 路由注册
// ServeMux 服务复用器
// 注册路由的处理函数最后都会用到ServerMux结构的Handle方法去注册路由处理函数。
/* 相当于路由和handler映射表
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry key 路由:{路由,处理方法}
es []muxEntry // slice of entries sorted from longest to shortest.
hosts bool // whether any patterns contain hostnames
}
type muxEntry struct {
h Handler 处理方法
pattern string 路由
}
*/
//创建一个ServeMux实例取代默认的DefaultServeMux
//3.
mux := http.NewServeMux()
mux.HandleFunc("/muxhandleFunc", Handler)
//4.
mux.Handle("/muxhandle", &HandlerStruct{content: "muxHandle hello word"})
//
// http.ListenAndServe(":8080", mux)
// 创建server
server := &http.Server{
Addr: ":8080",
Handler: mux,
}
// 创建监听管道 终端控制进程结束
sigCh := make(chan os.Signal)
// 将信号写进sigCh,监听指定信号 ctrl c ,kill
signal.Notify(sigCh, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigCh
// 通过监听信号,关闭服务,Shutdown优雅地关闭服务器而不中断任何服务
if err := server.Shutdown(context.Background()); err != nil {
log.Fatal("Shutdown server:", err)
}
}()
log.Println("Starting HTTP server...")
// 开启服务
err := server.ListenAndServe()
if err != nil {
if err == http.ErrServerClosed {
log.Print("Server closed under request")
} else {
log.Fatal("Server closed unexpected")
}
}
}
|