Iris
Getting Started
  • What is Iris
  • 📌Getting started
    • Installation
    • Quick start
  • 🔌Routing
    • Middleware
    • API Versioning
  • 🗜️Compression
    • Index
  • ✈️Redirect
    • Redirect from Context
    • Rewrite Middleware
    • Multi Application Instances
  • 🖼️ View/Templates
    • Documentation
    • Benchmarks
    • ➲ Examples
  • 📁File Server
    • Introduction
    • Listing
    • In-memory Cache
    • HTTP/2 Push + Embedded + Cache and Compression
    • The PrefixDir function
    • Serve files from Context
    • ➲ Examples
  • 🌎Localization
    • Documentation
    • Sitemap
    • ➲ Examples
  • 🛡️Security
    • Basic Authentication
    • CORS
    • Sessions & Cookies
    • CSRF
    • JSON Web Tokens
    • Access Control
    • Anti-bot CAPTCHA
    • ➲ Examples
  • 🚀Responses
    • Text
    • HTML
    • Markdown
    • XML
    • YAML
    • Binary
    • JSON
    • JSONP
    • Problem
    • Protocol Buffers
    • MessagePack
    • Gzip
    • Content Negotiation
    • Stream
    • Server-Sent Events
    • HTTP/2 Push
    • Recorder
    • Outroduction
    • ➲ Examples
  • 📥Requests
    • URL Query
    • Headers
    • URL Path Parameters
    • Form
    • Text
    • XML
    • YAML
    • Binary
    • JSON
    • Validation
    • Protocol Buffers
    • MessagePack
    • Gzip
    • ➲ Examples
  • 💉Dependency Injection
    • Documentation
    • Register Dependency from Context
    • Inputs
    • Outputs
    • ➲ Examples
  • 🦏MVC
    • Quick start
    • Documentation
    • Handle Errors
    • Sessions
    • Websockets
    • gRPC
    • ➲ Examples
  • 🤓Resources
    • Examples
    • Starter Kits
    • Publications
    • Benchmarks
    • Support
  • 📘Contents
    • Host
      • Automatic Public Domain with TLS
    • Configuration
    • Routing
      • Path Parameter Types
      • Reverse Lookups
      • Handle HTTP errors
      • Subdomains
      • Wrap the Router
      • Context Methods
    • HTTP Method Override
    • HTTP Referrer
    • URL Query Parameters
    • Forms
    • Model Validation
    • Cache
    • Cookies
    • Sessions
      • Database
      • Flash Messages
    • Websockets
    • Sitemap
    • Localization
    • Testing
Powered by GitBook
On this page
  • What is JSONP, and why was it created?
  • Send JSONP with Iris

Was this helpful?

  1. 🚀Responses

JSONP

Content-Type: "text/javascript"

What is JSONP, and why was it created?

Say you're on domain example.com, and you want to make a request to domain example.net. To do so, you need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is <script> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.

Enter JSONP. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

For example, say the server expects a parameter called callback to enable its JSONP capabilities. Then your request would look like:

http://www.example.net/sample?callback=mycallback

Without JSONP, this might return some basic JavaScript object, like so:

{ "foo": "bar" }

However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

mycallback({ "foo": "bar" });

As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:

mycallback = function(data){
  alert(data.foo);
};

And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!

It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.

https://stackoverflow.com/a/2067584 (source)

Send JSONP with Iris

The Context.JSONP(v, ...opts) is the method which sends JSONP responses to the client. It accepts the value and optional settings for rendering. The JSONP options structure looks like this:

type JSONP struct {
	Indent   string
	Callback string
}

If Indent field is empty and the application runs without optimizations, the Indent field will be automatically set to 4 spaces.

So, if we want to write a JSONP with indentation of two spaces and a callback extracted from URL Query Parameter of ?callback=mycallback, we write something like that:

func handler(ctx iris.Context) {
    callback := ctx.URLParamDefault("callback", "defaultCallback")
    response := map[string]interface{}{"foo": "bar"}
    options := iris.JSONP{Indent: "  ", Callback:true}
    ctx.JSONP(response, options)
}
type Item struct {
    Name    string `json:"name"`
}

func handler(ctx iris.Context) {
    response := Item{
        Name: "gopher",
    }

    ctx.JSONP(response, iris.JSONP{Callback: "addToCard"})
}
PreviousJSONNextProblem

Last updated 1 year ago

Was this helpful?

However, CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.

If we want to render a Go struct as JSONP's callback data, the struct's fields we want to render should be , and optionally tagged with the json struct tag. Look the exaple below:

*
exported