文章目录[隐藏]
golang web 服务器
程序读取当前目录文件
package main
import (
"fmt"
"log"
"net/http"
)
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
// fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
fmt.Println("path:", r.URL.Path)
// fmt.Println("scheme:", r.URL.Scheme)
fmt.Fprint(w, string(s))
}
func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, fmt.Sprintf("%v", s))
}
func faviconHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./favicon.ico")
}
func main() {
fmt.Println("Golang 服务器已启动,监听端口 4001")
http.Handle("/", String("Home Page 首页"))
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
http.HandleFunc("/favicon.ico", faviconHandler)
// 下载文件服务
http.Handle("/down/", http.StripPrefix("/down/", http.FileServer(http.Dir("./"))))
err := http.ListenAndServe("0.0.0.0:4001", nil)
if err != nil {
log.Fatal(err)
}
}
运行界面

文件浏览

问题
file server 下载一个大于 2GB 的文件时,总是下载到 1G 左右就结束下载,但是没有报告错误。
最终的结果是我发现问题出在 net/sendfile_windows.go 这个文件的 sendFile 函数里。
此问题在 win 环境下发生。目前没有解决
linux 大文件下载测试通过 。
“`golang
func sendFile(fd *netFD, r io.Reader) (written int64, err error, handled bool)
“`
golang 源码中这个函数前有一行注释:
// sendFile copies the contents of r to c using the TransmitFile
// system call to minimize copies.
//
// if handled == true, sendFile returns the number of bytes copied and any
// non-EOF error.
//
// if handled == false, sendFile performed no work.
//
// Note that sendfile for windows does not support >2GB file.
func sendFile(fd *netFD, r io.Reader) (written int64, err error, handled bool) {