go curl -F "filename=@stp.go" localhost:9050
https://blog.csdn.net/xmcy001122/article/details/104654096/
//HTTPS_POST HTTPS_GET HTTPS_PUT HTTPS_DELETE support https header as nil
const (
HTTPS_POST = "POST"
HTTPS_GET = "GET"
HTTPS_PUT = "PUT"
HTTPS_DELETE = "DELETE"
HTTPS_PATCH = "PATCH"
HTTPS_COPY = "COPY"
HTTPS_HEAD = "HEAD"
HTTPS_OPTIONS = "OPTIONS"
HTTPS_LINK = "LINK"
HTTPS_UNLINK = "UNLINK"
HTTPS_PURGE = "PURGE"
HTTPS_LOCK = "LOCK"
HTTPS_UNLOCK = "UNLOCK"
HTTPS_PROPFIND = "PROPFIND"
HTTPS_VIES = "VIEW"
)
func client(certPool *x509.CertPool) *http.Client {
var tr *http.Transport
tr = &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, time.Second*10) //设置建立连接超时
if err != nil {
return nil, err
}
err = conn.SetDeadline(time.Now().Add(time.Second * 10)) //设置发送接受数据超时
if err != nil {
return nil, err
}
return conn, nil
},
ResponseHeaderTimeout: time.Second * 10,
TLSClientConfig: &tls.Config{
RootCAs: certPool,
InsecureSkipVerify: true,
},
}
return &http.Client{Transport: tr}
}
const (
errStatusCode = 303
bodyMaxSize = 1024 * 1024
)
func getHTTPSResponse(method, url string, body string, head map[string]string) (Response, error) {
res := Response{
Status: errStatusCode,
Body: "",
Header: nil,
}
req, err := http.NewRequest(method, url, strings.NewReader(body))
if err != nil {
return res, err
}
for k, v := range head {
req.Header.Add(k, v)
}
trustCA := x509.NewCertPool()
resp, err := client(trustCA).Do(req)
if err != nil {
return res, err
}
var html string
if resp.StatusCode == 200 {
robots, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
//nolint
resp.Body.Close()
if len(robots) > bodyMaxSize {
return res, errors.New("the size of the request body exceeds 1mb")
}
html = string(robots)
} else {
html = ""
}
reponseHeader := make(map[string]string)
for k, v := range resp.Header {
var tmpValue string
for _, value := range v {
tmpValue += value
}
reponseHeader[k] = tmpValue
}
//nolint
defer resp.Body.Close()
res.Header = reponseHeader
res.Status = resp.StatusCode
res.Body = html
return res, nil
}
/*
func main() {
lis, err := net.Listen("tcp", ":9050")
if err != nil {
log.Fatalln("fatal error: ", err)
}
for {
conn, err := lis.Accept() // 接收客户端连接请求
if err != nil {
continue
}
go func(conn net.Conn) { // 并发处理客户端请求
buf := make([]byte, 120000)
n, err := conn.Read(buf)
log.Println(n)
log.Println(string(buf))
if err != nil{
log.Fatal(err)
}
conn.Write([]byte("hello\n"))
conn.Close()
}(conn)
}
}
*/
func upload(w http.ResponseWriter, req *http.Request) {
contentType := req.Header.Get("content-type")
contentLen := req.ContentLength
if !strings.Contains(contentType, "multipart/form-data") {
w.Write([]byte("content-type must be multipart/form-data"))
return
}
max := int64(1024*1024*1024)
if contentLen >= max {
w.Write([]byte("file to large,limit 4MB"))
return
}
err := req.ParseMultipartForm(max)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(req.MultipartForm.File) == 0 {
http.Error(w, "not have any file", http.StatusInternalServerError)
return
}
for name, files := range req.MultipartForm.File {
if len(files) != 1 {
http.Error(w, "too many files", http.StatusInternalServerError)
return
}
if name == "" {
http.Error(w, "is not FileData", http.StatusInternalServerError)
return
}
for _, f := range files {
handle, err := f.Open()
if err != nil {
http.Error(w, fmt.Sprintf("unknown error,fileName=%s,fileSize=%d,err:%s", f.Filename, f.Size, err.Error()), http.StatusInternalServerError)
return
}
path := "/" + f.Filename
dst, _ := os.Create(path)
io.Copy(dst, handle)
dst.Close()
}
}
}
func getContentType(fileName string) (extension, contentType string) {
arr := strings.Split(fileName, ".")
if len(arr) >= 2 {
extension = arr[len(arr)-1]
switch extension {
case "jpeg", "jpe", "jpg":
contentType = "image/jpeg"
case "png":
contentType = "image/png"
case "gif":
contentType = "image/gif"
case "mp4":
contentType = "video/mpeg4"
case "mp3":
contentType = "audio/mp3"
case "wav":
contentType = "audio/wav"
case "pdf":
contentType = "application/pdf"
case "doc", "":
contentType = "application/msword"
}
}
contentType = "application/octet-stream"
return
}
func download(w http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/favicon.ico" {
return
}
filename := req.RequestURI[1:]
enEscapeUrl, err := url.QueryUnescape(filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
f, err := os.Open("./" + enEscapeUrl)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
info, err := f.Stat()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, contentType := getContentType(filename)
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
io.Copy(w, f)
}
func main() {
http.HandleFunc("/upload", upload)
//http.HandleFunc("/", download)
err := http.ListenAndServe(":9050", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func cmain() {
//if len(os.Args) < 2 {
// fmt.Println("usage: need ip:port, such as 127.0.0.1:8096")
//}
conn, err := net.Dial("tcp", "127.0.0.1:9050")
if err != nil {
panic(err)
}
data := "GET /stp.go HTTP/1.1\nHost: localhost:9060\nUser-Agent: curl\nAccept: */*\n\n"
_, err = conn.Write([]byte(data))
if err != nil {
panic(err)
}
k := make([]byte, 1200)
n, err := conn.Read(k)
if err != nil && err != io.EOF {
panic(err)
}
fmt.Println(string(k[:n]))
n, err = conn.Read(k)
if err != nil && err != io.EOF {
panic(err)
}
fmt.Println(string(k[:n]))
}
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
/*
func main() {
lis, err := net.Listen("tcp", ":9050")
if err != nil {
log.Fatalln("fatal error: ", err)
}
for {
conn, err := lis.Accept() // 接收客户端连接请求
if err != nil {
continue
}
go func(conn net.Conn) { // 并发处理客户端请求
buf := make([]byte, 120000)
n, err := conn.Read(buf)
log.Println(n)
log.Println(string(buf))
if err != nil{
log.Fatal(err)
}
conn.Write([]byte("hello\n"))
conn.Close()
}(conn)
}
}
*/
func upload(w http.ResponseWriter, req *http.Request) {
contentType := req.Header.Get("content-type")
contentLen := req.ContentLength
if !strings.Contains(contentType, "multipart/form-data") {
w.Write([]byte("content-type must be multipart/form-data"))
return
}
max := int64(1024*1024*1024)
if contentLen >= max {
w.Write([]byte("file to large,limit 4MB"))
return
}
err := req.ParseMultipartForm(max)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(req.MultipartForm.File) == 0 {
http.Error(w, "not have any file", http.StatusInternalServerError)
return
}
for name, files := range req.MultipartForm.File {
if len(files) != 1 {
http.Error(w, "too many files", http.StatusInternalServerError)
return
}
if name == "" {
http.Error(w, "is not FileData", http.StatusInternalServerError)
return
}
for _, f := range files {
handle, err := f.Open()
if err != nil {
http.Error(w, fmt.Sprintf("unknown error,fileName=%s,fileSize=%d,err:%s", f.Filename, f.Size, err.Error()), http.StatusInternalServerError)
return
}
path := "/" + f.Filename
dst, _ := os.Create(path)
io.Copy(dst, handle)
dst.Close()
}
}
}
func getContentType(fileName string) (extension, contentType string) {
arr := strings.Split(fileName, ".")
if len(arr) >= 2 {
extension = arr[len(arr)-1]
switch extension {
case "jpeg", "jpe", "jpg":
contentType = "image/jpeg"
case "png":
contentType = "image/png"
case "gif":
contentType = "image/gif"
case "mp4":
contentType = "video/mpeg4"
case "mp3":
contentType = "audio/mp3"
case "wav":
contentType = "audio/wav"
case "pdf":
contentType = "application/pdf"
case "doc", "":
contentType = "application/msword"
}
}
contentType = "application/octet-stream"
return
}
func download(w http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/favicon.ico" {
return
}
filename := req.RequestURI[1:]
enEscapeUrl, err := url.QueryUnescape(filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
f, err := os.Open("./" + enEscapeUrl)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
info, err := f.Stat()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, contentType := getContentType(filename)
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
io.Copy(w, f)
}
func main() {
http.HandleFunc("/upload", upload)
//http.HandleFunc("/", download)
err := http.ListenAndServe(":9050", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func cmain() {
//if len(os.Args) < 2 {
// fmt.Println("usage: need ip:port, such as 127.0.0.1:8096")
//}
conn, err := net.Dial("tcp", "127.0.0.1:9050")
if err != nil {
panic(err)
}
data := "GET /stp.go HTTP/1.1\nHost: localhost:9060\nUser-Agent: curl\nAccept: */*\n\n"
_, err = conn.Write([]byte(data))
if err != nil {
panic(err)
}
k := make([]byte, 1200)
n, err := conn.Read(k)
if err != nil && err != io.EOF {
panic(err)
}
fmt.Println(string(k[:n]))
n, err = conn.Read(k)
if err != nil && err != io.EOF {
panic(err)
}
fmt.Println(string(k[:n]))
}