dip/functions.go
2020-01-26 16:38:57 +01:00

109 lines
2.2 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"github.com/gobuffalo/packr/v2"
"github.com/labstack/echo/v4"
"github.com/likexian/whois-go"
whoisparser "github.com/likexian/whois-parser-go"
)
// GetIPInfo returns IP address informations
func (ip *IP) GetIPInfo(c echo.Context) (err error) {
if c.QueryParam("ip") != "" {
ip.IP = c.QueryParam("ip")
} else {
ip.IP = c.RealIP()
}
err = ip.CheckIPAddress()
if err != nil {
return err
}
err = ip.GetHostname()
if err != nil {
log.Println(err)
}
return
}
// Dip returns webpage
func Dip(c echo.Context) (err error) {
var ip IP
ip.GetIPInfo(c)
if strings.Contains(c.Request().Header.Get(echo.HeaderAccept), echo.MIMETextHTML) {
return c.Render(http.StatusOK, "index.html", ip)
} else {
return c.JSON(http.StatusOK, ip)
}
}
// Static ...
func Static(box *packr.Box, c echo.Context) (err error) {
name := c.Param("*")
cnt, _ := box.FindString(name)
if strings.HasSuffix(name, ".js") {
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJavaScript)
} else if strings.HasSuffix(name, ".css") {
c.Response().Header().Set(echo.HeaderContentType, "text/css")
}
return c.String(http.StatusOK, cnt)
}
// CheckIPAddress check if ip is an IP address, return err if there's an error
func (ip *IP) CheckIPAddress() (err error) {
addr := net.ParseIP(ip.IP)
if addr == nil {
return fmt.Errorf("Supplied string isn't an IP address \"%s\"", ip.IP)
}
return
}
// GetHostname assign ip.Hostname value
func (ip *IP) GetHostname() (err error) {
revip, err := net.LookupAddr(ip.IP)
if err != nil {
return err
}
ip.Hostname = revip[0]
return
}
// GetWhois not implemented yet
func (ip *IP) GetWhois() (err error) {
resultraw, err := whois.Whois("example.com")
//resultraw, err := whois.Whois(ip.IP)
fmt.Println(resultraw)
result, err := whoisparser.Parse(resultraw)
if err != nil {
return
}
fmt.Println(result)
return
}
// Usage displays possible arguments
func Usage() {
flag.PrintDefaults()
os.Exit(1)
}
// IP defines dip main struct
type IP struct {
IP string `json:"ip"`
Hostname string `json:"hostname"`
City string `json:"city"`
Country string `json:"country"`
}