Advertisement
Guest User

Golang Templates

a guest
Nov 29th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.56 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bufio"
  5.     "log"
  6.     "net/http"
  7.     "os"
  8.     "strings"
  9.     "text/template"
  10. )
  11.  
  12. func main() {
  13.     templates := populateTemplates()
  14.  
  15.     http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
  16.         requestedFile := req.URL.Path[1:]
  17.         template := templates.Lookup(requestedFile + ".html")
  18.  
  19.         if template != nil {
  20.             template.Execute(w, nil)
  21.         } else {
  22.             w.WriteHeader(404)
  23.         }
  24.     })
  25.  
  26.     http.HandleFunc("/img/", serveResource)
  27.     http.HandleFunc("/css/", serveResource)
  28.  
  29.     http.ListenAndServe(":8080", nil)
  30. }
  31.  
  32. func serveResource(w http.ResponseWriter, req *http.Request) {
  33.     path := "../../public" + req.URL.Path
  34.     var contentType string
  35.     if strings.HasSuffix(path, ".css") {
  36.         contentType = "text/css"
  37.     } else if strings.HasSuffix(path, ".png") {
  38.         contentType = "image/png"
  39.     } else {
  40.         contentType = "text/plain"
  41.     }
  42.  
  43.     f, err := os.Open(path)
  44.     if err != nil {
  45.         w.WriteHeader(404)
  46.     } else {
  47.         defer f.Close()
  48.         w.Header().Add("Content Type", contentType)
  49.  
  50.         br := bufio.NewReader(f)
  51.         br.WriteTo(w)
  52.     }
  53. }
  54.  
  55. func populateTemplates() *template.Template {
  56.     result := template.New("templates")
  57.  
  58.     basePath := "../../templates"
  59.     templateFolder, err := os.Open(basePath)
  60.     if err != nil {
  61.         log.Fatal(err)
  62.     }
  63.     defer templateFolder.Close()
  64.  
  65.     templatePathsRaw, _ := templateFolder.Readdir(-1)
  66.  
  67.     templatePaths := new([]string)
  68.     for _, pathInfo := range templatePathsRaw {
  69.         if !pathInfo.IsDir() {
  70.             *templatePaths = append(*templatePaths, basePath+"/"+pathInfo.Name())
  71.         }
  72.     }
  73.  
  74.     result.ParseFiles(*templatePaths...)
  75.  
  76.     return result
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement