github.com/giovannyortegon/go@v0.0.0-20220115155912-8890063f5bdd/src/WebProfesional/3-Template/WebTemplate.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "log" 6 "net/http" 7 "text/template" 8 ) 9 10 type Users struct { 11 UserName string 12 Edad int 13 } 14 15 // var tmp = template.Must(template.New("T").ParseFiles("index.html", "base.html")) 16 var tmp = template.Must(template.New("T").ParseGlob("templates/**/*.html")) 17 var errorTemplate = template.Must(template.ParseFiles("templates/error/error.html")) 18 19 func handlError(rw http.ResponseWriter, status int) { 20 rw.WriteHeader(status) 21 fmt.Println("Ejecutando") 22 errorTemplate.Execute(rw, nil) 23 } 24 25 func renderTemplate(rw http.ResponseWriter, name string, data interface{}) { 26 27 err := tmp.ExecuteTemplate(rw, name, data) 28 29 if err != nil { 30 // panic(err) 31 //http.Error(rw, "No es posible retornar el template", http.StatusInternalServerError) 32 handlError(rw, http.StatusInternalServerError) 33 } 34 } 35 36 func Index(rw http.ResponseWriter, r *http.Request) { 37 fmt.Println("Funcion Index ") 38 39 // tmp := template.Must(template.New("index.html").ParseFiles("index.html", "base.html")) 40 41 user := Users{"Giovanny", 36} 42 43 renderTemplate(rw, "index.html", user) 44 // tmp.Execute(rw, user) 45 } 46 47 func Registro(rw http.ResponseWriter, r *http.Request) { 48 49 renderTemplate(rw, "registro.html", nil) 50 } 51 52 func main() { 53 mux := http.NewServeMux() 54 mux.HandleFunc("/", Index) 55 mux.HandleFunc("/registro", Registro) 56 57 fmt.Println("El servidor esta corriendo en el puerto 1234") 58 fmt.Println("Run server: http://localhost:1234/") 59 server := &http.Server{ 60 Addr: "localhost:1234", 61 Handler: mux, 62 } 63 log.Fatal(server.ListenAndServe()) 64 65 }