gitee.com/h79/goutils@v1.22.10/common/http/form.go (about) 1 package http 2 3 import ( 4 "gitee.com/h79/goutils/common/result" 5 "io" 6 "mime/multipart" 7 "os" 8 "path/filepath" 9 "reflect" 10 ) 11 12 var ( 13 FormType = reflect.TypeOf((*Form)(nil)).Elem() 14 ) 15 16 type Form interface { 17 CreateForm(w *multipart.Writer) error 18 } 19 20 type FileForm struct { 21 Field string 22 Value string 23 } 24 25 func (df *FileForm) CreateForm(w *multipart.Writer) error { 26 fh, err := os.Open(df.Value) 27 if err != nil { 28 return result.Error(-1, err.Error()) 29 } 30 defer fh.Close() 31 32 fw, err := w.CreateFormFile(df.Field, filepath.Base(df.Value)) 33 if err != nil { 34 return result.Error(result.ErrException, err.Error()) 35 } 36 37 _, err = io.Copy(fw, fh) 38 39 return err 40 } 41 42 type ReadForm struct { 43 Field string 44 Value string 45 R io.Reader 46 } 47 48 func (df *ReadForm) CreateForm(w *multipart.Writer) error { 49 50 fw, err := w.CreateFormFile(df.Field, df.Value) 51 if err != nil { 52 return result.Error(result.ErrException, err.Error()) 53 } 54 55 _, err = io.Copy(fw, df.R) 56 57 return err 58 }