40 lines
1.1 KiB
Go
40 lines
1.1 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"velvettear/godyn/config"
|
|
"velvettear/godyn/log"
|
|
)
|
|
|
|
// exported function(s)
|
|
func Run() {
|
|
log.Debug("starting godyn in server mode")
|
|
serverAddress := config.ServerListen() + ":" + strconv.Itoa(config.ServerPort())
|
|
http.HandleFunc("/", handleRequests)
|
|
log.Info("starting server '" + serverAddress + "'...")
|
|
err := http.ListenAndServe(serverAddress, nil)
|
|
if err != nil {
|
|
log.Fatal("encountered an error starting the server", err.Error())
|
|
}
|
|
}
|
|
|
|
// unexported function(s)
|
|
func handleRequests(writer http.ResponseWriter, request *http.Request) {
|
|
timestamp := time.Now()
|
|
ip := strings.TrimSpace(request.Header.Get("X-Real-Ip"))
|
|
if len(ip) == 0 {
|
|
if strings.HasPrefix(request.RemoteAddr, "[::") {
|
|
writer.WriteHeader(500)
|
|
writer.Write([]byte("error: could not process request\n"))
|
|
log.WarningTimed("could not answert request from '"+request.RemoteAddr+"'", timestamp.UnixMilli())
|
|
return
|
|
}
|
|
ip, _, _ = strings.Cut(request.RemoteAddr, ":")
|
|
}
|
|
writer.WriteHeader(200)
|
|
writer.Write([]byte(ip + "\n"))
|
|
log.InfoTimed("answered request from '"+ip+"'", timestamp.UnixMilli())
|
|
}
|