代码块样式测试:Go 与 Python 示例
这篇文章主要用来测试主题里的代码块。
要看的东西很简单:字体是不是清楚,缩进有没有乱,长行能不能横向滚动,亮色和暗色下语法高亮会不会刺眼。
Go example
先放一个简单的 HTTP 服务:
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
type Response struct {
Message string `json:"message"`
Time time.Time `json:"time"`
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(Response{
Message: "ok",
Time: time.Now(),
})
})
log.Println("server listening on :8080")
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Fatal(err)
}
}
再放一行比较长的代码,专门看窄屏时会不会撑破页面:
log.Printf("user=%s request_id=%s method=%s path=%s status=%d duration=%s", userID, requestID, r.Method, r.URL.Path, statusCode, time.Since(start))
Python example
再看一段 Python:
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from statistics import mean
@dataclass
class Article:
title: str
words: int
tags: list[str]
def load_articles(path: Path) -> list[Article]:
data = json.loads(path.read_text(encoding="utf-8"))
return [Article(**item) for item in data]
def summarize(articles: list[Article]) -> dict[str, object]:
total_words = sum(article.words for article in articles)
all_tags = sorted({tag for article in articles for tag in article.tags})
return {
"count": len(articles),
"total_words": total_words,
"average_words": round(mean(article.words for article in articles), 2),
"tags": all_tags,
}
if __name__ == "__main__":
articles = load_articles(Path("articles.json"))
print(json.dumps(summarize(articles), ensure_ascii=False, indent=2))
最后放一段 Shell,看看普通命令块的效果:
cd /data/myblog
hugo --buildDrafts --gc --minify