- 将原始main函数中的HTTP处理逻辑拆分到独立文件 - 新增main1.go实现基础HTTP服务器功能 - 新增main2.go增强路由处理和重定向逻辑 - 新增main3.go使用标准库处理程序优化代码结构 - 更新main.go调用新的main3函数并注释其他入口点 - 移除main.go中旧的HTTP处理相关导入和类型定义
41 lines
959 B
Go
41 lines
959 B
Go
package main
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
type StringHandle2 struct {
|
|
message string
|
|
}
|
|
|
|
func (sh *StringHandle2) 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)
|
|
|
|
switch request.URL.Path {
|
|
case "/favicon.ico":
|
|
http.NotFound(writer, request)
|
|
case "/message":
|
|
writeLen, err := io.WriteString(writer, sh.message)
|
|
if err != nil {
|
|
Printfln("ServeHTTP Error: %v", err)
|
|
return
|
|
}
|
|
Printfln("ServeHTTP Wrote %d bytes", writeLen)
|
|
default:
|
|
http.Redirect(writer, request, "/message", http.StatusTemporaryRedirect)
|
|
}
|
|
Printfln("--------------\n")
|
|
}
|
|
|
|
func main2() {
|
|
err := http.ListenAndServe("localhost:5000", &StringHandle2{message: "Hello World!"})
|
|
if err != nil {
|
|
Printfln("ListenAndServe Error: %v", err)
|
|
return
|
|
}
|
|
}
|