>백엔드 개발 >Golang >Go의 루트 디렉터리에서 정적 콘텐츠와 홈페이지를 제공할 때 충돌을 피하는 방법은 무엇입니까?

Go의 루트 디렉터리에서 정적 콘텐츠와 홈페이지를 제공할 때 충돌을 피하는 방법은 무엇입니까?

Linda Hamilton
Linda Hamilton원래의
2024-12-20 11:47:09554검색

How to Avoid Conflicts When Serving Static Content and a Homepage from the Root Directory in Go?

루트에서 홈페이지 및 정적 콘텐츠 제공

Go에서는 루트 디렉터리에서 정적 콘텐츠와 홈페이지를 모두 제공할 수 있습니다. 그러나 루트 URL에 두 방법을 모두 등록하면 충돌이 발생합니다.

정적 콘텐츠 제공

이미지, CSS 등의 정적 콘텐츠를 제공하려면 http.Handle을 사용하고 http.Dir. 그러나 루트 URL에 대해 이렇게 하면 홈페이지 핸들러와 충돌하게 됩니다.

홈페이지 제공

홈페이지를 서비스하려면 http.HandleFunc를 사용하고

제안된 솔루션: 명시적 파일 제공

충돌을 해결하려면 특정 루트 파일을 명시적으로 제공하는 것을 고려하십시오. 예를 들어 sitemap.xml, favicon.ico 및 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)
}

다른 리소스 이동

다른 모든 정적 리소스(예: CSS, JS)를 /static과 같은 하위 디렉터리로 복사합니다. 그런 다음 일반적으로 http.Handle 및 http.Dir을 사용하여 이 하위 디렉터리를 제공합니다.

위 내용은 Go의 루트 디렉터리에서 정적 콘텐츠와 홈페이지를 제공할 때 충돌을 피하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.