-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
handle_index.go
50 lines (43 loc) · 1002 Bytes
/
handle_index.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
package main
import (
"fmt"
"log"
"net"
"net/http"
"strings"
"gopkg.in/yaml.v3"
)
func (s *server) handleIndex() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
ip := net.ParseIP(r.RemoteAddr)
if ip != nil {
// redirect to IP
w.Header().Set("Location", "/"+ip.String())
w.WriteHeader(http.StatusFound)
return
}
// try to parse ID from request path
ip = net.ParseIP(strings.Trim(r.URL.Path[1:], " /"))
if ip != nil {
// redirect to IP
w.Header().Set("Location", "/"+ip.String())
w.WriteHeader(http.StatusFound)
return
}
b, err := yaml.Marshal(response{
IP: r.RemoteAddr,
UserAgent: r.UserAgent(),
})
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, string(b))
}
}