44 lines
1.3 KiB
Go
44 lines
1.3 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
)
|
|
|
|
// Display some information about this API for the default page
|
|
// TODO - static fileserver with docs
|
|
func HomeLink(w http.ResponseWriter, r *http.Request) {
|
|
//w.WriteHeader(http.StatusNotImplemented)
|
|
fmt.Fprintf(w, "VM Chargeback Tracking Program. API interface only. See Nathan Coad (nathan.coad@dell.com) for further details. ")
|
|
}
|
|
|
|
// Display error message for invalid requests
|
|
func HandleNotFound(w http.ResponseWriter, r *http.Request) {
|
|
ip, err := IPFromRequest(r)
|
|
if err != nil {
|
|
fmt.Println("Error", err)
|
|
http.Error(w, "VM Chargeback Tracking Program.. Invalid Path Specified.", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
fmt.Printf("Request from IP %s\n", ip.String())
|
|
http.Error(w, "VM Chargeback Tracking Program. Invalid Path Specified.", http.StatusNotFound)
|
|
// TODO - investigate rate limiting for invalid requests
|
|
}
|
|
|
|
// IPFromRequest extracts the user IP address from req, if present.
|
|
// @see https://blog.golang.org/context/userip/userip.go
|
|
func IPFromRequest(req *http.Request) (net.IP, error) {
|
|
ip, _, err := net.SplitHostPort(req.RemoteAddr)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
|
|
}
|
|
|
|
userIP := net.ParseIP(ip)
|
|
if userIP == nil {
|
|
return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
|
|
}
|
|
return userIP, nil
|
|
}
|