search
HomeBackend DevelopmentGolangGolang htmx Tailwind CSS: Create a Responsive Web Application

Background

In today’s web development landscape, JavaScript has long been the language of choice for creating dynamic and interactive web applications.

As a Go developer, what if you don’t want to use Javascript and still implement a responsive web application?

Imagine a sleek to-do list app that updates instantly as you check off tasks without a full-page reload. This is the power of Golang and htmx!

Combining Go and htmx allows us to create responsive and interactive web applications without writing a single line of JavaScript.

In this blog, we will explore how to use htmx and Golang to build web applications. (It can be used with other your favorite platforms, too.)

As a learning, we will implement basic create and delete operations for users.

What is htmx?

htmx is a modern HTML extension that adds bidirectional communication between the browser and the server.

It allows us to create dynamic web pages without writing JavaScript, as it provides access to AJAX, server-sent events, etc in HTML directly.

How htmx works?

  • When a user interacts with an element that has an htmx attribute (e.g., clicks a button), the browser triggers the specified event.
  • htmx intercepts the event and sends an HTTP request to the server-side endpoint specified in the attribute (e.g., hx-get="/my-endpoint").
  • The server-side endpoint processes the request and generates an HTML response.
  • htmx receives the response and updates the DOM according to the hx-target and hx-swap attributes. This can involve:

 — Replacing the entire element’s content.
 — Inserting new content before or after the element.
 — Appending content to the end of the element.

Let’s understand it in more depth with an example.

<button hx-get="/fetch-data" hx-target="#data-container">
   Fetch Data
</button>
<div>



<p>In the above code, when the button is clicked:</p>

<ol>
<li>htmx sends a GET request to /fetch-data.
</li>
<li>The server-side endpoint fetches data and renders it as HTML.</li>
<li>The response is inserted into the #data-container element.</li>
</ol>

<h3>
  
  
  Create and delete the user
</h3>

<p>Below are the required tools/frameworks to build this basic app.</p>

<ul>
<li>Gin (Go framework)</li>
<li>Tailwind CSS </li>
<li>htmx</li>
</ul>

<p><strong>Basic setup</strong> </p>

<ul>
<li>Create main.go file at the root directory.</li>
</ul>

<p><strong>main.go</strong><br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
 "fmt"
 "github.com/gin-gonic/gin"
)

func main() {
 router := gin.Default()

 router.Run(":8080")
 fmt.Println("Server is running on port 8080")
}

It sets up a basic Go server, running at port 8080.
Run go run main.go to run the application.

  • Create a HTML file at the root directory, to render the user list.

users.html


   
      <title>Go + htmx app </title>
      <script src="https://unpkg.com/htmx.org@2.0.0" integrity="sha384-wS5l5IKJBvK6sPTKa2WZ1js3d947pvWXbPJ1OmWfEuxLgeHcEbjUUA5i9V5ZkpCw" crossorigin="anonymous"></script>
      <script src="https://cdn.tailwindcss.com"></script>
   
   



<blockquote>
<p>We have included,</p>

<p><strong>htmx</strong> using the script tag — <u>https://unpkg.com/htmx.org@2.0.0</u></p>

<p><strong>Tailwind CSS</strong> with cdn link —<br>
<u>https://cdn.tailwindcss.com</u></p>
</blockquote>

<p>Now, we can use Tailwind CSS classes and render the templates with htmx.</p>

<p>As we see in users.html, we need to pass users array to the template, so that it can render the users list. </p>

<p>For that let’s create a hardcoded static list of users and create a route to render users.html .</p>

<h3>
  
  
  Fetch users
</h3>

<p><strong>main.go</strong><br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
 "fmt"
 "net/http"
 "text/template"

 "github.com/gin-gonic/gin"
)

func main() {
 router := gin.Default()

 router.GET("/", func(c *gin.Context) {
  users := GetUsers()

  tmpl := template.Must(template.ParseFiles("users.html"))
  err := tmpl.Execute(c.Writer, gin.H{"users": users})
    if err != nil {
       panic(err)
    }
 })

 router.Run(":8080")
 fmt.Println("Server is running on port 8080")
}

type User struct {
 Name  string
 Email string
}

func GetUsers() []User {
 return []User{
  {Name: "John Doe", Email: "johndoe@example.com"},
  {Name: "Alice Smith", Email: "alicesmith@example.com"},
 }
}

We have added a route / to render the user list and provide a static list of users (to which we will add new users ahead).

That’s all. Restart the server and let’s visit — http://localhost:8080/ to check whether it renders the user list or not. It will render the user list as below.

Golang   htmx   Tailwind CSS: Create a Responsive Web Application

Create user

Create file user_row.html. It will be responsible for adding a new user row to the user table.

user_row.html

<button hx-get="/fetch-data" hx-target="#data-container">
   Fetch Data
</button>
<div>



<p>In the above code, when the button is clicked:</p>

<ol>
<li>htmx sends a GET request to /fetch-data.
</li>
<li>The server-side endpoint fetches data and renders it as HTML.</li>
<li>The response is inserted into the #data-container element.</li>
</ol>

<h3>
  
  
  Create and delete the user
</h3>

<p>Below are the required tools/frameworks to build this basic app.</p>

<ul>
<li>Gin (Go framework)</li>
<li>Tailwind CSS </li>
<li>htmx</li>
</ul>

<p><strong>Basic setup</strong> </p>

<ul>
<li>Create main.go file at the root directory.</li>
</ul>

<p><strong>main.go</strong><br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
 "fmt"
 "github.com/gin-gonic/gin"
)

func main() {
 router := gin.Default()

 router.Run(":8080")
 fmt.Println("Server is running on port 8080")
}

It takes the name and email from the form input and executes the user_row.html.

Let’s try to add a new user to the table. Visit http://localhost:8080/ and click the Add User button.

Golang   htmx   Tailwind CSS: Create a Responsive Web Application

Yayy! We’ve successfully added a new user to the list ?.

To dive deeper into the detail implementation guide, check out the complete guide at Canopas.


If you like what you read, be sure to hit ? button! — as a writer it means the world!

I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.

Happy coding!?

The above is the detailed content of Golang htmx Tailwind CSS: Create a Responsive Web Application. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I write mock objects and stubs for testing in Go?How do I write mock objects and stubs for testing in Go?Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go?How can I define custom type constraints for generics in Go?Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How do you write unit tests in Go?How do you write unit tests in Go?Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How do you use the pprof tool to analyze Go performance?How do you use the pprof tool to analyze Go performance?Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How can I use tracing tools to understand the execution flow of my Go applications?How can I use tracing tools to understand the execution flow of my Go applications?Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Mar 25, 2025 am 11:17 AM

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

How do you use table-driven tests in Go?How do you use table-driven tests in Go?Mar 21, 2025 pm 06:35 PM

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

How can I use linters and static analysis tools to improve the quality and maintainability of my Go code?How can I use linters and static analysis tools to improve the quality and maintainability of my Go code?Mar 10, 2025 pm 05:38 PM

This article advocates for using linters and static analysis tools to enhance Go code quality. It details tool selection (e.g., golangci-lint, go vet), workflow integration (IDE, CI/CD), and effective interpretation of warnings/errors to improve cod

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version