go的markdown解析庫和session庫


最近學習go,就決定做一個博客來練練手,一下是用到的一些不錯的庫

markdown解析庫

使用markdown來寫博客文章,我用的是"github.com/russross/blackfriday"庫,用法非常簡單

首先安裝

直接使用go get github.com/russross/blackfriday安裝

使用

首先當然要引入:

import github.com/russross/blackfriday

然后

output := blackfriday.MarkdownBasic(input)

這里input是[]byte類型,可以將markdown類型的字符串強轉為[]byte,即input = []byte(string)

如果想過濾不信任的內容,使用以下方法:


import (
    "github.com/microcosm-cc/bluemonday"
    "github.com/russross/blackfriday"
)

// ...
unsafe := blackfriday.MarkdownCommon(input)
html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)

基本上就這些操作

我的使用方法是在添加新文章時,將表單提交的數據直接通過上面的方法轉換后,將markdown和轉換后的內容都存儲到數據庫中

不過我在前端渲染時,又出現了問題,就是轉換后的內容中的html標簽會直接顯示在網頁上,為避免這種狀況,我使用了自定義模板函數

// 定義模板函數
func unescaped(x string) interface{} { return template.HTML(x)}

// 注冊模板函數
t := template.New("post.html")
t = t.Funcs(template.FuncMap{"unescaped": unescaped})
t, _ = t.ParseFiles("templates/post.html")
t.Execute(w, post)

// 使用模板函數

{{ .Content|unescaped }}

session庫

在做登錄功能時用到了session庫github.com/gorilla/sessions

項目主頁:https://github.com/gorilla/sessions 官網: http://www.gorillatoolkit.org/pkg/sessions

安裝

go get github.com/gorilla/sessions

使用

使用也很方便

import (
    "net/http"
    "github.com/gorilla/sessions"
)

// 初始化一個cookie存儲對象
// something-very-secret應該是一個你自己的密匙,只要不被別人知道就行
var store = sessions.NewCookieStore([]byte("something-very-secret"))

func MyHandler(w http.ResponseWriter, r *http.Request) {
    // Get a session. We're ignoring the error resulted from decoding an
    // existing session: Get() always returns a session, even if empty.

    // 獲取一個session對象,session-name是session的名字
    session, err := store.Get(r, "session-name")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // 在session中存儲值
    session.Values["foo"] = "bar"
    session.Values[42] = 43
    // 保存更改
    session.Save(r, w)
}

另外還有獲取session值和刪除session值

// 獲取
var foo = session.Values["foo"]

// 刪除
// 將session的最大存儲時間設置為小於零的數即為刪除
session.Options.MaxAge = -1
session.Save(r, w)

更詳細的內容在http://www.gorillatoolkit.org/pkg/sessions


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM