This is a creation in Article, where the information may have evolved or changed.
"Code" Golang implemented file services (including uploads, downloaded server side and client side)
(2013-09-20 02:03:52)
reproduced
Label: Golang Go File server It |
Category: Go related |
Download (Support for power-down continuation) (client)
Package Main
Import (
"http"
"OS"
"IO"
"StrConv"
)
Const (
UA = "Golangdownloader from kejibo.com"
)
Func Main () {
F, err: =os. OpenFile ("./file.exe", Os. O_RDWR, 0666)//Actually here the O_RDWR should be o_rdwr| O_create, that is, the file does not exist in the case of an empty file, but because there are bugs under Windows, if you use this o_create, will be directly emptied the file, so here is not the logo, you set up a good file beforehand.
If Err!=nil {panic (err)}
Stat, err: =f.stat ()//Get file status
If Err!=nil {panic (err)}
F.seek (Stat. Size, 0)//The file pointer to the end of the file, of course, you say why not directly in the O_append mode open, yes it is OK. I'm just experimenting here.
URL: = "Http://dl.google.com/chrome/install/696.57/chrome_installer.exe"
var reqhttp. Request
Req. Method = "GET"
Req. useragent = UA
Req. Close =true
Req. URL, err= http. parseURL (URL)
If Err!=nil {panic (err)}
Header: =http. header{}
Header. Set ("Range", "bytes=" + StrConv. ITOA64 (Stat. Size) + "-")
Req. Header =header
RESP, err: =http. Defaultclient.do (&req)
If Err!=nil {panic (err)}
Written, err:= io. Copy (f, resp. Body)
If Err!=nil {panic (err)}
println ("Written:", written)
}
Download (server)
Package Main
Import (
"Flag"
"FMT"
"IO"
"Log"
"Net/http"
"OS"
"Path"
"StrConv"
)
var dir string
var Port int
var Statichandler http. Handler
Initialize parameters
Func init () {
Dir =path. Dir (OS. Args[0])
Flag. Intvar (&port, "Port", 800, "Server port")
Flag. Parse ()
Fmt. Println ("dir:", http. Dir (dir))
Statichandler =http. Fileserver (http. Dir (dir))
}
Func Main () {
http. Handlefunc ("/", Staticserver)
ERR: =http. Listenandserve (":" +strconv. Itoa (port), nil)
If Err!=nil {
Log. Fatal ("Listenandserve:", err)
}
}
Static file Processing
Func staticserver (w http. Responsewriter, req *http. Request) {
Fmt. Println ("Path:" + req. Url. Path)
Ifreq. Url. Path! = "/down/" {
Statichandler.servehttp (W, req)
Return
}
Io. WriteString (W, "Hello, world!\n")
}
Upload (client)
Package Main
Import (
"Bytes"
"FMT"
"IO"
"Io/ioutil"
"Mime/multipart"
"Net/http"
"OS"
)
Func postfile (filename string, targeturl string) error {
Bodybuf: =&bytes. buffer{}
bodywriter:= multipart. Newwriter (BODYBUF)
Critical one-step operation
Filewriter,err: = Bodywriter.createformfile ("UploadFile", filename)
If Err!=nil {
Fmt. PRINTLN ("Error writing to buffer")
return err
}
Open File Handle operation
FH, err: =os. Open (filename)
If Err!=nil {
Fmt. PRINTLN ("Error opening file")
return err
}
Iocopy
_, Err =io. Copy (FileWriter, FH)
If Err!=nil {
return err
}
contenttype:= Bodywriter.formdatacontenttype ()
Bodywriter.close ()
RESP, err: =http. Post (TargetUrl, ContentType, Bodybuf)
If Err!=nil {
return err
}
Deferresp. Body.close ()
Resp_body,err: = Ioutil. ReadAll (resp. Body)
If Err!=nil {
return err
}
Fmt. Println (resp. Status)
Fmt. Println (String (resp_body))
Returnnil
}
Sample usage
Func Main () {
target_url:= "Http://localhost:9090/upload"
FileName: = "./astaxie.pdf"
Postfile (filename, Target_url)
}
Upload (server)
Package Main
Import (
"Crypto/md5"
"Flag"
"FMT"
"Html/template"
"IO"
"Log"
"Net/http"
"OS"
"Path"
"StrConv"
"Time"
)
var dir string
var Port int
Initialize parameters
Func init () {
Dir =path. Dir (OS. Args[0])
Flag. Intvar (&port, "Port", 800, "Server port")
Flag. Parse ()
Fmt. Println ("dir:", http. Dir (dir))
}
Func Main () {
http. Handlefunc ("/upload", upload)
ERR: =http. Listenandserve (":" +strconv. Itoa (port), nil)
If Err!=nil {
Log. Fatal ("Listenandserve:", err)
}
}
Handling/upload Logic
Func Upload (w http. Responsewriter, R *http. Request) {
Fmt. Println ("Method:", R.method)//method of obtaining the request
If r.method== "GET" {
Crutime: = time. Now (). Unix ()
H: = MD5. New ()
Io. WriteString (H, StrConv. Formatint (crutime,10))
Token: = FMT. Sprintf ("%x", H.sum (nil))
T, _: = template. Parsefiles ("Upload.gtpl")
T.execute (W, token)
} else{
R.parsemultipartform (<< 20)
File, Handler, err: =r.formfile ("UploadFile")
If err! = Nil {
Fmt. PRINTLN (ERR)
Return
}
Defer file. Close ()
Fmt. fprintf (W, "%v", handler. Header)
F, err: =os. OpenFile ("./upload/" +handler. Filename, OS. O_wronly|os. o_create,0666)
If err! = Nil {
Fmt. PRINTLN (ERR)
Return
}
Defer F.close ()
Io. Copy (f, file)
}
}