1

I am doing a GO course, and whenever I run my server code, I don't get any errors but when I try to type in "localhost:8080" in the browser, I get a message saying "localhost didn’t send any data. ERR_EMPTY_RESPONS". I have the same exact code as the course, except I am using HTML and not TMPL. Why isn't my HTML displaying in the browser?

package main

import (
   "fmt"
   "html/template"
   "net/http"
)

const portNumber = ":8080"

func Home(w http.ResponseWriter, r *http.Request) {
   renderTemplate(w, "home.html")
}

func About(w http.ResponseWriter, r *http.Request) {

}

func renderTemplate(w http.ResponseWriter, html string) {
   parsedTemplate, _ := template.ParseFiles("./templates" + html)
   err := parsedTemplate.Execute(w, nil)
   if err != nil {
      fmt.Println("error parsing template:", err)
      return
   }
}

func main() {
   http.HandleFunc("/", Home)
   http.HandleFunc("/about", About)

   fmt.Println(fmt.Sprintf("Starting App on port %s", portNumber))

   _ = http.ListenAndServe(portNumber, nil)
}
2
  • What happens when you set a breakpoint in func Home? Commented Nov 13, 2022 at 0:37
  • 1
    The error returned from template.ParseFiles will probably explain the problem. Commented Nov 13, 2022 at 1:14

1 Answer 1

0

The ParseFiles method takes a path. You're missing the / after "./templates". So it should be:

   parsedTemplate, _ := template.ParseFiles("./templates/" + html)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.