Skip to content

Text Request

Learn how to handle text request bodies in Iris.

Basic Text Handling

go
package main

import "github.com/kataras/iris/v12"

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

    app.Post("/text", func(ctx iris.Context) {
        body := ctx.GetBody()
        text := string(body)

        ctx.JSON(iris.Map{
            "received": text,
            "length": len(text),
        })
    })

    app.Listen(":8080")
}

Reading with Size Limit

go
app.Post("/limited", iris.LimitRequestBodySize(1<<20), func(ctx iris.Context) {
    body, err := ctx.GetBody()
    if err != nil {
        ctx.StopWithError(iris.StatusBadRequest, err)
        return
    }

    ctx.JSON(iris.Map{
        "text": string(body),
        "size": len(body),
    })
})

Streaming Text

go
app.Post("/stream", func(ctx iris.Context) {
    reader := ctx.Request().Body
    buffer := make([]byte, 1024)
    content := []byte{}

    for {
        n, err := reader.Read(buffer)
        if err != nil && err != io.EOF {
            ctx.StopWithError(iris.StatusInternalServerError, err)
            return
        }

        if n == 0 {
            break
        }

        content = append(content, buffer[:n]...)
    }

    ctx.JSON(iris.Map{
        "content": string(content),
        "size": len(content),
    })
})

Best Practices

  1. Validation:

    • Check content type
    • Validate encoding
    • Set size limits
    • Handle empty bodies
    • Sanitize input
  2. Performance:

    • Use appropriate buffers
    • Handle large texts
    • Monitor memory usage
    • Implement timeouts
    • Clean resources
  3. Security:

    • Validate input
    • Set size limits
    • Check encoding
    • Monitor usage
    • Handle errors
  4. Implementation:

    • Handle encoding
    • Set timeouts
    • Document limits
    • Test edge cases
    • Log issues

Built with excellence by Hellenic Development, delivering enterprise-grade solutions.