4 ms·
I'm not familiar with Haskell so I can't exactly follow what you're trying to do, but I can take a stab at improving what your Go code is doing: package ma
by Zikes 12y ago
I'm not familiar with Haskell so I can't exactly follow what you're trying to do, but I can take a stab at improving what your Go code is doing:
package main
import (
"fmt"
"net/http"
)
func main() {
for _, url := range []string{
"http://httpbin.org/status/200",
"http://httpbin.org/status/200",
"http://httpbin.org/status/200",
"http://httpbin.org/status/404",
} {
fmt.Printf("%s: %d\n", url, checkUrl(url))
}
}
func checkUrl(url string) int {
response, err := http.Get(url)
if err != nil {
panic(err)
}
defer response.Body.Close()
return response.StatusCode
}
You say of your Haskell code that errors are values, and Go is no different in this regard. checkUrl could easily be modified to return (int, error) and return both values, rather than panicking when an error occurs.
- codygman 12y agoCool, that's a good refactoring. What if we don't care about the errors and just want to return nil or the value. The caveat is that when any of your http requests get a non 200 response code no further processing is done and nil is returned.
- Zikes 12y agoWhat I would do in that case is modify checkUrl to return a bool, change the return to return response.StatusCode == 200, and change the for loop contents to if !checkUrl(url){ fmt.Printf("Non-200 response for %s", url) break }