做ppt网站,企业形象设计是什么意思,新东方烹饪培训学校,公司名称注册查询系统文章目录 一、项目简介二、项目搭建前置知识三、首页- - -前端文件与后端结构体定义四、配置文件加载五、构造假数据- - -显示首页内容 代码地址#xff1a;https://gitee.com/lymgoforIT/goblog
一、项目简介
使用Go原生http开发一个简易的博客系统#xff0c;包含一下功能… 文章目录 一、项目简介二、项目搭建前置知识三、首页- - -前端文件与后端结构体定义四、配置文件加载五、构造假数据- - -显示首页内容 代码地址https://gitee.com/lymgoforIT/goblog
一、项目简介
使用Go原生http开发一个简易的博客系统包含一下功能
文章增删改查文章列表分页显示评论系统文章分类、归档
学习本项目能学到什么
使用Go开发web项目基本思路初步具有工程思维如路由分组、目录组织代码封装等。博客基本功能开发套路如博客与评论的查询、分类、归档、分页等。循序渐进掌握编程思维和思路。这一点是最重要的会不断优化代码而不是一步给出最终代码这样更能培养编程思维和思路。
页面效果 二、项目搭建前置知识
接下来我们会一步一步实现博客首页开始我们可能会把代码都写到main.go中后期再不断调整优化形成工程化的目录结构。
首先是启动一个http服务的代码如下
package mainimport (lognet/http
)func main(){server : http.Server{Addr: 127.0.0.1:8080,}http.HandleFunc(/, func(writer http.ResponseWriter, request *http.Request) {writer.Write([]byte(ok))})if err : server.ListenAndServe();err ! nil {log.Println(err)}
}
启动后浏览器访问可以看到ok字样
这里返回给前端的不过是一个字符串而已实际工作中一般前后端交互都是使用的JSON数据或者protoc协议的那么想要返回JSON字符串给前端又该如何做呢
其实也简单设置好请求头即可如下
package mainimport (encoding/jsonlognet/http
)type IndexData struct {Title string json:titleDesc string json:desc
}func index(w http.ResponseWriter, r *http.Request) {// 设置请求头指明返回的是JSON数据w.Header().Set(Content-Type, application/json)var indexData IndexDataindexData.Title go博客indexData.Desc 入门学习笔记jsonStr, _ : json.Marshal(indexData)w.Write(jsonStr)
}func main() {server : http.Server{Addr: 127.0.0.1:8080,}http.HandleFunc(/, index)if err : server.ListenAndServe(); err ! nil {log.Println(err)}
} 目前浏览器得到的响应结果都是后端直接返回的数据但我们前端是给用户使用的需要有一定页面才行。
在Go中渲染html页面可以使用Go自带的html/template库使用方式如下
首先建立template/index.html文件
!DOCTYPE html
html langen
headmeta charsetUTF-8titleTitle/title
/head
body
hello lym blog!!
br
标题{{.Title}}
br
描述{{.Desc}}
/body
/htmlpackage mainimport (encoding/jsonfmthtml/templatelognet/httpos
)type IndexData struct {Title string json:titleDesc string json:desc
}func index(w http.ResponseWriter, r *http.Request) {// 设置请求头指明返回的是JSON数据w.Header().Set(Content-Type, application/json)var indexData IndexDataindexData.Title go博客indexData.Desc 入门学习笔记jsonStr, _ : json.Marshal(indexData)w.Write(jsonStr)
}func indexHtml(w http.ResponseWriter, r *http.Request) {// 使用给定的名字分配一个html模板t : template.New(index.html)viewPath, _ : os.Getwd()// 将html文件关联到模板上t, _ t.ParseFiles(viewPath /template/index.html)var indexData IndexDataindexData.Title go博客indexData.Desc 入门学习笔记// 使用给定的数据结构解析模板并将结果写入werr : t.Execute(w, indexData)fmt.Println(err)
}func main() {server : http.Server{Addr: 127.0.0.1:8080,}http.HandleFunc(/, index)http.HandleFunc(/index, indexHtml)if err : server.ListenAndServe(); err ! nil {log.Println(err)}
}
此时访问index路径便会看到是页面展示了不过还没有css,js等静态文件渲染后期会慢慢加上。
三、首页- - -前端文件与后端结构体定义
有了前面的基础知识我们现在就可以搭建首页啦
因为本学习笔记主要注重的是后端逻辑所以前端页面和静态文件等是直接用的已有的放到项目目录下即可。如果有需要可以到码云上取https://gitee.com/lymgoforIT/goblog 首页展示时有很多数据是从后端获取的所以我们首先需要定义一些结构体用于数据渲染其中有一些通用数据且基本不怎么变的我们可以放到配置文件中而不用存DB比如博客系统的标题、标签以及相关系统变量等。
config/config.go
package configtype Viewer struct {Title string // 首页标题Description string // 首页描述Logo string // 博客系统logoNavigation []string // 导航栏Bilibili string // bilibiliAvatar string // 头像UserName string // 用户名UserDesc string // 用户描述
}// 系统相关配置
type SystemConfig struct {AppName stringVersion float32CurrentDir string // 项目路径CdnURL string // cdn地址用户缓存静态资源QiniuAccessKey string // 使用七牛云存储图片资源QiniuSecretKey stringValine bool // 评论系统用的ValineValineAppid stringValineAppkey stringValineServerURL string
}
其余数据基本是从DB获取的与DB交互的结构体我们一般会单独建立model文件夹存放。 models/post.go
package modelsimport (goblog/confightml/templatetime
)// 用于与DB交互与DB中字段一一对应
type Post struct {Pid int json:pid // 文章IDTitle string json:title // 文章标题Slug string json:slug // 自定义页面 pathContent string json:content // 文章的htmlMarkdown string json:markdown // 文章的MarkdownCategoryId int json:categoryId //分类idUserId int json:userId //用户idViewCount int json:viewCount //查看次数Type int json:type //文章类型 0 普通1 自定义文章CreateAt time.Time json:createAt // 创建时间UpdateAt time.Time json:updateAt // 更新时间
}// 用于给前端响应所以有了分类名称和用户名等信息而不是分类id或者用户id
type PostMore struct {Pid int json:pid // 文章IDTitle string json:title // 文章标题Slug string json:slug // 自定义页面 pathContent template.HTML json:content // 文章的htmlCategoryId int json:categoryId // 文章的MarkdownCategoryName string json:categoryName // 分类名UserId int json:userId // 用户idUserName string json:userName // 用户名ViewCount int json:viewCount // 查看次数Type int json:type // 文章类型 0 普通1 自定义文章CreateAt string json:createAtUpdateAt string json:updateAt
}type PostReq struct {Pid int json:pidTitle string json:titleSlug string json:slugContent string json:contentMarkdown string json:markdownCategoryId int json:categoryIdUserId int json:userIdType int json:type
}type SearchResp struct {Pid int orm:pid json:pid // 文章IDTitle string orm:title json:title
}type PostRes struct {config.Viewerconfig.SystemConfigArticle PostMore
}
models/home.go
用于封装前端需要的首页数据
package modelsimport goblog/configtype HomeResponse struct {config.ViewerCategorys []CategoryPosts []PostMoreTotal intPage intPages []intPageEnd bool // 当前页是否是最后一页决定分页那里是否显示左右箭头
}
四、配置文件加载
这里配置文件我们用的toml实际工作中可能yaml用的更多一点。
config/config.toml
[viewer]Title Go语言博客Description Go语言博客Logo /resource/images/logo.pngNavigation [首页,/, GO语言,/golang, 归档,/pigeonhole, 关于,/about]Bilibili https://space.bilibili.com/473844125Zhihu https://www.zhihu.com/people/ma-shen-zhi-luAvatar https://gimg2.baidu.com/image_search/srchttp%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13147603927%2F1000.jpgreferhttp%3A%2F%2Finews.gtimg.comapp2002sizef9999,10000qa80n0g0nfmtjpeg?sec1647242040tc6108010ed46b4acebe18955acdd2d24UserName 张三UserDesc 长得非常帅的程序员
[system]CdnURL https://static.mszlu.com/goblog/es6/md-assetsQiniuAccessKey 替换自己的QiniuSecretKey 替换自己的Valine trueValineAppid 替换自己的ValineAppkey 替换自己的ValineServerURL 替换自己的toml文件我们可以使用github.com/BurntSushi/toml包获取 go get github.com/BurntSushi/toml配置文件加载常规套路是定义全局变量使用init加载
config/config.go
package configimport (osgithub.com/BurntSushi/toml
)var Cfg *TomlConfigfunc init() {Cfg new(TomlConfig)var err errorCfg.System.CurrentDir, err os.Getwd()if err ! nil {panic(any(err))}Cfg.System.AppName lym-go-blogCfg.System.Version 1.0_, err toml.DecodeFile(config/config.toml, Cfg)if err ! nil {panic(any(err))}
}type TomlConfig struct {Viewer ViewerSystem SystemConfig
}type Viewer struct {Title string // 首页标题Description string // 首页描述Logo string // 博客系统logoNavigation []string // 导航栏Bilibili string // bilibiliAvatar string // 头像UserName string // 用户名UserDesc string // 用户描述
}// 系统相关配置
type SystemConfig struct {AppName stringVersion float32CurrentDir string // 项目路径CdnURL string // cdn地址用户缓存静态资源QiniuAccessKey string // 使用七牛云存储图片资源QiniuSecretKey stringValine bool // 评论系统用的ValineValineAppid stringValineAppkey stringValineServerURL string
}
五、构造假数据- - -显示首页内容
main.go
注意看代码注释
package mainimport (goblog/configgoblog/modelshtml/templatelognet/httptime
)type IndexData struct {Title string json:titleDesc string json:desc
}// 前端html页面中使用了一些函数所以这里需要定义一下
// 是否偶数
func IsODD(num int) bool {return num%2 0
}func GetNextName(strs []string, index int) string {return strs[index1]
}// 日期按指定格式转换
func Date(layout string) string {return time.Now().Format(layout)
}func index(w http.ResponseWriter, r *http.Request) {t : template.New(index.html)// 拿到当前的路径path : config.Cfg.System.CurrentDir//访问博客首页模板的时候因为有多个模板的嵌套解析文件的时候需要将其涉及到的所有模板都进行解析home : path /template/home.htmlheader : path /template/layout/header.htmlfooter : path /template/layout/footer.htmlpersonal : path /template/layout/personal.htmlpost : path /template/layout/post-list.htmlpagination : 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,},{Cid: 2,Name: python,},}var posts []models.PostMore{{Pid: 1,Title: go博客,Content: 这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容,UserName: 张三,ViewCount: 123,CreateAt: 2023-12-17,CategoryId: 1,CategoryName: go,Type: 0,},{Pid: 2,Title: 这是第二篇博客,Content: 这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容,UserName: 李四,ViewCount: 1314,CreateAt: 2023-12-17,CategoryId: 1,CategoryName: go,Type: 0,},}var hr models.HomeResponse{Viewer: config.Cfg.Viewer,Categorys: categorys,Posts: posts,Total: 2,Page: 1,Pages: []int{1},PageEnd: true,}t.Execute(w, hr)
}func main() {//程序入口一个项目 只能有一个入口//web程序http协议 ip portserver : http.Server{Addr: 127.0.0.1:8080,}http.HandleFunc(/, index)// 因为静态文件放到了public/resource目录下但是页面中写路径的时候都写的resource所以这里转一下http.Handle(/resource/, http.StripPrefix(/resource/, http.FileServer(http.Dir(public/resource/))))if err : server.ListenAndServe(); err ! nil {log.Println(err)}
}
此时通过流量器访问8080端口便可看到如下界面了
文章转载自: http://www.morning.sqgsx.cn.gov.cn.sqgsx.cn http://www.morning.ybshj.cn.gov.cn.ybshj.cn http://www.morning.fpxms.cn.gov.cn.fpxms.cn http://www.morning.ktbjk.cn.gov.cn.ktbjk.cn http://www.morning.jjsxh.cn.gov.cn.jjsxh.cn http://www.morning.bauul.com.gov.cn.bauul.com http://www.morning.jrbyz.cn.gov.cn.jrbyz.cn http://www.morning.mcmpq.cn.gov.cn.mcmpq.cn http://www.morning.qsmch.cn.gov.cn.qsmch.cn http://www.morning.c7495.cn.gov.cn.c7495.cn http://www.morning.mldrd.cn.gov.cn.mldrd.cn http://www.morning.tjmfz.cn.gov.cn.tjmfz.cn http://www.morning.smzr.cn.gov.cn.smzr.cn http://www.morning.fwkpp.cn.gov.cn.fwkpp.cn http://www.morning.qnbzs.cn.gov.cn.qnbzs.cn http://www.morning.lchtb.cn.gov.cn.lchtb.cn http://www.morning.dnmzl.cn.gov.cn.dnmzl.cn http://www.morning.hqwxm.cn.gov.cn.hqwxm.cn http://www.morning.zbgqt.cn.gov.cn.zbgqt.cn http://www.morning.xsbhg.cn.gov.cn.xsbhg.cn http://www.morning.frllr.cn.gov.cn.frllr.cn http://www.morning.mjpgl.cn.gov.cn.mjpgl.cn http://www.morning.ftzll.cn.gov.cn.ftzll.cn http://www.morning.glxmf.cn.gov.cn.glxmf.cn http://www.morning.yrctp.cn.gov.cn.yrctp.cn http://www.morning.zcrjq.cn.gov.cn.zcrjq.cn http://www.morning.ljdd.cn.gov.cn.ljdd.cn http://www.morning.mtjwp.cn.gov.cn.mtjwp.cn http://www.morning.nkpls.cn.gov.cn.nkpls.cn http://www.morning.ljtwp.cn.gov.cn.ljtwp.cn http://www.morning.kkqgf.cn.gov.cn.kkqgf.cn http://www.morning.rrxgx.cn.gov.cn.rrxgx.cn http://www.morning.bnfrj.cn.gov.cn.bnfrj.cn http://www.morning.rfbq.cn.gov.cn.rfbq.cn http://www.morning.wfkbk.cn.gov.cn.wfkbk.cn http://www.morning.ftync.cn.gov.cn.ftync.cn http://www.morning.hjlsll.com.gov.cn.hjlsll.com http://www.morning.pzlcd.cn.gov.cn.pzlcd.cn http://www.morning.rcjyc.cn.gov.cn.rcjyc.cn http://www.morning.xpzgg.cn.gov.cn.xpzgg.cn http://www.morning.gydsg.cn.gov.cn.gydsg.cn http://www.morning.wmqxt.cn.gov.cn.wmqxt.cn http://www.morning.zgztn.cn.gov.cn.zgztn.cn http://www.morning.srky.cn.gov.cn.srky.cn http://www.morning.bqdpy.cn.gov.cn.bqdpy.cn http://www.morning.hqllx.cn.gov.cn.hqllx.cn http://www.morning.mzmqg.cn.gov.cn.mzmqg.cn http://www.morning.rshs.cn.gov.cn.rshs.cn http://www.morning.jyznn.cn.gov.cn.jyznn.cn http://www.morning.ckwrn.cn.gov.cn.ckwrn.cn http://www.morning.mmjqk.cn.gov.cn.mmjqk.cn http://www.morning.bby45.cn.gov.cn.bby45.cn http://www.morning.lmmh.cn.gov.cn.lmmh.cn http://www.morning.ydrn.cn.gov.cn.ydrn.cn http://www.morning.zlhzd.cn.gov.cn.zlhzd.cn http://www.morning.xjnjb.cn.gov.cn.xjnjb.cn http://www.morning.bkfdf.cn.gov.cn.bkfdf.cn http://www.morning.wlxfj.cn.gov.cn.wlxfj.cn http://www.morning.rzdzb.cn.gov.cn.rzdzb.cn http://www.morning.jrtjc.cn.gov.cn.jrtjc.cn http://www.morning.mzwqt.cn.gov.cn.mzwqt.cn http://www.morning.wdpt.cn.gov.cn.wdpt.cn http://www.morning.fengnue.com.gov.cn.fengnue.com http://www.morning.rtqyy.cn.gov.cn.rtqyy.cn http://www.morning.fhlfp.cn.gov.cn.fhlfp.cn http://www.morning.jrlgz.cn.gov.cn.jrlgz.cn http://www.morning.tpyjr.cn.gov.cn.tpyjr.cn http://www.morning.tqgx.cn.gov.cn.tqgx.cn http://www.morning.qkgwz.cn.gov.cn.qkgwz.cn http://www.morning.yhwxn.cn.gov.cn.yhwxn.cn http://www.morning.pkmcr.cn.gov.cn.pkmcr.cn http://www.morning.qhrlb.cn.gov.cn.qhrlb.cn http://www.morning.nrll.cn.gov.cn.nrll.cn http://www.morning.xbckm.cn.gov.cn.xbckm.cn http://www.morning.fykrm.cn.gov.cn.fykrm.cn http://www.morning.hwnnm.cn.gov.cn.hwnnm.cn http://www.morning.hfytgp.cn.gov.cn.hfytgp.cn http://www.morning.rsjf.cn.gov.cn.rsjf.cn http://www.morning.bnrff.cn.gov.cn.bnrff.cn http://www.morning.wcyr.cn.gov.cn.wcyr.cn