# Go语言Windows环境Web服务器实现 下面是一个使用Go语言在Windows环境下实现的简单Web服务器程序,包含基本的路由处理和静态文件服务功能。 ```go package main import ( "fmt" "log" "net/http" "os" "path/filepath" ) func main() { // 设置路由处理 http.HandleFunc("/", rootHandler) http.HandleFunc("/hello", helloHandler) // 设置静态文件服务 staticDir := "./static" http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir)))) // 创建静态文件目录 if err := os.MkdirAll(staticDir, 0755); err != nil { log.Printf("创建静态目录失败: %v", err) } // 启动服务器 port := "8080" log.Printf("服务器启动,监听端口 %s...", port) log.Fatal(http.ListenAndServe(":"+port, nil)) } // 根路径处理 func rootHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } fmt.Fprintf(w, "欢迎访问Go Web服务器") } // /hello路径处理 func helloHandler(w http.ResponseWriter, r *http.Request) { name := r.URL.Query().Get("name") if name == "" { name = "访客" } fmt.Fprintf(w, "你好, %s!", name) } ``` ## 代码说明 1. 程序创建了一个监听8080端口的Web服务器 2. 实现了三个主要功能: - 根路径("/")返回欢迎信息 - "/hello"路径支持查询参数name - "/static/"路径提供静态文件服务 ## 使用说明 1. 将代码保存为`main.go` 2. 在命令行中运行:`go run main.go` 3. 访问以下URL测试: - http://localhost:8080/ - http://localhost:8080/hello?name=张三 - 在项目目录下创建static文件夹并放入文件,通过http://localhost:8080/static/文件名访问 ## 编译为Windows可执行文件 ```bash go build -o webserver.exe main.go ``` ## 额外注意事项 1. 在生产环境中应考虑使用更高效的路由器如gorilla/mux或gin框架替代标准库的简单路由 2. 静态文件服务应考虑添加缓存控制头以提高性能 3. Windows防火墙可能会阻止端口访问,需要确保防火墙允许8080端口的入站连接 [2025-07-04 19:22:16 | AI写代码神器 | 579点数解答]