Skip to content

Commit

Permalink
Improve error messsages
Browse files Browse the repository at this point in the history
  • Loading branch information
balki committed Apr 28, 2023
1 parent d983f84 commit bbd21d7
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions anyhttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,24 +115,24 @@ func (s *SysdConfig) GetListener() (net.Listener, error) {
if s.CheckPID {
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil {
return nil, err
return nil, fmt.Errorf("invalid LISTEN_PID, err: %w", err)
}
if pid != os.Getpid() {
return nil, fmt.Errorf("fd not for you")
return nil, fmt.Errorf("unexpected PID, current:%v, LISTEN_PID: %v", os.Getpid(), pid)
}
}

numFds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
if err != nil {
return nil, err
return nil, fmt.Errorf("invalid LISTEN_FDS, err: %w", err)
}

fdNames := strings.Split(os.Getenv("LISTEN_FDNAMES"), ":")

if s.FDIndex != nil {
idx := *s.FDIndex
if idx < 0 || idx >= numFds {
return nil, fmt.Errorf("invalid fd")
return nil, fmt.Errorf("invalid fd index, expected between 0 and %v, got: %v", numFds, idx)
}
fd := StartFD + idx
if idx < len(fdNames) {
Expand All @@ -148,10 +148,17 @@ func (s *SysdConfig) GetListener() (net.Listener, error) {
return makeFdListener(fd, name)
}
}
return nil, fmt.Errorf("fdName not found: %q", *s.FDName)
return nil, fmt.Errorf("fdName not found: %q, LISTEN_FDNAMES:%q", *s.FDName, os.Getenv("LISTEN_FDNAMES"))
}

return nil, fmt.Errorf("neither FDIndex nor FDName set")
return nil, errors.New("neither FDIndex nor FDName set")
}

// UnknownAddress Error is returned when address does not match any known syntax
type UnknownAddress string

func (u UnknownAddress) Error() string {
return fmt.Sprintf("unknown address: %q", string(u))
}

// GetListener gets a unix or systemd socket listener
Expand All @@ -164,7 +171,7 @@ func GetListener(addr string) (net.Listener, error) {
if strings.HasPrefix(addr, "sysd/fdidx/") {
idx, err := strconv.Atoi(strings.TrimPrefix(addr, "sysd/fdidx/"))
if err != nil {
return nil, err
return nil, fmt.Errorf("invalid fdidx, addr:%q err: %w", addr, err)
}
sysdc := NewSysDConfigWithFDIdx(idx)
return sysdc.GetListener()
Expand All @@ -175,15 +182,15 @@ func GetListener(addr string) (net.Listener, error) {
return sysdc.GetListener()
}

return nil, nil
return nil, UnknownAddress(addr)
}

// ListenAndServe is the drop-in replacement for `http.ListenAndServe`.
// Supports unix and systemd sockets in addition
func ListenAndServe(addr string, h http.Handler) error {

listener, err := GetListener(addr)
if err != nil {
if _, ok := err.(UnknownAddress); err != nil && !ok {
return err
}

Expand Down

0 comments on commit bbd21d7

Please sign in to comment.