blob: 86d8da751f9d5d77e4c602266568f73558b8763a [file] [log] [blame]
Olivier Duperray2eb97332012-01-23 09:28:32 +11001// Copyright 2010 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Andrew Gerrand78d9a602010-04-28 12:36:39 +10005package main
6
7import (
Shenghou Ma52cd4c82012-02-25 01:09:05 +08008 "html/template"
Andrew Gerrand78d9a602010-04-28 12:36:39 +10009 "io/ioutil"
Rob Pikef9489be2011-11-08 15:43:02 -080010 "net/http"
Andrew Gerrand78d9a602010-04-28 12:36:39 +100011)
12
Andrew Gerrandadd4e162011-01-26 14:56:52 +100013type Page struct {
14 Title string
15 Body []byte
Andrew Gerrand78d9a602010-04-28 12:36:39 +100016}
17
Russ Cox44526cd2011-11-01 22:06:05 -040018func (p *Page) save() error {
Andrew Gerrandadd4e162011-01-26 14:56:52 +100019 filename := p.Title + ".txt"
20 return ioutil.WriteFile(filename, p.Body, 0600)
Andrew Gerrand78d9a602010-04-28 12:36:39 +100021}
22
Russ Cox44526cd2011-11-01 22:06:05 -040023func loadPage(title string) (*Page, error) {
Andrew Gerrand78d9a602010-04-28 12:36:39 +100024 filename := title + ".txt"
25 body, err := ioutil.ReadFile(filename)
26 if err != nil {
27 return nil, err
28 }
Andrew Gerrandadd4e162011-01-26 14:56:52 +100029 return &Page{Title: title, Body: body}, nil
Andrew Gerrand78d9a602010-04-28 12:36:39 +100030}
31
Stephen Maa2332a32010-09-30 13:19:33 +100032func editHandler(w http.ResponseWriter, r *http.Request) {
Andrew Gerrand0d676f32013-10-08 11:14:35 +110033 title := r.URL.Path[len("/edit/"):]
Andrew Gerrand78d9a602010-04-28 12:36:39 +100034 p, err := loadPage(title)
35 if err != nil {
Andrew Gerrandadd4e162011-01-26 14:56:52 +100036 p = &Page{Title: title}
Andrew Gerrand78d9a602010-04-28 12:36:39 +100037 }
Rob Pikef56db6f2011-11-23 20:17:22 -080038 t, _ := template.ParseFiles("edit.html")
Andrew Gerrand4896b172011-03-09 12:59:13 +110039 t.Execute(w, p)
Andrew Gerrand78d9a602010-04-28 12:36:39 +100040}
41
Stephen Maa2332a32010-09-30 13:19:33 +100042func viewHandler(w http.ResponseWriter, r *http.Request) {
Andrew Gerrand0d676f32013-10-08 11:14:35 +110043 title := r.URL.Path[len("/view/"):]
Andrew Gerrand78d9a602010-04-28 12:36:39 +100044 p, _ := loadPage(title)
Rob Pikef56db6f2011-11-23 20:17:22 -080045 t, _ := template.ParseFiles("view.html")
Andrew Gerrand4896b172011-03-09 12:59:13 +110046 t.Execute(w, p)
Andrew Gerrand78d9a602010-04-28 12:36:39 +100047}
48
49func main() {
50 http.HandleFunc("/view/", viewHandler)
51 http.HandleFunc("/edit/", editHandler)
52 http.ListenAndServe(":8080", nil)
53}