Golang Application Development from Scratch

Author

Reads 646

Two professionals collaborating on software development in a modern indoor setting.
Credit: pexels.com, Two professionals collaborating on software development in a modern indoor setting.

Developing a Golang application from scratch can be a daunting task, but with a solid understanding of the basics, you'll be well on your way.

You'll need to start by installing Go on your machine, which can be done by downloading the Go installer from the official Go website.

First impressions matter, and a good starting point is to create a new Go project using the go mod init command. This initializes a new module and creates a go.mod file.

As you begin building your application, you'll need to write Go code. Go code is typically written in a main package, which is where your program entry point is located.

A unique perspective: Golang Comments

Project Structure

As you design your GoLang application, don't forget to focus on a robust and scalable structure. This means building a foundation that's easy to work with and can adapt to changing needs.

Testability is key, as writing programs that are easy to test dramatically affects developer productivity. This makes it easier to maintain and improve old code, and even allows new team members to confidently add to the project.

Credit: youtube.com, The BEST Tool to Structure Golang Projects

A good project structure should also be readable, making it easy for anyone to understand the code and make changes. This is especially important when working on a team, as it ensures everyone is on the same page.

To achieve this, consider the following essential elements of a robust project structure:

  • Testability
  • Readability
  • Adaptability

Adaptability is also crucial, as it allows your project to grow and change with your needs.

Project and Tools

To get started with our project, let's talk about the tools and framework we'll be using. We'll be working with Golang, specifically version 1.15 and above. This will ensure we have the latest features and performance improvements.

Our web framework of choice is Gin, a popular and efficient choice for Go developers. We'll also be using Postgresql for our database needs, and Golang-migrate to manage our database migrations.

Having a solid IDE is also crucial for productivity. While you can use any IDE you like, I highly recommend Goland, which is an amazing tool that will make your development experience even better.

Here are the tools we'll be using in our project:

  • Gin Web Framework
  • Go version 1.15+
  • Postgresql
  • Golang-migrate
  • Goland (or your favorite IDE)

The Application Structure

Credit: youtube.com, How To Structure A Programming Project…

A robust and scalable structure is essential for any project, and it's something I've learned the hard way.

Testability is key, as it makes it easier to write tests and maintain old code. This also helps new people to add to the project without feeling overwhelmed.

Having a readable structure is crucial, as it makes it easier for developers to understand and improve the code.

Adaptability is also important, as it allows the project to adapt to changing needs and complexity.

Here are the three things I look for in my application structure:

  • Testability
  • Readability
  • Adaptability

Anatomy of GOPATH

The GOPATH is a directory where all your Go code and project dependencies live. It's similar to how Python looks for imported libraries in the Python path, but Go expects all your Go projects to live within the GOPATH, specifically /go/src.

The GOPATH directory is made up of 3 subdirectories: /bin, /pkg, and /src. Let's break each of these down.

Readers also liked: Go Html Template

Credit: youtube.com, Mastering Go: Unraveling the Secrets of GOPATH and GOROOT

/bin contains Go commands you've installed, such as third-party linters or local versions of official tools. For example, you might have installed a linter like golint or a local version of the official Go Tour.

/pkg contains installed third-party packages, which can be found under directories like /pkg/mod. This is where you'll see packages you've installed from Github, such as dataframe-go or mux.

/src is where your personal source code lives, along with any projects you've worked on. This is where you'll find the code for your projects, like golang-helloworld.

Here's a quick rundown of the GOPATH structure:

Coding Basics

Go is a statically typed language, which means you need to declare the type of every variable before using it. This helps catch errors early on and makes the code more maintainable.

Variables in Go are declared using the "var" keyword. For example, "var x int" declares a variable named x of type int.

Data types in Go are divided into several categories, including numeric types, string types, and boolean types. Understanding these data types is crucial for writing effective Go code.

A different take: Gcloud Api Using Golang

Type Declaration

Credit: youtube.com, Go Programming: Session 3.1 - Variable Declaration and Data Types

In Go, variables, function parameters, and return values all need to have declared types.

Variables are set using the same syntax as function parameters, with the variable name coming first.

Type declaration is straightforward, and you can set multiple variables of the same type by separating their names with commas.

For example, you can set variables x, y, and z as integers with no assigned values.

This shorthand method is a convenient way to declare multiple variables at once, making your code more efficient.

Short Assignment Statements

In Go, the := operator is a powerful tool for setting multiple variables at once with implicit types. This means the language will automatically determine the type of each variable based on the value assigned.

You can use the := operator to create variables without explicitly declaring their types. For example, you can set multiple variables to the same value in a single line of code.

Go's implicit type resolution can make your code more concise and easier to read. It's especially useful when working with simple data types like booleans and strings.

The := operator can resolve boolean values, as seen in the example where x and y are set to true or false based on the value assigned.

