[Golang] JSONP Server Implementation Code


My previous posts [4] shows how to use JSONP in front-end to request data from a server in different domain. In this post, we will show how to implement the back-end server that returns data (HTTP request headers) with Go programming language.

You need to have some basic knowledge about writing web applications in Go. Please refer to [2] if you have no idea about Go web applications.

The basic idea of JSONP server is as follows:

  1. Get the name of front-end callback function from the query string in HTTP request.
  2. Encode the data to be returned to the client in JSON format. In this case, it's the HTTP headers encoded in JSON.
  3. Set the Content-Type as application/javascript in HTTP response.
  4. return the string callbackName(JSONString); to the client, where callbackName is the name of callback in query string, and JSONString is the JSON-encoded data in step 2.

The complete implementation in Go is as follows:

server.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, indexHtml)
}

func jsonpHandler(w http.ResponseWriter, r *http.Request) {
	callbackName := r.URL.Query().Get("callback")
	if callbackName == "" {
		fmt.Fprintf(w, "Please give callback name in query string")
		return
	}

	b, err := json.Marshal(r.Header)
	if err != nil {
		fmt.Fprintf(w, "json encode error")
		return
	}

	w.Header().Set("Content-Type", "application/javascript")
	// return `callbackName(jsonString);`
	fmt.Fprintf(w, "%s(%s);", callbackName, b)
}

func main() {
	http.HandleFunc("/jsonp", jsonpHandler)
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8000", nil)
}

The front-end code for this JSONP server is as follows:

index.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

const indexHtml = `<!DOCTYPE html>
<html>
<head><title>Go JSONP Server</title></head>
<body>
<button id="btn">Click to get HTTP header via JSONP</button>
<pre id="result"></pre>
<script>
'use strict';

var btn = document.getElementById("btn");
var result = document.getElementById("result");

function myCallback(acptlang) {
  result.innerHTML = JSON.stringify(acptlang, null, 2);
}

function jsonp() {
  result.innerHTML = "Loading ...";
  var tag = document.createElement("script");
  tag.src = "/jsonp?callback=myCallback";
  document.querySelector("head").appendChild(tag);
}

btn.addEventListener("click", jsonp);
</script>
</body>
</html>`

Tested on:

  • Ubuntu Linux 16.10
  • Go 1.8
  • Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[1]
[2]
[3]JSON and Go - The Go Blog
[4]