Go from Beginner to Expert: A Complete Guide to Learn Golang PART-20

Step-by-Step Guide on Building web applications in Golang

Md. Faiyaj Zaman
6 min readMar 17, 2023

--

Welcome to this tutorial on building web applications in Golang. In this tutorial, we’ll take you through the basics of creating a simple HTTP server, handling HTTP requests, working with templates and dynamic data, building REST APIs, and testing them using Golang.

Please check out the previous Step-by-Step Guide to understand File I/O and Error Handling in Golang.

Overview of building web applications in Golang

Golang, also known as Go, is an open-source programming language that is designed to be fast, efficient, and scalable.

It is an excellent choice for building web applications because it provides features such as built-in concurrency, garbage collection, and support for low-level programming. Golang’s standard library also includes a robust set of packages for building web applications.

Handling HTTP requests in Golang

HTTP (Hypertext Transfer Protocol) is a protocol used for transferring data over the web. Golang provides built-in support for handling HTTP requests and responses using the “net/http” package.

In Golang, you can create an HTTP server by creating a “http.ServeMux” and registering handlers for each route.

Here’s an example code snippet for handling an HTTP request in Golang:

package main

import (

"fmt"

"net/http"

)

func helloWorld(w http.ResponseWriter, r *http.Request) {

fmt.Fprintf(w, "Hello, World!")

}

func main() {

http.HandleFunc("/", helloWorld)

http.ListenAndServe(":8080", nil)

}

This code creates a simple HTTP server that listens on port 8080 and returns “Hello, World!” for any request made to the root path.

Creating a simple HTTP server in Golang

Creating an HTTP server in Golang is relatively straightforward. Here’s an example code snippet for creating a simple HTTP server in Golang:

package main

import (

"fmt"

"net/http"

"log"

)

func main() {

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

fmt.Fprintf(w, "Welcome to my website!")

})

log.Fatal(http.ListenAndServe(":8080", nil))

}

This code creates a simple HTTP server that listens on port 8080 and returns “Welcome to my website!” for any request made to the root path. The log.Fatal function is used to log any errors that occur while the server is running.

Working with templates and dynamic data

Templates are an essential aspect of web development because they allow you to separate your application’s logic from its presentation.

Golang provides support for working with templates using the “html/template” package. Here’s an example code snippet for working with templates in Golang:

package main

import (

"html/template"

"log"

"os"

)

type Person struct {

Name string

Age int

}

func main() {

t, err := template.ParseFiles("template.html")

if err != nil {

log.Fatal("Error parsing template:", err)

}

p := Person{Name: "Faiyaj Zaman", Age: 28}

err = t.Execute(os.Stdout, p)

if err != nil {

log.Fatal("Error executing template:", err)

}

}

This code defines a Person struct with Name and Age fields, and creates an instance of it with the values "Faiyaj Zaman" and 28.

It then parses an HTML template file named "template.html" using the template.ParseFiles function, and executes the template with the Person instance using the t.Execute function.

The os.Stdout parameter specifies that the output should be printed to the console. If any errors occur during parsing or execution, they will be logged using the log.Fatal function.

Introducing REST APIs and building them in Golang

REST (Representational State Transfer) is an architectural style used for designing web services. Golang provides support for building REST APIs using the “net/http” package.

Here’s an example code snippet for building a simple REST API in Golang:

package main

import (

"encoding/json"

"log"

"net/http"

)

type Person struct {

Name string

Age int

}

func getPerson(w http.ResponseWriter, r *http.Request) {

p := Person{Name: "Faiyaj Zaman", Age: 28}

json.NewEncoder(w).Encode(p)

}

func main() {

http.HandleFunc("/person", getPerson)

log.Fatal(http.ListenAndServe(":8080", nil))

}

This code creates a simple HTTP server that listens on port 8080 and returns a JSON-encoded Person object for any request made to the "/person" path.

The json.NewEncoder function is used to encode the Person object to JSON format and write it to the response writer. If any errors occur during JSON encoding or server listening, they will be logged using the log.Fatal function.

Understanding HTTP and REST APIs

HTTP and REST APIs are essential concepts to understand when building web applications.

HTTP is the protocol used for transferring data over the web, while REST is an architectural style used for designing web services.

REST APIs use HTTP methods such as GET, POST, PUT, and DELETE to interact with resources on a server.

Building and testing a basic REST API using Golang

Now that we have a basic understanding of REST APIs in Golang, let’s build and test a simple REST API using Golang.

We’ll be using the “net/http” package and the “testing” package for this example.

Here’s an example code snippet for building and testing a basic REST API using Golang:package main

import (

"encoding/json"

"log"

"net/http"

"net/http/httptest"

"testing"

)

type Person struct {

Name string

Age int

}

func getPerson(w http.ResponseWriter, r *http.Request) {

p := Person{Name: "John Doe", Age: 30}

json.NewEncoder(w).Encode(p)

}

func TestGetPersonEndpoint(t *testing.T) {

req, err := http.NewRequest("GET", "/person", nil)

if err != nil {

t.Fatal(err)

}

rr := httptest.NewRecorder()

handler := http.HandlerFunc(getPerson)

handler.ServeHTTP(rr, req)

if status := rr.Code; status != http.StatusOK {

t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)

}

expected := `{"Name":"John Doe","Age":30}` + "\n"

if rr.Body.String() != expected {

t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected)

}

}

func main() {

http.HandleFunc("/person", getPerson)

log.Fatal(http.ListenAndServe(":8080", nil))

}

This is a piece of Go code that defines a simple HTTP server that responds with a JSON-encoded person object when it receives a request to the “/person” endpoint. It also includes a test function that tests the server’s response to a GET request to the “/person” endpoint.

The first section of the code imports necessary packages for working with HTTP requests, JSON encoding/decoding, and testing.

The code then defines a Person struct with two fields, Name and Age, which will be used to create the JSON response.

The getPerson function is defined to create a Person object with hardcoded values and encode it as JSON to the HTTP response.

The TestGetPersonEndpoint function is a test function that sends a GET request to the “/person” endpoint using an HTTP request object, and records the response using an HTTP recorder object. It then checks the response status code and body against expected values.

Finally, the main function sets up an HTTP server to handle requests to the “/person” endpoint using the getPerson function as the handler function, and listens on port 8080 for incoming requests. If an error occurs during this process, it is logged using the log package’s Fatal function.

In this tutorial, we’ve covered the basics of building web applications in Golang. We introduced the HTTP protocol and explained how to handle HTTP requests in Golang, create a simple HTTP server, work with templates and dynamic data, and build REST APIs.

We also discussed the importance of understanding HTTP and REST APIs and provided an example of building and testing a basic REST API using Golang. With this knowledge, you can start building your own web applications in Golang.

Please check out the next step by step guide on database connectivity in golang.

Please hit the Follow button to get more posts like this.

Happy coding!

--

--