-4

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?

1
  • The quoted code doesn't serve any static files, so "how do I modify this code to do something completely different" is too broad a question. Can you narrow it down to some particular issue you're having? Commented Aug 6, 2018 at 13:03

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.