golang實現markdown頂部導航移到左側
來源:互聯網
上載者:User
最近寫一個文檔,由於文檔太長,加上頁面導航後,發現頁面導航只能在頁面頂部,查看文檔很不方便。所以就寫了個工具可以把產生好的HTML頁面頂部導航移到左側。我自己覺得挺好用的就分享出來了。```text程式使用方式:./mdleft -s ./test.html -d ./test_v0.1.0.html -t markdown左側導航說明:-s原HTML檔案-d輸出檔案-t左側導航標題和HTML檔案標題```---![left.jpg](https://static.studygolang.com/180712/0e2c77c48d66b7d21720fe80678ce5ae.jpg)------## 源碼```gopackage mainimport ("bytes""flag""fmt""io/ioutil""log""os""path/filepath""strings""github.com/PuerkitoBio/goquery")func main() {var err errorvar srcPath, destPath, title stringflag.StringVar(&srcPath, "s", "", "source html file")flag.StringVar(&destPath, "d", "", "output html file")flag.StringVar(&title, "t", "", "title")flag.Parse()if srcPath == "" {flag.Usage()log.Fatalln("source file is empty")}srcPath, err = filepath.Abs(srcPath)if err != nil {flag.Usage()log.Fatalln(err)}if destPath == "" {fileName := filepath.Base(srcPath)if ind := strings.Index(fileName, "."); ind != -1 {fileName = fileName[:ind] + "_v0.0.0" + fileName[ind:]} else {fileName += "_v0.0.0"}destPath = filepath.Join(filepath.Dir(srcPath), fileName)}if !fileExists(srcPath) {log.Fatalf("file not exists:%s\n", srcPath)}// 讀取檔案data, err := ioutil.ReadFile(srcPath)if err != nil {log.Fatalln(err)}doc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(data))if err != nil {log.Fatalln(err)}// 擷取頂部導航列表leftUl := doc.Find("body").Find("ul").First()doc.Find("body").Find("ul").First().Remove()// 擷取主體rightDiv := doc.Find("body").Find("div").First()doc.Find("body").Find("div").First().Remove()// 添加樣式doc.Find("head").AppendHtml(styleLeftRight)// 添加左側導航列表doc.Find("body").AppendHtml(leftDivStr)if title != "" {doc.Find("title").First().SetText(title)doc.Find("body").Find("div.left-div").AppendHtml(getDocTitle(title))}doc.Find("body").Find("div.left-div").AppendSelection(leftUl)doc.Find("body").AppendHtml(rightDivStr)// 添加右側主體doc.Find("body").Find("div.right-div").AppendSelection(rightDiv)// 添加調整右側寬度的jsdoc.Find("html").AppendHtml(scriptWidth)// 輸出檔案ret, err := doc.Html()if err != nil {log.Fatalln(err)}err = ioutil.WriteFile(destPath, []byte(ret), 0644)if err != nil {log.Fatalln(err)}}func fileExists(name string) (ok bool) {if _, err := os.Stat(name); err != nil {if os.IsNotExist(err) {return false}}return true}func getDocTitle(s string) (title string) {return fmt.Sprintf(`<h2 style="color:rgb(40, 153, 206)" >%s</h2>`, s)}var (leftDivStr = `<div id="left-001" class="left-div"></div>`rightDivStr = `<div id="right-001" class="right-div"></div>`styleLeftRight = `<style>body {border: 1px solid #ddd;outline: 1300px solid #fff;margin: 16px auto;}.left-div {float: left;padding-right: 10px;position: fixed;overflow-y: scroll;height: 100%}.right-div {float: right;padding-left: 10px;}</style> `scriptWidth = `<script type="text/javascript">var width = window.innerWidth - document.getElementById("left-001").offsetWidth-50;document.getElementById("right-001").style.width = width+"px";</script>`)````99 次點擊