package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close() // leave the defer keyword off, you do get an error
robots, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", robots)
}
// 결과
//
// ...
// User-agent: facebookexternalhit
// Allow: /imgres
//
// Sitemap: https://www.google.com/sitemap.xml
package main
import (
"fmt"
)
func main() {
s := "start"
defer fmt.Println(s)
s = "end"
}
// 결과
//
// start
package main
import (
"fmt"
)
func main() {
x, y := 1, 0
ret := x / y
fmt.Println(ret)
}
// 결과
//
// panic: runtime error: integer divide by zero
package main
import (
"net/http"
)
func main() {
// basic web handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello Go!"))
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err.Error())
}
}
- any deferred call to close resources are still going to work even if a function panics
package main
import (
"fmt"
)
func main() {
fmt.Println("start")
defer fmt.Println("this was deferred")
panic("something bad changed")
fmt.Println("end")
}
// 결과
//
// start
// this was deferred
// panic: something bad changed
package main
import (
"fmt"
"log"
)
func main() {
fmt.Println("start")
panicker()
fmt.Println("end")
}
func panicker() {
fmt.Println("about to panic")
defer func() {
if err := recover(); err != nil {
log.Println("Error:", err)
}
}()
panic("something bad happened")
fmt.Println("done panicking")
}
// 결과
//
// start
// about to panic
// 2022/03/17 07:22:13 Error: something bad happened
// end
댓글 영역