add command line flags
This commit is contained in:
parent
a1d3313299
commit
4b0f083f72
43
whoami.go
43
whoami.go
@ -3,38 +3,49 @@ package main
|
||||
import (
|
||||
"net/http"
|
||||
"net"
|
||||
"strings"
|
||||
"encoding/base32"
|
||||
"os"
|
||||
"strings"
|
||||
"flag"
|
||||
)
|
||||
|
||||
// DomainFromIP derives a meshname subdomain for the authoritative DNS server address
|
||||
func DomainFromIP(target net.IP) string {
|
||||
|
||||
// define tld
|
||||
var tld = flag.String("tld", "mesh.cat", "The top level domain for our network")
|
||||
|
||||
// domainFromIP derives a meshname subdomain for the authoritative DNS server address
|
||||
func domainFromIP(target net.IP) string {
|
||||
host := strings.ToLower(base32.StdEncoding.EncodeToString(target)[0:26])
|
||||
tld := ".mesh.cat"
|
||||
domain := strings.Join([]string{host, tld}, "")
|
||||
domain := strings.Join([]string{host, ".", *tld, "\n"}, "")
|
||||
return domain
|
||||
}
|
||||
|
||||
// handle HTTP requests
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
ip, port, err := net.SplitHostPort(r.RemoteAddr)
|
||||
_, _ = port, err
|
||||
parsedIP := net.ParseIP(ip)
|
||||
// return domain for IPv6 only
|
||||
if parsedIP.To4() == nil {
|
||||
w.Write([]byte(DomainFromIP(parsedIP)))
|
||||
w.Write([]byte(domainFromIP(parsedIP)))
|
||||
} else {
|
||||
// set the response status code to 422
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
w.Write([]byte("ipv4 not supported\n"))
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// define path
|
||||
http.HandleFunc("/", handler)
|
||||
listenPort := "3000"
|
||||
// Get the first command-line argument
|
||||
if len(os.Args) > 1 {
|
||||
listenPort = os.Args[1]
|
||||
}
|
||||
print("Listening on port: ", listenPort, "\n")
|
||||
listenPort = strings.Join([]string{":", listenPort}, "")
|
||||
http.ListenAndServe(listenPort, nil)
|
||||
// define ip address
|
||||
address := flag.String("address", "[::0]", "The interface address to listen on")
|
||||
// define port
|
||||
port := flag.String("port", "8008", "The port to listen on")
|
||||
// parse the command-line arguments
|
||||
flag.Parse()
|
||||
// construct listening address
|
||||
listenAddr := strings.Join([]string{*address, ":", *port}, "")
|
||||
print("Listening on address: ", listenAddr, "\n")
|
||||
// start server
|
||||
http.ListenAndServe(listenAddr, nil)
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user