模板加载

1. 静态资源加载

前面我们虽然首页显示出来了,但是js这些并没有加载,使用下面的方式将/resource/js/index.js这样的请求路径映射到/public对应的文件夹下

http.Handle("/resource/",http.StripPrefix("/resource/",http.FileServer(http.Dir("public/resource/"))))
1

2. 路由

//router/router.go
package router

import (
	"ms-go-blog/api"
	"ms-go-blog/views"
	"net/http"
)

func Router()  {
	//1. 页面  views 2. api 数据(json) 3. 静态资源
	http.HandleFunc("/",views.HTML.Index)
	http.HandleFunc("/api/v1/post",api.API.SaveAndUpdatePost)
	http.Handle("/resource/",http.StripPrefix("/resource/",http.FileServer(http.Dir("public/resource/"))))
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//views/views.go
package views

var HTML = &HTMLApi{}
type HTMLApi struct {

}

1
2
3
4
5
6
7
8
//views/index.go
package views

import (
	"html/template"
	"log"
	"ms-go-blog/config"
	"ms-go-blog/models"
	"net/http"
	"time"
)
func IsODD(num int) bool  {
	return num%2 == 0
}
func GetNextName(strs []string,index int) string{
	return strs[index+1]
}
func Date(layout string)  string{
	return time.Now().Format(layout)
}

func (*HTMLApi) Index(w http.ResponseWriter,r *http.Request)  {
	t := template.New("index.html")
	//1. 拿到当前的路径
	path:= config.Cfg.System.CurrentDir
	//访问博客首页模板的时候,因为有多个模板的嵌套,解析文件的时候,需要将其涉及到的所有模板都进行解析
	home := path + "/template/home.html"
	header := path + "/template/layout/header.html"
	footer := path + "/template/layout/footer.html"
	personal := path + "/template/layout/personal.html"
	post := path + "/template/layout/post-list.html"
	pagination := path + "/template/layout/pagination.html"
	t.Funcs(template.FuncMap{"isODD":IsODD,"getNextName":GetNextName,"date":Date})
	t,err := t.ParseFiles(path + "/template/index.html",home,header,footer,personal,post,pagination)
	if err != nil {
		log.Println("解析模板出错:",err)
	}
	//页面上涉及到的所有的数据,必须有定义
	var categorys = []models.Category{
		{
			Cid: 1,
			Name: "go",
		},
	}
	var posts = []models.PostMore{
		{
			Pid: 1,
			Title: "go博客",
			Content: "内容",
			UserName: "码神",
			ViewCount: 123,
			CreateAt: "2022-02-20",
			CategoryId:1,
			CategoryName: "go",
			Type:0,
		},
	}
	var hr = &models.HomeResponse{
		config.Cfg.Viewer,
		categorys,
		posts,
		1,
		1,
		[]int{1},
		true,
	}
	t.Execute(w,hr)
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//api/api.go
package api

var API = &Api{}

type Api struct {
}

1
2
3
4
5
6
7
8
//api/post.go
package api

import "net/http"

func (*Api) SaveAndUpdatePost(w http.ResponseWriter,r *http.Request)  {

}

1
2
3
4
5
6
7
8
9
package main

import (
	"log"
	"ms-go-blog/router"
	"net/http"
)

func main()  {
	//程序入口,一个项目 只能有一个入口
	//web程序,http协议 ip port
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	//路由
	router.Router()
	if err := server.ListenAndServe();err != nil{
		log.Println(err)
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

3. 模板处理

package models

import (
	"html/template"
	"io"
	"log"
	"time"
)

type TemplateBlog struct {
	*template.Template
}
type HtmlTemplate struct {
	Index TemplateBlog
	Category TemplateBlog
	Custom TemplateBlog
	Detail TemplateBlog
	Login TemplateBlog
	Pigeonhole TemplateBlog
	Writing TemplateBlog
}

func (t *TemplateBlog) WriteData(w io.Writer,data interface{})  {
	err := t.Execute(w,data)
	if err != nil {
		w.Write([]byte("error"))
	}
}
func InitTemplate(templateDir string) (HtmlTemplate,error)  {
	tp,err := readTemplate(
		[]string{"index","category","custom","detail","login","pigeonhole","writing"},
		templateDir,
		)
	var htmlTemplate HtmlTemplate
	if err != nil {
		return htmlTemplate,err
	}
	htmlTemplate.Index = tp[0]
	htmlTemplate.Category = tp[1]
	htmlTemplate.Custom = tp[2]
	htmlTemplate.Detail = tp[3]
	htmlTemplate.Login = tp[4]
	htmlTemplate.Pigeonhole = tp[5]
	htmlTemplate.Writing = tp[6]
	return htmlTemplate,nil
}

func IsODD(num int) bool  {
	return num%2 == 0
}
func GetNextName(strs []string,index int) string{
	return strs[index+1]
}
func Date(layout string)  string{
	return time.Now().Format(layout)
}
func DateDay(date time.Time) string {
	return date.Format("2006-01-02 15:04:05")
}
func readTemplate(templates []string,templateDir string) ([]TemplateBlog,error)  {
	var tbs []TemplateBlog
	for _,view := range templates{
		viewName := view+".html"
		t := template.New(viewName)
		//访问博客首页模板的时候,因为有多个模板的嵌套,解析文件的时候,需要将其涉及到的所有模板都进行解析
		home := templateDir + "home.html"
		header := templateDir + "layout/header.html"
		footer := templateDir + "layout/footer.html"
		personal := templateDir + "layout/personal.html"
		post := templateDir + "layout/post-list.html"
		pagination := templateDir + "layout/pagination.html"
		t.Funcs(template.FuncMap{"isODD":IsODD,"getNextName":GetNextName,"date":Date,"dateDay":DateDay})
		t,err := t.ParseFiles(templateDir + viewName,home,header,footer,personal,post,pagination)
		if err != nil {
			log.Println("解析模板出错:",err)
			return nil, err
		}
		var tb TemplateBlog
		tb.Template = t
		tbs = append(tbs,tb)
	}
	return tbs,nil
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

common/common.go

package common

import (
	"ms-go-blog/config"
	"ms-go-blog/models"
	"sync"
)

var Template models.HtmlTemplate

func LoadTemplate()  {
	w := sync.WaitGroup{}
	w.Add(1)
	go func() {
		//耗时
		var err error
		Template,err = models.InitTemplate(config.Cfg.System.CurrentDir + "/template/")
		if err != nil {
			panic(err)
		}
		w.Done()
	}()
	w.Wait()
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

view/index.go

package views

import (
	"ms-go-blog/common"
	"ms-go-blog/config"
	"ms-go-blog/models"
	"net/http"
)

func (*HTMLApi) Index(w http.ResponseWriter,r *http.Request)  {
	index := common.Template.Index
	//页面上涉及到的所有的数据,必须有定义
	var categorys = []models.Category{
		{
			Cid: 1,
			Name: "go",
		},
	}
	var posts = []models.PostMore{
		{
			Pid: 1,
			Title: "go博客",
			Content: "内容",
			UserName: "码神",
			ViewCount: 123,
			CreateAt: "2022-02-20",
			CategoryId:1,
			CategoryName: "go",
			Type:0,
		},
	}
	var hr = &models.HomeResponse{
		config.Cfg.Viewer,
		categorys,
		posts,
		1,
		1,
		[]int{1},
		true,
	}

	index.WriteData(w,hr)
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

main.go

package main

import (
	"log"
	"ms-go-blog/common"
	"ms-go-blog/router"
	"net/http"
)

func init()  {
	//模板加载
	common.LoadTemplate()
}
func main()  {
	//程序入口,一个项目 只能有一个入口
	//web程序,http协议 ip port
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	//路由
	router.Router()
	if err := server.ListenAndServe();err != nil{
		log.Println(err)
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26