Categories
Golang

Golang: Making HTTP Requests

Go aka Golang is a very promising programming language with a lot of potential. It’s very performant, easy to grasp and maintain, productive and backed by Google. In our earlier posts, we have tried to provide guidelines to learn Go and later we saw how to work with JSON in Go. In this blog post, we’re going to see how we can make http requests using Go. We shall make use of the net/http package in Go which provides all the stuff we need to make http requests or create new http servers. That is, this package would help you do all things “http”. To check / verify that we made correct requests, we would be using httpbin which is a nice service to test our http client requests.

A Simple HTTP Request

Let’s make a very simple GET request and see how we can read the response. We would be sending a simple HTTP GET request to https://httpbin.org/get and read the response. For that we can just import the net/http package and use the http.Get function call. Let’s see an example:

We have created a separate MakeRequest function and called it from our main function. So going ahead, we will just see the changes inside this function and won’t need to think about the entire program. Inside this function, we have passed the url to http.Get and received two values – the response object and any errors that might have happened during the operation. We did a check to see if there were any errors. If there weren’t any errors, err would be nil. Please note that this err would be reported only if there was an issue connecting to the server and getting a response back. However, it would not be concerned about what http status code the server sent. For example, if the server sends a http 500 (which is internal server error), you will get that status code and error message on the resp object, not on err.

Next, we read the resp.Body which implements the io.ReadCloser interface and we can use ioutil.ReadAll to fully read the response. This function also returns two values – a byte slice ([]byte) and err. Again, we check for any potential errors in reading the response body. If there were no errors, we print out the body. Please note the string(body) part. Here, we’re converting the byte slice to a string. If we don’t do it, log.Println would print out representation of the byte slice, a list of all the bytes in that slice, individually. But we want a string representation. So we go ahead and make the conversion.

We would see the printed output is a JSON string. You will notice the httpbin service outputs JSON messages. So in the next example, we would see how we can send and read JSON messages.

JSON Requests and Responses

Now let’s send a JSON message. How do we do that? If you’re coming from Python / Node / Ruby, you might be used to passing a dictionary like structure to your favorite requests library and just mention it should be sent as JSON. Your library does the conversion for you and sends the request with required headers. In Go, however, things are more explicit, which is a good thing in fact. You will know what you’re doing, how you’re doing it. If the JSON related functionality is new to you, please do check our blog post – Golang: Working with JSON.

In Go, we would first convert our data structure to a byte slice containing the JSON representation of the data. Then we pass it to the request with the proper content type. Let’s see a code example:

We first created message which is a map containing a string value, an integer value and another embedded map. Then we json.Marshal it to get the []byte out of it. We also check for any errors that might happen during the marshalling. Next, we make a POST request using the http.Post function. We pass the url, our content type, which is JSON and then we create and pass a new bytes.Buffer object from the bytes representation. Why do we need to create a buffer here? The http.Post function expects an implementation of io.Reader – which is a brilliant design, anything that implements an io.Reader can be passed here. So we could even read this part from disk or network or any custom readers we want to implement. In our case, we can just create a bytes buffer which implements the io.Reader interface. We send the request and check for errors.

Next we declare another result variable (which is also a map type) to store the results returned from the request. We could read the full body first (like previous example) and then do json.Unmarshal on it. However, since the resp.Body is an io.Reader, we can just pass it to json.NewDecoder and then call Decode on it. Remember, we have to pass a pointer to our map, so we passed &result instead of just result.  The Decode function returns an error too. But we assumed it would not matter and didn’t check. But best practice would have been to handle it as well. We logged the result and result["data"]. The httpbin service sends different information about the request as the response. You can see those in the result map. If you want to see the data you sent, they will be in the data key of the result map.

Posting Form

In our last example, we have submitted JSON payload. What if we wanted to submit form values? We have the handy http.PostForm function for that. This function takes the url and url.Values from net/url package. The url.Values is a custom type which is actually map[string][]string internally. That is – it’s a map which contains string keys and against each key, there can be multiple string values ([]string). In a form request, you can actually submit multiple values against one field name. That’s the reason it’s a slice of string, instead of just a key to value mapping.

Here’s an example code snippet:

We would be reading the form key from the result map to retrieve our form values. We have seen how we can easily send form values using the net/http package. Next we would like to send a file along with typical form fields. For that we would also need to learn how to customize http requests on our own.

Custom Clients / Requests

The http.Get, http.Post or http.PostForm calls we have seen so far uses a default client already created for us. But now we are going to see how we can initialize our own Client instances and use them to make our own Requests. Let’s first see how we can create our own clients and requests to do the same requests we have made before. A quick example follows:

As you can see, we just take a new instance of http.Client and then create a new request by calling http.NewRequest function. It takes the http method, url and the request body. In our case, it’s a plain GET request, so we pass nil for the body. We then call the Do method on the client  and parse the response body. So that’s it – create a client, create a request and then let the client Do the request. Interestingly the client also has convenient methods like Get, Post, PostForm – so we can directly use them. That’s what http.Get, http.Post, http.PostForm and other root level functions actually do. They call these methods on the DefaultClient which is already created beforehand. In effect, we could just do:

And it would work similarly. Now you might be wondering – why not just use the DefaultClient, why create our own? What is the benefit?

Customizing the Client

If we look at the definition of the http.Client structure, it has these fields:

If we want, we can set our own transport implementation, we can control how the redirection is handled, pass a cookie jar to save cookies and pass them to the next request or simply set a timeout. The timeout part is often very significant in making http requests. The DefaultClient does not set a timeout by default. So if a malicious service wants, it can start blocking your requests (and your goroutines) indefinitely, causing havoc in your application. Customizing the client gives us more control over how the requests are sent.

File Upload

For uploading files while sending a http request, we need to use the mime/multipart package with the net/http package. We will first see the code example and then walk through it to understand what we’re doing. The code might seem a lot (it includes a lot of error handling) and complex. But please bear with me, once you go through the code and understand what’s happening, it will seem so simpler 🙂

So what are we doing here?

  • First we are opening the file we want to upload. In our case, I have created a file named “name.txt” that just contains my name.
  • We create a bytes.Buffer to hold the request body we will be passing with our http.Request later on.
  • We create a multipart.Writer object and pass a pointer to our bytes.Buffer object so the multipart writer can write necessary bytes to it.
  • The multipart writer has convenient methods to create a form file or a form field. It gives us back a writer to which we can write our file content or the field values. We create a file field and copy our file contents to it. Then we create a normal field and write “Value” to it.
  • Once we have written our file and normal form field, we call the Close method on the multipart writer object. Closing it writes the final, ending boundary to the underlying bytes.Buffer object we passed to it. This is necessary, otherwise the request body may remain incomplete.
  • We create a new post request like we saw before. We passed the bytes.Buffer we created as the request body. The body now contains the multi part form data written with the help of the mime/multipart package.
  • We send the request as before. But we set the content type by calling multiPartWriter.FormDataContentType() – which ensures the correct content type and boundary being set.
  • We decode the response from httpbin and check the output.

If everything goes well, we will see the form field and the file name in the response we received from httpbin. The concept here is simple. We are sending a http request with a custom body. We could construct the request body ourselves but we just took the help of the mime/multipart package to construct it in a relatively easier fashion.

Always Close The Response Body

Here’s a lesson I learned the hard way. When we make a http request, we get a response and an error back. We may feel lazy and decide not to check for errors or close the response body (just like in the examples above). And from the laziness comes disaster. If we do not close the response body, the connection may remain open and cause resource leak. But if the error is not nil that is in case of an error, the response can be nil. So we can’t just do a defer resp.Body.Close() in this case. We have to properly check error and then close the response body.

Always Use a Timeout

