Jun. 12, 2020
The panic recover is only alive within the current thread, that means each goroutine need it’s own panic recover
The panic in this goroutine, wont be caught by the recover, it will panic.
defer func() { if rec := recover(); rec != nil { fmt.Println("Catched panic", rec) } }() fmt.Println("Hello, playground") wg := sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() panic("You can't catch me!") }() wg.Wait() To catch the panic inside of the goroutine, you need code the recover again
defer func() { if rec := recover(); rec != nil { fmt.Println("Catched panic", rec) } }() fmt.Println("Hello, playground") wg := sync.WaitGroup{} wg.Add(1) go func() { defer func() { if rec := recover(); rec != nil { fmt.Printf("Now catched `%v`\n", rec) } }() defer wg.Done() panic("You can't catch me!") }() wg.Wait() More reading
Website: jma.dev
Weekly tech bookmarks: funcmarks
Apr. 4, 2018
targetURL := "http://www.example.com/one/two/three.json?output=four" u, err := url.Parse(targetURL) if err != nil { panic(err) } fmt.Println(path.Base(u.Path)) // three.json
Apr. 4, 2018
Example to download a file from url and save on local
io.Copy() read 32kb (maximum) from input and write to output reapeatly, so dont need worry about memory.
func DownloadFile(filepath string, url string) error { // Create the file out, err := os.Create(filepath) if err != nil { return err } defer out.Close() // Get the data resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() // Write the body to file _, err = io.Copy(out, resp.Body) if err != nil { return err } return nil } reference: Code Example
Mar. 28, 2018
var fibTests = []struct { n int // input expected int // expected result }{ {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}, {7, 13}, } source: 5 simple tips and tricks for writing unit tests in #golang