yatwiki/AuthorHash.go

27 lines
603 B
Go

package yatwiki
import (
"crypto/md5"
"encoding/hex"
"net/http"
"strings"
)
func RemoteAddrToIPAddress(remoteAddr string) string {
return strings.TrimRight(strings.TrimRight(remoteAddr, `0123456789`), `:`) // trim trailing port; IPv4 and IPv6-safe
}
func Author(r *http.Request, trustXForwardedFor bool) string {
userAgentHash := md5.Sum([]byte(r.UserAgent()))
ipAddress := RemoteAddrToIPAddress(r.RemoteAddr)
if trustXForwardedFor {
if xff := r.Header.Get("X-Forwarded-For"); len(xff) > 0 {
ipAddress = xff
}
}
return ipAddress + "-" + hex.EncodeToString(userAgentHash[:])[:6]
}