Upload File

{{end}}

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

”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 HTMX 和 Golang 上传文件

使用 HTMX 和 Golang 上传文件

发布于2024-11-04
浏览:375

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

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 

Google UUID

go get github.com/google/uuid

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"}}
    {{range .}}
  • {{ . }}
  • {{end}}
{{end}}

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"}}



    Upload File

Upload File

{{end}}

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

Then I have also brought in the Bootstrap CSS library, this is just to give our page elements some nice styling. It is not compulsory for this demo.

In the page itself, we have a form that does the upload. Let’s break down what is within the

tags.

First we have a

with an id of messages , this is the container where we will be loading all our server messages that come in as HTML. Remember the messages template, yeah, this is where the list of messages will be going into.

After that, we have the form input element that is set to file to ensure that it displays a file upload widget. We have given it the name avatar to reference it at the backend, but you can give this any name you want. I gave it avatar because i was using it to upload profile images.

Finally, we have the button which has been supercharged with HTMX. I have displayed it again below so we can go through it


First, I have added hx-post="/upload" , this tells it to submit the form to the /upload endpoint that we will be creating very soon and will handle the file upload.

Next is hx-encoding="multipart/form-data", this is compulsory for uploading files with HTMX to let the server know you’re sending along a file with the request.

Then we have hx-target="#messages" which tells the button to insert any response from the server into the

with an id of messages.

These three define our configuration for uploading the file to our backend.

Below is a preview of what our page looks like:

File Uploads with HTMX and Golang

Processing the File Upload

Now that we have our templates, it’s time to write the code that will display our upload page and also handle our file uploads.

To begin, at the root of the Go project, create a uploads folder. This is the folder where all our uploaded files will be stored.

With that in place, let’s write our main file.

Create the file main.go at the root of your project and add the following code:

package main

import (
    "html/template"
    "log"
    "net/http"
    "io"
    "os"
    "path/filepath"
    "github.com/google/uuid"
    "github.com/gorilla/mux"
)

var tmpl *template.Template

func init(){
    tmpl, _ = template.ParseGlob("templates/*.html")
}

func main() {


    router := mux.NewRouter()

    router.HandleFunc("/", homeHandler).Methods("GET")

    router.HandleFunc("/upload", UploadHandler).Methods("POST")

    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", router))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {

    tmpl.ExecuteTemplate(w, "upload", nil)

}

func UploadHandler(w http.ResponseWriter, r *http.Request) {


        // Initialize error messages slice
        var serverMessages []string

        // Parse the multipart form, 10 MB max upload size
        r.ParseMultipartForm(10  0 {
                tmpl.ExecuteTemplate(w, "messages", serverMessages)
                return
            }

        }
        defer file.Close()

        // Generate a unique filename to prevent overwriting and conflicts
        uuid, err := uuid.NewRandom()
        if err != nil {
            serverMessages = append(serverMessages, "Error generating unique identifier")
            tmpl.ExecuteTemplate(w, "messages", serverMessages)

            return
        }
        filename := uuid.String()   filepath.Ext(handler.Filename) // Append the file extension

        // Create the full path for saving the file
        filePath := filepath.Join("uploads", filename)

        // Save the file to the server
        dst, err := os.Create(filePath)
        if err != nil {
            serverMessages = append(serverMessages, "Error saving the file")
            tmpl.ExecuteTemplate(w, "messages", serverMessages)

            return
        }
        defer dst.Close()
        if _, err = io.Copy(dst, file); err != nil {
            serverMessages = append(serverMessages, "Error saving the file")
            tmpl.ExecuteTemplate(w, "messages", serverMessages)
            return
        }


        serverMessages = append(serverMessages, "File Successfully Saved")
        tmpl.ExecuteTemplate(w, "messages", serverMessages)


}

Yope, that’s a bunch of code. Don’t worry, we’ll go through it all step by step to figure out what this is all doing.

First we define our package main and import a bunch of libraries we will be making use of. These imports include the Gorilla mux router and the Google UUID library that we installed earlier.

After that, I create a global tmpl variable to hold all the HTML templates in the project and in the init() function, the templates are all loaded from the templates folder.

The main() Function

Now to the main() function. Here, we have initlialized the Gorilla Mux router and set up two routes.

The GET / base route which will be handled by a homeHandler function and displays our upload form, and the POST /upload route that will be handled by UploadHandler and handles the upload itself.

Finally, we print out a message to indicate that our server is running, and run the server on port 8080.

The Handler Functions

First we have homeHandler . This is the function that handles our base route, and it simply calls ExecuteTemplate on the tmpl variable with the name we gave to our template

tmpl.ExecuteTemplate(w, "upload", nil)

This call is enough to simply render our upload page to the screen when we visit the base route.

After that is the UploadHandler function. This is where the real magic happens, so let’s walk through the function.

First, we create a slice of strings called serverMessages to hold any message we want to send back to the client.

After that, we call ParseMultipartForm on the request pointer to limit the size of uploaded files to within 20MB.