A different take: Golang Source

Constants

Credit: youtube.com, Programming For Beginners - Constants

Constants are a fundamental concept in programming, and Go supports them in a way that's music to the ears of Python programmers.

Go supports constants, just like other programming languages, but it's a feature that's especially welcome for Python developers who are used to having this ability.

Constants in Go can be used to give names to values that don't change, making code easier to read and maintain.

For Python developers, this is a breath of fresh air, as they're used to being able to do things like this with constants.

A fresh viewpoint: Go vs Golang

Bonus: Code Formatting

In Go, a code formatter is a built-in tool that cleans up ugly indents and formatting in your source code.

This tool is a lifesaver, especially when you're working on a project with multiple contributors. It ensures that your code looks neat and consistent throughout.

Try messing up the indents in your main function, and then run the built-in CLI method to format your project source code. This should fix all the nasty formatting issues.

The code formatter is a part of the Go environment setup, so you don't need to install anything extra. It's a convenient feature that comes out-of-the-box with Go.

Here's an interesting read: Golang Go

Request Handling

Credit: youtube.com, Handling web request in golang

Request handling is a crucial aspect of building a GoLang application. The http.Handler type is the core of request handling, and it's what gets called when a request is made to the server.

Middleware functions, such as the logging middleware, are used to pre-process requests before they reach the main handler method. This allows you to chain handlers and add middleware as needed.

The logging middleware is a simple example of how to create middleware in GoLang, and it demonstrates how to use the http.HandlerFunc type to convert functions into http.Handlers that the server can use.

Request Routing

You can chain handlers and add as many middleware as you'd like before your main handler method.

To properly handle requests by HTTP verb, make decisions based on the URL, and access HTTP headers, check the documentation of the http.Request type first.

The ServeMux type has a Handle function that allows you to add handlers for specific URLs.

On a similar theme: Golang Add to Map

Credit: youtube.com, What Is Application Request Routing? - SecurityFirstCorp.com

Middleware functions, like the logging middleware, are used for pre-processing requests before they get to the actual handler.

The logging middleware simply times how long the request takes and prints out the associated URL.

You can create middleware to perform actions like ensuring a user is authenticated or checking if a JWT token hasn't expired yet.

The http.HandlerFunc type is used to convert functions with signatures that match http.Handler's ServeHttp method into http.Handlers.

The ServeHttp method is used by the server to handle requests.

Index Handler

The index handler is a crucial part of a Go web application, responsible for rendering the site's index page.

It returns a http.Handler, which is created similarly to the logging middleware, and is responsible for executing a cached template named "base" and populating the result with specified values.

To verify that the index handler is functioning as expected, unit tests can be written to check things like the request response, valid body, and content persistence to the database.

Credit: youtube.com, Requestor and Request Handler

These tests are typically stored in a file named main_test.go and can be run from the command-line.

Go's testing and httptest packages provide useful types and functions for exercising web servers and their handlers.

In testing, a request for the index page is created, a http.ResponseRecorder is used to capture the response, and the status code and body are asserted to be good.

Templating and Serving

Go's templating engine is really powerful and comes right out of the box with support for HTML and text templating.

The templates are stored in a directory called "templates" that lives right next to our main.go file. The templates look like this, with a top-level template that includes a dynamic "body" template.

We can use the templates.ExecuteTemplate function to render the template, passing in arguments for where the result of the execution will be written, the name of the template, and a data object that contains values for each Action in the template.

Templating

A programmer with headphones focuses on coding at a computer setup with dual monitors.
Credit: pexels.com, A programmer with headphones focuses on coding at a computer setup with dual monitors.

Templating is a powerful tool in Go that comes pre-installed with support for HTML and text templating.

Go's template package supports constructs for conditional logic, iteration over slices and arrays, and even adding custom functions for non-standard behaviors.

You can store your templates in a directory that lives next to your main.go file, like in this example where the template directory is right next to the main.go file.

To render a template, you need to call templates.ExecuteTemplate, passing in the arguments for where the result will be written, the name of the template, and a data object that contains values for each Action in the template.

In this example, the template "base" is rendered because it's the top level template that includes the dynamic "body" template.

For more insights, see: Golang Test Main

Serving Static Content

Serving static content is a crucial part of making your web application look and feel professional. This involves serving CSS styling and JavaScript scripts that enhance the user experience.

Credit: youtube.com, Echo Quick Start Guide | 8.Providing Templates and Static Content

You can use Go's built-in http.FileServer handler to serve static content. This handler is easy to add to your server by declaring a function that returns a http.Handler.

Create a directory called "public" next to your main.go file and place all your static content in there. This is where your templates will look for the styles and scripts they need to function properly.

You can find an example of how to structure your static files in the GitHub repo provided. The key is to keep all your static content organized and easily accessible.

