github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume2/section1/smptemplate/smptemplate.go (about) 1 // Simple example of creating and using a template in Go 2 package main 3 4 import ( 5 "fmt" 6 "html/template" 7 "log" 8 "net/http" 9 10 "github.com/EngineerKamesh/gofullstack/volume1/section5/socialmedia" 11 ) 12 13 // Handler for displaying a social media post 14 func displaySocialMediaPostHandler(w http.ResponseWriter, r *http.Request) { 15 16 myPost := socialmedia.NewPost("EngineerKamesh", socialmedia.Moods["thrilled"], "Go is awesome!", "Check out the Go web site!", "https://golang.org", "/images/gogopher.png", "", []string{"go", "golang", "programming language"}) 17 fmt.Printf("myPost: %+v\n", myPost) 18 renderTemplate(w, "./templates/socialmediapost.html", myPost) 19 } 20 21 // Template rendering function 22 func renderTemplate(w http.ResponseWriter, templateFile string, templateData interface{}) { 23 24 t, err := template.ParseFiles(templateFile) 25 if err != nil { 26 log.Fatal("Error encountered while parsing the template: ", err) 27 } 28 t.Execute(w, templateData) 29 } 30 31 func main() { 32 33 http.HandleFunc("/display-social-media-post", displaySocialMediaPostHandler) 34 http.Handle("/", http.FileServer(http.Dir("./static"))) 35 http.ListenAndServe(":8080", nil) 36 }