refactor(server):重构HTTP服务器实现
- 将原始main函数中的HTTP处理逻辑拆分到独立文件 - 新增main1.go实现基础HTTP服务器功能 - 新增main2.go增强路由处理和重定向逻辑 - 新增main3.go使用标准库处理程序优化代码结构 - 更新main.go调用新的main3函数并注释其他入口点 - 移除main.go中旧的HTTP处理相关导入和类型定义
This commit is contained in:
46
24-httpserver/httpserver/main1.go
Normal file
46
24-httpserver/httpserver/main1.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type StringHandle1 struct {
|
||||
message string
|
||||
}
|
||||
|
||||
func (sh *StringHandle1) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
|
||||
Printfln("\n----------\nMethod: %v Protocol: %v Host: %v URL: %v URL.Host: %v RequestURI: %v",
|
||||
request.Method, request.Proto, request.Host,
|
||||
request.URL.String(), request.URL.Host, request.RequestURI)
|
||||
for name, val := range request.Header {
|
||||
Printfln("Header: %v = %v", name, val)
|
||||
}
|
||||
Printfln("RemoteAddr: %v", request.RemoteAddr)
|
||||
Printfln("ContentLength: %v", request.ContentLength)
|
||||
Printfln("Body: %v", request.Body)
|
||||
Printfln("TLS: %v", request.TLS)
|
||||
Printfln("--------------")
|
||||
if request.URL.Path == "/favicon.ico" {
|
||||
Printfln("Request for favicon.ico detected - returning 404")
|
||||
Printfln("--------------\n")
|
||||
writer.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
writeLen, err := io.WriteString(writer, sh.message)
|
||||
if err != nil {
|
||||
Printfln("ServeHTTP Error: %v", err)
|
||||
return
|
||||
}
|
||||
Printfln("ServeHTTP Wrote %d bytes", writeLen)
|
||||
Printfln("--------------\n")
|
||||
}
|
||||
|
||||
func main1() {
|
||||
err := http.ListenAndServe("localhost:5000", &StringHandle1{message: "Hello World!"})
|
||||
if err != nil {
|
||||
Printfln("ListenAndServe Error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user