zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Servlet的数据库访问
    Servlet 网页重定向
    Intellij idea创建javaWeb以及Servlet简单实现
    Tomcat
    QQ简易版
    单例
    centos7 jdk安装
    centos7 allure安装
    centos中执行apt-get命令提示apt-get command not found
    centos mysql使用踩过的坑
  • 原文地址:https://www.cnblogs.com/itogo/p/5635605.html
Copyright © 2011-2022 走看看