05-Web服务器练习
package main
import (
"fmt"
"net/http"
"os"
)
func OpenSendFile(fName string, w http.ResponseWriter) {
//pathFileName := "C:/itcast/test" + fNmae
pathFileName := "./05-Web服务器练习" + fName
fmt.Println("地址:",pathFileName)
f, err := os.Open(pathFileName)
if err != nil {
fmt.Println("Open err :", err)
w.Write([]byte("No such file or directol"))
return
}
defer f.Close()
buf := make([]byte,4096)
for {
n, _ := f.Read(buf) // 从本地将文件内容读取
if n == 0{
return
}
w.Write(buf[:n]) // 写到客户端(浏览器)上
}
}
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("客户端请求。 ", r.URL)
OpenSendFile(r.URL.String(), w)
}
func main() {
//注册回调函数。该回调函数会在服务器被访问时,自动被调用。
//http.HandleFunc("/itcast", myHandler)
http.HandleFunc("/", myHandler)
//绑定服务器监听地址
http.ListenAndServe("127.0.0.1:8000", nil)
}
写入自己的博客中才能记得长久