-
Notifications
You must be signed in to change notification settings - Fork 6
/
ajax-octet.go
47 lines (39 loc) · 1.08 KB
/
ajax-octet.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
// Minimal Client/Server AJAX Communication using golang web-server and JQuery
// Visit: http://127.0.0.1:8080
package main
import (
"encoding/json"
"html/template"
"net/http"
"path"
)
type Data struct {
Name string
}
// Default Request Handler
func defaultHandler(w http.ResponseWriter, r *http.Request) {
fp := path.Join("templates", "ajax-octet.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// AJAX Request Handler
func ajaxHandler(w http.ResponseWriter, r *http.Request) {
data := Data{"World!"}
w.Header().Set("Content-type", "application/json")
err := json.NewEncoder(w).Encode(&data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
func main() {
http.HandleFunc("/", defaultHandler)
http.HandleFunc("/ajax", ajaxHandler)
http.ListenAndServe(":8080", nil)
}