Try to use your own http client and set a timeout. Not setting a timeout can block the connection and the goroutine and thus cause havoc. So do something like this:

 

Categories
Javascript

Proxy in JavaScript

As we can already guess from the name, a Proxy object works as a “proxy” to another object and allows us to customize the behavior of the said object in certain ways. Let’s say you have an obj named awesomeAPI which has some properties and methods. You want to “trap” any calls to the object. May be you want to debug something and log every time a property is read/set on the object? Or when a method is called? Since the object has “API” in it’s name, let’s assume it makes a HTTP call to an external API We want to cache the response instead of hitting the resource every time a method is called – we can use a proxy to do that. In fact there can be so many useful use cases for Proxy in JavaScript as we will see.

A Basic Proxy

To create a new proxy, we need two things – one target object and a handler. The target object is the object we want to proxy. The handler is an object which will define certain methods to control what happens when an operation is requested on the target object through the proxy. The proxy object traps the requests, instead of performing the requested operations directly on target object, the proxy would first see if there’s a handler method defined for that operation in our handler object. If a method is available, it’s called. Otherwise the operation is forwarded to the target object directly.

The description alone might not be clear enough. Let’s go ahead and see a basic example.

If you run the code example, you will notice a message on your console – “Trapping GET for hello” followed by the actual “Hello” printed by the target object. What’s happening here? We are creating a new Proxy object for the obj object. We have a handler which sets a trap for get. Now any time we access a property on proxiedObject, the get method on the handler is called with the target object, name of the property and the receiver. We will focus on the property name and the target arguments for now. In our handler code, we have just logged the name of the property on the console and then returned the actual value from the target object. We could of course return any value we wish – may be a transformed value? a cached value? Well, anything we wanted.

You may be wondering – we made a function call, hello() but why would that get trapped by get which is for property access? Methods in JavaScript are actually properties. A method call happens in two stages – get the method (read the property) and then an apply call. So when we called proxiedObject.hello(), it looked up the hello property first. Then called it.

Traps in Our Proxies

The methods we define on the handler objects correspond to certain operations. For example, get is called during property lookup, has is called when the in operator is used, set is for setting property values.  These methods are the “traps” for the corresponding operations. Traps are optional, you can just define the ones you need. If any trap is not set for a particular operation, it’s forwarded to the target object directly.

Here’s an example:

In this example, we have trapped the property set operation and instead of storing the number as it is, we are squaring it and saving the squared value. However, we have defined no traps for the get operation, so when we access the number,  the operation is forwarded to the target object and we get the actual value without any changes.

Now that you know how to trap the operations on an object using a Proxy, you can check out the available traps from the awesome MDN docs here.

Going Ahead

There is an excellent chapter on meta programming with proxies in Exploring ES6 book. The MDN docs on the Proxy object is also pretty nice with adequate examples and complete API references.

 

 

Categories
Javascript

Promises in JavaScript

We encounter promises in real life every now and then. You have promised to deliver that project within the next week. Your friend has promised to play Overwatch with you tonight. If you think about it, promises are everywhere around us. Promises in JavaScript also play similar roles. A Promise object in JS is an object that promises to come up with a value or in the case of any error, a reason for the failure. But we don’t know when the promise will complete, so we attach callbacks to the promise object which get called on value or error.

Why Promises are useful?

Of course before we can dive into the technicalities of promises, you will have this question. Why does Promise matter in the first place? What is the use case? If you have written any JS code that fetches some data over the internet, you may have already got used to the fact that JavaScript is single threaded and uses asynchronous operations in places. To deal with asynchronous JS parts, we are long used to using callbacks and event listeners.

This looks good but if you have written a few level of nested callbacks, you will soon find out the callback hell is real. You may also architect a few Pyramids of Doom.

Pyramid of Doom

Promises are one of clean ways to solve this problem. Without getting into technical parts, we can rewrite the download image example using Promises like this:

