Catalogue
Asynchronous Processing with jQuery in the Go Revel Framework

Asynchronous Processing with jQuery in the Go Revel Framework

🌐 日本語で読む

Overview

We’ll implement asynchronous Ajax processing in the Go Revel framework.

CSRF Protection

Install the library for CSRF protection in the Revel framework with the following command:

1
$ go get github.com/cbonello/revel-csrf
  • app/init.go

To run the CSRF check at Ajax execution time, configure init.go so that the check is disabled there.

The CSRF filter configuration is shown below.

1
2
3
4
5
6
func init()
revel.Filters = []revel.Filter{
...
...
csrf.CSRFFilter, // CSRF prevention.
...

Since the API URL invoked in conf/routes is checked for CSRF at Ajax execution time,
configure init.go to exclude it from the check.

1
csrf.ExemptedFullPath("/api_execute")

View-side Configuration

  • views/header.html

Embed the hash value for the CSRF check as meta information inside <head>〜</head>.

1
<meta name="csrf-token" content="{{ .csrf_token }}">

jQuery File

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
function setAjaxToken( token ) {
// ajax --- start --------------------------------------------------
$.ajaxSetup({
crossDomain: false,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", token );
}
}
});
}

$(document).ready(function () {
$(document).on("click", ".ajax_execute", function (event) {
event.preventDefault();

setAjaxToken( postData['_token'] );

var ajaxParamas = {};
ajaxParamas["type"] = "POST";
ajaxParamas["url"] = action;
ajaxParamas["data"] = postData;
ajaxParamas["cache"] = false;
ajaxParamas["dataType"] = "json";

$.ajax(ajaxParamas)
.success( function(res) {
console.log("(^-^) OK")
}).error ( function() {
console.log("(>_<) NG")
});
return false;
})

It may not have been quite as simple as I’d hoped, but
we’ve got CSRF protection in place.

kenzo0107

kenzo0107