-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload_file_test.go
75 lines (68 loc) · 1.51 KB
/
upload_file_test.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"io"
"net/http"
"os"
"testing"
)
func uploadForm(w http.ResponseWriter, r *http.Request) {
var (
name = "upload_form.html"
)
myTemplates.ExecuteTemplate(w, name, nil)
}
func TestUploadFormServer(t *testing.T) {
var (
pattern = "/upload-form"
handler http.HandlerFunc = uploadForm
)
mux := http.NewServeMux()
mux.HandleFunc(pattern, handler)
server := http.Server{
Addr: "localhost:8080",
Handler: mux,
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
func upload(w http.ResponseWriter, r *http.Request) {
// Ambil Form File
file, fileHeader, err := r.FormFile("file")
if err != nil {
panic(err)
}
// Membuat File Destinasi
destination, err := os.Create("./resources/" + fileHeader.Filename)
if err != nil {
panic(err)
}
// Masukkan File UPload ke Direktori Destinasi
_, err = io.Copy(destination, file)
if err != nil {
panic(err)
}
// Ambil Form Name
name := r.PostFormValue("name")
// Execute Template
myTemplates.ExecuteTemplate(w, "upload_success.html", map[string]interface{}{
"Name": name,
"File": "/static/" + fileHeader.Filename,
})
}
func TestUploadSuccessServer(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/", uploadForm)
mux.HandleFunc("/upload", upload)
// static
http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./resources"))))
server := http.Server{
Addr: "localhost:8080",
Handler: mux,
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}