Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Http 无法从命令行访问go服务器/将web服务器逻辑添加到现有代码_Http_Go - Fatal编程技术网

Http 无法从命令行访问go服务器/将web服务器逻辑添加到现有代码

Http 无法从命令行访问go服务器/将web服务器逻辑添加到现有代码,http,go,Http,Go,在我的第一次迭代中,我得到了以下编译和工作: package main import ( "fmt" "sync" ) var wg sync.WaitGroup func routineHandle (query string, ch chan <- string) { ch <- query wg.Wait() } func ping () { ch := make(chan string) wg.Add(1) go routineHandle

在我的第一次迭代中,我得到了以下编译和工作:

package main

import (
  "fmt"
  "sync"
)

var wg sync.WaitGroup

func routineHandle (query string, ch chan <- string) {
  ch <- query
  wg.Wait()
}

func ping () {
  ch := make(chan string)
  wg.Add(1)
  go routineHandle("testquery",ch)
  wg.Done()
  msg := <-ch
  fmt.Println("Channel Message",msg)
}

func main () {
  ping()
}
您会注意到我的第二段代码中添加了一些内容:

  • 我添加了
    net/http
  • 我将
    http侦听器
    添加到
    main方法
  • 我在ping函数中添加了响应编写器和请求参数
  • 我从
    fmt.Println()
    更改为
    c.Write
最终目标是键入查询,然后在
routinehold
goroutine中使用该查询

就像我说的,我不知道如何在没有gui的
ubuntu设备上测试这个最终实现


最后要注意的一件事。如果您发现任何问题,请告诉我。我想知道在http服务器内运行goroutine是否会导致问题

问题中的代码错误地使用了等待组(应交换等待和完成,不应全局共享该组),并且与通道冗余。删除使用等待组修复代码

package main

import (
    "net/http"
)

func routineHandle(query string, ch chan<- string) {
    ch <- query
}

func ping(w http.ResponseWriter, r *http.Request) {
    ch := make(chan string)
    go routineHandle("testquery", ch)
    msg := <-ch
    w.Write([]byte(msg))
}

func main() {
    http.HandleFunc("/", ping)
    http.ListenAndServe(":1234", nil)
}
主程序包
进口(
“net/http”
)

func路由句柄(查询字符串,ch chanNo我不认为使用http服务器运行例程会导致任何问题。我已经创建了一些例程,通过在我的处理程序中使用go例程将数据保存到数据库中。您所能做的就是不必使用go例程。这里,您只需在其中一个中处理请求go@ThunderCat所以你建议我把我的日常事务处理好ping方法中的代码?@ThunderCat你能提供一个可行的解决方案吗?我正在试图了解你想要的东西go@ThunderCat但是我将来可能需要运行并发操作?你能提供一个并发和通道的例子吗?现在你确实有并发问题,因为全局共享的waitgroup。只需要除去它,http服务器将为您处理它(每个请求将作为单独的goroutine运行)。
package main

import (
    "net/http"
)

func routineHandle(query string, ch chan<- string) {
    ch <- query
}

func ping(w http.ResponseWriter, r *http.Request) {
    ch := make(chan string)
    go routineHandle("testquery", ch)
    msg := <-ch
    w.Write([]byte(msg))
}

func main() {
    http.HandleFunc("/", ping)
    http.ListenAndServe(":1234", nil)
}