How to create HTML tables with sorting and filtering functionality in Go?

To create HTML tables with sorting and filtering functionality in Go, you can use the following steps:

  1. Use Go's HTML/template package to create an HTML template that includes a table structure. You can define placeholders for the table headers and rows.
{{define "table"}} <table> <thead> <tr> <th><a href="?sort=id">ID</a></th> <th><a href="?sort=name">Name</a></th> <th><a href="?sort=age">Age</a></th> </tr> </thead> <tbody> {{range .}} <tr> <td>{{.ID}}</td> <td>{{.Name}}</td> <td>{{.Age}}</td> </tr> {{end}} </tbody> </table> {{end}}
  1. In your Go code, define a struct type for the data that will be displayed in the table. For example:
type User struct { ID int Name string Age int }
  1. Implement a handler function or method to handle the HTTP request to display the table. This handler function should retrieve the data, apply any sorting or filtering based on the query parameters, and render the HTML template. Here's an example of how you can do this using the standard library net/http package:
func tableHandler(w http.ResponseWriter, r *http.Request) { // Retrieve the data and store it in a slice of User structs data := []User{ {ID: 1, Name: "John Doe", Age: 30}, {ID: 2, Name: "Jane Smith", Age: 25}, // ... } // Apply sorting based on the "sort" query parameter sortBy := r.URL.Query().Get("sort") switch sortBy { case "id": sort.Slice(data, func(i, j int) bool { return data[i].ID < data[j].ID }) case "name": sort.Slice(data, func(i, j int) bool { return data[i].Name < data[j].Name }) case "age": sort.Slice(data, func(i, j int) bool { return data[i].Age < data[j].Age }) } // Render the HTML template t := template.Must(template.New("table").ParseFiles("table.html")) t.ExecuteTemplate(w, "table", data) }
  1. Register the tableHandler function as an HTTP handler for the desired URL path. For example, using the http.HandleFunc function:
func main() { http.HandleFunc("/table", tableHandler) http.ListenAndServe(":8080", nil) }
  1. Create a CSS file to style the table as desired. This step is optional but can greatly enhance the appearance of the table.

  2. Create an HTML file (e.g., table.html) that includes a link to the CSS file and invokes the template defined in step 1. For example:

<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> {{template "table" .}} </body> </html>

With these steps, accessing the /table URL will display an HTML table with sorting and filtering functionality in Go, based on the data provided in the tableHandler function. The table headers will have links that allow sorting by the corresponding column when clicked.