Skip to content

Instantly share code, notes, and snippets.

@strothj
Created May 19, 2016 05:02
Show Gist options
  • Save strothj/78cc9e1e4756c17f6680e4e4412541cb to your computer and use it in GitHub Desktop.
Save strothj/78cc9e1e4756c17f6680e4e4412541cb to your computer and use it in GitHub Desktop.
package khp
import (
"encoding/hex"
"errors"
"net"
"net/http"
"net/url"
"strings"
"golang.org/x/net/context"
)
// ParseKeyserver returns a url.URL from keyserver.
func ParseKeyserver(keyserver string) (string, error) {
url, err := url.Parse(keyserver)
if err != nil {
return "", nil
}
url.Path = ""
if strings.ToLower(url.Scheme) == "hkp" {
url.Scheme = "http"
host, port, err := net.SplitHostPort(url.Host)
if err != nil {
if nerr, b := err.(*net.AddrError); b {
if nerr.Err == "missing port in address" {
url.Host = net.JoinHostPort(url.Host, "11371")
return url.String(), nil
}
return "", err
}
return "", err
}
if len(port) == 0 {
url.Host = net.JoinHostPort(host, "11371")
}
}
if strings.ToLower(url.Scheme) == "hkps" {
url.Scheme = "https"
}
return url.String(), nil
}
package khp
import (
"testing"
)
var parseTests = []struct {
url string
parsed string
err error
}{
{"http://example.com/asdfasdf", "http://example.com", nil},
{"http://example.com", "http://example.com", nil},
{"https://example.com", "https://example.com", nil},
{"https://example.com/asdfasdf", "https://example.com", nil},
{"hkp://example.com", "http://example.com:11371", nil},
{"hkp://example.com/asdfasd", "http://example.com:11371", nil},
{"hkp://example.com:1234", "http://example.com:1234", nil},
{"hkp://example.com:1234/asdfasd", "http://example.com:1234", nil},
{"hkps://example.com", "https://example.com", nil},
{"hkps://example.com/asdfads", "https://example.com", nil},
{"hkps://example.com:1234", "https://example.com:1234", nil},
{"hkps://example.com:1234/asdf", "https://example.com:1234", nil},
}
func TestParseKeyServer(t *testing.T) {
for _, test := range parseTests {
parsed, err := ParseKeyserver(test.url)
if err != test.err {
t.Fatalf("err url=%v actual=%v expected=%v", test.url, err, test.err)
}
if parsed != test.parsed {
t.Fatalf("parsed actual=%v expected=%v", parsed, test.parsed)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment