Home > Backend Development > Golang > How to Serve Static Content from the Root Directory and a Homepage Handler in Go?

How to Serve Static Content from the Root Directory and a Homepage Handler in Go?

Susan Sarandon
Release: 2024-12-18 22:19:10
Original
130 people have browsed it

How to Serve Static Content from the Root Directory and a Homepage Handler in Go?

Serve Static Content from Root While Maintaining Homepage Handler

In Golang, serving static content from the root directory and handling the homepage with a dedicated handler poses a challenge.

Traditionally, a simple web server would use http.HandleFunc to register the homepage handler like this:

http.HandleFunc("/", HomeHandler)
Copy after login

However, when attempting to serve static content from the root directory using http.Handle, a panic occurs due to duplicate registrations for "/".

Alternative Approach: Serve Explicit Root Files

One solution is to avoid using http.ServeMux and instead explicitly serve each file in the root directory. This approach works well for mandatory root-based files like sitemap.xml, favicon.ico, and robots.txt.

package main

import (
    "fmt"
    "net/http"
)

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "HomeHandler")
}

func serveSingle(pattern string, filename string) {
    http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, filename)
    })
}

func main() {
    http.HandleFunc("/", HomeHandler) // homepage

    // Mandatory root-based resources
    serveSingle("/sitemap.xml", "./sitemap.xml")
    serveSingle("/favicon.ico", "./favicon.ico")
    serveSingle("/robots.txt", "./robots.txt")

    // Normal resources
    http.Handle("/static", http.FileServer(http.Dir("./static/")))

    http.ListenAndServe(":8080", nil)
}
Copy after login

This approach ensures that only specific root-based files are served explicitly, while other resources can be moved to a subdirectory and served via the http.FileServer middleware.

The above is the detailed content of How to Serve Static Content from the Root Directory and a Homepage Handler in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template