Web API in Go Training
This course was designed for anyone wanting to learn how to use the standard library to create robust, effective, and performant Web API's in Go. Students will first learn about the constructs in the standard library that enable creating handlers, and how to use that knowledge to create custom API's. They will continue to use that knowledge to build on as they create custom routers, deal with validating and responding to error conditions from user input, and finish with learning how to write unit and integration tests for their API's.
Length
2 days. Each day is 4 hours long including a 15 minute break.Class Size
Our classes are priced for small and large classes. We offer classes starting at only five students, up to 100 students. We recognize that each company has specific needs and budgets.
For pricing, fill out our contact us form and you'll receive an automated reply with our current rates.
Target Audience
- You have been doing daily Go development for 1-3 months.
- You want to learn how to create Web API's in Go
- You want to understand Go's HTTP handling capabilities
- You are building web APIs that require complex routing
- You want to understand multiplexing and HTTP request handling in Go
- You want to implement custom routing solutions
- You are transitioning to building web services in Go
Prerequisites
- Familiarity and comfort navigating and basic file manipulation at the command line.
- Familiarity and comfort with a modern code editor, including creating and modifying files and projects.
- You have 1 to 3 months of daily Go experience.
- You have at least 6 months of experience with other modern development languages such as Java, C#, Swift, JavaScript, Python, Rust, etc.
- Familiarity with basic programming concepts and structures such as variables, loops, conditionals, etc.
- Computers should be capable of modern software development, such as access to install and run binaries, install a code editor, etc. Full instructions referenced here: preparing your environment for Go development. It may be necessary for them to have root/admin access to their computer.
Recommended Preparation
- Install and configure an editor for Go.
- Have a functioning Go environment installed with Go 1.13 or later.
- Sign up for a Github account if you don't already have one.
Suggested Followup Learning
- Testing, Stubbing, and Automating Go Work Environments
- gRPC & gRPC Gateway Development in Go
- Advanced Go Development
- Profiling and Optimization in Go
Expected Outcomes
- Students will learn about the structures in the standard library needed to create Web API's.
- Students will be able to explain and implement Go's http.Handler interface for handling web requests
- Students will be able to create custom HTTP handlers to process different API endpoints and route types
- Students will learn to design and implement middleware patterns to handle logging, authentication, and other cross-cutting concerns
- Students will develop production-quality web services with comprehensive error handling and status codes
- Students will demonstrate the ability to structure web applications using maintainable patterns and best practices for Go services
- Students will understand and implement Go's built-in ServeMux for basic HTTP routing
- Students will learn to create and mount multiple muxers for organizing route hierarchies
- Students will build custom muxers to handle specific routing requirements like HTTP method-based routing
- Students will evaluate the limitations of built-in muxing and understand when to use third-party routers
- Students will implement path stripping and prefix handling for nested route structures
- Students will understand the proper patterns needed to create testable, reusable code for Web API's in Go.
- Students will learn how to deal with JSON as well as create custom JSON implementations.
- Students will learn how to create unit tests and integration tests for web API's.
Course Details
Day One
Introduction to Go Web Development: Building a Simple HTTP Server and Web Services
In this chapter, you will dive into the basics of web development using Go. You’ll learn how to build a simple web server, create HTTP handlers, and set up routing using Go’s powerful `net/http` package. Starting with a basic "Hello, World!" web application, we will guide you through key concepts such as routing, serving static files, handling headers, and securing your server with TLS. By the end of this chapter, you’ll have a solid foundation for developing web services in Go, complete with the ability to handle multiple routes and build reliable HTTP applications.
Building HTTP Handlers for Web Applications: Handling Routes, Processing Requests, and Sending Responses
In this chapter, we explore the fundamentals of building HTTP handlers in Go, which are the backbone of any web application. You will learn about the `http.Handler` interface, `HandlerFunc`, and how to implement them effectively to process requests and send responses. We’ll also delve into how middleware can extend your handlers by adding functionalities such as logging, authentication, and more. By the end of this chapter, you’ll be equipped to create robust and reusable HTTP handlers for your web services, complete with middleware for pre- and post-processing requests.
Break
Tea/Coffee Break.
Advanced Routing and Muxing in Go: Building Robust Web Application Routes
This chapter dives deep into the implementation of routing and multiplexing for advanced web development in Go. It covers the basics of using Go’s built-in `http.ServeMux` for simple routing, along with the limitations of this default multiplexer. The chapter then transitions into constructing more complex routing setups, including: - **Using Multiple Muxers:** Learn how to handle and mount multiple muxers, how path stripping works, and the importance of proper path handling. - **Custom Muxer Development:** A step-by-step guide to building a custom muxer from scratch using Go’s `http.Handler` interface, illustrating how you can gain full control over your routing logic.
Modern HTTP Routing with Go 1.22+
This module covers modern web development patterns using Go 1.22+ enhanced routing capabilities and production-ready patterns. - Completion of standard-web/intro module - Completion of standard-web/handlers module - Basic understanding of HTTP fundamentals - Familiarity with Go 1.22+ Go 1.22 introduced significant enhancements to `http.ServeMux`, making third-party routers unnecessary for many applications. This module teaches modern web development patterns using these new capabilities combined with production best practices.
Mastering HTML Templates in Go
This chapter explores the use of HTML templating in Go, starting with the standard library packages `text/template` and `html/template`. You'll learn the basic workflow for rendering templates, including how to inject dynamic data, manage template syntax, and implement advanced features such as conditional statements and loops. We cover essential topics such as handling spaces, creating custom functions, and safely working with HTML to prevent security risks like cross-site scripting (XSS) attacks.
Day Two
Working with JSON: Encoding and Decoding in Go: Safely handling JSON serialization and deserialization
Handling JSON effectively is a core skill when building modern Go applications, as JSON is widely used for data exchange in APIs and web services. In this chapter, we will explore how to safely encode (serialize) and decode (deserialize) JSON in Go using the `encoding/json` package. We will cover both basic and advanced topics, including struct tags, handling inconsistent JSON formats, custom marshaling/unmarshaling techniques, and how to manage sensitive data like passwords and personal information. Through practical examples, you'll learn to confidently convert Go structs to JSON, handle errors, and ensure that your JSON interactions are safe and efficient.
Building Production-Ready Web Services: Best Practices for Secure, Maintainable, and Performant Go Applications
This chapter focuses on creating web services that are not only functional but also ready for production by implementing best practices for security, scalability, maintainability, and performance. It emphasizes the importance of a structured codebase, security through TLS, graceful shutdown mechanisms, and monitoring tools like tracing and logging. Key areas covered include: - **Application Structure:** Organizing code into modules and packages for maintainability, following conventions for handler structuring, and separating responsibilities for better testability.
Break
Tea/Coffee Break.
Testing HTTP Handlers with Net/HTTP: Writing Tests for HTTP Services and Utilizing the net/http/httptest Package
In this chapter, we dive into testing HTTP handlers in Go, leveraging the `net/http/httptest` package. Testing HTTP handlers can be approached in two distinct styles: Unit Style Testing and Integration Style Testing. Each style serves different purposes in ensuring that your web applications work as expected. We will explore both approaches, demonstrating how to mock HTTP requests, simulate responses, and write efficient tests for your web services. Additionally, you'll learn how to create test servers, utilize middleware, and handle request bodies and form data. By the end of this module, you’ll have the skills to write comprehensive and reliable tests for Go-based web applications.
Prerequisites
Testing Basics: Writing and Running Unit Tests
This chapter introduces the fundamentals of testing in Go, with a focus on writing and running unit tests using the built-in `testing` package. You'll learn how to structure tests, the importance of naming conventions, and how to utilize the `*testing.T` type to create effective test cases. Key concepts such as the difference between `Error` and `Fatal`, crafting meaningful failure messages, and organizing internal vs. external tests are explored. Additionally, we'll cover useful helper functions, alternative testing packages, and provide practical examples to help you develop reliable, maintainable tests for your Go applications.
Table-Driven Testing for Flexible and Scalable Tests
Table-driven testing is a powerful and efficient way to create clean, reusable, and scalable tests in Go. By defining test cases as data in tables, you can minimize duplication and easily extend test coverage by adding new cases. This chapter covers how to implement table-driven tests, demonstrating how to isolate test logic, reduce redundancy, and ensure your tests remain organized. You will also learn advanced techniques like running sub-tests, parallelizing table-driven tests, and handling setup and teardown logic for enhanced performance and clarity
Interfaces and Polymorphism in Go: Understanding Go's approach to interfaces and dynamic behavior in type systems
Interfaces in Go provide a way to specify the behavior of an object: `If something can do this, then it can be used here`. This chapter will take a look at how to use interfaces to abstract that behavior. Concepts such as the `Empty Interface`, satisfying multiple interfaces, and asserting for behavior will be covered. Additionally, this chapter will cover the difference between `value` and `pointer` receivers and how they affect the ability to satisfy an interface. > The larger the interface, the weaker the abstraction. -- Rob Pike
Embedding and Composition for Code Reuse: Using Go’s embedding feature for cleaner, more modular code
This chapter delves into Go's powerful embedding and composition mechanisms, which allow developers to build cleaner, modular, and reusable code without traditional inheritance. Instead of subclassing, Go enables embedding types within structs and interfaces, promoting fields and methods automatically. You will explore how embedding works, how method promotion simplifies code, and how to handle collisions and method overriding effectively. This chapter also covers how embedding can be used to satisfy interfaces, making your code more versatile and maintainable through practical examples.
Error Handling and Best Practices (Dealing with errors, panics, recover)
Go's approach to error handling is simple but powerful, emphasizing clear control flow over error-prone constructs like `try/catch`. In this chapter, you will learn how to effectively manage errors in Go using idiomatic patterns. The chapter covers basic error handling, creating and returning errors, and best practices such as wrapping errors for better context. You will also explore advanced topics like custom error types, sentinel errors, error chain traversal, modern error inspection with `errors.Is()` and `errors.As()`, custom unmarshal error handling, and the use of Go's `panic` and `recover` for managing unexpected failures. By the end, you'll have a deep understanding of how Go's error model leads to more reliable and maintainable code, while learning when and how to use recovery mechanisms for graceful error handling.