最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于原生Go語(yǔ)言開(kāi)發(fā)一個(gè)博客系統(tǒng)

 更新時(shí)間:2024年02月28日 10:50:18   作者:lucky九年  
這篇文章主要為大家詳細(xì)介紹了如何基于原生Go語(yǔ)言開(kāi)發(fā)一個(gè)簡(jiǎn)單的博客系統(tǒng),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

如何使用原生Go開(kāi)發(fā)一個(gè)web項(xiàng)目

循序漸進(jìn),掌握編程思維和思路

初步具有工程思維,能適應(yīng)一般的開(kāi)發(fā)工作

1. 搭建項(xiàng)目

package main

import (
	"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 IndexData
	indexData.Title = "碼神之路go博客"
	indexData.Desc = "現(xiàn)在是入門(mén)教程"
	jsonStr,_ := json.Marshal(indexData)
	w.Write(jsonStr)
}

func main()  {
	//程序入口,一個(gè)項(xiàng)目 只能有一個(gè)入口
	//web程序,http協(xié)議 ip port
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/",index)
	if err := server.ListenAndServe();err != nil{
		log.Println(err)
	}
}

2. 響應(yīng)頁(yè)面

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 IndexData
	indexData.Title = "碼神之路go博客"
	indexData.Desc = "現(xiàn)在是入門(mén)教程"
	err := t.Execute(w,indexData)
	fmt.Println(err)
}

func main()  {
	//程序入口,一個(gè)項(xiàng)目 只能有一個(gè)入口
	//web程序,http協(xié)議 ip port
	server := 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. 首頁(yè)

3.1 頁(yè)面解析

func index(w http.ResponseWriter,r *http.Request)  {
	var indexData IndexData
	indexData.Title = "碼神之路go博客"
	indexData.Desc = "現(xiàn)在是入門(mén)教程"
	t := template.New("index.html")
	//1. 拿到當(dāng)前的路徑
	path,_ := os.Getwd()
	//訪問(wèn)博客首頁(yè)模板的時(shí)候,因?yàn)橛卸鄠€(gè)模板的嵌套,解析文件的時(shí)候,需要將其涉及到的所有模板都進(jìn)行解析
	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)

	//頁(yè)面上涉及到的所有的數(shù)據(jù),必須有定義
	t.Execute(w,indexData)
}

3.2 首頁(yè)數(shù)據(jù)格式定義

config/config.go

package config

type Viewer struct {
	Title string
	Description  string
	Logo  string
	Navigation  []string
	Bilibili string
	Avatar string
	UserName string
	UserDesc string
}
type SystemConfig struct {
	AppName             string
	Version             float32
	CurrentDir          string
	CdnURL string
	QiniuAccessKey string
	QiniuSecretKey string
	Valine bool
	ValineAppid string
	ValineAppkey string
	ValineServerURL string
}

models/category.go

package models

type Category struct {
    Cid      int
    Name     string
    CreateAt string
    UpdateAt string
}

models/post.go

package models

import (
	"goblog/config"
	"html/template"
	"time"
)

type Post struct {
	Pid        int    `json:"pid"`                // 文章ID
	Title      string `json:"title"`            // 文章ID
	Slug       string `json:"slug"`              // 自定也頁(yè)面 path
	Content    string `json:"content"`        // 文章的html
	Markdown   string `json:"markdown"`      // 文章的Markdown
	CategoryId int    `json:"categoryId"` //分類id
	UserId     int    `json:"userId"`         //用戶id
	ViewCount  int    `json:"viewCount"`   //查看次數(shù)
	Type       int    `json:"type"`              //文章類型 0 普通,1 自定義文章
	CreateAt   time.Time `json:"createAt"`     // 創(chuàng)建時(shí)間
	UpdateAt   time.Time `json:"updateAt"`     // 更新時(shí)間
}

