golang http服务器通过套接字发送r.URL.Path

huangapple go评论155阅读模式
英文:

golang http server send r.URL.Path over socket

问题

我有一个HTTP服务器,我想使用套接字将r.URL.Path文本发送给客户端。

我得到一个错误:undefined: conn in conn.Write
这是因为conn在另一个函数中定义了。

我尝试过的方法:

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")) //这里我尝试发送它
}

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

I have a http server, and I want to send the r.URL.Path text to a client using a socket

I get a error: undefined: conn in conn.Write
This is becauase conn is defined in another function

What I have tried:

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)
}

答案1

得分: 1

你的问题实际上在于你尝试声明变量的方式。
如果你想让conn在全局范围内可用,请使用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")) //在这里我试图发送它
}

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

Your problem is actually in the way you try to declare variables.
If you want your conn to be on global scope, use 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)
}

huangapple
  • 本文由 发表于 2017年5月15日 01:53:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/43967130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定