This is a creation in Article, where the information may have evolved or changed.
Recently learned go, decided to do a blog to practice practiced hand, some of the good library used
Markdown Parsing Library
Use Markdown to write blog posts, I use "github.com/russross/blackfriday" library, the usage is very simple
Install first
Direct use of the go get github.com/russross/blackfriday installation
Use
First of all, of course to introduce:
import github.com/russross/blackfriday
And then
output := blackfriday.MarkdownBasic(input)
Here input is the []byte type, which can convert a string of type markdown to []byte, i.e.input = []byte(string)
If you want to filter untrusted content, use the following methods:
import ( "github.com/microcosm-cc/bluemonday" "github.com/russross/blackfriday")// ...unsafe := blackfriday.MarkdownCommon(input)html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
Basically, these operations
My use is to add a new article, the data submitted by the form is converted directly through the above method, the markdown and the converted content are stored in the database
However, when I render on the front end, the problem is that the HTML tags in the converted content will be displayed directly on the Web page, in order to avoid this situation, I used the custom template function
// 定义模板函数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 Library
The session library is used in the login function.github.com/gorilla/sessions
Project home: Https://github.com/gorilla/sessions
Official website: http://www.gorillatoolkit.org/pkg/sessions
Installation
go get github.com/gorilla/sessions
Use
Also very convenient to use
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)}
Also get session value and delete session value
// 获取var foo := session.Values["foo"]// 删除// 将session的最大存储时间设置为小于零的数即为删除session.Options.MaxAge = -1session.Save(r, w)
More detailed information on the http://www.gorillatoolkit.org/pkg/sessions