2017-05-14 115 views
-2

我有一个HTTP服务器,我想使用套接字golang http服务器发送r.URL.Path在插座

我得到一个错误发送r.URL.Path文本到客户端:未定义:康恩在conn.Write 这是becauase康恩在另一个函数

定义我曾尝试:

package main 

import (
    "net" 
    "io" 
    "net/http" 
) 


ln, _ := net.Listen("tcp", ":8081") 
conn, _ := ln.Accept() 

func hello(w http.ResponseWriter, r *http.Request) { 
    io.WriteString(w, "Hello world!") 
    conn.Write([]byte(r.URL.Path + "\n")) //Here I'm attemping to send it 
} 

func main() { 


    http.HandleFunc("/", hello) 
    http.ListenAndServe(":8000", nil) 
} 
+0

你得到任何错误? – grooveplex

+0

undefined:conn.Write @grooveplex – rtgojtr

+0

函数'hello'不能引用'main'中的局部变量'conn'。也许你想要一个包级变量。 –

回答

1

你的问题实际上是在您尝试声明变量的方式。
如果你希望你的康恩是在全球范围内,使用var

package main 

import (
    "io" 
    "net/http" 
    "net" 
) 


var ln, _ = net.Listen("tcp", ":8081") 
var conn, _ = ln.Accept() 

func hello(w http.ResponseWriter, r *http.Request) { 
    io.WriteString(w, "Hello world!") 
    conn.Write([]byte(r.URL.Path + "\n")) //Here I'm attemping to send it 
} 

func main() { 
    http.HandleFunc("/", hello) 
    http.ListenAndServe(":8000", nil) 
} 
+0

由于某种原因io.WriteString(W,“你好世界”)给我这个错误:恐慌:运行时错误:无效的内存地址或零指针解引用 [信号0xc0000005代码= 0x0地址= 0x20 pc = 0x23323 @Alexey Soshin – rtgojtr

+0

@ D.Jow你得到了错误,因为没有客户端通过端口'8081'连接到服务器。 – putu