LoginSignup
0
0

More than 5 years have passed since last update.

chroma をつかってコードハイライトを生成するサンプル

Last updated at Posted at 2019-01-26

go のコードの一部です。

type Ping struct {
    Status int
    Result string
}

func Sample(w http.ResponseWriter, r *http.Request) {
    lexer := lexers.Get("ruby")
    style := styles.Get("monokai")
    if style == nil {
        style = styles.Fallback
    }
    formatter := html.New(html.WithClasses())
    iterator, err := lexer.Tokenise(nil, "def hoge; x=3; 6; end")
    buf := new(bytes.Buffer)
    err = formatter.Format(buf, style, iterator)
    if err != nil {
        fmt.Println(err)
    }

    sourceCode := buf.String()
    ping := Ping{http.StatusOK, sourceCode}
    res, _ := json.Marshal(ping)
    w.Header().Set("Content-Type", "application/json")
    w.Write(res)
}

これで、以下のような json を得る。

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0