I am a beginner for Go. I try to build a static web server in my local computer. Actually, I have been read How do you serve a static html file using a go web server?
My question is, if I have a Home.html
. I want to open Home.html
when I link localhost:7777
.
It's like index.html
, but I want to replace index.html
with Home.html
.
Here is my code:
package main
import (
"fmt"
"net/http"
"log"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world!")
}
func main() {
http.HandleFunc("/", helloHandler)
//
err := http.ListenAndServe(":7777", nil)
if err != nil {
log.Fatal("ListenAndServe", err)
} else {
log.Println("listen 7777")
}
}
How do I re-write this code?
What keywords for this problem?
To serve any static file to an endpoint, you can use http.ServeFile
or http.ServeContent
if you want more control.
In this case, you can write:
func helloHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w,r,"Home.html")
}
Be sure to set the name to the path of Home.html
. It is possible for the program to not find the file when using a relative path when running from elsewhere.