読者です 読者をやめる 読者になる 読者になる

DELAEMON BLOG

Live as if you were to die tomorrow. Learn as if you were to live forever.

golang wiki

http://golang.org/dl/go1.3.darwin-amd64-osx10.8.pkg でインストールした

% go version
go version go1.3 darwin/amd64

http://golang.jp/codelab-wiki
やってみたけど、現在は存在しない関数、構造体使っていたので動くようにしたコードが以下

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
    "html/template"
    "regexp"
)

const lenPath = len("/view/")

type Page struct {
    Title string
    Body[]byte
}

var templates = make(map[string]*template.Template)

var titleValidator = regexp.MustCompile("^[a-zA-Z0-9]+$")

func (p *Page) save() (err error) {
    filename := p.Title + ".txt"
    return ioutil.WriteFile(filename, p.Body, 0600)
}

func loadPage(title string) (*Page, error) {
    filename := title + ".txt"
    body,err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return &Page{Title: title, Body: body}, nil
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there I Love %s!", r.URL.Path[1:])
}

func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
    p, err := loadPage(title)
    if err != nil {
        http.Redirect(w, r, "/edit/" + title, http.StatusFound)
        return
    }
    renderTemplate(w, "view", p)
}

func editHandler(w http.ResponseWriter, r *http.Request, title string) {
    p, err := loadPage(title)
    if err != nil {
        p = &Page{Title: title}
    }
    renderTemplate(w, "edit", p)
}

func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
    body := r.FormValue("body")
    p := &Page{Title: title, Body: []byte(body)}
    err := p.save()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    err := templates[tmpl].Execute(w,p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        title := r.URL.Path[lenPath:]
        if !titleValidator.MatchString(title) {
            http.NotFound(w, r)
            return
        }
        fn(w, r, title)
    }
}

func init() {
    for _, tmpl := range []string{"edit", "view"} {
        t := template.Must(template.ParseFiles(tmpl + ".html"))
        templates[tmpl] = t
    }
}

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/view/", makeHandler(viewHandler))
    http.HandleFunc("/edit/", makeHandler(editHandler))
    http.HandleFunc("/save/", makeHandler(saveHandler))
    http.ListenAndServe(":8080", nil)
}

こいつ・・・動くぞ

go tool 6g wiki.go
go tool 6l wiki.6
./6.out

もっと簡単にできた

go build wiki.go
./wiki

実行ファイル作らないでも動かせる

go run wiki.go

アクセス
http://localhost:8080/edit/hoge