Golang - Iris Web Framework #15: Forms

18 tháng 02, 2020 - 1717 lượt xem

Forms, dữ liệu  bài đăng và các tệp đã tải lên có thể được truy xuất bằng các phương thức của Context sau.

// FormValueDefault returns a single parsed form value by its "name",
// including both the URL field's query parameters and the POST or PUT form data.
//
// Returns the "def" if not found.
FormValueDefault(name string, def string) string
// FormValue returns a single parsed form value by its "name",
// including both the URL field's query parameters and the POST or PUT form data.
FormValue(name string) string
// FormValues returns the parsed form data, including both the URL
// field's query parameters and the POST or PUT form data.
//
// The default form's memory maximum size is 32MB, it can be changed by the
// `iris.WithPostMaxMemory` configurator at
// main configuration passed on `app.Run`'s second argument.
//
// NOTE: A check for nil is necessary.
FormValues() map[string][]string

// PostValueDefault returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name".
//
// If not found then "def" is returned instead.
PostValueDefault(name string, def string) string
// PostValue returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name"
PostValue(name string) string
// PostValueTrim returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name",  without trailing spaces.
PostValueTrim(name string) string
// PostValueInt returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name", as int.
//
// If not found returns -1 and a non-nil error.
PostValueInt(name string) (int, error)
// PostValueIntDefault returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name", as int.
//
// If not found returns or parse errors the "def".
PostValueIntDefault(name string, def int) int
// PostValueInt64 returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name", as float64.
//
// If not found returns -1 and a no-nil error.
PostValueInt64(name string) (int64, error)
// PostValueInt64Default returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name", as int64.
//
// If not found or parse errors returns the "def".
PostValueInt64Default(name string, def int64) int64
// PostValueInt64Default returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name", as float64.
//
// If not found returns -1 and a non-nil error.
PostValueFloat64(name string) (float64, error)
// PostValueInt64Default returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name", as float64.
//
// If not found or parse errors returns the "def".
PostValueFloat64Default(name string, def float64) float64
// PostValueInt64Default returns the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name", as bool.
//
// If not found or value is false, then it returns false, otherwise true.
PostValueBool(name string) (bool, error)
// PostValues returns all the parsed form data from POST, PATCH,
// or PUT body parameters based on a "name" as a string slice.
//
// The default form's memory maximum size is 32MB, it can be changed by the
// `iris.WithPostMaxMemory` configurator at
// main configuration passed on `app.Run`'s second argument.
PostValues(name string) []string
// FormFile returns the first uploaded file that received from the client.
//
// The default form's memory maximum size is 32MB, it can be changed by the
//  `iris.WithPostMaxMemory` configurator at
// main configuration passed on `app.Run`'s second argument.
FormFile(key string) (multipart.File, *multipart.FileHeader, error)

 


Multipart/Urlencoded Form

func main() {
    app := iris.Default()

    app.Post("/form_post", func(ctx iris.Context) {
        message := ctx.FormValue("message")
        nick := ctx.FormValueDefault("nick", "anonymous")

        ctx.JSON(iris.Map{
            "status":  "posted",
            "message": message,
            "nick":    nick,
        })
    })

    app.Run(iris.Addr(":8080"))
}

 


Một ví dụ khác: query + post form

POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=manu&message=this_is_great

 

func main() {
    app := iris.Default()

    app.Post("/post", func(ctx iris.Context) {
        id := ctx.URLParam("id")
        page := ctx.URLParamDefault("page", "0")
        name := ctx.FormValue("name")
        message := ctx.FormValue("message")
        // or `ctx.PostValue` for POST, PUT & PATCH-only HTTP Methods.

        app.Logger().Infof("id: %s; page: %s; name: %s; message: %s",
            id, page, name, message)
    })

    app.Run(iris.Addr(":8080"))
}

 

id: 1234; page: 1; name: manu; message: this_is_great

 


Upload files

Iris Context cung cấp một trình trợ giúp để tải lên các tệp (lưu tệp vào đĩa cứng của hệ thống từ dữ liệu tệp yêu cầu). Đọc thêm về phương thức Context.UploadFormFiles bên dưới.

UploadFormFiles tải lên bất kỳ (các) tệp nào đã nhận từ máy khách đến vị trí thực tế của hệ thống "destDirectory".

Đối số tùy chọn thứ hai "trước" cho người gọi sửa đổi *miltipart.FileHeader trước khi lưu vào đĩa, nó có thể được sử dụng để thay đổi tên tệp dựa trên yêu cầu hiện tại, tất cả các tùy chọn của FileHeader có thể được thay đổi. Bạn có thể bỏ qua nó nếu bạn không cần sử dụng chức năng này trước khi lưu tệp vào đĩa.

Lưu ý rằng nó không kiểm tra nếu yêu cầu được truyền phát.

Trả về độ dài được sao chép là int64 và không phải là lỗi nếu ít nhất một tệp mới không thể được tạo do quyền của hệ điều hành hoặc net/http.ErrMissingFile nếu không nhận được tệp.

Nếu bạn muốn nhận và chấp nhận các tệp và quản lý chúng theo cách thủ công, bạn có thể sử dụng Context.FormFile thay thế và tạo một chức năng sao chép phù hợp với nhu cầu của bạn, dưới đây là để sử dụng chung.

Kích thước tối đa bộ nhớ của biểu mẫu mặc định là 32MB, nó có thể được thay đổi bởi bộ cấu hình iris#WithPostMaxMemory ở cấu hình chính được truyền trên đối số thứ hai của app.Run.

UploadFormFiles(destDirectory string,
                before ...func(Context, *multipart.FileHeader)) (n int64, err error)

Ví dụ:

const maxSize = 5 << 20 // 5MB

func main() {
    app := iris.Default()
    app.Post("/upload", iris.LimitRequestBodySize(maxSize), func(ctx iris.Context) {
        //
        // UploadFormFiles
        // uploads any number of incoming files ("multiple" property on the form input).
        //

        // The second, optional, argument
        // can be used to change a file's name based on the request,
        // at this example we will showcase how to use it
        // by prefixing the uploaded file with the current user's ip.
        ctx.UploadFormFiles("./uploads", beforeSave)
    })

    app.Run(iris.Addr(":8080"))
}

func beforeSave(ctx iris.Context, file *multipart.FileHeader) {
    ip := ctx.RemoteAddr()
    // make sure you format the ip in a way
    // that can be used for a file name (simple case):
    ip = strings.Replace(ip, ".", "_", -1)
    ip = strings.Replace(ip, ":", "_", -1)

    // you can use the time.Now, to prefix or suffix the files
    // based on the current time as well, as an exercise.
    // i.e unixTime :=    time.Now().Unix()
    // prefix the Filename with the $IP-
    // no need for more actions, internal uploader will use this
    // name to save the file into the "./uploads" folder.
    file.Filename = ip + "-" + file.Filename
}

curl

curl -X POST http://localhost:8080/upload \
  -F "files[]=@./myfile.zip" \
  -F "files[]=@./mysecondfile.zip" \
  -H "Content-Type: multipart/form-data"

Xem thêm ví dụ tại https://github.com/kataras/iris/tree/master/_examples/http_request.

Phần tiếp theo chúng ta sẽ tìm hiểu về Model Validation.

Bình luận

avatar
Trịnh Minh Thúy 2020-02-19 04:48:47.116924 +0000 UTC
Hay quá
Avatar
avatar
Nguyễn Hàn Duy 2020-03-02 03:35:22.976258 +0000 UTC
Thanks ad
Avatar
* Vui lòng trước khi bình luận.
Ảnh đại diện
  0 Thích
0