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
|
package main
import (
"fmt"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("static"))
var logs [100]string
n := 0
// Define a handler function for the root path
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
addRotLog(&logs, &n, fmt.Sprintf("Accessed %s", r.URL.Path))
// Serve the index.html file from the static directory
http.StripPrefix("/", fs).ServeHTTP(w, r)
})
http.HandleFunc("/logs", createGetLogs(&logs))
http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "foo!")
})
// Start the server on port 8080
fmt.Println("Server is listening on port 8080...")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Error starting server: %s\n", err)
}
}
func createGetLogs(logs *[100]string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
for _, s := range logs {
fmt.Fprintln(w, s)
}
}
}
func addRotLog(logs *[100]string, last *int, value string) {
if *last == 100 {
for i := 0 ; i < 99; i++ {
logs[i] = logs[i+1]
}
} else {
logs[*last] = value
*last++
}
}
|