Loading...

Building a Web Application with Golang: A Fun Guide for Beginners

Hey there! If you’re looking to build a web app with Go, you’ve landed on the right page! Golang has become a popular choice for developers who want to create fast, efficient, and scalable web applications. And guess what? It’s not as complicated as you may think!

In this guide, we’ll go over the steps of building a web application from scratch. We’ll keep it simple and fun, so even if you’re new to Go, you’ll be able to follow along. So, let’s get started!

What Do You Need?

Before we dive in, here’s what you’ll need:

  • A basic understanding of Go programming language. If you’re new to Go, check out the official Go tutorial. It’s a great starting point!
  • Go installed on your computer. You can download the latest version from the official website.
  • A text editor installed on your computer. Visual Studio Code is a great option, but feel free to use any text editor you’re comfortable with.

Setting Up the Project

The first step in building a web application with Golang is to set up the project. Don’t worry, it’s easy! Just follow these steps:

  1. Open the terminal and create a new directory for your project:
$ mkdir myapp $ cd myapp
Code language: Bash (bash)
  1. Create a new Go file for your main function:
$ touch main.go
Code language: Bash (bash)
  1. Open the file in your text editor and let’s start coding!

Importing Required Packages

Now that we have the project set up, it’s time to import the required packages. For this guide, we’ll be using the net/http package, which provides a set of functions for building HTTP servers.

package main import ( "fmt" "net/http" )
Code language: Go (go)

Writing the Main Function

With the packages imported, it’s time to write the main function for our web application.

func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") }) http.ListenAndServe(":8080", nil) }
Code language: Go (go)

In the code above, we’re using the http.HandleFunc function to handle incoming HTTP requests to the root URL "/". The function takes two arguments: http.ResponseWriter and http.Request. The http.ResponseWriter interface is used to construct an HTTP response, while the http.Request struct represents an incoming HTTP request.

The fmt.Fprintf function writes a string to the http.ResponseWriter interface. In this case, we’re writing the string “Hello, World!” to the response.

Finally, the http.ListenAndServe function starts the HTTP server and listens for incoming requests. In this case, we’re listening on port 8080.

Running the Web Application

With the main function written, it’s time to run the web application:

$ go run main.go
Code language: Bash (bash)

Once you’ve run the command, you should see the following output in the terminal:

Listening on :8080...
Code language: Bash (bash)

Now, open your web browser and navigate to http://localhost:8080. You should see the message “Hello, World!” displayed in your browser. Congratulations, you’ve just built your first web application with Golang!

Adding Routers for Different URL Paths

So far, we’ve only handled the root URL "/". But what if we want to handle different URL paths? That’s where routers come in! Routers allow us to handle different URLs with different functions and return different responses.

For this guide, we’ll be using the github.com/gorilla/mux package, which provides a powerful router for handling different URLs with different functions.

First, let’s install the github.com/gorilla/mux package:

$ go get -u github.com/gorilla/mux
Code language: Bash (bash)

Next, let’s import the package and create a new router:

import ( "fmt" "github.com/gorilla/mux" "net/http" ) func main() { router := mux.NewRouter() router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") }) router.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, Mehul!") }) http.ListenAndServe(":8080", router) }
Code language: Go (go)

In the code above, we’ve created a new router using the mux.NewRouter function. We’ve also added two new router handlers, one for the root URL "/" and one for the URL "/hello".

Run the web application and navigate to http://localhost:8080/hello. You should see the message “Hello, Mehul!” displayed in your browser.

Adding a Template Engine for Dynamic HTML Pages

Now that we have added routers to our web application, let’s add a template engine to render dynamic HTML pages. A template engine separates the HTML code from the Go code, making it easier to maintain and update our web pages.

For this guide, we’ll be using the html/template package, which is a built-in template engine in Golang.

First, let’s create a new directory for our templates and a new HTML file for our homepage:

$ mkdir templates $ touch templates/home.html
Code language: Bash (bash)

Next, let’s write some HTML code for our homepage:

<!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h1>Hello, {{.}}!</h1> </body> </html>
Code language: HTML, XML (xml)

In the code above, we’re using a Go template to inject a dynamic value into the HTML page. The value {{.}} will be replaced with the name passed to the template.

With the template written, let’s write the Go code to render it:

package main import ( "html/template" "net/http" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { tmpl, err := template.ParseFiles("templates/home.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = tmpl.Execute(w, "Mehul") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }) http.ListenAndServe(":8080", router) }
Code language: Go (go)

In the code above, we’re using the `template.ParseFiles` function to parse the HTML template. The `tmpl.Execute` function is used to render the template and write the result to the `http.ResponseWriter` interface. In this case, we’re passing the name “Mehul” to the template. Now, if you run the web application and navigate to `http://localhost:8080`, you should see the message “Hello, Mehul!” displayed in your browser.

Conclusion

In this guide, we’ve gone through the process of building a web application with Golang from scratch. We’ve covered setting up the project, importing required packages, writing the main function, adding routers, and adding a template engine. By following the steps in this guide, you should now have a solid foundation in building web applications with Golang. The next step is to build upon this knowledge and create more complex applications. Happy coding! And remember to have fun while learning! 🚀

Sharing is caring

Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far