go的markdown解析庫和session庫

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

最近學習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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.