1
0
Fork 0

resolver: make decoders return string instead of byte slice

This commit is contained in:
Henrik Hautakoski 2026-02-19 10:23:11 +01:00
parent ae79cd131e
commit c36a83c9b8
3 changed files with 16 additions and 20 deletions

View file

@ -5,16 +5,12 @@ import (
"io" "io"
) )
func Jsonip(r io.Reader) ([]byte, error) { func Jsonip(r io.Reader) (string, error) {
var v struct { var v struct {
Ip string `json:"ip"` Ip string `json:"ip"`
Location string `json:"geo-ip"` Location string `json:"geo-ip"`
Help string `json:"API Help"` Help string `json:"API Help"`
} }
var val []byte
err := json.NewDecoder(r).Decode(&v) err := json.NewDecoder(r).Decode(&v)
if err == nil { return v.Ip, err
val = []byte(v.Ip)
}
return val, err
} }

View file

@ -5,16 +5,12 @@ import (
"io" "io"
) )
func MyIP(r io.Reader) ([]byte, error) { func MyIP(r io.Reader) (string, error) {
var v struct { var v struct {
Ip string `json:"ip"` Ip string `json:"ip"`
Country string `json:"country"` Country string `json:"country"`
Cc string `json:"cc"` Cc string `json:"cc"`
} }
var val []byte
err := json.NewDecoder(r).Decode(&v) err := json.NewDecoder(r).Decode(&v)
if err == nil { return v.Ip, err
val = []byte(v.Ip)
}
return val, err
} }

View file

@ -1,6 +1,7 @@
package http package http
import ( import (
"bufio"
"context" "context"
"io" "io"
"net" "net"
@ -11,7 +12,7 @@ import (
"dnsupdater/ip/internal" "dnsupdater/ip/internal"
) )
type Decoder func(io.Reader) ([]byte, error) type Decoder func(io.Reader) (string, error)
type Service struct { type Service struct {
ServiceName string ServiceName string
@ -31,16 +32,19 @@ func (s Service) Lookup(ctx context.Context) (net.IP, error) {
} }
if s.Decoder == nil { if s.Decoder == nil {
s.Decoder = io.ReadAll s.Decoder = func(r io.Reader) (string, error) {
line, err := bufio.NewReader(r).ReadString('\n')
if err == nil || err == io.EOF {
line = strings.TrimRight(line, "\r\n")
line = strings.TrimSpace(line)
}
return line, err
}
} }
body, err := s.Decoder(resp.Body) body, err := s.Decoder(resp.Body)
if err != nil { if err != nil && err != io.EOF {
return nil, err return nil, err
} }
return internal.ParseIP(string(body))
// Trim spaces and stuff.
ip_str := strings.TrimSpace(string(body))
return internal.ParseIP(ip_str)
} }