首页 > 解决方案 > 不可能的类型切换案例:ErrorType (type reflect.Type) cannot have dynamic type *os.SyscallError (missing Align method)

问题描述

试图确定连接错误是什么并将值返回给程序。

d := net.Dialer{Timeout: 20*time.Second}
conn, errors := d.Dial("tcp", fmt.Sprintf("%v:%v", host, port))
if errors != nil {
    if oerr, ok := errors.(*net.OpError); ok {
        ErrorType := reflect.TypeOf(oerr.Err)
        switch ErrorType.(type) {
            case *os.SyscallError:
                fmt.Println("connect: connection timed out to", host, "on port", port )
            case *poll.TimeoutError:
                fmt.Println("connect: connection refused to", host, "on port", port )
            default:
                panic("Unknown connection errot")
        }
    }
} else {
    fmt.Println("connect: connection successful to", host, "on port", port )
}

if conn != nil {
    conn.Close()
}

得到以下错误 # command-line-arguments ./main.go:33:9: possible type switch case: ErrorType (type reflect.Type) cannot have dynamic type *os.SyscallError (missing Align method) ./main.go :35:15:未定义:民意调查

标签: go

解决方案


这段代码并不优雅,但现在可以使用。

package main

import (
    "flag"
    "fmt"
    "net"
    "os"
    "time"
)

// Run the port scanner
func main() {
    var host, port string
    flag.StringVar(&host, "H", "", "host to scan")
    flag.StringVar(&port, "p", "", "port to scan")
    flag.Parse()

    if host == "" || port == "" {
        fmt.Println("Usage: portscan -H <host> -p port")
        os.Exit(1)
    }

    d := net.Dialer{Timeout: 20*time.Second}
    conn, errors := d.Dial("tcp", fmt.Sprintf("%v:%v", host, port))
    if errors != nil {
        if oerr, ok := errors.(*net.OpError); ok {
            switch oerr.Err.(type) {
            case *os.SyscallError:
                fmt.Println("connect: connection refused to", host, "on port", port )
            default:
                if oerr.Timeout() {
                    fmt.Println("connect: connection timed out to", host, "on port", port )
                } else {
                    panic("Unknown connection error")
                }
            }
        }
    } else {
        fmt.Println("connect: connection successful to", host, "on port", port )
    }

    if conn != nil {
        conn.Close()
    }
}

推荐阅读