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:
import (
"html/template"
"net/http"
)
type Page struct {
Title string
Anchor string
}
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
}
}
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>
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
.