-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
58 lines (51 loc) · 1.27 KB
/
main.go
File metadata and controls
58 lines (51 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"flag"
"fmt"
"io/fs"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
var path string
var listen string
func init() {
tempDir := os.TempDir()
flag.StringVar(&path, "path", tempDir, "file save path, default is os temp dir (typically /tmp in *nix)")
flag.StringVar(&listen, "listen", ":8080", "listen address, default is :8080")
}
type SaveHandler struct{}
func (SaveHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
bytes, _ := ioutil.ReadAll(request.Body)
filename := strings.ReplaceAll(request.RequestURI, "/", " ")
fullFilePath := fmt.Sprintf("%s/%s/%s", path, request.Method, filename)
dir := filepath.Dir(fullFilePath)
err := os.MkdirAll(dir, fs.ModePerm)
if err != nil {
response.Write([]byte(err.Error()))
return
}
err = ioutil.WriteFile(fullFilePath, bytes, fs.ModePerm)
if err != nil {
response.Write([]byte(err.Error()))
return
}
response.Write([]byte("Saved"))
}
func main() {
flag.Parse()
log.Printf("Save to %s", path)
log.Printf("Server listening on %s", listen)
s := &http.Server{
Addr: listen,
Handler: SaveHandler{},
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
}