dongtang6681 2018-06-07 17:13
浏览 34
已采纳

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

In my first iteration, I got the following to compile and work:

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

This successfully uses 1 channel to perform the goroutine routineHandle

Now, I want to add web server capabilities which perform the following:

  • Listens on a port and accepts/returns requests
  • Hooks into the routineHandle so we can utilize that goroutine as an Api Server Method

My code is on a linux box without a gui so I don't know how to test the web server capabilities.

My code looks like as follows:

package main

import (
  "fmt"
  "sync"
  "net/http"
)

var wg sync.WaitGroup

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

func ping (w http.ResponseWriter, r *http.Request) {
  ch := make(chan string)
  wg.Add(1)
  go routineHandle("testquery",ch)
  wg.Done()
  msg := <-ch
  //fmt.Println("Channel Message",msg)
  w.Write([]byte msg)
}

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

You'll notice a few additions with my second piece of code:

  • I added the net/http package
  • I added the http listener to the main method
  • I added response writer and request parameters to the ping function
  • I changed from fmt.Println() to c.Write

The end goal would be for typing in a query, and then using that query in the routineHandle goroutine

Like I Said Though, I don't know how to test this final implementation on an ubuntu box without a gui

One last thing to note. If you notice any issues PLEASE let me know. I wonder if running a goroutine inside a http server would cause an issue

  • 写回答

1条回答 默认 最新

  • dongyulian5801 2018-06-07 20:11
    关注

    The code in the question uses the wait group incorrectly (wait and done should be swapped, the group should not be shared globally) and redundantly with the channel. Delete the use of the wait group to fix the code.

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?