Files
  • main.go
  • client
  • data
main.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
71
72
73
74
75
76
77
78
79
80
81
82
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
)

func main() {
	var data [][]string
	parse(&data)

	reversed := reverse(data)

	// Handle requests for the main page
	http.Handle("/", http.FileServer(http.Dir("./client")))

	// Handle requests for the lottery data
	http.HandleFunc("/data/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		params := r.URL.Query()

		from, until := 0, len(data)
		if val, ok := params["from"]; ok {
			if n, _ := strconv.Atoi(val[0]); n > 0 {
				if from = n; n > len(data) {
					from = len(data)
				}
			}
		}

		if val, ok := params["until"]; ok {
			if n, _ := strconv.Atoi(val[0]); n > 0 {
				if until = n; n > len(data) {
					until = len(data)
				}
			}
		}

		var obj [][]string
		if val, ok := params["sort"]; ok && val[0] == "old" {
			obj = reversed[from:until]
		} else {
			obj = data[from:until]
		}

		b, err := json.Marshal(obj)

		if err != nil {
			log.Fatal(err)
		}

		fmt.Fprintf(w, string(b))

	})

	http.ListenAndServe(":8080", nil)
}

// Parse the JSON data
func parse(data *[][]string) {
	b, err := ioutil.ReadFile("data/rawdata.json")

	if err != nil {
		log.Fatal(err)
	}

	json.Unmarshal([]byte(b), data)
}

func reverse(arr [][]string) [][]string {
	a := make([][]string, len(arr))
	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = arr[j], arr[i]
	}
	return a
}