加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

Go:你会如何“漂亮打印”/“Prettify”HTML?

发布时间:2020-12-14 16:41:04 所属栏目:资源 来源:网络整理
导读:在 Python,PHP和许多其他语言中,可以转换html文档并“美化”它.在Go中,使用MarshIndent函数可以非常轻松地完成JSON和XML(来自结构/接口). Go中的XML示例: http://play.golang.org/p/aBNfNxTEG1 package mainimport ( "encoding/xml" "fmt" "os")func main()
在 Python,PHP和许多其他语言中,可以转换html文档并“美化”它.在Go中,使用MarshIndent函数可以非常轻松地完成JSON和XML(来自结构/接口).

Go中的XML示例:

http://play.golang.org/p/aBNfNxTEG1

package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {
    type Address struct {
        City,State string
    }
    type Person struct {
        XMLName   xml.Name `xml:"person"`
        Id        int      `xml:"id,attr"`
        FirstName string   `xml:"name>first"`
        LastName  string   `xml:"name>last"`
        Age       int      `xml:"age"`
        Height    float32  `xml:"height,omitempty"`
        Married   bool
        Address
        Comment string `xml:",comment"`
    }

    v := &Person{Id: 13,FirstName: "John",LastName: "Doe",Age: 42}
    v.Comment = " Need more details. "
    v.Address = Address{"Hanga Roa","Easter Island"}

    output,err := xml.MarshalIndent(v,"  ","    ")
    if err != nil {
        fmt.Printf("error: %vn",err)
    }

    os.Stdout.Write(output)
}

但是,这仅适用于将struct / interface转换为[]字节.我想要的是自动转换一串html代码和缩进.例:

原始HTML

<!doctype html><html><head>
<title>Website Title</title>
</head><body>
<div class="random-class">
<h1>I like pie</h1><p>It's true!</p></div>
</body></html>

Prettified HTML

<!doctype html>
<html>
    <head>
        <title>Website Title</title>
    </head>
    <body>
        <div class="random-class">
            <h1>I like pie</h1>
            <p>It's true!</p>
        </div>
    </body>
</html>

如何使用字符串完成这项工作?

解决方法

我遇到了同样的问题,我只是通过自己在Go中创建一个HTML格式化包来解决它.

这里是:

GoHTML – HTML formatter for Go

请检查此包裹.

谢谢,

敬事

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读