为什么代理未定义?

时间:2017-12-26 13:02:45

标签: go

func check(e error) {
  if e != nil {
    panic(e)
  }
}
func main() {
  addr := flag.String("addr", ":9999", "server addr")
  flag.Parse()
  http.HandleFunc("/", WhitelistHandler)
  http.ListenAndServe(*addr, nil)
}
func WhitelistHandler(w http.ResponseWriter, r *http.Request) {
  pwd, _ := os.Getwd()
  dat, err := ioutil.ReadFile(pwd + "/whitelist.pac")
  check(err)
  p := strings.Split(r.URL.Path, "/")
  if len(p) > 1 {
    proxy := p[1]
  } else {
    proxy := "127.0.0.1:9998"
  }
  if strings.Contains(p[0], "socks") {
    io.WriteString(w, string(`var wall_proxy = "SOCKS5 `) + string(proxy) + string(";SOCKS ") + string(proxy) + string(`;";`) + string("\n") + string(dat))
  } else {
    io.WriteString(w, string(`var wall_proxy = "PROXY `) + string(proxy) + string(`";`) + string("\n") + string(dat))
  }
}

如果我这样做,我会得到:

./gowhitelist.go:36:68: undefined: proxy
./gowhitelist.go:38:67: undefined: proxy

1 个答案:

答案 0 :(得分:4)

  

为什么代理未定义?

因为它被if声明隐藏。

您需要在proxy语句之前定义if变量:

proxy := "" // or var proxy string
if len(p) > 1 {
  proxy = p[1]
} else {
  proxy = "127.0.0.1:9998"
}