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)
    }
    
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Oct 6, 2015 at 7:06
\$\endgroup\$
2
  • 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\$ Commented Oct 7, 2015 at 13:46
  • \$\begingroup\$ I ran this program, it worked quite well. I know fmt.Scanln(&input) is a bad approach. \$\endgroup\$ Commented Oct 7, 2015 at 15:04

1 Answer 1

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.

answered Jun 26, 2018 at 18:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.