To serve your static content, run the command "go build" and then "go run main.go". This will make your static files available to your templates.

Broaden your view: How to Run Golang File

Dependency Management

Installing dependencies in Go is straightforward. You can leverage popular modules like gorilla/mux to serve Go code via a web server.

To install gorilla/mux, run $ go get followed by $ go install. The -u flag updates the module to the latest version.

The dependency is added to go.mod, along with the proper version number. This allows you to import and use the module in your project.

You can also use $ go mod vendor to build the dependency in your /vendors folder, keeping it local to your project.

If this caught your attention, see: Install Golang Windows

Installing Dependency

Credit: youtube.com, Learning Golang: Dependencies, Modules and How to manage Packages

Installing Dependency is a crucial step in any project. We'll be using the gorilla/mux module, a lightweight request router and dispatcher.

To install this module, we'll run $ go get followed by $ go install. The -u flag grabs the latest version.

Our module dependency is added to go.mod, along with the proper version number. The version number ensures we're using the correct version of the dependency.

We can use $ go mod vendor to build this dependency in our /vendors folder. This keeps it local to our project.

This process is essential for managing our dependencies effectively.

For another approach, see: Golang Version Manager

Go Path vs Go Root

The Go Path, also known as GOPATH, is a single directory where all Go projects and dependencies live. This is a key concept in Go, and it's where all the magic happens.

In Go, the GOPATH directory is where all projects and dependencies are installed, making it a crucial part of the development process.

Credit: youtube.com, GoRoot vs. GoPath | What is GoRoot in Go | What is GoPath in Go

The Go Root, or GOROOT, is a directory that contains Go's source code. This directory is automatically registered by Homebrew when installing Go.

Here's a quick comparison of the two:

To work with Go, you'll need to add your GOPATH to your shell's startup script. This will allow your system to recognize the GOPATH and use it for development.

Testing and Development

TDD is a great approach to development, and it's especially well-suited for Go applications. The article demonstrates this with a TDD implementation of the Weight Service.

The first step in TDD is to write tests before writing the actual code. In this example, the author creates a file called weight_test.go and adds tests for the Weight Service methods.

Writing tests quickly and focusing on mocking external dependencies is key. The author uses this approach to write tests for the methods that interact with the database.

In true TDD style, the author implements the logic of the methods one by one, starting with the three in the Weight Service. This approach ensures that each test passes before moving on to the next one.

Credit: youtube.com, Test Like a Pro in Go!

The author didn't strictly follow TDD for the database interactions, but it's still a good example of how to structure Go applications. The key takeaway is to create one test, make it pass, and then create the next one.

The building blocks for adding routes and a handler to create a weight entry for a given user are already in place. The reader is left to implement this part, but it's a great opportunity to practice TDD and see the code come together.

The accompanying Github repository is a great resource for those who want to see the complete code and learn from it.

Terminology

Every Go program contains a package called main, which serves as the project's entry point.

Packages in Go are similar to modules in Python or packages in Java, and they mirror packaging concepts in other programming languages.

Modules are third-party libraries installed by Go, and they are essentially projects published for general use as dependencies in your projects.

You can choose to keep module versions project-specific, similar to Python virtual environments, to avoid clashing dependency versions between projects.

Here's a quick rundown of the key terms:

  • Package: the main entry point of a Go program
  • Module: a third-party library installed by Go
  • Vendor: a project-specific version of a module

Application Examples

Credit: youtube.com, Golang Tutorial for Beginners | Full Go Course

Go is a versatile language that powers some of the world's most popular applications.

Netflix's streaming service is a great example of Go's capabilities, making your viewing experience more enjoyable.

The language's efficiency and scalability enable it to handle high traffic volumes, ensuring a seamless experience for users.

Go is also used in other top applications, such as those developed by companies like Dropbox, which rely on its reliability and performance.

Dropbox's use of Go shows the language's ability to handle large amounts of data and complex tasks.

The language's simplicity and ease of use also make it a great choice for developers, allowing them to focus on building innovative applications.

Frequently Asked Questions

What is Golang best used for?

Golang is best used for building scalable, concurrent, and high-performance systems, particularly in cloud-native applications, microservices architecture, and networking. Its efficiency and reliability make it a popular choice for enterprise software development.

Is Netflix using Golang?

Yes, Netflix is a notable user of Golang, leveraging it for internal tool development, such as Chaos Monkey. This highlights Golang's suitability for high-performance systems.

Cora Stoltenberg

Junior Writer

Cora Stoltenberg is a skilled writer with a passion for crafting engaging content on a wide range of topics. Her expertise spans various categories, including Search Engine Optimization (SEO) Strategies, where she provides actionable tips and insights to help businesses improve their online presence. With a keen eye for detail and a knack for simplifying complex concepts, Cora's writing is both informative and accessible to readers of all levels.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.