swarm/api: implement NoResolverError with information about TLD

MultiResolver needs to provide information about TLD that has
no resolver configured for.
This commit is contained in:
Janos Guljas 2017-12-18 23:07:48 +01:00
parent c0a4d9e1e6
commit 0d6a735a72
2 changed files with 29 additions and 7 deletions

View File

@ -17,7 +17,6 @@
package api package api
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -42,9 +41,22 @@ type Resolver interface {
Resolve(string) (common.Hash, error) Resolve(string) (common.Hash, error)
} }
// errNoResolver is returned by MultiResolver.Resolve if no resolver // NoResolverError is returned by MultiResolver.Resolve if no resolver
// can be found for the address. // can be found for the address.
var errNoResolver = errors.New("no resolver") type NoResolverError struct {
TLD string
}
func NewNoResolverError(tld string) *NoResolverError {
return &NoResolverError{TLD: tld}
}
func (e *NoResolverError) Error() string {
if e.TLD == "" {
return "no ENS resolver"
}
return fmt.Sprintf("no ENS endpoint configured to resolve .%s TLD names", e.TLD)
}
// MultiResolver is used to resolve URL addresses based on their TLDs. // MultiResolver is used to resolve URL addresses based on their TLDs.
// Each TLD can have multiple resolvers, and the resoluton from the // Each TLD can have multiple resolvers, and the resoluton from the
@ -84,14 +96,16 @@ func NewMultiResolver(opts ...MultiResolverOption) (m *MultiResolver) {
// will be returned. // will be returned.
func (m MultiResolver) Resolve(addr string) (h common.Hash, err error) { func (m MultiResolver) Resolve(addr string) (h common.Hash, err error) {
rs := m.resolvers[""] rs := m.resolvers[""]
if ext := path.Ext(addr); ext != "" { tld := path.Ext(addr)
rstld, ok := m.resolvers[ext[1:]] if tld != "" {
tld = tld[1:]
rstld, ok := m.resolvers[tld]
if ok { if ok {
rs = rstld rs = rstld
} }
} }
if rs == nil { if rs == nil {
return h, errNoResolver return h, NewNoResolverError(tld)
} }
for _, r := range rs { for _, r := range rs {
h, err = r.Resolve(addr) h, err = r.Resolve(addr)

View File

@ -259,7 +259,7 @@ func TestMultiResolver(t *testing.T) {
{ {
desc: "No resolvers, returns error", desc: "No resolvers, returns error",
r: NewMultiResolver(), r: NewMultiResolver(),
err: errNoResolver, err: NewNoResolverError(""),
}, },
{ {
desc: "One default resolver, returns resolved address", desc: "One default resolver, returns resolved address",
@ -332,6 +332,14 @@ func TestMultiResolver(t *testing.T) {
addr: testAddr, addr: testAddr,
result: testHash, result: testHash,
}, },
{
desc: "One TLD resolver, no default resolver, returns error for different TLD",
r: NewMultiResolver(
MultiResolverOptionWithResolver(ethResolve, "eth"),
),
addr: testAddr,
err: NewNoResolverError("test"),
},
} }
for _, x := range tests { for _, x := range tests {
t.Run(x.desc, func(t *testing.T) { t.Run(x.desc, func(t *testing.T) {