這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
最近學習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 = -1session.Save(r, w)
更詳細的內容在http://www.gorillatoolkit.org/pkg/sessions