《Web Development with Go》中的html.template

模板应用,深入其它

main.go

package main

import (
	//"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"html/template"

	"github.com/gorilla/mux"
)

var templates map[string]*template.Template

func init() {
	if templates == nil {
		templates = make(map[string]*template.Template)
	}

	templates["index"] = template.Must(template.ParseFiles("templates/index.html", "templates/base.html"))
	templates["add"] = template.Must(template.ParseFiles("templates/add.html", "templates/base.html"))
	templates["edit"] = template.Must(template.ParseFiles("templates/edit.html", "templates/base.html"))
}

func renderTemplate(w http.ResponseWriter, name string, template string, viewModel interface{}) {
	tmpl, ok := templates[name]
	if !ok {
		http.Error(w, "The template does not exist.", http.StatusInternalServerError)
	}
	err := tmpl.ExecuteTemplate(w, template, viewModel)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

type Note struct {
	Title       string    `josn:"title"`
	Description string    `json: "description"`
	CreatedOn   time.Time `json:"createdon"`
}

type EditNote struct {
	Note
	Id string
}

var noteStore = make(map[string]Note)
var id int = 0

func getNotes(w http.ResponseWriter, r *http.Request) {
	fmt.Println(noteStore)
	renderTemplate(w, "index", "base", noteStore)
}

func addNote(w http.ResponseWriter, r *http.Request) {
	renderTemplate(w, "add", "base", nil)
}

func saveNote(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	title := r.PostFormValue("title")
	description := r.PostFormValue("description")
	note := Note{title, description, time.Now()}
	id++

	k := strconv.Itoa(id)
	noteStore[k] = note

	http.Redirect(w, r, "/", 302)
}

func editNote(w http.ResponseWriter, r *http.Request) {
	var viewModel EditNote

	vars := mux.Vars(r)
	k := vars["id"]
	if note, ok := noteStore[k]; ok {
		viewModel = EditNote{note, k}
	} else {
		http.Error(w, "Could not find the resource to edit.", http.StatusBadRequest)
	}
	renderTemplate(w, "edit", "base", viewModel)
}
func updateNote(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	k := vars["id"]
	var noteToUpd Note
	if note, ok := noteStore[k]; ok {
		r.ParseForm()
		noteToUpd.Title = r.PostFormValue("title")
		noteToUpd.Description = r.PostFormValue("description")
		noteToUpd.CreatedOn = note.CreatedOn
		delete(noteStore, k)
		noteStore[k] = noteToUpd
	} else {
		http.Error(w, "Could not find the resource to update.", http.StatusBadRequest)
	}
	http.Redirect(w, r, "/", 302)
}
func deleteNote(w http.ResponseWriter, r *http.Request) {
	//Read value from route variable
	vars := mux.Vars(r)
	k := vars["id"]
	// Remove from Store
	if _, ok := noteStore[k]; ok {
		//delete existing item
		delete(noteStore, k)
	} else {
		http.Error(w, "Could not find the resource to delete.", http.StatusBadRequest)
	}
	http.Redirect(w, r, "/", 302)
}

func main() {
	r := mux.NewRouter().StrictSlash(false)
	fs := http.FileServer(http.Dir("public"))
	r.Handle("/public/", fs)
	r.HandleFunc("/", getNotes)
	r.HandleFunc("/notes/add", addNote)
	r.HandleFunc("/notes/save", saveNote)
	r.HandleFunc("/notes/edit/{id}", editNote)
	r.HandleFunc("/notes/update/{id}", updateNote)
	r.HandleFunc("/notes/delete/{id}", deleteNote)

	server := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}
	log.Println("Listening...")
	server.ListenAndServe()
}

  

base.html

{{define "base"}}
<html>

<head>{{template "head" .}}</head>
<body>{{template "body" .}}</body>
</html>
{{end}}

  

add.html

{{define "head"}}<title>Add Note</title>{{end}}
{{define "body"}}
<h1>Add Note</h1>
<form action="/notes/save" method="post">
  <p>Title:<br> <input type="text" name="title"></p>
  <p>Description:<br> 
  <textarea rows="4" cols="50" name="description"></textarea> </p>
  <p><input type="submit" value="submit"/> </p>
</form>
{{end}}

  

index.html

{{define "head"}}<title>Index</title>{{end}}
{{define "body"}}
<h1>Notes List</h1>
<p>
<a href="/notes/add">Add Note</a>
</p>

<div>
  <table border="1">
    <tr>
      <th>Title</th>
      <th>Description</th>
      <th>Created On</th>
      <th>Action</th>
    </tr>
  
      {{range $key,$value := .}}
  
      <tr>
        <td>{{$value.Title}}</td>
        <td>{{$value.Description}}</td>
        <td>{{$value.CreatedOn}}</td>
        <td>
          <a href="/notes/edit/{{$key}}">Edit</a>|
          <a href="/notes/delete/{{$key}}">Delete</a>
        </td>
      </tr>
      {{end}}
      
  </table>
</div>
{{end}}

  

edit.html

{{define "head"}}<title>Edit Note</title>{{end}}
{{define "body"}}
<h1>Edit Note</h1>
<form action="/notes/update/{{.Id}}" method="post">
  <p>Title:<br> <input type="text" value="{{.Note.Title}}" name="title"></p>
  <p> Description:<br> <textarea rows="4" cols="50" name="description">
  {{.Note.Description}}</textarea> </p>
  <p><input type="submit" value="submit"/></p>
</form>
{{end}}

  

猜你喜欢

转载自www.cnblogs.com/aguncn/p/11964546.html