Home Backend Development Golang File Uploads with HTMX and Golang

File Uploads with HTMX and Golang

Aug 20, 2024 am 06:32 AM

Ofcourse you have already heard about the awesomeness of HTMX (you haven’t? well, good thing you’re here ?)

Today, we will be combining the simplicity of HTMX with the power of Golang to upload files to our server. Yeah, we are going to be building another exciting web feature with HTMX and Go.

By the way, if you really want a practical project-based guide on building fullstack apps with HTMX, check out my HTMX + Go: Build Fullstack Applications with Golang and HTMX course [Discount Included].

So, let’s begin.

Setting Up the Go Project

The first step is to setup a simple Go project. We can do that by creating a folder, going into it and initialising it as a Go project using the commands below:

mkdir go-htmx-file-uploads
cd go-htmx-file-uploads
go mod init go-htmx-file-uploads
Copy after login

Once we have the project initialized, let’s now install some dependencies we will be requiring within our project.

This will be a simple server that will contain a single page with our upload form and also an endpoint that will be used to upload the file.

For routing, we will be using the Gorilla Mux routing library, but feel free to use any routing solution of your choice. We will also be using Google’s UUID library for Go to generate random names for our files when we upload them. This is a personal preference as you can generate file names in different ways.

Install these two with the commands below:

Gorillla Mux

go get -u github.com/gorilla/mux 
Copy after login

Google UUID

go get github.com/google/uuid
Copy after login

With these two installed, our project is fully set up, and we can move to the next step.

Creating our Templates

We will be creating two HTML templates for this little project.

The first template will be an HTML fragment that simply takes a slice of string messages that we can send from the server to the client.

This fragment will take this slice of messages and loop through it to create an HTML list to be returned to the client (remember how HTMX works with Hypermedia APIs, pretty cool huh ?).

So, let’s create that first.

At the root of the Go project, first create a templates folder inside which we will be storing all our templates.

Next, create a file messages.html inside the templates folder and add the following code to it:

{{define "messages"}}
<ul>
    {{range .}}
        <li>{{ . }}</li>
    {{end}}
</ul>
{{end}}
Copy after login

This defines a messages template and loops through the incoming slice of string messages to form an HTML list.

For our next template, we will be creating the file upload page itself.

Inside the templates folder, create a new file upload.html and paste in the code below:

{{define "upload"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://unpkg.com/htmx.org@1.9.12"></script>
    <title>Upload File</title>
</head>
<body>

    <div class="row">
        <div class="col-md-6 p-5 mt-5">
            <h4>Upload File</h4>
            <form  class="form">
                <div id="messages"></div>
                <div class="mb-3">
                    <label for="avatarInput" class="form-label">Select Image</label>
                    <input type="file" class="form-control" id="avatarInput" name="avatar" required>
                </div>
                <button 
                    hx-post="/upload" 
                    hx-encoding="multipart/form-data" 
                    hx-target="#messages" 
                    type="submit" class="btn btn-primary">Upload</button>
            </form>
        </div>
    </div>



</body>
</html>
{{end}}
Copy after login

Perfect!

Now let’s go through the code in this file.

First, we have defined the template with the name upload, this is the name we will use to reference it later in our route handlers.

We then have some boilerplate HTML code in the head section, but I have included two important libraries here (well, just one is really important, the other is just for CSS vibes).

The HTMX library has been included with the

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.

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.

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.

See all articles