1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 02:17:05 +00:00

Add example for struct validation(3rd-party) through json request body binding

Former-commit-id: 78bbbe068f219e5a264951c900b77cb9b70f2079
This commit is contained in:
Gerasimos (Makis) Maropoulos
2018-07-24 04:33:53 +03:00
parent 7337396e3c
commit 247a558394
6 changed files with 480 additions and 293 deletions

View File

@@ -5,6 +5,8 @@ import (
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@@ -44,10 +46,53 @@ func main() {
ctx.UploadFormFiles("./uploads", beforeSave)
})
app.Post("/upload_manual", func(ctx iris.Context) {
// Get the max post value size passed via iris.WithPostMaxMemory.
maxSize := ctx.Application().ConfigurationReadOnly().GetPostMaxMemory()
err := ctx.Request().ParseMultipartForm(maxSize)
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.WriteString(err.Error())
return
}
form := ctx.Request().MultipartForm
files := form.File["files[]"]
failures := 0
for _, file := range files {
_, err = saveUploadedFile(file, "./uploads")
if err != nil {
failures++
ctx.Writef("failed to upload: %s\n", file.Filename)
}
}
ctx.Writef("%d files uploaded", len(files)-failures)
})
// start the server at http://localhost:8080 with post limit at 32 MB.
app.Run(iris.Addr(":8080"), iris.WithPostMaxMemory(32<<20))
}
func saveUploadedFile(fh *multipart.FileHeader, destDirectory string) (int64, error) {
src, err := fh.Open()
if err != nil {
return 0, err
}
defer src.Close()
out, err := os.OpenFile(filepath.Join(destDirectory, fh.Filename),
os.O_WRONLY|os.O_CREATE, os.FileMode(0666))
if err != nil {
return 0, err
}
defer out.Close()
return io.Copy(out, src)
}
func beforeSave(ctx iris.Context, file *multipart.FileHeader) {
ip := ctx.RemoteAddr()
// make sure you format the ip in a way