| package main |
| |
| import ( |
| "io/ioutil" |
| "log" |
| "net/http" |
| "os" |
| "text/template" |
| ) |
| |
| func main() { |
| http.Handle("/", makeServer()) |
| log.Fatal(http.ListenAndServe(":8080", nil)) |
| } |
| |
| func makeServer() *server { |
| root, err := os.Getwd() |
| if err != nil { |
| panic(err) |
| } |
| d, err := ioutil.ReadFile("template.html") |
| if err != nil { |
| panic(err) |
| } |
| return &server{ |
| root: root, |
| template: template.Must(template.New("template").Parse(string(d))), |
| } |
| } |
| |
| type server struct { |
| root string |
| template *template.Template |
| } |
| |
| func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| path := req.URL.Path |
| b, err := ioutil.ReadFile(s.root + "/src" + path) |
| if err != nil { |
| log.Printf("serve %s: %s", path, err) |
| http.Error(w, err.Error(), 500) |
| return |
| } |
| v := struct { |
| Title string |
| Body string |
| }{ |
| Title: path, |
| Body: string(b), |
| } |
| if err := s.template.Execute(w, v); err != nil { |
| log.Printf("serve %s: %s", path, err) |
| } |
| } |