Skip to content

Instantly share code, notes, and snippets.

@sugilog
Created January 24, 2015 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugilog/27d661e1a67243b43865 to your computer and use it in GitHub Desktop.
Save sugilog/27d661e1a67243b43865 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"io/ioutil"
"html/template"
)
type Page struct {
Title string
Body []byte
}
func ( p *Page ) save() error {
filename := p.Title + ".txt"
fmt.Println( "Save", "Title:", p.Title, "filename:", filename, "Body:", string( p.Body ) )
err := ioutil.WriteFile( filename, p.Body, 0600 )
if err != nil {
fmt.Println( err )
}
return err
}
func detectTitle( r *http.Request, path string ) string {
title := r.URL.Path[ len( path ) : ]
if title == "" {
title = "index"
}
fmt.Println( "Title:", title )
return title
}
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 viewHandlerWithPath( w http.ResponseWriter, r *http.Request ) {
viewHandler( w, r, "/view/" )
}
func viewHandlerWithoutPath( w http.ResponseWriter, r *http.Request ) {
viewHandler( w, r, "/" )
}
func viewHandler( w http.ResponseWriter, r *http.Request, path string ) {
title := detectTitle( r, path )
p, err := loadPage( title )
if err != nil {
p = &Page{ Title: title, Body: []byte( "no content" ) }
}
t, err := template.ParseFiles( "views/view.html" )
t.Execute( w, p )
}
func editHandler( w http.ResponseWriter, r *http.Request ) {
title := detectTitle( r, "/edit/" )
p, err := loadPage( title )
if err != nil {
p = &Page{ Title: title }
}
t, err := template.ParseFiles( "views/edit.html" )
t.Execute( w, p )
}
func saveHandler( w http.ResponseWriter, r *http.Request ) {
title := detectTitle( r, "/save/" )
body := r.FormValue( "body" )
p := &Page{ Title: title, Body: []byte( body ) }
p.save()
http.Redirect( w, r, "/view/" + title, http.StatusFound )
}
func main() {
http.HandleFunc( "/edit/", editHandler )
http.HandleFunc( "/save/", saveHandler )
http.HandleFunc( "/view/", viewHandlerWithPath )
http.HandleFunc( "/", viewHandlerWithoutPath )
http.ListenAndServe( "localhost:8080", nil )
}
<h1>Editing {{ .Title }}</h1>
<form action="/save/{{ .Title }}" method="POST">
<div>
<textarea name="body" rows="50" cols="80">{{ printf "%s" .Body }}</textarea>
</div>
<div>
<input type="submit" value="Save" />
</div>
</form>
<h1>{{ .Title }}</h1>
<p>[<a href="/edit/{{ .Title }}">edit</a>]</p>
<div><pre>{{ printf "%s" .Body }}</pre></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment