-
Notifications
You must be signed in to change notification settings - Fork 3
/
parser_test.go
110 lines (91 loc) · 2.37 KB
/
parser_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package ginform_test
import (
"context"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/mazrean/formstream"
ginform "github.com/mazrean/formstream/gin"
)
func TestExample(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/user", strings.NewReader(`
--boundary
Content-Disposition: form-data; name="name"
mazrean
--boundary
Content-Disposition: form-data; name="password"
password
--boundary
Content-Disposition: form-data; name="icon"; filename="icon.png"
Content-Type: image/png
icon contents
--boundary--`))
req.Header.Set("Content-Type", "multipart/form-data; boundary=boundary")
rec := httptest.NewRecorder()
router := gin.Default()
router.POST("/user", createUserHandler)
router.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Errorf("status code is wrong: expected: %d, actual: %d\n", http.StatusCreated, rec.Code)
return
}
if user.name != "mazrean" {
t.Errorf("user name is wrong: expected: mazrean, actual: %s\n", user.name)
}
if user.password != "password" {
t.Errorf("user password is wrong: expected: password, actual: %s\n", user.password)
}
if user.icon != "icon contents" {
t.Errorf("user icon is wrong: expected: icon contents, actual: %s\n", user.icon)
}
}
func createUserHandler(c *gin.Context) {
parser, err := ginform.NewParser(c)
if err != nil {
log.Println(err)
c.Status(http.StatusBadRequest)
return
}
err = parser.Register("icon", func(r io.Reader, _ formstream.Header) error {
name, _, _ := parser.Value("name")
password, _, _ := parser.Value("password")
return saveUser(c.Request.Context(), name, password, r)
}, formstream.WithRequiredPart("name"), formstream.WithRequiredPart("password"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "failed to register",
})
log.Println(err)
return
}
err = parser.Parse()
if err != nil {
log.Println(err)
c.Status(http.StatusBadRequest)
return
}
c.Status(http.StatusCreated)
}
var (
user = struct {
name string
password string
icon string
}{}
)
func saveUser(_ context.Context, name string, password string, iconReader io.Reader) error {
user.name = name
user.password = password
sb := strings.Builder{}
_, err := io.Copy(&sb, iconReader)
if err != nil {
return fmt.Errorf("failed to copy: %w", err)
}
user.icon = sb.String()
return nil
}