模板应用,深入其它

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}}

  

《Web Development with Go》中的html.template的更多相关文章

  1. Web Development Terms

    I've come across lots of terms while learning web development. I'm feeling myself overwhelmed. Here ...

  2. Web 建站技术中,HTML、HTML5、XHTML、CSS、SQL、JavaScript、PHP、ASP.NET、Web Services 是什么(转)

    Web 建站技术中,HTML.HTML5.XHTML.CSS.SQL.JavaScript.PHP.ASP.NET.Web Services 是什么?修改 建站有很多技术,如 HTML.HTML5.X ...

  3. Reloading Java Classes 301: Classloaders in Web Development — Tomcat, GlassFish, OSGi, Tapestry 5 and so on Translation

    The Original link : http://zeroturnaround.com/rebellabs/rjc301/ Copyright reserved by Rebel Inc In t ...

  4. 《Agile Web Development With Rails》读后感--rails基于web设计的best Practices

    最近看完<Agile Web Development with Rails>一书,受益匪浅.书中先是用一个简单的web应用带你进入Rails的世界,然后在你大致熟悉之后,再带你了解Rail ...

  5. 【外文阅读】Web Development in 2020: What Coding Tools You Should Learn---Quincy Larson

    原文链接:https://mail.qq.com/cgi-bin/readtemplate?t=safety&check=false&gourl=https%3A%2F%2Fwww.f ...

  6. Learning web development with MDN

    Learning web development with MDN Server-side website programming Dynamic Websites – Server-side pro ...

  7. Beginners Guide To Web Development

    Web Development Front End Development Back End Development

  8. (转) Web 建站技术中,HTML、HTML5、XHTML、CSS、SQL、JavaScript、PHP、ASP.NET、Web Services 是什么?

    Web 建站技术中,HTML.HTML5.XHTML.CSS.SQL.JavaScript.PHP.ASP.NET.Web Services 是什么? 建站有很多技术,如 HTML.HTML5.XHT ...

  9. Asp.net mvc web api 在项目中的实际应用

    Asp.net mvc web api 在项目中的实际应用 前言:以下只是记录本人在项目中的应用,而web api在数据传输方面有多种实现方式,具体可根据实际情况而定! 1:数据传输前的加密,以下用到 ...

  10. C# asp.net IIS 在web.config和IIS中设置Session过期时间

    有时候在web.config设置sessionState 或者类文件里设置Session.Timeout,在IIS里访问时每次都是达不到时间就超时,原因是因为在IIS中设置了Session的超时时间, ...

随机推荐

  1. C# -- 使用缓冲区进行文件下载操作

    C# -- 使用缓冲区进行文件下载操作 1. 为避免下载超大文件占用内存资源,文件下载使用缓冲区,一点一点读取文件资源. string str0 = @"ftp://localhost:21 ...

  2. Python第一个程序Hello Word

    [源代码] print('Hello Python World!') [过程] 打开命令提示窗口(cmd),在源程序所在路径下执行,python 文件名.py. [截图]

  3. js-08-数组学习

    一.数组语法格式 var name=[item1,item2,......] 二.数组的声明创建 var arr=new Aarray( ) //声明一个空数组对象 var arr=new Array ...

  4. CSS入门(css简介与样式汇总、CSS的使用方式和特征、CSS基础选择器和复杂选择器、边框阴影)

    一.CSS的作用 1.以统一的方式实现样式的定义 2.提高页面样式的可重用性和可维护性 3.实现了内容(HTML)和表示(CSS)的分离 HTML和CSS之间有什么关系? HTML:构建网页的结构 C ...

  5. C lang:character input and output (I/O)

    Xx_Introduction Character input and output is by more line character conpose of the text flow  Defin ...

  6. 为Dynamics 365 USD设置打开调试面板的自定义快捷键

    我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...

  7. Pluralsight 科技公司公布自己的avaScript 成为最受欢迎的开发技术

    根据 SDTimes 报道,Pluralsight 科技公司公布自己的 Technology Index,JavaScript 位居榜首. Pluralsight,是美国的一家面向软件开发者的在线教育 ...

  8. MySQL数据库:group分组

    group by:分组 GroupBy语句从英文的字面意义上理解就是"根据(by)一定的规则进行分组(Group)".它的作用是通过一定的规则将一个数据集划分成若干个小的区域,然后 ...

  9. Codefest19受虐记

    date: 2019-08-28 前言 比赛链接:Codefest 19 A题 思路: 这是一道水题.你对着样例递推打一个表出来,会发现结果三个一组循环. 例如:A = [3, 4, 7, 3, 4, ...

  10. JVM-7-类加载机制

    什么是类的加载 类的加载指的是将类的.class文件中的二进制数据读入到内存中,将其放在运行时数据区的方法区内,然后在堆区创建一个java.lang.Class对象,用来封装类在方法区内的数据结构. ...