In most cases, we will be consumers of promises, so don’t worry if the downloadImageWithPromise doesn’t immediately make sense. We will dive into promise creation soon. For now, take a look at how easy it is to consume a promise. No more callbacks or headaches. The code is clean, easy to reason about and should be easy to maintain in the long run.

With the latest JS changes, some of the important APIs are also based on promises. So it’s very essential that we understand the basics of Promises before hand.

Making a Promise

If you were a little confused about the downloadImageWithPromise function, worry no more, we will break it down now. And hopefully, it will no longer remain confusing. The basic idea of making promises in JavaScript that when we don’t immediately have a value to return from our function (for example an async operation), we should return a promise instead. So the user / consumer can rely on that promise and retrieve the value from it in the future. In our code, when the async operation is complete, we should “settle” the promise object we returned. Settling means either resolving / fullfilling or rejecting the promise with an error.

Creating a new promise object is simple. We use the new keyword with the Promise constructor. We pass it an “executor” function. The executor function takes two arguments – a resolve callback and a reject callback. We run our async operations within this executor function and when the operation completes, we either call the resolve or reject callback with appropriate values.

To make things clearer, we separated our executor function. This is basically how promise works. The promise constructor takes a executor function. The executor function takes two callback, resolve and reject. As soon as one of these callbacks is called, the promise is settled and the value (or the error) is made available to the consumer.

Consuming a Promise

Promise objects have two convenient methods – then and catch – we can pass callbacks to these methods which will be later called in order. When these callbacks are called, we will get the values passed to our callbacks. Let’s take a quick example:

And here’s an example with rejection:

Chaining Callbacks

The then method returns a promise. So we can keep chaining multiple promises one after one.

First things first – the Promise.resolve and Promise.reject methods immediately return a resolved or rejected promise with the value we pass. This is convenient where we need to return a promise but we don’t need any delay, so need for an executor function and the separate callbacks. We can just do Promise.resolve or Promise.reject and be done with it.

We can see how we chained multiple then methods and passed multiple callbacks to gradually transform the values. If we return a promise from one of this callbacks to then methods, it will be settled before passing on to the next callback.

Please note: If you look at the Promise related docs on MDN or some other places, you will find that the then method can take two callbacks, one for success and one for failure. The catch method is simply then(undefined, errorHandler) in disguise. But there’s a problem with using two callbacks to the then method. Take a look at this example:

Running the code will get us an error:  UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Less than 10. 

So what’s happening here? The error callback in a then method gets called only if there’s any error in the previous step (in this case the getMePromise function). But it can not handle the error caused in the same level (from within the successCallback function). This is why a then().catch() chain works better than passing two callbacks to the then method itself.

Promise in Real Life

We have got some basic ideas about Promise. Now we will see a real life example of using promise. We would use the axios npm package to fetch a web page content. This package has a nice promise based API. Let’s install it first:

Now we can use the package.

The axios.get function makes a HTTP GET request to the URL provided and returns a promise. We then attach success and error callbacks.

Multiple Promises

Sometimes we may need to deal with multiple promises. We can do that using Promise.all. It takes a list (iterable) of promises and returns a single promise that we can track. This single promise is resolved when all the promises in the list has resolved or one has failed (whichever happens first). It will return the results of the resolved promises in the same order. Let’s see an example:

Here we create two promises separately, put them in a list and pass it to Promise.all(). Then we attach our callbacks to the new promise we got. Note how we got two results in the same order inside the callback to the then method.

There is another convenient method – Promise.race() which is similar but settles as soon as one of the passed promises is resolved or rejected.

Migrating from Callback

In most cases, you can use various utilities available to convert callback based APIs to promise based one. In case, it’s not possible, just wrap their APIs in your own promises. For example, the popular request package on npm has a little different callback syntax. So we can wrap it in our own promise like this:

In  this case, we make the request call from inside an executor function and return the promise. We pass a callback to the request function just like it expects. Inside the callback we make use of our resolve / reject callbacks to settle the promise.

Further Reading