V
V
v- death2015-08-14 17:47:53
go
v- death, 2015-08-14 17:47:53

How to fix the output?

Here I read the content of the file and run it through the built-in template engine. The error is that when you enter from the browser, instead of displaying something on the screen, it displays it in the console.
Own code

package main

import (
  "net/http"
  "io/ioutil"
    "html/template"
    "os"
    "fmt"
)

func hello(res http.ResponseWriter, req *http.Request) {
    	
  bs, err := ioutil.ReadFile("TestPage.txt")
    if err != nil {
        return
    }
    str := string(bs)
    t := template.New("Test Template")       
    t, _ = t.Parse(str)  
    
    p:= map[string]string{
    "H": "Hydrogen",
    "He": "Helium",
    }
    
    template := t.Execute(os.Stdout, p) ////По моему ошибка в этой строке. Но как исправить незнаю.
    
    res.Header().Set(
        "Content-Type", 
        "text/html",
    )
     fmt.Println(template)
    
}


func main() {
      
    http.HandleFunc("/hello", hello)
    http.ListenAndServe(":8080", nil)
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2015-08-14
@vGrabko99

template.Execute() - this function writes where you need. You give the first argument where to write, the second what data is available in the template. Those. we send http.ResponseWriter to it, and the second is your mapping "p".

package main

import (
  "html/template"
  "io/ioutil"
  "net/http"
)

func hello(res http.ResponseWriter, req *http.Request) {

  bs, err := ioutil.ReadFile("TestPage.txt")
  if err != nil {
    return
  }
  str := string(bs)
  t := template.New("Test Template")
  t, _ = t.Parse(str)

  p := map[string]string{
    "H":  "Hydrogen",
    "He": "Helium",
  }

  res.Header().Set(
    "Content-Type",
    "text/html",
  )
  t.Execute(res, p)

}

func main() {

  http.HandleFunc("/hello", hello)
  http.ListenAndServe(":8080", nil)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question