Created
July 8, 2017 16:07
-
-
Save starius/41a468d3cf4570fd58a0e536f963102e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"io" | |
"log" | |
"net/http" | |
"time" | |
) | |
var ( | |
httpAddr = flag.String("http-addr", "127.0.0.1:23760", "HTTP server addrer.") | |
) | |
const indexPage = ` | |
<html> | |
<body> | |
<form action="/upload" method="post" enctype="multipart/form-data"> | |
Select file to upload: | |
<br> | |
<input type="file" name="data" id="data"> | |
<br> | |
<input type="text" name="name" id="name"> | |
<br> | |
<input type="submit" value="Upload File" name="submit"> | |
</form> | |
</body> | |
</html> | |
` | |
func h(res http.ResponseWriter, req *http.Request) { | |
if req.Method == "GET" && req.URL.Path == "/" { | |
res.Write([]byte(indexPage)) | |
return | |
} else if req.Method == "POST" && req.URL.Path == "/upload" { | |
log.Printf("Started uploading\n") | |
r, _, err := req.FormFile("data") | |
if err != nil { | |
log.Printf("req.FormFile: %v.", err) | |
res.WriteHeader(http.StatusBadRequest) | |
return | |
} | |
log.Printf("req.FormFile finished\n") | |
for { | |
log.Printf("Chunk...\n") | |
buf := make([]byte, 1e6) | |
n, err := io.ReadFull(r, buf) | |
buf1 := buf | |
if err == io.ErrUnexpectedEOF { | |
buf1 = buf[:n] | |
} else if err != nil { | |
log.Printf("io.ReadFull: %v.", err) | |
res.WriteHeader(http.StatusInternalServerError) | |
return | |
} | |
// TODO: Write to somewhere... | |
if len(buf1) < len(buf) { | |
break | |
} | |
} | |
return | |
} | |
} | |
func main() { | |
flag.Parse() | |
s := &http.Server{ | |
Addr: *httpAddr, | |
ReadTimeout: 1000 * time.Second, | |
WriteTimeout: 1000 * time.Second, | |
MaxHeaderBytes: 1 << 16, | |
} | |
s.Handler = http.HandlerFunc(h) | |
log.Fatal(s.ListenAndServe()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment