用golang写一个具有下载功能的http server
时间: 2023-03-07 17:01:23 浏览: 161
深入理解Golang之http server的实现
很高兴为您解答。Golang可以很容易地编写一个具有下载功能的HTTP服务器,只需要几行代码即可实现。可以使用net/http包来实现,下面是一个示例:package mainimport (
"fmt"
"io"
"net/http"
)func downloadFile(w http.ResponseWriter, r *http.Request) { // Set the file name and content type
fileName := "name-of-file.pdf"
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+fileName) // Create a buffer to store our output
buffer := make([]byte, 4096) // Open the file
file, err := os.Open(fileName)
if err != nil {
fmt.Println(err)
}
defer file.Close() // Read the file into the buffer
for {
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
fmt.Println(err)
return
}
if n == 0 {
break
} // Write the buffer to the client
if _, err := w.Write(buffer[:n]); err != nil {
fmt.Println(err)
return
}
}
}func main() {
http.HandleFunc("/", downloadFile)
http.ListenAndServe(":8080", nil)
}
阅读全文