r.ParseMultipartForm(10 



Next, we get a hold on our file by referencing the name of the file field with FormFile on the request pointer.

With our reference to the file, we check if there is actually a file, and if not, we return a message saying that no file was submitted or an error was encountered when trying to retrieve the file to account for other errors.

file, handler, err := r.FormFile("avatar")
        if err != nil {
            if err == http.ErrMissingFile {
                serverMessages = append(serverMessages, "No file submitted")
            } else {
                serverMessages = append(serverMessages, "Error retrieving the file")
            }

            if len(serverMessages) > 0 {
                tmpl.ExecuteTemplate(w, "messages", serverMessages)
                return
            }

        }

At this point, if our messages slice is not empty, we return the messages to the client and exit the function.

If a file is found, we keep the file open and move to generating a new name for it with the UUID library and also handle the errors in that process accordingly.

We build a new file name with the generated string and the file extension and set it’s path to the uploads folder.

    uuid, err := uuid.NewRandom()
        if err != nil {
            serverMessages = append(serverMessages, "Error generating unique identifier")
            tmpl.ExecuteTemplate(w, "messages", serverMessages)

            return
        }
        filename := uuid.String()   filepath.Ext(handler.Filename) 

        // Create the full path for saving the file
        filePath := filepath.Join("uploads", filename)

Once the new file path is constructed, we then use the os library to create the file path

After that, we use the io library to move the file from it’s temporary location to the new location and also handle errors accordingly.

    dst, err := os.Create(filePath)
        if err != nil {
            serverMessages = append(serverMessages, "Error saving the file")
            tmpl.ExecuteTemplate(w, "messages", serverMessages)

            return
        }
        defer dst.Close()
        if _, err = io.Copy(dst, file); err != nil {
            serverMessages = append(serverMessages, "Error saving the file")
            tmpl.ExecuteTemplate(w, "messages", serverMessages)
            return
        }

If we get no errors from the file saving process, we then return a successful message to the client using our messages template as we have done with previous messages.

serverMessages = append(serverMessages, "File Successfully Saved")
tmpl.ExecuteTemplate(w, "messages", serverMessages)

And that’s everything.

Now let’s take this code for a spin.

Testing the File Upload

Save the file and head over to the command line.

At the root of the project, use the command below to run our little file upload application:

go run main.go

Now go to your browser and head over to http://localhost:8080, you should see the upload screen displayed.

Try testing with no file to see the error message displayed. Then test with an actual file and also see that you get a successful message.

Check the uploads folder to confirm that the file is actually being saved there.

File Uploads with HTMX and Golang

And Wholla! You can now upload files to your Go servers using HTMX.

Conclusion

If you have enjoyed this article, and will like to learn more about building projects with HTMX, I’ll like you to check out HTMX Go: Build Fullstack Applications with Golang and HTMX, and The Complete HTMX Course: Zero to Pro with HTMX to further expand your knowledge on building hypermedia-driven applications with HTMX.

版本声明 本文转载于:https://dev.to/coderonfleek/file-uploads-with-htmx-and-golang-57ad?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 跨域场景下CORS何时使用预检请求?
    跨域场景下CORS何时使用预检请求?
    CORS:了解跨域请求的“预检”请求跨域资源共享 (CORS) 在制作 HTTP 时提出了挑战跨域请求。为了解决这些限制,引入了预检请求作为解决方法。预检请求说明预检请求是先于实际请求(例如 GET 或 POST)的 OPTIONS 请求)并用于与服务器协商请求的权限。这些请求包括两个附加标头:Ac...
    编程 发布于2024-11-05
  • 如何使用 PHP 的 glob() 函数按扩展名过滤文件?
    如何使用 PHP 的 glob() 函数按扩展名过滤文件?
    在 PHP 中按扩展名过滤文件使用目录时,通常需要根据扩展名检索特定文件。 PHP 提供了一种使用 glob() 函数来完成此任务的有效方法。要按扩展名过滤文件,请使用语法:$files = glob('/path/to/directory/*.extension');例如,要检索目录 /path/...
    编程 发布于2024-11-05
  • 理解 JavaScript 中的 Promise 和 Promise Chaining
    理解 JavaScript 中的 Promise 和 Promise Chaining
    什么是承诺? JavaScript 中的 Promise 就像你对未来做某事的“承诺”。它是一个对象,表示异步任务的最终完成(或失败)及其结果值。简而言之,Promise 充当尚不可用但将来可用的值的占位符。 承诺国家 Promise 可以存在于以下三种状态之一: ...
    编程 发布于2024-11-05
  • 安全分配
    安全分配
    今天,关于 JavaScript 中安全赋值运算符 (?=) 的新提案引起了热烈讨论。我喜欢 JavaScript 随着时间的推移而不断改进,但这也是我最近在一些情况下遇到的问题。我应该将快速示例实现作为函数,对吧? 如果您还没有阅读该提案,以下是其建议: const [error, value] ...
    编程 发布于2024-11-05
  • 创建队列接口
    创建队列接口
    创建字符队列的接口。 需要开发的三个实现: 固定大小的线性队列。 循环队列(复用数组空间)。 动态队列(根据需要增长)。 1 创建一个名为 ICharQ.java 的文件 // 字符队列接口。 公共接口 ICharQ { // 向队列中插入一个字符。 void put(char ch); ...
    编程 发布于2024-11-05
  • Pip 的可编辑模式何时对本地 Python 包开发有用?
    Pip 的可编辑模式何时对本地 Python 包开发有用?
    使用 Pip 在 Python 中利用可编辑模式进行本地包开发在 Python 的包管理生态系统中,Pip 拥有“-e”(或'--editable') 特定场景的选项。什么时候使用这个选项比较有利?答案在于可编辑模式的实现,官方文档中有详细说明:“从本地以可编辑模式安装项目(即 se...
    编程 发布于2024-11-05
  • 当您在浏览器中输入 URL 时会发生什么?
    当您在浏览器中输入 URL 时会发生什么?
    您是否想知道当您在浏览器中输入 URL 并按 Enter 键时幕后会发生什么?该过程比您想象的更加复杂,涉及多个步骤,这些步骤无缝地协同工作以提供您请求的网页。在本文中,我们将探讨从输入 URL 到查看完全加载的网页的整个过程,阐明使这一切成为可能的技术和协议。 第 1 步:输入 U...
    编程 发布于2024-11-05
  • 如何有效管理大量小HashMap对象的“OutOfMemoryError:超出GC开销限制”?
    如何有效管理大量小HashMap对象的“OutOfMemoryError:超出GC开销限制”?
    OutOfMemoryError: Handling Garbage Collection Overhead在Java中,当过多时会出现“java.lang.OutOfMemoryError: GC Overhead limit allowed”错误根据 Sun 的文档,时间花费在垃圾收集上。要解决...
    编程 发布于2024-11-05
  • 为什么在 Python 列表初始化中使用 [[]] * n 时列表会链接在一起?
    为什么在 Python 列表初始化中使用 [[]] * n 时列表会链接在一起?
    使用 [[]] * n 进行列表初始化时的列表链接问题使用 [[]] 初始化列表列表时 n,程序员经常会遇到一个意想不到的问题,即列表似乎链接在一起。出现这种情况是因为 [x]n 语法创建对同一基础列表对象的多个引用,而不是创建不同的列表实例。为了说明该问题,请考虑以下代码:x = [[]] * ...
    编程 发布于2024-11-05
  • Python 变得简单:从初学者到高级 |博客
    Python 变得简单:从初学者到高级 |博客
    Python Course Code Examples This is a Documentation of the python code i used and created , for learning python. Its easy to understand and L...
    编程 发布于2024-11-05
  • 简化 TypeScript 中的类型缩小和防护
    简化 TypeScript 中的类型缩小和防护
    Introduction to Narrowing Concept Typescript documentation explains this topic really well. I am not going to copy and paste the same descrip...
    编程 发布于2024-11-05
  • 何时应该使用 session_unset() 而不是 session_destroy() ,反之亦然?
    何时应该使用 session_unset() 而不是 session_destroy() ,反之亦然?
    理解 PHP 中 session_unset() 和 session_destroy() 的区别PHP 函数 session_unset() 和 session_destroy() 有不同的用途管理会话数据。尽管它们在清除会话变量方面有明显相似之处,但它们具有不同的效果。session_unset(...
    编程 发布于2024-11-05
  • 如何选择在 C++ 中解析 INI 文件的最佳方法?
    如何选择在 C++ 中解析 INI 文件的最佳方法?
    在 C 中解析 INI 文件:各种方法指南在 C 中处理初始化 (INI) 文件时,开发人员经常遇到有效解析这些文件以提取所需信息的挑战。本文探讨了用 C 解析 INI 文件的不同方法,讨论了它们的优点和注意事项。本机 Windows API 函数一种方法是利用 Windows API 函数INI ...
    编程 发布于2024-11-05
  • 代码日:重新聚焦
    代码日:重新聚焦
    2024 年 8 月 19 日星期一 今天是我 100 天编程之旅的一半! ?除了记录我的进步之外,我还喜欢分享学习技巧。我最喜欢的新方法之一是番茄工作法,它需要专注于一项任务 25 分钟,然后休息 5 分钟。四个周期后,您会休息更长的时间。这有助于保持注意力并防止倦怠。 我尝试过 App Stor...
    编程 发布于2024-11-05
  • 为什么我在 Visual Studio 2015 中收到编译器错误 C2280“尝试引用已删除的函数”?
    为什么我在 Visual Studio 2015 中收到编译器错误 C2280“尝试引用已删除的函数”?
    Visual Studio 2015 中编译器错误 C2280“尝试引用已删除的函数”Visual Studio 2015 编译器与其 2013 的前身不同,自动为定义移动构造函数或移动赋值运算符的类生成删除的复制构造函数。 C 标准强制执行此行为,以防止在首选移动的情况下发生意外复制。在您的代码片...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3