模板应用,深入其它

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. Linux日志中如何查找关键字及其前后的信息

    在日常工作中,我们经常需要查看日志,比如可以通过 tail 命令实时查看日志,也可以通过 cat 等命令查看日志信息. 但现在我们要讨论的是,如何从日志中通过关键字过滤出我们想要的内容,方法有多种,今 ...

  2. 检测一个App是不是有UWP血统

    Win + Shift + Enter   

  3. Java时区问题

    Java时区相关 时间格式 UTC是以原子时计时,更加精准,适应现代社会的精确计时.不过一般使用不需要精确到秒时,视为等同.GMT是前世界标准时,UTC是现世界标准时.每年格林尼治天文台会发调时信息, ...

  4. MinU: v2 Vulnhub Walkthrough

    主机层面扫描: 22 和 3306 端口 3306 端口默认是MySQL端口,但是这里尝试爆破报错,最后通http访问发现非MySQL协议,而是一个http的服务 http的协议我们进行目录枚举下 枚 ...

  5. APP爬虫(1)想学新语言,又没有动力,怎么办?

    最近Python和GO语言很火,想学但是只能看得懂21天精通这种级别的教程.公司的项目暂时不会上py或go的技术栈,给的薪资福利待遇还可以,暂时又不想辞职.没有项目实战经验,完全看不懂大神写的干货,怎 ...

  6. CODING 祝大家中秋快乐!

  7. MySQL能否授予查看存储过程定义权限给用户

    在其他RDBMS中,可以将查看某个存储过程(PROCEDURE)定义的权限给某个用户,例如在SQL Server中,可以单独将查看ProcedureName定义的权限授予UserA GRANT VIE ...

  8. combination sum && combination sum II

    1.Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), f ...

  9. JavaScript-----7.循环

    1.循环 在JS中主要有以下三种类型的循环 for循环 while循环 do...while循环 2. for循环 2.1 语法结构如下: for (初始化变量: 条件表达式: 操作表达式) { // ...

  10. 10. Go 语言反射

    Go 语言反射 反射是指在程序运行期对程序本身进行访问和修改的能力.程序在编译时,变量被转换为内存地址,变量名不会被编译器写入到可执行部分.在运行程序时,程序无法获取自身的信息. 支持反射的语言可以在 ...