原生GO開發的博客系統

Go博客實戰教程,是一個練手級項目教程,使用原生Go開發,未使用任何框架。

如何使用原生Go開發一個web項目
循序漸進,掌握編程思維和思路
初步具有工程思維,能適應一般的開發工作

1. 搭建項目

package mainimport ("encoding/json""log""net/http"
)type IndexData struct {Title string `json:"title"`Desc string `json:"desc"`
}
func index(w http.ResponseWriter,r *http.Request)  {w.Header().Set("Content-Type","application/json")var indexData IndexDataindexData.Title = "碼神之路go博客"indexData.Desc = "現在是入門教程"jsonStr,_ := json.Marshal(indexData)w.Write(jsonStr)
}func main()  {//程序入口,一個項目 只能有一個入口//web程序,http協議 ip portserver := http.Server{Addr: "127.0.0.1:8080",}http.HandleFunc("/",index)if err := server.ListenAndServe();err != nil{log.Println(err)}
}

2. 響應頁面

func indexHtml(w http.ResponseWriter,r *http.Request)  {t := template.New("index.html")viewPath, _ := os.Getwd()t,_ = t.ParseFiles(viewPath + "/template/index.html")var indexData IndexDataindexData.Title = "碼神之路go博客"indexData.Desc = "現在是入門教程"err := t.Execute(w,indexData)fmt.Println(err)
}func main()  {//程序入口,一個項目 只能有一個入口//web程序,http協議 ip portserver := http.Server{Addr: "127.0.0.1:8080",}http.HandleFunc("/",index)http.HandleFunc("/index.html",indexHtml)if err := server.ListenAndServe();err != nil{log.Println(err)}
}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>hello mszlu blog!!
{{.Title}}{{.Desc}}
</body>
</html>

3. 首頁

3.1 頁面解析

func index(w http.ResponseWriter,r *http.Request)  {var indexData IndexDataindexData.Title = "碼神之路go博客"indexData.Desc = "現在是入門教程"t := template.New("index.html")//1. 拿到當前的路徑path,_ := os.Getwd()//訪問博客首頁模板的時候,因為有多個模板的嵌套,解析文件的時候,需要將其涉及到的所有模板都進行解析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,_ = t.ParseFiles(path + "/template/index.html",home,header,footer,personal,post,pagination)//頁面上涉及到的所有的數據,必須有定義t.Execute(w,indexData)
}

3.2 首頁數據格式定義

config/config.go

package configtype Viewer struct {Title stringDescription  stringLogo  stringNavigation  []stringBilibili stringAvatar stringUserName stringUserDesc string
}
type SystemConfig struct {AppName             stringVersion             float32CurrentDir          stringCdnURL stringQiniuAccessKey stringQiniuSecretKey stringValine boolValineAppid stringValineAppkey stringValineServerURL string
}

models/category.go

package modelstype Category struct {Cid      intName     stringCreateAt stringUpdateAt string
}

models/post.go

package modelsimport ("goblog/config""html/template""time"
)type Post struct {Pid        int    `json:"pid"`                // 文章IDTitle      string `json:"title"`            // 文章IDSlug       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"`     // 更新時間
}type PostMore struct {Pid          int    `json:"pid"`                    // 文章IDTitle        string `json:"title"`                // 文章IDSlug         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:"createAt"`UpdateAt     string `json:"updateAt"`
}type PostReq struct {Pid        int    `json:"pid"`Title      string `json:"title"`Slug       string `json:"slug"`Content    string `json:"content"`Markdown   string `json:"markdown"`CategoryId int    `json:"categoryId"`UserId     int    `json:"userId"`Type       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 modelstype HomeData struct {config.ViewerCategorys []CategoryPosts []PostMoreTotal intPage intPages []intPageEnd bool
}

4. 配置文件讀取

config.toml:

[viewer]Title = "碼神之路Go語言博客"Description = "碼神之路Go語言博客"Logo = "/resource/images/logo.png"Navigation = ["首頁","/", "GO語言","/golang", "歸檔","/pigeonhole", "關于","/about"]Bilibili = "https://space.bilibili.com/473844125"Zhihu = "https://www.zhihu.com/people/ma-shen-zhi-lu"Avatar = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13147603927%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647242040&t=c6108010ed46b4acebe18955acdd2d24"UserName = "碼神之路"UserDesc = "長得非常帥的程序員"
[system]CdnURL = "https://static.mszlu.com/goblog/es6/md-assets"QiniuAccessKey = "替換自己的"QiniuSecretKey = "替換自己的"Valine = trueValineAppid = "替換自己的"ValineAppkey = "替換自己的"ValineServerURL = "替換自己的"
package configimport ("github.com/BurntSushi/toml""os"
)type TomlConfig struct {Viewer ViewerSystem SystemConfig
}
type Viewer struct {Title stringDescription  stringLogo  stringNavigation  []stringBilibili stringAvatar stringUserName stringUserDesc string
}
type SystemConfig struct {AppName             stringVersion             float32CurrentDir          stringCdnURL stringQiniuAccessKey stringQiniuSecretKey stringValine boolValineAppid stringValineAppkey stringValineServerURL string
}
var Cfg *TomlConfigfunc init()  {Cfg = new(TomlConfig)var err errorCfg.System.CurrentDir, err = os.Getwd()if err != nil {panic(err)}Cfg.System.AppName = "mszlu-go-blog"Cfg.System.Version = 1.0_,err = toml.DecodeFile("config/config.toml",&Cfg)if err != nil {panic(err)}
}

5. 假數據-顯示首頁內容

package mainimport ("html/template""log""ms-go-blog/config""ms-go-blog/models""net/http""time"
)type IndexData struct {Title string `json:"title"`Desc string `json:"desc"`
}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 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)
}func main()  {//程序入口,一個項目 只能有一個入口//web程序,http協議 ip portserver := http.Server{Addr: "127.0.0.1:8080",}http.HandleFunc("/",index)http.Handle("/resource/",http.StripPrefix("/resource/",http.FileServer(http.Dir("public/resource/"))))if err := server.ListenAndServe();err != nil{log.Println(err)}
}

