Simple Http Server with Templated Response in Go
In this post we are going to see how easy it is to host an Http Server in go (GoLang). As we discussed in the previous post we have to use specialized packages for any go app. In order to host an Http server, we need to use net/http package.
In the following code, we are using the package. The package provides methods to listen to Http requests. It also allows to define simple routes. Here we are just defining main route for the app.
Building and running the app is as easy as ever. Here we are building to create the executable. We are then simply running the executable.
The request is handled by SimpleIndexHandler method. It just respond with a simple message. It also add any sub-route specified in the request. Here we are just requesting the app. Since there are no sub-path, it just returns a hello message in the response.
If we do specify a sub-path, it is added to the response.
Serving HTML Response
Serving Html response is also very easy. Let’s add a simple Html file to the same folder. Let’s name it index.html.
http package provides ServerFile method. Here we can provide a file name with any necessary path information. It picks up the file and serve the html content of the file.
When we build and run the application again. The request to index sub-path is served with the contents of index.html.
Templated Html Response
We can also serve Html response built from a template. The template does support variables passed, which is then used and formatted inside the template. Here we are defining a Student type. It has an Id (int) and Name (string) field.
We can use this type to build up our response. Here we have defined a new function to build up the response. Here we would be needing html/template package. The package provides necessary methods to parse the template, pass arguments and rendering a response.
This can be served up simply by using HandleFunc provided by http package.
And here is the response in the client browser when top-student route is requested.
Using Template Files
We can also keep the template in a file. Here we are adding IndexTemplated.html file. The file assumes certain parameter with properties Id and Name.
The same html/template package provides functionality to load template from a list of files. We can then pass arguments to the template and then build up the rendered response. Here we are serving up the response using /top-student-from-file sub-path.
When we build and run it, the response is provided as follows: