This repository has been archived by the owner on Aug 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainHandler.go
70 lines (60 loc) · 1.77 KB
/
MainHandler.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
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"fmt"
"net/http"
"encoding/json"
)
type MainResponse struct {
AcceptedLanguages []string `json:"acceptedLanguages"`
Readme string `json:"readme,omitempty"`
}
func MakeJson(r *http.Request, mr *MainResponse, pretty bool) (string, string) {
var jsonBytes []byte
if (pretty) {
mr.Readme = "/readme"
jsonBytes, _ = json.MarshalIndent(mr, "", " ")
} else {
jsonBytes, _ = json.Marshal(mr)
}
return string(jsonBytes), "application/json"
}
func MakeJavascript(r *http.Request, mr *MainResponse, pretty bool) (string, string) {
response, _ := MakeJson(r, mr, pretty)
response = "window.visitor = " + response
return response, "text/javascript"
}
func MakeJsonP(r *http.Request, mr *MainResponse, pretty bool) (string, string) {
callback := r.URL.Query().Get("callback")
if callback == "" {
callback = "callback"
}
response, _ := MakeJson(r, mr, pretty)
response = callback + "(" + response + ")"
return response, "text/javascript"
}
func MainHandler(w http.ResponseWriter, r *http.Request) {
format := r.URL.Path[1:]
mr := &MainResponse{}
GetAcceptLanguageResponse(r, mr)
var response string
var contentType string
switch format {
case "jsonp":
response, contentType = MakeJsonP(r, mr, false)
case "js":
response, contentType = MakeJavascript(r, mr, false)
case "json":
response, contentType = MakeJson(r, mr, false)
case "":
response, contentType = MakeJson(r, mr, true)
}
if response != "" {
w.Header().Set("Content-Type", contentType)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-type")
fmt.Fprintln(w, response)
} else {
http.NotFound(w, r)
}
}