0
\$\begingroup\$

I am trying to experiment with golang.

This code spins off two Go routines: one to download data and another to read from the body. Both go threads are synced by the data channel.

I have two questions:

  1. Should I have to dispose the body inside downloadData method?
  2. Is this type of coding acceptable in Go?

    package main
    
    import (
        "fmt"
        "net/http"
        "time"
    )
    
    func main() {
        data := make(chan *http.Response)
        go downloadData(data)
        go readData(data)
        var input string
        fmt.Scanln(&input)
    }
    
    func downloadData(data chan *http.Response) {
        resp, _ := http.Get("http://www.google.com")
        defer resp.Body.Close()
        time.Sleep(time.Second * 1)
        data <- resp
    }
    
    func readData(data chan *http.Response) {
        response := <-data
        fmt.Println(response)
    }
    
\$\endgroup\$
  • 1
    \$\begingroup\$ 1) Never ignore errors. 2) Don't abuse fmt.Scanln to prevent main from exiting. Simply remove the final go keyword or if you really need to prevent main from exiting just do select {}. 3) No you cannot expect to read the body in readData if you've closed the body at the end of downloadData (via defer). \$\endgroup\$ – Dave C Oct 7 '15 at 13:46
  • \$\begingroup\$ I ran this program, it worked quite well. I know fmt.Scanln(&input) is a bad approach. \$\endgroup\$ – Paritosh Oct 7 '15 at 15:04
2
\$\begingroup\$
  • After spinning two routines main should wait for them to terminate. See sync package for common synchronisation primitives. fmt.Scanln is for input reading.
  • http.Get may return error. Proper way would be to handle it.
  • resp.Body will be closed when downloadData returns and readData won't be able to use it anymore.

Regarding your questions:

  1. As stated by documentation resp.Body must be closed. Close it as soon as you don't need it anymore.
  2. The code lacks error checks and proper routines synchronisation. Despite the fact this code is compiling, this is not acceptable Go code and it must be fixed.

I suggest you to read Effective Go for concurrency and error handling overview.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.