后續內容在gitee上面: 傳送門

記得給一個start

使用 : 直接克隆地址到自己的go項目中,瀏覽器訪問 127.0.0.1:8080可訪問

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/715402.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/715402.shtml
英文地址,請注明出處:http://en.pswp.cn/news/715402.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Vue3_2024_1天【Vue3創建和響應式,對比Vue2】

前言&#xff1a; Vue3對比Vue2版本&#xff0c;它在性能、功能、易用性和可維護性方面都有顯著的提升和改進。 性能優化&#xff1a;模板編譯器的優化、對Proxy的支持以及使用了更加高效的Virtual DOM算法等。這使得Vue3的打包大小減少了41%&#xff0c;初次渲染提速55%&#…

【MATLAB源碼-第153期】基于matlab的OFDM系統插入導頻和訓練符號兩種信道估計方式誤碼率對比仿真。

操作環境&#xff1a; MATLAB 2022a 1、算法描述 OFDM&#xff08;Orthogonal Frequency Division Multiplexing&#xff0c;正交頻分復用&#xff09;是一種高效的無線信號傳輸技術&#xff0c;廣泛應用于現代通信系統&#xff0c;如Wi-Fi、LTE和5G。OFDM通過將寬帶信道劃分…

使用docker方式測試部署django項目(客戶催)

需求 1&#xff1a;已有django項目–weidanyewu 2&#xff1a;希望在服務器上測試部署–客戶催 3&#xff1a;沒完善django的啟動 4&#xff1a;使用臨時數據庫進行演示 5&#xff1a;使用python3.10版本鏡像 6&#xff1a;展示端口80 7&#xff1a;后臺執行django程序 8&#…

【C語言】熟悉文件順序讀寫函數

前言 本篇詳細介紹了 文件順序讀寫常用函數&#xff0c;快來看看吧~ 歡迎關注個人主頁&#xff1a;逸狼 創造不易&#xff0c;可以點點贊嗎~ 如有錯誤&#xff0c;歡迎指出~ 目錄 前言 ?編輯 文件順序讀寫函數 fgetc函數 示例 fputc函數 逐個字符寫入 寫入26個字母 文…

手寫模擬器,解放雙手!效果炸裂的生產工具

手寫模擬器是一款基于Handright的仿手寫圖片生成軟件&#xff0c;可以讓你的電腦和手機也能寫出漂亮的手寫字&#xff0c;你只需要輸入你想要寫的內容&#xff0c;選擇你喜歡的字體和背景&#xff0c;就可以生成一張高仿真的手寫圖片&#xff0c;用于各種場合&#xff0c;比如做…

uniapp中canvas的基礎使用

canvas簡介 canvas是uniapp中提供的一個組件,用于生成自定義的圖形界面。通過canvas,我們可以通過JavaScript代碼在頁面上繪制各種圖形和圖像。 使用canvas 在頁面中添加canvas 首先需要在頁面的template中添加一個canvas組件: <template><view><canvas ca…

linux:iostat 用法詳解

文章目錄 描述語法參數例子 描述 iostat 是一個在類Unix操作系統中常用的系統監控工具&#xff0c;尤其是Linux系統中&#xff0c;它主要用于收集和報告中央處理器(CPU)使用情況以及磁盤輸入/輸出(I/O)統計數據。以下是 iostat 命令的基本用法及其參數詳解&#xff1a; 語法 …

代碼隨想錄三刷 day11 | 棧與隊列之 20. 有效的括號 1047. 刪除字符串中的所有相鄰重復項 150. 逆波蘭表達式求值

三刷day11 20. 有效的括號1047. 刪除字符串中的所有相鄰重復項150. 逆波蘭表達式求值 20. 有效的括號 題目鏈接 解題思路&#xff1a; 有三種不匹配的情況&#xff1a; 第一種情況&#xff0c;字符串里左方向的括號多余了 。 第二種情況&#xff0c;括號沒有多余&#xff0c;…

