golang http server provides file download function
- 2020-10-23 20:07:55
- OfStack
Introduction to the
Go (also known as Golang) is a statically strongly typed, compiled, concurrent, and garbage collection programming language developed by Google.
Robert Griesemer, Rob Parker (Rob Pike) and Ken Thompson (Ken Thompson) began designing Go in September 2007, and later Ian Lance Taylor and Russ Cox joined the project. Go is based on the Inferno operating system. Go was officially announced as an open source project in November 2009 and was implemented on the Linux and Mac OS X platforms, followed by the Windows system. In 2016, Go was chosen as the "TIOBE Language of the Year 2016" by software evaluation company TIOBE. Currently, Go releases a level 2 version every six months (that is, upgrading from ES32en.x to ES34en.y).
go is golang the full name is golang or go for short
golang implements http server to provide file download function, the specific code is as follows:
func FileDownload(w http.ResponseWriter, r *http.Request) {
filename := get_filename_from_request(r)
file, _ := os.Open(filename)
defer file.Close()
fileHeader := make([]byte, 512)
file.Read(fileHeader)
fileStat, _ := file.Stat()
w.Header().Set("Content-Disposition", "attachment; filename=" + filename)
w.Header().Set("Content-Type", http.DetectContentType(fileHeader))
w.Header().Set("Content-Length", strconv.FormatInt(fileStat.Size(), 10))
file.Seek(0, 0)
io.Copy(w, file)
return
}
ps: Take a look at golang's simplest, http server
Simple hello world
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
http.HandleFunc("/", helloWorld)
e:=http.ListenAndServe(":8888",nil)
if e!=nil{
fmt.Println(e.Error())
}
}
func helloWorld(w http.ResponseWriter, r *http.Request) {
str:="Hello World"
n,e:=io.WriteString(w, str)
if e!=nil{
fmt.Println(e.Error())
} else {
fmt.Println(n," " ,len(str))
}
}
conclusion
Above is the site to introduce golang http server provides file download function, I hope to help you!