Home Backend Development Golang Golang htmx Tailwind CSS: Create a Responsive Web Application

Golang htmx Tailwind CSS: Create a Responsive Web Application

Nov 23, 2024 pm 04:05 PM

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>

<div class="code" style="position:relative; padding:0px; margin:0px;"><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")
}
Copy after login
Copy after login

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

<!DOCTYPE html>
<html>
   <head>
      <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>
   </head>
   <body>



<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"},
 }
}
Copy after login

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>

Copy after login
  • Gin (Go framework)
  • Tailwind CSS
  • htmx

Basic setup

  • Create main.go file at the root directory.

main.go

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")
}
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

See all articles