-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod_ajax.go
59 lines (52 loc) · 1.27 KB
/
mod_ajax.go
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"fmt"
"html/template"
"net/http"
"time"
)
var page = `
<script type="text/javascript">
var int=self.setInterval("ajaxFunction()",1000);
function ajaxFunction(){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "/ajax?api=showclock", true);
ajaxRequest.send(null);
}
</script>
<pre><a id='ajaxDiv'></a></pre>`
func ajax(w http.ResponseWriter, r *http.Request) {
//this must add at begin of every session code
c, err := r.Cookie("session")
if err != nil || c.Value == "" {
http.Error(w, "Session expired", 401)
return
}
//return results request by ajax page
if r.Method == "GET" {
if r.FormValue("api") == "showclock" {
fmt.Fprint(w, time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"))
return
}
}
//build page content
b := `<pre>
This module is a simple ajax application who show a real time clock.</pre>` + page
//finally show the page
p := Page{
Title: "Test page",
Status: c.Value,
Body: template.HTML(b),
}
t.ExecuteTemplate(w, "index.html", p)
}
func init() {
http.HandleFunc("/ajax", ajax)
}