文件服务server.go
package main
import (
"io"
"net/http"
"os"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
file, err := os.Create("./newFile")
if err != nil {
panic(err)
}
_, err = io.Copy(file, r.Body)
if err != nil {
panic(err)
}
w.Write([]byte("upload success"))
}
func main() {
http.HandleFunc("/upload", uploadHandler)
http.ListenAndServe(":5050", nil)
}
文件传送client.go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
file, err := os.Open("./a.txt")
if err != nil {
panic(err)
}
defer file.Close()
res, err := http.Post("http://127.0.0.1:5050/upload", "binary/octet-stream", file)
if err != nil {
panic(err)
}
defer res.Body.Close()
message, _ := ioutil.ReadAll(res.Body)
fmt.Printf(string(message))
}
有疑问加站长微信联系(非本文作者)