type PostMore struct {
	Pid          int    `json:"pid"`                    // 文章ID
	Title        string `json:"title"`                // 文章ID
	Slug         string `json:"slug"`                  // 自定也頁(yè)面 path
	Content      template.HTML `json:"content"`            // 文章的html
	CategoryId   int    `json:"categoryId"`     // 文章的Markdown
	CategoryName string `json:"categoryName"` // 分類名
	UserId       int    `json:"userId"`             // 用戶id
	UserName     string `json:"userName"`         // 用戶名
	ViewCount    int    `json:"viewCount"`       // 查看次數(shù)
	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"` // 文章ID
	Title string `orm:"title" json:"title"`
}

type PostRes struct {
	config.Viewer
	config.SystemConfig
	Article PostMore
}

models/home.go

package models


type HomeData struct {
	config.Viewer
	Categorys []Category
	Posts []PostMore
	Total int
	Page int
	Pages []int
	PageEnd bool
}

4. 配置文件讀取

config.toml:

[viewer]
    Title = "碼神之路Go語(yǔ)言博客"
    Description = "碼神之路Go語(yǔ)言博客"
    Logo = "/resource/images/logo.png"
    Navigation = ["首頁(yè)","/", "GO語(yǔ)言","/golang", "歸檔","/pigeonhole", "關(guān)于","/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 = "長(zhǎng)得非常帥的程序員"
[system]
    CdnURL = "https://static.mszlu.com/goblog/es6/md-assets"
    QiniuAccessKey = "替換自己的"
    QiniuSecretKey = "替換自己的"
    Valine = true
    ValineAppid = "替換自己的"
    ValineAppkey = "替換自己的"
    ValineServerURL = "替換自己的"
package config

import (
	"github.com/BurntSushi/toml"
	"os"
)

type TomlConfig struct {
	Viewer Viewer
	System SystemConfig
}
type Viewer struct {
	Title string
	Description  string
	Logo  string
	Navigation  []string
	Bilibili string
	Avatar string
	UserName string
	UserDesc string
}
type SystemConfig struct {
	AppName             string
	Version             float32
	CurrentDir          string
	CdnURL string
	QiniuAccessKey string
	QiniuSecretKey string
	Valine bool
	ValineAppid string
	ValineAppkey string
	ValineServerURL string
}
var Cfg *TomlConfig

func init()  {
	Cfg = new(TomlConfig)
	var err error
	Cfg.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. 假數(shù)據(jù)-顯示首頁(yè)內(nèi)容

package main

import (
	"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. 拿到當(dāng)前的路徑
	path := config.Cfg.System.CurrentDir
	//訪問(wèn)博客首頁(yè)模板的時(shí)候,因?yàn)橛卸鄠€(gè)模板的嵌套,解析文件的時(shí)候,需要將其涉及到的所有模板都進(jìn)行解析
	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)
	}
	//頁(yè)面上涉及到的所有的數(shù)據(jù),必須有定義
	var categorys = []models.Category{
		{
			Cid: 1,
			Name: "go",
		},
	}
	var posts = []models.PostMore{
		{
			Pid: 1,
			Title: "go博客",
			Content: "內(nèi)容",
			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()  {
	//程序入口,一個(gè)項(xiàng)目 只能有一個(gè)入口
	//web程序,http協(xié)議 ip port
	server := 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)
	}
}

后續(xù)內(nèi)容在gitee上面: 傳送門(mén)

到此這篇關(guān)于基于原生Go語(yǔ)言開(kāi)發(fā)一個(gè)博客系統(tǒng)的文章就介紹到這了,更多相關(guān)Go博客系統(tǒng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • golang實(shí)現(xiàn)webgis后端開(kāi)發(fā)的步驟詳解

    golang實(shí)現(xiàn)webgis后端開(kāi)發(fā)的步驟詳解

    這篇文章主要介紹如何用golang結(jié)合postgis數(shù)據(jù)庫(kù),使用gin、grom框架實(shí)現(xiàn)后端的MVC的接口搭建,文中有詳細(xì)的流程步驟及代碼示例,需要的朋友可以參考下
    2023-06-06
  • golang監(jiān)聽(tīng)文件變化的實(shí)例

    golang監(jiān)聽(tīng)文件變化的實(shí)例

    這篇文章主要介紹了golang監(jiān)聽(tīng)文件變化的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-03-03
  • Go調(diào)用opencv實(shí)現(xiàn)圖片矯正的代碼示例

    Go調(diào)用opencv實(shí)現(xiàn)圖片矯正的代碼示例

    這篇文章主要為大家詳細(xì)介紹了Go調(diào)用opencv實(shí)現(xiàn)圖片矯正的代碼示例,文中的示例代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-09-09
  • Go語(yǔ)言高效I/O并發(fā)處理雙緩沖和Exchanger模式實(shí)例探索

    Go語(yǔ)言高效I/O并發(fā)處理雙緩沖和Exchanger模式實(shí)例探索

    這篇文章主要介紹了Go語(yǔ)言高效I/O并發(fā)處理雙緩沖和Exchanger模式實(shí)例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • GO語(yǔ)言(golang)基礎(chǔ)知識(shí)

    GO語(yǔ)言(golang)基礎(chǔ)知識(shí)

    這篇文章主要介紹了GO語(yǔ)言(golang)基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-01-01
  • 初識(shí)Golang?Mutex互斥鎖的使用

    初識(shí)Golang?Mutex互斥鎖的使用

    在學(xué)習(xí)操作系統(tǒng)的時(shí)候,我們應(yīng)該都學(xué)習(xí)過(guò)臨界區(qū)、互斥鎖這些概念,用于在并發(fā)環(huán)境下保證狀態(tài)的正確性。在?Go語(yǔ)言?里面互斥鎖是?sync.Mutex?,我們本篇文章就來(lái)學(xué)習(xí)下為什么要使用互斥鎖、如何使用互斥鎖,以及使用時(shí)的常見(jiàn)問(wèn)題
    2022-10-10
  • Go 常量基礎(chǔ)概念(聲明更改只讀)

    Go 常量基礎(chǔ)概念(聲明更改只讀)

    這篇文章主要為大家介紹了Go常量基礎(chǔ)概念包括常量的聲明更改只讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • Go語(yǔ)言容器化之從Docker到Kubernetes詳解

    Go語(yǔ)言容器化之從Docker到Kubernetes詳解

    容器化技術(shù)是現(xiàn)代軟件開(kāi)發(fā)和部署的重要手段,它可以幫助開(kāi)發(fā)者將應(yīng)用程序和其所需的依賴項(xiàng)打包成一個(gè)可移植的容器,然后在任何支持容器化的環(huán)境中運(yùn)行,這篇文章主要介紹了Go語(yǔ)言容器化之從Docker到Kubernetes的相關(guān)資料,需要的朋友可以參考下
    2026-04-04
  • golang生成JSON以及解析JSON

    golang生成JSON以及解析JSON

    這篇文章主要介紹了golang生成JSON以及解析JSON,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • Go語(yǔ)言輕量級(jí)高性能嵌入式規(guī)則引擎RuleGo使用詳解

    Go語(yǔ)言輕量級(jí)高性能嵌入式規(guī)則引擎RuleGo使用詳解

    這篇文章主要為大家介紹了Go語(yǔ)言輕量級(jí)高性能嵌入式規(guī)則引擎RuleGo使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11

最新評(píng)論

稷山县| 斗六市| 英德市| 广河县| 吉木乃县| 常德市| 浪卡子县| 彰化市| 正镶白旗| 朝阳区| 聂拉木县| 平武县| 福建省| 渝北区| 沙洋县| 靖安县| 安国市| 钟祥市| 衡水市| 永善县| 晋江市| 大荔县| 东丽区| 龙川县| 吉木萨尔县| 汉中市| 孝义市| 三河市| 广昌县| 邵阳市| 广汉市| 罗江县| 阳新县| 泰安市| 新野县| 上饶县| 镇赉县| 承德市| 宜兰市| 石柱| 潞西市|