Program Tip

Go 웹 서버를 사용하여 정적 HTML 파일을 어떻게 제공합니까?

programtip 2020. 11. 27. 21:10
반응형

Go 웹 서버를 사용하여 정적 HTML 파일을 어떻게 제공합니까?


go 웹 서버를 사용하여 index.html (또는 다른 정적 HTML 파일)을 어떻게 제공합니까?

go 웹 서버에서 제공 할 수있는 기본적인 정적 HTML 파일 (예 : 기사 등)이 필요합니다. HTML 템플릿을 사용하는 경우처럼 HTML은 go 프로그램 외부에서 수정할 수 있어야합니다.

이것은 하드 코딩 된 텍스트 ( "Hello world!") 만 호스팅하는 내 웹 서버입니다.

package main

import (
  "fmt"
  "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello world!")
}

func main() {
  http.HandleFunc("/", handler)
  http.ListenAndServe(":3000", nil)
}

이 작업은 Golang net / http 패키지를 사용하면 매우 쉽습니다.

당신이해야 할 일은 :

package main

import (
        "net/http"
)

func main() {
        http.Handle("/", http.FileServer(http.Dir("./static")))
        http.ListenAndServe(":3000", nil)
}

정적 파일이 static프로젝트의 루트 디렉토리에 이름이 지정된 폴더에 있다고 가정합니다 .

폴더 static에 있으면 사용 가능한 모든 파일을 나열하는 대신 해당 인덱스 파일을 렌더링하는 index.html파일 호출 http://localhost:3000/이 있습니다.

또한 해당 폴더에있는 다른 파일 (예 http://localhost:3000/clients.html:)을 호출하면 해당 파일이 브라우저에서 올바르게 렌더링 된 것으로 표시됩니다 (최소한 Chrome, Firefox 및 Safari :).

업데이트 : "/"와 다른 URL에서 파일 제공

당신은 파일을 제공 할 경우, 폴더에서 말하는 ./publicURL에서 : localhost:3000/static당신이해야 할 추가 기능을 사용 : func StripPrefix(prefix string, h Handler) Handler다음과 같이 :

package main

import (
        "net/http"
)

func main() {
        http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
        http.ListenAndServe(":3000", nil)
}

덕분에의 모든 파일을 다음에서 ./public사용할 수 있습니다.localhost:3000/static

http.StripPrefix기능이 없으면 파일에 액세스하려고 localhost:3000/static/test.html하면 서버에서 파일 을 찾습니다../public/static/test.html

이는 서버가 전체 URI를 파일에 대한 상대 경로로 취급하기 때문입니다.

다행히도 내장 함수로 쉽게 해결할 수 있습니다.


NOT a FTP server: That is something different than what I intended, which would be to serve the index.html homepage, like a normal web server would. Like, when I go to mydomain.com in my browser, I want index.html rendered.

That is mainly what "Writing Web Applications" describes, and what a project like hugo (static html site generator) does.

It is about reading a file, and responsing with a ContentType "text/html":

func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    err := server.renderFile(w, r.URL.Path)
    if err != nil {
        w.Header().Set("Content-Type", "text/html; charset=utf-8")
        w.WriteHeader(http.StatusNotFound)
        server.fn404(w, r)
    }
}

with renderFile() essentially reading and setting the right type:

 file, err = ioutil.ReadFile(server.MediaPath + filename)
 if ext != "" {
    w.Header().Set("Content-Type", mime.TypeByExtension(ext))
 }

참고URL : https://stackoverflow.com/questions/26559557/how-do-you-serve-a-static-html-file-using-a-go-web-server

반응형