Web Development with Go
# CHAPTER 25
Web Development with Go
1. Introduction
In Chapter 23, we built an API that returned raw JSON data to be consumed by front-end frameworks like React or Angular. However, sometimes you don't want a complex Javascript frontend. Sometimes you just want to return a fully rendered HTML webpage directly from the server. Go provides a brilliant standard package calledhtml/template specifically for Server-Side Rendering (SSR).
2. Learning Objectives
By the end of this chapter, you will be able to:- Serve static files (CSS, Images, Javascript).
-
Use
html/templateto render HTML files.
- Inject dynamic Go variables into HTML.
- Write basic Middleware to intercept HTTP requests.
3. Serving Static Files
To build a website, you need CSS and images. You must tell Go to publicly expose a folder containing these files.*If you have a file ./static/style.css, a user can now view it at http://localhost:8080/static/style.css.*
4. HTML Templates
Writing HTML directly insidefmt.Fprintf(w, "<h1>Hello</h1>") is messy. Instead, we create a separate .html file and use Go's templating engine to inject data into it safely.
1. Create a file named index.html:
We use double curly braces {{ . }} to indicate where Go should inject data.
2. Create the Go Handler (main.go):
5. Template Logic (Loops and If Statements)
Go's templating engine is powerful. You can write loops and conditionals directly inside the HTML file!6. Middleware Basics
Middleware is a function that intercepts an incoming HTTP request *before* it reaches your final handler. It is used for Logging, Authentication, or checking API Keys.A basic Middleware takes an http.HandlerFunc, does some work, and then calls the original handler.
7. Common Mistakes
-
Unexported Template Data: If you pass a struct to
tmpl.Execute, but the struct fields are lowercase (userName), the HTML file will render completely blank where the data should be. Templates are external to your package, so fields MUST be exported (Capitalized).
-
Cross-Site Scripting (XSS) Fears: You might worry that injecting user data into HTML is a security risk. Don't worry! Go's
html/templatepackage is Context-Aware. It automatically sanitizes and escapes malicious javascript injections natively.
8. Best Practices
-
Parse Templates Once: Parsing templates on every single HTTP request is slow. In production, you should use
template.ParseGlob("templates/*.html")once at the very top of yourmain()function, and reuse that parsed variable in your handlers.
9. Exercises
-
1.
Create a simple
about.htmlfile.
-
2.
In Go, define a
CompanyInfostruct containing the company name and year founded.
- 3. Serve the HTML page, passing the struct to display the data dynamically.
10. MCQs with Answers & Explanations
Which package provides Context-Aware HTML rendering in Go?
What syntax is used to inject Go variables inside an HTML template file?
If you pass a struct to an HTML template, but the fields are lowercase, what happens?
Which function allows you to serve static assets like CSS files and Images?
if statements and for loops inside Go HTML templates?
a) Yes, using {{ if }} and {{ range }} b) No, templates are strictly data-only
Answer: a) Yes.
What is the primary purpose of HTTP Middleware?
html/template safe from Cross-Site Scripting (XSS) injection attacks?
a) Yes, it auto-escapes inputs based on whether it is placed in an HTML body, attribute, or JS script tag b) No, you must use a third-party library
Answer: a) Yes, it is heavily Context-Aware and secure by default.
Q8. Should you call template.ParseFiles() inside the Handler function for high-traffic websites?
a) Yes, so it always gets the latest file b) No, parsing files is disk I/O heavy. Parse them once at startup and cache them.
Answer: b) No, parse them once at startup.
Which function actually executes the parsed template and sends the HTML to the browser?
What does {{ range .Users }} do in an HTML template?
11. Interview Preparation
Interview Questions:-
1.
Why is
html/templatepreferred overtext/templatefor web development in Go? (Answer: Context-aware auto-escaping for security).
- 2. What is Middleware? Describe a scenario where you would implement it in a Go REST API.
- 3. Why must struct fields be capitalized to be used in HTML templates?
12. Summary
Go is fully equipped to build both JSON APIs and traditional, server-rendered websites. Thehtml/template package provides a highly secure, fast way to build dynamic pages. By combining templating with Middleware, you can build full-stack web applications without relying on external frameworks.