How to create and use HTML anchor tags for linking within the same page in Go?

In Go, you can use the "html/template" package to create and use HTML anchor tags for linking within the same page. Here's an example:

  1. Import the necessary packages:
import ( "html/template" "net/http" )
  1. Define a struct to hold the data for your HTML template:
type Page struct { Title string Anchor string }
  1. Create a handler function to render the HTML template:
func handler(w http.ResponseWriter, r *http.Request) { data := Page{ Title: "My Page", Anchor: "#section1", } tmpl, err := template.New("index").ParseFiles("index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = tmpl.Execute(w, data) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
  1. Create an HTML file (index.html) containing the anchor tag:
<html> <head> <title>{{ .Title }}</title> </head> <body> <h1>My Page</h1> <a href="{{ .Anchor }}">Go to Section 1</a> <!-- Rest of your HTML content --> <h2 id="section1">Section 1</h2> <!-- Section 1 content --> </body> </html>
  1. Initialize your HTTP server and register the handler function:
func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }

Now, when you run your Go program and visit http://localhost:8080, you will see a link titled "Go to Section 1". When clicked, it will scroll down to the target section with the ID section1.