Skip to content

Commit

Permalink
Add /me
Browse files Browse the repository at this point in the history
  • Loading branch information
SomeoneWeird committed Oct 4, 2024
1 parent bbb24e1 commit 06c62d2
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion pkg/api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"net/http"
"regexp"
"strings"

"github.com/dogeorg/reflector/pkg/database"
"github.com/go-chi/chi/v5"
Expand Down Expand Up @@ -38,8 +39,23 @@ func CreateEntry(db *database.Database) http.HandlerFunc {

func GetIP(db *database.Database) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

token := chi.URLParam(r, "token")

if token == "me" {
ip := r.RemoteAddr
if fwdIP := r.Header.Get("X-Forwarded-For"); fwdIP != "" {
ip = fwdIP
}
// Strip the port from the IP address
if colonIndex := strings.LastIndex(ip, ":"); colonIndex != -1 {
ip = ip[:colonIndex]
}
json.NewEncoder(w).Encode(map[string]string{"ip": ip})
return
}

ip, err := db.GetIP(token)
if err != nil {
http.Error(w, "IP not found", http.StatusNotFound)
Expand All @@ -51,7 +67,6 @@ func GetIP(db *database.Database) http.HandlerFunc {
return
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"ip": ip})
}
}
Expand Down

0 comments on commit 06c62d2

Please sign in to comment.