go - 不可能的类型切换案例: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:未定义:民意调查
解决方案
这段代码并不优雅,但现在可以使用。
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()
}
}
推荐阅读
- java - 如果我们使用 requestdispatcher.forward() 转发来自 spring mvc 的请求并且仍然返回 true 会发生什么?
- r - 有没有一个函数可以接近() %in% 是 == 吗?
- java - java火花1.6 csv文件
- python - Odoo 11如何覆盖one2many字段的自动生成模式视图
- sql - SQL Server:计算一条记录可以应用于表的次数
- c# - 如何在 C# 中使用 mailkit 在草稿中添加字节 [] 附件
- jenkins - 有没有办法在有条件的情况下跳过整个 Jenkins 流水线(不是阶段)
- windows - 你能用 AutoHotkey 绑定一个键来最小化所有打开的窗口吗?
- python - 如何按单元格/元素将自定义函数应用于两个数据框?
- r - R:Renderui 没有正确初始化