模板应用,深入其它

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. Spring Boot Request method DELETE not supported

    1: 开启HiddenHttpMethodFilter 最新版本的spring boot 默认不开启 restful 分割api @Bean @ConditionalOnMissingBean({Hi ...

  2. 精通awk系列(11):awk的工作流程

    回到: Linux系列文章 Shell系列文章 Awk系列文章 awk工作流程 参考自:man awk的"AWK PROGRAM EXECUTION"段. man --pager= ...

  3. 每天3分钟操作系统修炼秘籍(12):OOM和swap分区

    点我查看秘籍连载 OOM和swap分区 进程的虚拟内存空间是映射到整个物理内存空间的,所以在进程自身看来它拥有了整个物理内存,它也能使用整个物理内存,只需在使用的时候请求操作系统帮忙分配更多空间即可. ...

  4. Redis 常用知识

    Redis 介绍 Redis 一个开源的使用ANSI C语言编写.遵守BSD协议,内存中的数据结构存储系统,它可以用作Key-Value数据库.缓存和消息中间件,并提供多种语API. 支持多种数据结构 ...

  5. C# 打开文件/跳转链接

    mark一下~ 打开文件 1.打开文件夹: System.Diagnostics.Process.Start(FolderPath);-- 打开文件夹 System.Diagnostics.Proce ...

  6. C#基础之多线程与异步

    1.基本概念 多线程与异步是两个不同概念,之所以把这两个放在一起学习,是因为这两者虽然有区别,但也有一定联系. 多线程是一个技术概念,相对于单线程而言,多线程是多个单线程同时处理逻辑.例如,假如说一个 ...

  7. 【坑】Maven [ERROR] 不再支持源选项 5。请使用 6 或更高版本

    在pom.xml文件中添加如下代码: 注意:jdk使用自己下载的版本,我的是13 <properties> <project.build.sourceEncoding>UTF- ...

  8. MySQL语句使用。

    目录 MySQL的DDL.DML.DQL语句和单表增.删.改.查 实验准备: 实验开始: DDL语句 DML语句 DQL语句 单表操作的分组统计 MySQL的DDL.DML.DQL语句和单表增.删.改 ...

  9. redhat 6.5 更换yum源

    新安装了redhat6.5.安装后,登录系统,使用yum update 更新系统.提示: Loaded plugins: product-id, security, subscription-mana ...

  10. STM32 HAL_Deleay() 函数 导致程序卡死

    出现问题场景:   我的程序有RTOS操作系统.使用的驱动库是STM32官方最新的HAL库. 移植好LwIP以太网协议后,在初始化网卡阶段程序卡死.   出现问题原因:   后经过蠢笨的printf打 ...