@@ -80,6 +80,77 @@ func main() {
8080}
8181```
8282
83+ Multipart/form-data usage example
84+ ---------------------------------
85+
86+ ``` go
87+ package main
88+
89+ import (
90+ " bytes"
91+ " fmt"
92+ " github.com/mholt/binding"
93+ " io"
94+ " log"
95+ " mime/multipart"
96+ " net/http"
97+ )
98+
99+ // We expect a multipart/form-data upload with
100+ // a file field named 'data'
101+ type MultipartForm struct {
102+ Data *multipart.FileHeader ` json:"data"`
103+ }
104+
105+ func (f *MultipartForm ) FieldMap () binding .FieldMap {
106+ return binding.FieldMap {
107+ &f.Data : " data" ,
108+ }
109+ }
110+
111+ // Handlers are still clean and simple
112+ func handler (resp http .ResponseWriter , req *http .Request ) {
113+ multipartForm := new (MultipartForm)
114+ errs := binding.Bind (req, multipartForm)
115+ if errs.Handle (resp) {
116+ return
117+ }
118+
119+ // To access the file data you need to Open the file
120+ // handler and read the bytes out.
121+ var fh io.ReadCloser
122+ var err error
123+ if fh, err = multipartForm.Data .Open (); err != nil {
124+ http.Error (resp,
125+ fmt.Sprint (" Error opening Mime::Data %+v " , err),
126+ http.StatusInternalServerError )
127+ return
128+ }
129+ defer fh.Close ()
130+ dataBytes := bytes.Buffer {}
131+ var size int64
132+ if size, err = dataBytes.ReadFrom (fh); err != nil {
133+ http.Error (resp,
134+ fmt.Sprint (" Error reading Mime::Data %+v " , err),
135+ http.StatusInternalServerError )
136+ return
137+ }
138+ // Now you have the attachment in databytes.
139+ // Maximum size is default is 10MB.
140+ log.Printf (" Read %v bytes with filename %s " ,
141+ size, multipartForm.Data .Filename )
142+ }
143+
144+ func main () {
145+ http.HandleFunc (" /upload" , handler)
146+ http.ListenAndServe (" :3000" , nil )
147+ }
148+
149+ ```
150+
151+ You can test from CLI using the excellent httpie client
152+
153+ ` http -f POST localhost:3000/upload data@myupload `
83154
84155Custom data validation
85156-----------------------
0 commit comments