您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關利用golang怎么實現一個文件上傳功能,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
package main import ( "bufio" "encoding/base64" "errors" "fmt" "io" "net" "net/url" "os" "path/filepath" "strconv" "strings" "unsafe" ) func main() { if len(os.Args) != 3 { fmt.Printf(`usage: %s ip:port user:pass get file: wget --auth-no-challenge --user=user --password=pass --content-disposition "http://ip:port?/home/tmp.txt" curl -u user:pass -OJ "http://ip:port?/home/tmp.txt" post file: wget -qO - --auth-no-challenge --user=user --password=pass --post-file=C:\tmp.txt "http://ip:port?/home/tmp.txt" curl -u user:pass --data-binary @C:\tmp.txt "http://ip:port?/home/tmp.txt" `, os.Args[0]) return } addr, err := net.ResolveTCPAddr("tcp", os.Args[1]) if err != nil { panic(err) } ser, err := net.ListenTCP("tcp", addr) if err != nil { panic(err) } fmt.Printf("Listen: [%s]\n", addr) authStr = "Basic " + base64.StdEncoding.EncodeToString([]byte(os.Args[2])) for { ln, err := ser.AcceptTCP() if err != nil { panic(err) } go func(l *net.TCPConn) { err := handleFile(l) if err != nil { respData(l, err.Error()) } l.Close() }(ln) } } const ( maxMemory = 10 << 20 // 緩存10MB respMsg = "HTTP/1.1 200 OK\r\nContent-Type:text/plain;charset=utf-8\r\nContent-Disposition:attachment;filename=resp.txt\r\nContent-Length:%d\r\n\r\n%s" getHeader = "HTTP/1.1 200 OK\r\nContent-Type:application/octet-stream\r\nContent-Disposition:attachment;filename=%s\r\nContent-Length:%d\r\nContent-Transfer-Encoding:binary\r\n\r\n" ) var authStr string // 授權信息 func respData(w io.Writer, data string) { msg := data + "\r\n" fmt.Fprintf(w, respMsg, len(msg), msg) } func handleFile(l *net.TCPConn) error { br := bufio.NewReaderSize(l, maxMemory) method, path, length, err := getHeaderMsg(br) if err != nil { return err } fmt.Printf("[%s - %s - %d]\n", method, path, length) if method == "GET" { return httpGetFile(path, l, length) } err = httpPostFile(path, br, length) if err != nil { return err } respData(l, "post ok") return nil } // 內存復用,更快速,省內存 func bytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) } func getHeaderMsg(r *bufio.Reader) (string, string, int64, error) { // 讀取第一行,提取有用信息 line, _, err := r.ReadLine() if err != nil { return "", "", 0, err } header := strings.Fields(bytesToString(line)) if len(header) < 3 { // 首行至少3列數據 return "", "", 0, errors.New("header error") } method, path := header[0], "" s := strings.Index(header[1], "?") if s >= 0 { path, _ = url.QueryUnescape(header[1][s+1:]) } if path == "" { // ?號后面就是文件路徑,需要解碼url一下 return "", "", 0, errors.New("path error") } var length int64 if method == "GET" { fi, err := os.Stat(path) if err != nil { return "", "", 0, err } length = fi.Size() // GET請求提前得到文件大小 } else if method != "POST" { return "", "", 0, errors.New(method + " not support") } var authCheck string for { line, _, err = r.ReadLine() if err != nil { return "", "", 0, err } if len(line) == 0 { break // 遇到空行,之后為請求體 } header = strings.Split(bytesToString(line), ":") if len(header) == 2 { // 頭部[key: val]解析 header[0] = strings.ToLower(strings.TrimSpace(header[0])) header[1] = strings.TrimSpace(header[1]) if method == "POST" && header[0] == "content-length" { length, _ = strconv.ParseInt(header[1], 10, 64) } else if header[0] == "authorization" { authCheck = header[1] } } } if authCheck != authStr { return "", "", 0, errors.New("authorization error") } return method, path, length, nil } func httpPostFile(path string, r io.Reader, length int64) error { fw, err := os.Create(path) if err != nil { return err } defer fw.Close() pr := newProgress(r, length) _, err = io.CopyN(fw, pr, length) pr.Close() return err } func httpGetFile(path string, w io.Writer, size int64) error { fr, err := os.Open(path) if err != nil { return err } defer fr.Close() fmt.Fprintf(w, getHeader, filepath.Base(path), size) pr := newProgress(fr, size) _, err = io.Copy(w, pr) pr.Close() return err } type progress struct { r io.Reader cnt int64 rate chan int64 } func newProgress(r io.Reader, size int64) io.ReadCloser { p := &progress{r: r, rate: make(chan int64)} // 之所以這樣做進度,是因為打印耗性能,因此在協程中打印進度 // 在處理數據中用非阻塞方式往chan中傳處理字節數 go func(rate <-chan int64, all int64) { for cur := range rate { fmt.Printf("\rhandle:%4d%%", cur*100/all) } fmt.Printf("\rhandle: 100%%\r\n\r\n") }(p.rate, size) return p } func (p *progress) Read(b []byte) (int, error) { n, err := p.r.Read(b) p.cnt += int64(n) select { // 非阻塞方式往chan中寫數據 case p.rate <- p.cnt: default: } return n, err } func (p *progress) Close() error { close(p.rate) // 關閉chan,通知打印協程退出 return nil }
執行UpDownFile-h可以查看幫助文檔,里面有wget和curl上傳和下載文件的命令,方便忘記命令的時候copy一下下。
工具雖小,但確實解決了我個人的臨時上傳下載文件需求,再也不用到處安裝各種服務器咯,爽爽噠。
usage: UpDownFile ip:port get file: wget --auth-no-challenge --user=user --password=pass --content-disposition "http://ip:port?/home/tmp.txt" curl -u user:pass -OJ "http://ip:port?/home/tmp.txt" post file: wget -qO - --auth-no-challenge --user=user --password=pass --post-file=C:\tmp.txt "http://ip:port?/home/tmp.txt" curl -u user:pass --data-binary @C:\tmp.txt "http://ip:port?/home/tmp.txt"
關于利用golang怎么實現一個文件上傳功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。