POST将内容附着在body部分.
server端将这部分内容读出即可.
curl -sL --data @main.go localhost:8079/t?name=assk.go
可是这样做的问题是, 所有的换行符都丢失了:
func tipFunc(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/plain")
defer req.Body.Close() // it is ok to close more than once...
chunk, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Fprintf(rw, "\nerror reading body: %v\n", err)
rw.WriteHeader(http.StatusBadRequest)
return
}
url := req.URL
filename := url.Query().Get("name")
if filename != "" {
filename = path.Join("tip", filename)
_ = os.MkdirAll(path.Dir(filename), os.ModePerm) // it may fail
err := ioutil.WriteFile(filename, chunk, 0666)
if err != nil {
fmt.Fprintf(rw, "\nerror: %v\n", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
log.Printf("[tip]:save to %v", filename)
fmt.Fprintf(rw, "\nsaved to %v\n", filename)
} else {
log.Print("[tip]:no filename provided.")
io.WriteString(rw, "\nno file name\n")
}
}
而上传文件是有标准过程的:
func uploadFunc(rw http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
switch r.Method {
case "GET":
t := uploadPageTemplate
// if err != nil {
// rw.Header().Set("Content-Typpe", "text/plain")
// fmt.Fprintf(rw, "\nerror: %v\n", err)
// return
// }
rw.Header().Set("Content-Type", "text/html")
t.Execute(rw, "bien")
default:
err := r.ParseMultipartForm(1 * (1 << 20)) // up to 1MB
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "\nerror: %v\n", err)
return
}
input, handler, err := r.FormFile("up")
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "\nerror: %v\n", err)
return
}
defer input.Close()
//fmt.Fprintf(rw, "%v\n", handler.Header)
outpath := path.Join("./upload", handler.Filename)
os.MkdirAll(path.Dir(outpath), os.ModePerm)
fout, err := os.OpenFile(outpath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "\nerror: %v\n", err)
return
}
defer fout.Close()
io.Copy(fout, input)
log.Printf("save to %v", outpath)
//io.WriteString(rw, "muy bien\n")
fmt.Fprintf(rw, "\nserver accepted: %v\n", handler.Filename)
}
}
curl -s --form "up=@main.go" localhost:8079/upload
reference link:
http://blog.csdn.net/wulong710/article/details/53127606
http://www.cnblogs.com/zhangym/p/5841732.html
http://dmdgeeker.com/goBook/
http://blog.csdn.net/u010278923/article/details/76101074
http://www.levigross.com/2015/11/21/mutual-tls-authentication-in-go/
https://github.com/nareix/blog/blob/master/posts/golang-tls-guide.md