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

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

Linda Hamilton
Release: 2024-12-18 11:05:10
Original
120 people have browsed it

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

Serving Homepage and Static Content from Root in Go

In Go, serving both static content and a homepage from the root directory while handling specific URLs requires a tailored approach. By default, registering a handler for the root path ("/") conflicts with serving static content from the same directory.

To address this, one option is to use an alternative FileServer implementation that checks for the existence of a file before attempting to serve it. For files not present, it can defer to the homepage handler or return a 404 error.

The following code demonstrates this approach:

package main

import (
    "fmt"
    "net/http"
    "os"
)

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

func exists(path string) bool {
    _, err := os.Stat(path)
    return !os.IsNotExist(err)
}

func FileServerWithFallback(dir string) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        path := dir + r.URL.Path
        if exists(path) {
            http.ServeFile(w, r, path)
            return
        }
    }
}

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

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

In this code, the exists function checks if a file exists at a given path. The FileServerWithFallback handler serves a file if it exists in the provided directory. Otherwise, it allows the request to proceed to the homepage handler.

By using this customized FileServer implementation, static content can be served from the root directory while still allowing the homepage handler to be invoked as expected.

The above is the detailed content of How to Serve Both a Homepage and Static Content from the Root Directory 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