\$\begingroup\$
\$\endgroup\$
2
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:
- Should I have to dispose the body inside downloadData method?
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
- 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:
- As stated by documentation resp.Body must be closed. Close it as soon as you don't need it anymore.
- 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
lang-golang
fmt.Scanln
to preventmain
from exiting. Simply remove the finalgo
keyword or if you really need to prevent main from exiting just doselect {}
. 3) No you cannot expect to read the body inreadData
if you've closed the body at the end ofdownloadData
(viadefer
). \$\endgroup\$