[伴學筆記]01-操作系統概述 [南京大學2024操作系統]

文章目錄 前言jyy:01-操作系統概述 [南京大學2024操作系統]為什么要學操作系統?學習操作系統能得到什么? 什么是操作系統?想要明白什么是操作系統:時間線:1940s1950s-1960s1960-1970s年代. 信息來源: 前言 督促自己,同時分享所得,閱讀完本篇大約需要10分鐘,希望為朋友的技術…

編碼規則轉換

思考&#xff1a; 如何將一個機內碼轉換為區內碼&#xff1f; 只要將機內碼減去 A0A0 就可以啦 如果只讓我們用加法器來解決呢&#xff1f; 注意我們的數據占用了 32 位&#xff0c;如果想用補碼進行減法運算的話&#xff0c;符號位怎么辦&#xff1f;&#xff1f;&#xf…

《探索數據結構之美:如何高效實現哈希表》

摘要&#xff1a;哈希表是一種基于鍵值對的數據結構&#xff0c;它通過哈希函數將鍵映射到表中一個位置&#xff0c;以實現快速的插入、刪除和查找操作。在本期播客中&#xff0c;我們將深入剖析哈希表的數據結構&#xff0c;分享如何用Python語言實現一個哈希表項目。此外&…

【深度學習筆記】計算機視覺——微調

微調 前面的一些章節介紹了如何在只有6萬張圖像的Fashion-MNIST訓練數據集上訓練模型。 我們還描述了學術界當下使用最廣泛的大規模圖像數據集ImageNet&#xff0c;它有超過1000萬的圖像和1000類的物體。 然而&#xff0c;我們平常接觸到的數據集的規模通常在這兩者之間。 假…

【計算機是怎么跑起來的】軟件,體驗一次手工匯編

【計算機是怎么跑起來的】軟件,體驗一次手工匯編 二進制機器語言匯編語言操作碼操作數寄存器內存地址和I/O地址參考書:計算機是怎么跑起來的 第三章外設在路上。。。先整理一下本書涉及的理論知識,反正后面做視頻也要重寫QAQ 程序的作用是驅動硬件工作,所以在編寫程序之前必…

【C++庖丁解牛】類與對象

&#x1f4d9; 作者簡介 &#xff1a;RO-BERRY &#x1f4d7; 學習方向&#xff1a;致力于C、C、數據結構、TCP/IP、數據庫等等一系列知識 &#x1f4d2; 日后方向 : 偏向于CPP開發以及大數據方向&#xff0c;歡迎各位關注&#xff0c;謝謝各位的支持 目錄 1.面向過程和面向對象…

對單例模式的餓漢式、懶漢式的思考

目錄 1 什么是單例模式&#xff1f;1.1 什么是餓漢式&#xff1f;1.2 什么是懶漢式&#xff1f; 2 我對餓漢式的思考3 懶漢式3.1 解決懶漢式的線程安全問題3.1.1 加鎖&#xff1a;synchronized&#xff08;synchronized修飾靜態方法&#xff09;3.1.2 對“3.1.1”性能的改進 1 …

環形鏈表詳解(讓你徹底理解環形鏈表)

文章目錄 一.什么是環形鏈表&#xff1f;二.環形鏈表的例題&#xff08;力扣&#xff09; 三.環形鏈表的延伸問題 補充 一.什么是環形鏈表&#xff1f; 環形鏈表是一種特殊類型的鏈表數據結構&#xff0c;其最后一個節點的"下一個"指針指向鏈表中的某個節點&#xff…

Python 教學平臺,支持“多班教學”的課程授課方式|ModelWhale 版本更新

龍行龘龘、前程朤朤&#xff0c;ModelWhale 新一輪的版本更新&#xff0c;期待為大家帶來更優質的使用體驗。 本次更新中&#xff0c;ModelWhale 主要進行了以下功能迭代&#xff1a; 新增 課程&#xff08;包括課件、作業、算力&#xff09;按班級管理&#xff08;團隊版? …

springcloud的搭建和封裝,已進行開源,相互學習代碼知識。

springcloud架構的統一父工程&#xff0c;&#xff08;管理子模塊&#xff0c;管理依賴插件&#xff0c;依賴版本等&#xff09; abillty:能力服務塊&#xff1a;存放一些非業務相關的微服務&#xff0c;比如網關&#xff0c;身份認證等 exce: 網關中的一些異常信息處理 gatewa…

基于Springboot的人事管理系統 (有報告)。Javaee項目,springboot項目。

演示視頻&#xff1a; 基于Springboot的人事管理系統 &#xff08;有報告&#xff09;。Javaee項目&#xff0c;springboot項目。 項目介紹&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三層體系結構&am…

【Git】merge時報錯:refusing to merge unrelated histories

文章目錄 一、問題二、解決辦法1、將feature分支的東西追加到master分支中2、將feature里的東西直接覆蓋到master分支中 一、問題 今天將feature分支合并到master時報錯&#xff1a;refusing to merge unrelated histories&#xff08;拒絕合并無關歷史&#xff09; 報錯原因&…