This repository has been archived on 2021-08-10. You can view files and clone it, but cannot push or open issues or pull requests.
gtools/nettools/net.go
Michael 59aa50a521 access message function
Signed-off-by: Michael <michael.lindman@gmail.com>
2020-09-21 19:09:28 +01:00

50 lines
1.1 KiB
Go

package nettools
import (
"fmt"
"html"
"net"
"net/http"
"git.0cd.xyz/michael/gtools/colour"
)
// IP returns IP address from requester
func IP(r *http.Request) (net.IP, error) {
realip := r.Header.Get("x-forwarded-for")
if realip != "" {
return net.ParseIP(realip), nil
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return nil, err
}
return net.ParseIP(ip), nil
}
// Hostname returns hostname
func Hostname(ip net.IP) ([]string, error) {
names, err := net.LookupAddr(ip.String())
unknown := []string{"unknown host"}
if err != nil {
return unknown, err
}
if len(names) == 0 {
return unknown, fmt.Errorf("unknown hostname for %v", ip.String())
}
return names, nil
}
// AccessMessage returns client access message
func AccessMessage(r *http.Request, statuscode int) (out string, err error) {
ip, err := IP(r)
if err != nil {
return "", err
}
hostname, err := Hostname(ip)
if err != nil {
return "", err
}
return fmt.Sprintf("%s %v - %s %s %s\n", ip, hostname, r.Method, colour.Status(statuscode), html.EscapeString(r.URL.Path)), nil
}