Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use golang built-in net/http to receive files

Shulou Source: shulou.com Published: 2022-06-01 23:49:53 09月19日 Update

This article mainly introduces "how to use golang to receive files with net/http". In daily operation, I believe many people have doubts about how to use golang to receive files with net/http. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use golang to receive files with net/http". Next, please follow the editor to study!

SaveFile (processing submissions)

Package mainimport ("fmt", "io", "io/ioutil", "log", "net/http"os") / / read the html file func ReadHtmlFile (filePath string) ([] byte, error) {file, err: = os.Open (filePath) if err! = nil {log.Println ("open file err is", err) return nil Err} htmlByte, err: = ioutil.ReadAll (file) if err! = nil {log.Println ("pase html err is", err) return nil, err} return htmlByte, err} / / output html files to func OutHtml (htmlbytes [] byte) http.Handler {return http.HandlerFunc (func (w http.ResponseWriter) R * http.Request) {w.Write (htmlbytes)})} / / the file received by post Save to specified directory func SaveFile (toFile string) http.Handler {/ / tofile specified save directory return http.HandlerFunc (func (w http.ResponseWriter, r * http.Request) {if r.Method = = "POST" {file, _, err: = r.FormFile ("attachment") / / from form Receive the submitted file if err! = nil {log.Println (err) return} / / log.Println (file) Defer file.Close () f Err: = os.OpenFile (toFile, os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0666) / / if the file does not exist Then create if err! = nil {log.Println (err) return} defer f.Close () _ Err = io.Copy (f, file) / / the file submitted by post Redirect to f if err! = nil {log.Println (err)})} func main () {htmlbyte Err: = ReadHtmlFile ("D:\ VsCodeProject\ NetHttpGo\ src\ static\ index.html") if err! = nil {log.Println (err)} outhtml: = OutHtml (htmlbyte) saveFile: = SaveFile ("D:\ VsCodeProject\\ NetHttpGo\\ src\ a.jpg") http.Handle ("/", outhtml) http.Handle ("/ file") SaveFile) fmt.Println ("listening.") Http.ListenAndServe (": 8081", nil)} at this point, the study on "how to use golang to receive files with net/http" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Files learning more directories help practical next articles methods theories knowledge articles websites materials follow questions easy to use deal with practice solutions Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MariaDB NVidia Docker Shulou Tech Info