Skip to content

JSONP Response

Learn how to send JSONP responses in Iris.

Basic JSONP Response

go
package main

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

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

    app.Get("/jsonp", func(ctx iris.Context) {
        data := iris.Map{
            "message": "Hello World",
            "status": "success",
        }

        callback := ctx.URLParam("callback")
        ctx.JSONP(data, callback)
    })

    app.Listen(":8080")
}

Custom JSONP Options

go
app.Get("/custom", func(ctx iris.Context) {
    data := iris.Map{
        "name": "John",
        "age":  25,
    }

    callback := ctx.URLParam("callback")
    ctx.JSONP(data, callback, iris.JSONP{
        Indent: "    ",
        Prefix: ")]}',\n",
    })
})

Error Handling

go
app.Get("/error", func(ctx iris.Context) {
    callback := ctx.URLParam("callback")
    if callback == "" {
        ctx.StopWithError(iris.StatusBadRequest, fmt.Errorf("callback parameter is required"))
        return
    }

    data := iris.Map{
        "error": "Something went wrong",
        "code":  500,
    }

    ctx.JSONP(data, callback)
})

Best Practices

  1. Security:

    • Validate callback
    • Escape output
    • Set headers
    • Handle errors
    • Monitor usage
  2. Performance:

    • Enable compression
    • Cache responses
    • Monitor size
    • Handle timeouts
    • Optimize output
  3. Implementation:

    • Follow standards
    • Handle errors
    • Document usage
    • Test thoroughly
    • Monitor issues
  4. Maintenance:

    • Regular updates
    • Monitor usage
    • Update security
    • Document changes
    • Review code

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