设为首页 加入收藏

TOP

go的markdown解析库和session库
2017-09-30 13:51:01 】 浏览:7518
Tags: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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇go-使用 unsafe 修改 struct 中的.. 下一篇golang zip 压缩,解压(含目录文..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目