This lesson is locked. Login or Subscribe for more access!

The httpUtil Package

Duration: 3 mins

Learn about the http util package and how it makes debugging easier!

Instructor

Matt Boyle

Share with a friend!

Transcript

Hey folks, I want to do a quick bonus lesson on HTTP util and dump response function because I found it really really useful over the years for figuring out what response I'm getting from HTTP requests when I'm trying to debug things either locally or maybe I have a small CLI script, something like that.

It also can help with development and I'll talk about that a little bit in a minute. So I have this URL here which is JSON placeholder. This is great for testing that your HTTP connectivity is good and you can make requests from your app basically does give back a bunch of random json that you can work with.

And then all I'm going to do is going to make a HTTP get request to it and one common mistake I see beginners make is just because a HTTP request didn't yield a error it doesn't mean it was successful and what I mean by that is getting back a 4xx response or a 5xx response from a HTTP request is actually valid the server responded so the request was successful but it response you wanted.

You might have wanted a 2xx response, for example. So it's a pretty good idea to always check the status code is greater than 200 or 201 or whatever you might need it to be and handle the fact that there could be an error here because you might get a 4xx error here or a 5xx error that we need to handle.

Anyway, that's an aside. So let's assume that we are getting a bad response. We're going to see what it looks like. And we can use HTTP util dump response, which you can see here and it does exactly what it says it's in. It takes a response. You can say whether you want the body or not. And then we can log it to the console.

And as you can see, when you do that and you run the program, it prints out all the headers, the response code, and then also all of the JSON. You could then take this JSON if you wanted to, and then you could put it into one of the many sites on the web, such as Matt Holt's site that takes JSON and converts Go Struts from it.

So if you're not using a website that has a go sdk you can make your own very very quickly by using the dump response function and then going to the website and generating ghost trucks from it. So use this sparingly you don't want to be filling your logs with every response you're ever going to receive but there may be times when you're developing or you're trying to debug a specific api or you're getting a strange response from a partner where you may need to use this.

So I hope you found this helpful I found it very helpful over the years and I wish someone had shown it to me sooner.