Golang: 命令行参数解析(flag)

2020-12-25

Go 自带 flag 包,可以用于解析命令行参数。但用起来非常繁琐,更谈不上优雅,远不如 Python 的 argparse 包简洁明了,易于使用。

语法

类型

  • flag.Flag
  • flag.FlagSet
  • flag.Getter
  • flag.Value

方法

func Bool(name string, value bool, usage string) *bool
func BoolVar(p *bool, name string, value bool, usage string)

func Duration(name string, value time.Duration, usage string) *time.Duration
func DurationVar(p *time.Duration, name string, value time.Duration, usage string)

func Float64(name string, value float64, usage string) *float64
func Float64Var(p *float64, name string, value float64, usage string)

func Func(name, usage string, fn func(string) error)

func Int(name string, value int, usage string) *int
func IntVar(p *int, name string, value int, usage string)

func Int64(name string, value int64, usage string) *int64
func Int64Var(p *int64, name string, value int64, usage string)

func String(name string, value string, usage string) *string
func StringVar(p *string, name string, value string, usage string)

func Uint(name string, value uint, usage string) *uint
func UintVar(p *uint, name string, value uint, usage string)

func Uint64(name string, value uint64, usage string) *uint64
func Uint64Var(p *uint64, name string, value uint64, usage string)

func Var(value Value, name string, usage string)
  1. 带 Var 结尾的方法表示将值绑定到一个变量上。
func Arg(i int) string  // i-th argument
func Args() []string    // non-flag arguments

func NArg() int         // number of arguments remaining after flags have been processed
func NFlag() int        // number of command-line flags that have been set

func Parse()
func Parsed() bool
func Set(name, value string) error

func PrintDefaults()    // 帮助信息
func UnquoteUsage(flag *Flag) (name string, usage string)  // 返回 flag 的名称和用法

func Visit(fn func(*Flag))
func VisitAll(fn func(*Flag))

type ErrorHandling

FlagSet

func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

上面的方法 FlagSet 也都有一份。

示例:Todo

package main

import (
    "flag"
    "fmt"
)

var (
    addFlag       = flag.String("add", "", "Add a new task")
    listFlag      = flag.Bool("list", false, "List all tasks")
    removeFlag    = flag.Int("remove", -1, "Remove a task by its index")
    removeAllFlag = flag.Bool("remove-all", false, "Remove all tasks")
    doneFlag      = flag.Int("done", -1, "Mark a task as done by its index")
    undoneFlag    = flag.Int("undone", -1, "Mark a task as undone by its index")
)

func main() {
    flag.Parse()
    args := make(map[string]interface{}, 10)
    args["add"] = *addFlag
    args["list"] = *listFlag
    args["remove"] = *removeFlag
    args["remove"] = *removeAllFlag
    args["done"] = *doneFlag
    args["undone"] = *undoneFlag
    fmt.Printf("%#v\n", args)
    // map[string]interface {}{"add":"", "done":-1, "list":false, "remove":false, "undone":-1}
    fmt.Println("Other arguments:", flag.Args())
    // Other arguments: []
}

参考资料与拓展阅读

Go 知名项目

2020-12-21

按照 stars 排序,就取头部的一些项目分析一下:

  1. golang/go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The Go programming language
    跳过
  2. kubernetes/kubernetes shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Production-Grade Container Scheduling and Management
    K8S,跳过
  3. avelino/awesome-go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A curated list of awesome Go frameworks, libraries and software
    一个重要的学习参考。
  4. moby/moby shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Moby Project - a collaborative project for the container ecosystem to assemble container-based systems
    Docker,跳过
  5. gin-gonic/gin shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
    Gin,跳过
  6. gohugoio/hugo shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The world’s fastest framework for building websites.
    Hugo,知名静态网站生成工具
  7. fatedier/frp shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet.
    frp, 知名网络工具
  8. syncthing/syncthing shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Open Source Continuous File Synchronization
    知名文件同步工具
  9. junegunn/fzf shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    :cherry_blossom: A command-line fuzzy finder
    fzf,知名 find 命令替代品
  10. prometheus/prometheus shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The Prometheus monitoring system and time series database.
    知名监控平台
  11. caddyserver/caddy shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Fast, multi-platform web server with automatic HTTPS
    知名 HTTP 服务器
  12. astaxie/build-web-application-with-golang shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A golang ebook intro how to build a web with golang
    《Go Web 编程》
  13. gogs/gogs shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Gogs is a painless self-hosted Git service
    知名 Git 服务器
  14. etcd-io/etcd shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Distributed reliable key-value store for the most critical data of a distributed system
    知名 KV 存储服务
  15. v2ray/v2ray-core shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A platform for building proxies to bypass network restrictions.
    知名网络工具
  16. traefik/traefik shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The Cloud Native Application Proxy
    知名代理服务
  17. ethereum/go-ethereum shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Official Go implementation of the Ethereum protocol
    知名区块链项目
  18. FiloSottile/mkcert shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A simple zero-config tool to make locally trusted development certificates with any names you'd like.
  19. minio/minio shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Multi-Cloud Object Storage
  20. rclone/rclone shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    "rsync for cloud storage" - Google Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Wasabi, Google Cloud Storage, Yandex Files
  21. hashicorp/terraform shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Terraform enables you to safely and predictably create, change, and improve infrastructure. It is an open source tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
  22. wagoodman/dive shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A tool for exploring each layer in a docker image
  23. evanw/esbuild shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An extremely fast JavaScript and CSS bundler and minifier
    知名前端构建工具
  24. pingcap/tidb shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    TiDB is an open-source, cloud-native, distributed, MySQL-Compatible database for elastic scale and real-time analytics. Try free: https://tidbcloud.com/signup
    知名国产数据库
  25. istio/istio shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Connect, secure, control, and observe services.
    知名服务网格组件
  26. go-gitea/gitea shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Git with a cup of tea, painless self-hosted git service
    知名 Git 服务(gogs fork)
  27. unknwon/the-way-to-go_ZH_CN shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    《The Way to Go》中文译本,中文正式名《Go 入门指南》
  28. cli/cli shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    GitHub’s official command line tool
    GitHub 官方命令行工具
  29. go-gorm/gorm shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The fantastic ORM library for Golang, aims to be developer friendly
    知名 Go ORM 库
  30. beego/beego shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    beego is an open-source, high-performance web framework for the Go programming language.
    知名 Go web 框架
  31. jesseduffield/lazygit shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    simple terminal UI for git commands
    Git 终端界面
  32. Dreamacro/clash shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A rule-based tunnel in Go.
    网络工具
  33. spf13/cobra shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A Commander for modern Go CLI interactions
  34. docker/compose shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Define and run multi-container applications with Docker
  35. halfrost/LeetCode-Go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    ✅ Solutions to LeetCode by Go, 100% test coverage, runtime beats 100% / LeetCode 题解
  36. harness/drone shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Drone is a Container-Native, Continuous Delivery Platform
    知名 CI/CD 服务
  37. hashicorp/consul shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Consul is a distributed, highly available, and data center aware solution to connect and configure applications across dynamic, distributed infrastructure.
    知名服务发现和配置管理服务
  38. cockroachdb/cockroach shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    CockroachDB - the open source, cloud-native distributed SQL database.
    数据库
  39. nektos/act shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Run your GitHub Actions locally 🚀
    开发工具:GitHub Action
  40. hashicorp/vault shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A tool for secrets management, encryption as a service, and privileged access management
    安全相关服务
  41. kubernetes/minikube shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Run Kubernetes locally
    知名 K8S 项目
  42. influxdata/influxdb shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Scalable datastore for metrics, events, and real-time analytics
    知名时序数据库
  43. go-kit/kit shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A standard library for microservices.
    微服务框架
  44. mattermost/mattermost-server shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Mattermost is an open source platform for secure collaboration across the entire software development lifecycle.
    研发团队协作工具
  45. jesseduffield/lazydocker shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The lazier way to manage everything docker
    Docker 管理工具
  46. labstack/echo shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    High performance, minimalist Go web framework
    知名 HTTP 框架
  47. kataras/iris shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The fastest HTTP/2 Go Web Framework. A true successor of expressjs and laravel. Supports AWS Lambda, gRPC, MVC, Unique Router, Websockets, Sessions, Test suite, Dependency Injection and more. Thank you / 谢谢 https://github.com/kataras/iris/issues/1329
    知名 HTTP 框架
  48. portainer/portainer shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Making Docker and Kubernetes management easy.
    知名容器管理平台
  49. helm/helm shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The Kubernetes Package Manager
    知名 K8S 项目
  50. github/hub shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A command-line tool that makes git easier to use with GitHub.
  51. inconshreveable/ngrok shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Introspected tunnels to localhost
  52. openfaas/faas shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    OpenFaaS - Serverless Functions Made Simple
    知名 FaaS 项目
  53. ehang-io/nps shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    一款轻量级、高性能、功能强大的内网穿透代理服务器。支持 tcp、udp、socks5、http 等几乎所有流量转发,可用来访问内网网站、本地支付接口调试、ssh 访问、远程桌面,内网 dns 解析、内网 socks5 代理等等……,并带有功能强大的 web 管理端。a lightweight, high-performance, powerful intranet penetration proxy server, with a powerful web management terminal.
  54. nsqio/nsq shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A realtime distributed messaging platform
    知名 MQ 服务
  55. coreybutler/nvm-windows shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A node.js version management utility for Windows. Ironically written in Go.
    开发工具:前端相关
  56. photoprism/photoprism shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    AI-Powered Photos App for the Decentralized Web 🌈💎✨
    照片管理系统
  57. sirupsen/logrus shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Structured, pluggable logging for Go.
    重要的日志库
  58. yeasy/docker_practice shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Learn and understand Docker&Container technologies, with real DevOps practice!
    电子书:Docker 技术入门与实战
  59. gofiber/fiber shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    ⚡️ Express inspired web framework written in Go
    知名 Web 框架
  60. k3s-io/k3s shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Lightweight Kubernetes
    知名 K8S 项目
  61. tsenart/vegeta shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    HTTP load testing tool and library. It's over 9000!
    HTTP 压测工具
  62. schollz/croc shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Easily and securely send things from one computer to another :crocodile: :package:
    工具:文件传输
  63. zyedidia/micro shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A modern and intuitive terminal-based text editor
    工具:编辑器
  64. spf13/viper shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Go configuration with fangs
    配置管理库
  65. rancher/rancher shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Complete container management platform
    知名容器管理平台
  66. tmrts/go-patterns shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Curated list of Go design patterns, recipes and idioms
    设计模式
  67. go-delve/delve shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Delve is a debugger for the Go programming language.
    调试工具
  68. urfave/cli shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A simple, fast, and fun package for building command line apps in Go
    命令行库
  69. asim/go-micro shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A Go microservices framework
    知名 Go 微服务框架
  70. dgraph-io/dgraph shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Native GraphQL Database with graph backend
    GraphQL 数据库(?)
  71. dapr/dapr shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Dapr is a portable, event-driven, runtime for building distributed applications across cloud and edge.
    知名微服务平台
  72. iawia002/lux shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    👾 Fast and simple video download library and CLI tool written in Go
    工具:视频下载
  73. go-kratos/kratos shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Your ultimate Go microservices framework for the cloud-native era.
    微服务框架
  74. zeromicro/go-zero shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A cloud-native Go microservices framework with cli tool for productivity.
    微服务框架
  75. valyala/fasthttp shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
    HTTP 库
  76. quii/learn-go-with-tests shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Learn Go with test-driven development
    资料:TDD
  77. goharbor/harbor shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An open source trusted cloud native registry project that stores, signs, and scans content.
  78. gorilla/websocket shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A fast, well-tested and widely used WebSocket implementation for Go.
  79. chai2010/advanced-go-programming-book shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    :books: 《Go 语言高级编程》开源图书,涵盖 CGO、Go 汇编语言、RPC 实现、Protobuf 插件实现、Web 框架实现、分布式系统等高阶主题(完稿)
  80. restic/restic shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Fast, secure, efficient backup program
  81. fyne-io/fyne shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Cross platform GUI in Go inspired by Material Design
  82. gorilla/mux shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A powerful HTTP router and URL matcher for building Go web servers with 🦍
    知名 HTTP 路由库
  83. gocolly/colly shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Elegant Scraper and Crawler Framework for Golang
    爬虫框架
  84. yudai/gotty shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Share your terminal as a web application
    终端分享
  85. grafana/k6 shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A modern load testing tool, using Go and JavaScript - https://k6.io
    测试工具
  86. stretchr/testify shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A toolkit with common assertions and mocks that plays nicely with the standard library
  87. derailed/k9s shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    🐶 Kubernetes CLI To Manage Your Clusters In Style!
    K8S 相关
  88. joewalnes/websocketd shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Turn any program that uses STDIN/STDOUT into a WebSocket server. Like inetd, but for WebSockets.
  89. matryer/xbar shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Put the output from any script or program into your macOS Menu Bar (the BitBar reboot)
  90. grpc/grpc-go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The Go language implementation of gRPC. HTTP/2 based RPC
  91. v2fly/v2ray-core shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A platform for building proxies to bypass network restrictions.
    网络工具
  92. grafana/loki shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Like Prometheus, but for logs.
    日志服务
  93. filebrowser/filebrowser shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    📂 Web File Browser
    Web 项目
  94. uber-go/zap shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Blazing fast, structured, leveled logging in Go.
    知名日志库
  95. jaegertracing/jaeger shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    CNCF Jaeger, a Distributed Tracing Platform
  96. buger/goreplay shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    GoReplay is an open-source tool for capturing and replaying live HTTP traffic into a test environment in order to continuously test your system with real data. It can be used to increase confidence in code deployments, configuration changes and infrastructure changes.
  97. helm/charts shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    ⚠️(OBSOLETE) Curated applications for Kubernetes
  98. hoanhan101/ultimate-go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The Ultimate Go Study Guide
  99. cloudreve/Cloudreve shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    🌩 支持多家云存储的云盘系统 (Self-hosted file management and sharing system, supports multiple storage providers)
  100. chrislusf/seaweedfs shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    SeaweedFS is a fast distributed storage system for blobs, objects, files, and data lake, for billions of files! Blob store has O(1) disk seek, cloud tiering. Filer supports Cloud Drive, cross-DC active-active replication, Kubernetes, POSIX FUSE mount, S3 API, S3 Gateway, Hadoop, WebDAV, encryption, Erasure Coding.
  101. go-redis/redis shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Type-safe Redis client for Golang
  102. antonmedv/fx shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Terminal JSON viewer
  103. cayleygraph/cayley shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An open-source graph database
  104. vitessio/vitess shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Vitess is a database clustering system for horizontal scaling of MySQL.
  105. julienschmidt/httprouter shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A high performance HTTP request router that scales well
  106. kubernetes/kops shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Kubernetes Operations (kOps) - Production Grade k8s Installation, Upgrades and Management
  107. containers/podman shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Podman: A tool for managing OCI containers and pods.
  108. hashicorp/packer shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Packer is a tool for creating identical machine images for multiple platforms from a single source configuration.
  109. docker-slim/docker-slim shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    DockerSlim (docker-slim): Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)
  110. hyperledger/fabric shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Hyperledger Fabric is an enterprise-grade permissioned distributed ledger framework for developing solutions and applications. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.
  111. ipfs/go-ipfs shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    IPFS implementation in Go
  112. rakyll/hey shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    HTTP load generator, ApacheBench (ab) replacement
  113. wtfutil/wtf shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The personal information dashboard for your terminal
  114. greyireland/algorithm-pattern shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    算法模板,最科学的刷题方式,最快速的刷题路径,你值得拥有~
  115. google/cadvisor shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Analyzes resource usage and performance characteristics of running containers.
  116. grpc-ecosystem/grpc-gateway shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    gRPC to JSON proxy generator following the gRPC HTTP spec
  117. inancgumus/learngo shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    1000+ Hand-Crafted Go Examples, Exercises, and Quizzes
  118. authelia/authelia shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The Single Sign-On Multi-Factor portal for web apps
  119. flipped-aurora/gin-vue-admin shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    基于 vite+vue3+gin 搭建的开发基础平台(已完成 setup 语法糖版本),集成 jwt 鉴权,权限管理,动态路由,显隐可控组件,分页封装,多点登录拦截,资源权限,上传下载,代码生成器,表单生成器等开发必备功能。
  120. golang/dep shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Go dependency management tool experiment (deprecated)
  121. ahmetb/kubectx shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Faster way to switch between clusters and namespaces in kubectl
  122. txthinking/brook shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A cross-platform network tool designed for developers. 一个为开发者设计的跨平台网络工具.
  123. xtaci/kcptun shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A Stable & Secure Tunnel based on KCP with N:M multiplexing and FEC. Available for ARM, MIPS, 386 and AMD64。KCP プロトコルに基づく安全なトンネル。KCP 프로토콜을 기반으로 하는 보안 터널입니다。
  124. GoogleContainerTools/skaffold shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Easy and Repeatable Kubernetes Development
  125. bcicen/ctop shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Top-like interface for container metrics
  126. boltdb/bolt shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An embedded key/value database for Go.
  127. kubernetes/ingress-nginx shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    NGINX Ingress Controller for Kubernetes
  128. google/gvisor shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Application Kernel for Containers
  129. dutchcoders/transfer.sh shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Easy and fast file sharing from the command-line.
  130. revel/revel shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A high productivity, full-stack web framework for the Go language.
  131. ory/hydra shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    OpenID Certified™ OpenID Connect and OAuth Provider written in Go - cloud native, security-first, open source API security for your infrastructure. SDKs for any language. Works with Hardware Security Modules. Compatible with MITREid.
  132. pulumi/pulumi shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Pulumi - Universal Infrastructure as Code. Your Cloud, Your Language, Your Way 🚀
  133. charmbracelet/bubbletea shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A powerful little TUI framework 🏗
  134. CodisLabs/codis shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Proxy based Redis cluster solution supporting pipeline and scaling dynamically
  135. go-sql-driver/mysql shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Go MySQL Driver is a MySQL driver for Go's (golang) database/sql package
  136. snail007/goproxy shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    🔥 Proxy is a high performance HTTP(S) proxies, SOCKS5 proxies,WEBSOCKET, TCP, UDP proxy server implemented by golang. Now, it supports chain-style proxies,nat forwarding in different lan,TCP/UDP port forwarding, SSH forwarding.Proxy 是 golang 实现的高性能 http,https,websocket,tcp,socks5 代理服务器,支持内网穿透,链式代理,通讯加密,智能 HTTP,SOCKS5 代理,黑白名单,限速,限流量,限连接数,跨平台,KCP 支持,认证 API。
  137. aquasecurity/trivy shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Scanner for vulnerabilities in container images, file systems, and Git repositories, as well as for configuration issues and hard-coded secrets
  138. Netflix/chaosmonkey shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Chaos Monkey is a resiliency tool that helps applications tolerate random instance failures.
  139. cilium/cilium shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    eBPF-based Networking, Security, and Observability
  140. casbin/casbin shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An authorization library that supports access control models like ACL, RBAC, ABAC in Golang
  141. jmoiron/sqlx shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    general purpose extensions to golang's database/sql
  142. gravitational/teleport shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Certificate authority and access plane for SSH, Kubernetes, web apps, databases and desktops
  143. qax-os/excelize shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Go language library for reading and writing Microsoft Excel™ (XLAM / XLSM / XLSX / XLTM / XLTX) spreadsheets
  144. fogleman/primitive shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Reproducing images with geometric primitives.
  145. gizak/termui shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Golang terminal dashboard
  146. peterq/pan-light shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    百度网盘不限速客户端, golang + qt5, 跨平台图形界面
  147. AdguardTeam/AdGuardHome shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Network-wide ads & trackers blocking DNS server
  148. influxdata/telegraf shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The plugin-driven server agent for collecting & reporting metrics.
  149. emirpasic/gods shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    GoDS (Go Data Structures) - Sets, Lists, Stacks, Maps, Trees, Queues, and much more
  150. PuerkitoBio/goquery shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A little like that j-thing, only in Go.
  151. go-chi/chi shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    lightweight, idiomatic and composable router for building Go HTTP services
  152. go-martini/martini shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Classy web framework for Go
    知名 Go Web 框架
  153. golang/groupcache shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases.
    知名 Go 缓存库
  154. bettercap/bettercap shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    The Swiss Army knife for 802.11, BLE, IPv4 and IPv6 networks reconnaissance and MITM attacks.
  155. getlantern/lantern shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Lantern 官方版本下载 蓝灯 翻墙 代理 科学上网 外网 加速器 梯子 路由 lantern proxy vpn censorship-circumvention censorship gfw accelerator
  156. kubernetes/dashboard shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    General-purpose web UI for Kubernetes clusters
  157. micro/micro shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    API first development platform
  158. gopherjs/gopherjs shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A compiler from Go to JavaScript for running Go code in a browser
  159. halfrost/Halfrost-Field shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    ✍🏻 这里是写博客的地方 —— Halfrost-Field 冰霜之地
  160. containerd/containerd shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An open and reliable container runtime
  161. argoproj/argo-workflows shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Workflow engine for Kubernetes
  162. hashicorp/nomad shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Nomad is an easy-to-use, flexible, and performant workload orchestrator that can deploy a mix of microservice, batch, containerized, and non-containerized applications. Nomad is easy to operate and scale and has native Consul and Vault integrations.
  163. elastic/beats shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    :tropical_fish: Beats - Lightweight shippers for Elasticsearch & Logstash
  164. nats-io/nats-server shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    High-Performance server for NATS.io, the cloud and edge native messaging system.
  165. json-iterator/go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A high-performance 100% compatible drop-in replacement of "encoding/json"
  166. tomnomnom/gron shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Make JSON greppable!
  167. dgraph-io/badger shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Fast key-value DB in Go.
  168. ent/ent shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An entity framework for Go
  169. containrrr/watchtower shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A process for automating Docker container base image updates.
  170. dolthub/dolt shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Dolt – It's Git for Data
  171. talkgo/night shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Weekly Go Online Meetup via Bilibili | Go 夜读|通过 bilibili 在线直播的方式分享 Go 相关的技术话题,每天大家在微信/telegram/Slack 上及时沟通交流编程技术话题。
  172. geektutu/7days-golang shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    7 days golang programs from scratch (web framework Gee, distributed cache GeeCache, object relational mapping ORM framework GeeORM, rpc framework GeeRPC etc) 7 天用 Go 动手写/从零实现系列
  173. FiloSottile/age shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A simple, modern and secure encryption tool (and Go library) with small explicit keys, no config options, and UNIX-style composability.
  174. ardanlabs/gotraining shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Go Training Class Material :
  175. google/grumpy shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Grumpy is a Python to Go source code transcompiler and runtime.
  176. go-playground/validator shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    :100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
  177. rqlite/rqlite shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    The lightweight, distributed relational database built on SQLite
  178. milvus-io/milvus shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An open-source vector database for scalable similarity search and AI applications.
  179. GoogleContainerTools/kaniko shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Build Container Images In Kubernetes
  180. thanos-io/thanos shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Highly available Prometheus setup with long term storage capabilities. A CNCF Incubating project.
  181. dgrijalva/jwt-go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:
  182. golangci/golangci-lint shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Fast linters Runner for Go
  183. tidwall/gjson shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Get JSON values quickly - JSON parser for Go
  184. git-lfs/git-lfs shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Git extension for versioning large files
  185. sqshq/sampler shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Tool for shell commands execution, visualization and alerting. Configured with a simple YAML file.
  186. OpenDiablo2/OpenDiablo2 shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An open source re-implementation of Diablo 2
  187. goreleaser/goreleaser shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Deliver Go binaries as fast and easily as possible
  188. mailhog/MailHog shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Web and API based SMTP testing
    SMTP 工具
  189. github/gh-ost shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    GitHub's Online Schema Migrations for MySQL

Go 练手小项目

2020-12-21

开始在学习 Go 语言了,先在 GitHub 上找一批小项目用来学习。

  1. julienschmidt/httprouter shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A high performance HTTP request router that scales well
  2. golang/groupcache shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases.
  3. robfig/cron shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    a cron library for go
  4. jroimartin/gocui shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Minimalist Go package aimed at creating Console User Interfaces.
  5. tylertreat/comcast shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Simulating shitty network connections so you can build better systems.
  6. pkg/errors shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Simple error handling primitives
  7. schachmat/wego shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    weather app for the terminal
  8. teh-cmc/go-internals shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    A book about the internals of the Go programming language.
  9. simeji/jid shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    json incremental digger
  10. patrickmn/go-cache shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
  11. wercker/stern shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    ⎈ Multi pod and container log tailing for Kubernetes
  12. allegro/bigcache shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Efficient cache for gigabytes of data written in Go.
  13. microsoft/ethr shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Ethr is a Comprehensive Network Measurement Tool for TCP, UDP & ICMP.
  14. samber/lo shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    💥 A Lodash-style Go library based on Go 1.18+ Generics (map, filter, contains, find...)
  15. goproxyio/goproxy shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A global proxy for Go modules.
  16. eranyanay/1m-go-websockets shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    handling 1M websockets connections in Go
  17. fogleman/nes shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    NES emulator written in Go.
  1. inconshreveable/ngrok shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    Introspected tunnels to localhost
  2. sirupsen/logrus shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Structured, pluggable logging for Go.
  3. tmrts/go-patterns shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Curated list of Go design patterns, recipes and idioms
  4. gorilla/websocket shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A fast, well-tested and widely used WebSocket implementation for Go.
  5. gorilla/mux shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A powerful HTTP router and URL matcher for building Go web servers with 🦍
  6. julienschmidt/httprouter shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A high performance HTTP request router that scales well
  7. rakyll/hey shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    HTTP load generator, ApacheBench (ab) replacement
  8. ahmetb/kubectx shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Faster way to switch between clusters and namespaces in kubectl
  9. charmbracelet/bubbletea shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A powerful little TUI framework 🏗
  10. jmoiron/sqlx shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    general purpose extensions to golang's database/sql
  11. emirpasic/gods shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w
    GoDS (Go Data Structures) - Sets, Lists, Stacks, Maps, Trees, Queues, and much more
  12. PuerkitoBio/goquery shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A little like that j-thing, only in Go.
  13. go-martini/martini shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Classy web framework for Go
  14. golang/groupcache shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases.
  15. FiloSottile/age shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    A simple, modern and secure encryption tool (and Go library) with small explicit keys, no config options, and UNIX-style composability.
  16. dgrijalva/jwt-go shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:
  17. tidwall/gjson shields.io:github/stars shields.io:github/languages/code-size shields.io:github/commit-activity/w shields.io:github/license
    Get JSON values quickly - JSON parser for Go

gvm: Golang 版本管理

2020-12-19

https://github.com/moovweb/gvm stars license language

安装

bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

使用

source ~/.gvm/scripts/gvm

gvm listall

# gvm 默认从 github 克隆代码到本地,然后进行编译
# 可以采用 gitee 仓库加速
git clone git@gitee.com:mirrors/go ~/.gvm/archive/go

gvm install go1.16

gvm list
gvm use go1.16

go version
# go version go1.16 linux/amd64

Golang 结构体

2020-12-18
package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type Address struct {
    City    string `json:"city"`
    Country string `json:"country"`
}

type User struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

type Person struct {
    Name    string  `json:"name"`
    Age     int     `json:"age"`
    Address Address `json:"address"`
    // 这么写,JSON 会多一层
    // User    `json:"user"`
    User
}

func (p Person) SayHello() {
    fmt.Println("Hello, my name is", p.Name)
}

func main() {
    person := Person{
        Name: "Bob",
        Age:  30,
        Address: Address{
            City:    "London",
            Country: "UK",
        },
        User: User{
            Username: "bob1999",
            Password: "pa55w0rd",
        },
    }

    // 属性操作
    fmt.Println("Name:", person.Name)
    fmt.Println("Age:", person.Age)
    fmt.Println("City:", person.Address.City)
    fmt.Println("Country:", person.Address.Country)
    fmt.Println("Username:", person.Username)
    fmt.Println("Password:", person.Password)
    fmt.Printf("%+v\n", person)
    fmt.Printf("%#v\n", person)

    // 方法调用
    person.SayHello()

    // 通过反射获取标签内容
    t := reflect.TypeOf(person)
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        tag := field.Tag.Get("json")
        fmt.Println(field.Name, ":", tag)
    }

    // JSON 序列化
    jsonData, err := json.Marshal(person)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("JSON:", string(jsonData))
}

// Name: Bob
// Age: 30
// City: London
// Country: UK
// Username: bob1999
// Password: pa55w0rd
// main.Person{name:"Bob", age:30, address:main.Address{city:"London", country:"UK"}, User:main.User{username:"bob1999", password:"pa55w0rd"}}

其他知识点:

  1. 字段名大小写问题:首字母小写的话,只有本包可以访问

  2. Zero-value Struct

type Fruit struct {
    name string
}
var apple Fruit
fmt.Println(apple) // {}
  1. new 关键字
package main

import "fmt"

type Employee struct {
    Name string
    Age  int
}

func main() {
    p := new(Employee)
    fmt.Println(p) // &{ 0}

    var p2 Employee
    fmt.Println(p2) // { 0}

    p3 := Employee{"Me", 30}
    fmt.Println(p3) // {Me 30}
}
  1. struct 字面量
type Person struct {
    Name  string
    Age   int
    Email string
}

p1 := Person{
    Name:  "Alice",
    Age:   25,
    Email: "alice@example.com",
}
p2 := Person {"Alice", 25, "alice@example.com"}
  1. 指针

  2. 匿名结构体

package main

import (
    "fmt"
)

func main() {
    user := struct {
        username string
    }{
        username: "admin",
    }
    fmt.Printf("%+v\n", user)
    // {username:admin}
    fmt.Printf("%#v\n", user)
    // struct { username string }{username:"admin"}
    fmt.Printf("%v\n", user)
    // {admin}
    fmt.Println(user)
    // {admin}
}

场景:

  1. 定义一个临时结构体接收反序列化数据
  2. 内嵌结构体

  3. 匿名属性(或者应该叫啥,我也不知道)

  4. 内嵌类型不能重复,

  5. 前面的例子可以看出,可以直接访问匿名属性(结构体)内部属性,
  6. 但是如果同名就只能老老实实通过类型名字来访问了
package main

import (
    "fmt"
)

type Book struct {
    string // book name (anno field)

    // syntax error: unexpected [, expected field name or embedded type
    // []Author
    Authors []Author // slice of authors

    Publisher
}

type Author struct {
    string // author name (anno field)
}

type Publisher struct {
    string // publisher name (anno field)
}

func main() {
    p := Book{
        string: "Learning Python",
        Authors: []Author{
            {string: "Stanley B.Lippman"},
            {string: "Josée LaJoie"},
            {"Barbara E.Moo"},
        },
        Publisher: Publisher{"人民邮电出版社"},
    }
    p.string = "C++ Primer" // change attr

    fmt.Println(p)
    fmt.Printf("%v\n", p)
    fmt.Printf("%+v\n", p)
    fmt.Printf("%#v\n", p)
    fmt.Printf("%v\n", p.string)
    fmt.Printf("%v\n", p.Authors[0].string)
    fmt.Printf("%v\n", p.Publisher)
    fmt.Printf("%v\n", p.Publisher.string)
}

// {C++ Primer [{Stanley B.Lippman} {Josée LaJoie} {Barbara E.Moo}] {人民邮电出版社}}
// {C++ Primer [{Stanley B.Lippman} {Josée LaJoie} {Barbara E.Moo}] {人民邮电出版社}}
// {string:C++ Primer Authors:[{string:Stanley B.Lippman} {string:Josée LaJoie} {string:Barbara E.Moo}] Publisher:{string:人民邮电出版社}}
// main.Book{string:"C++ Primer", Authors:[]main.Author{main.Author{string:"Stanley B.Lippman"}, main.Author{string:"Josée LaJoie"}, main.Author{string:"Barbara E.Moo"}}, Publisher:main.Publisher{string:"人民邮电出版社"}}
// C++ Primer
// Stanley B.Lippman
// {人民邮电出版社}
// 人民邮电出版社
  1. 将函数通过属性的方式定义
type FoodNameGetter func(string) string

type Food struct {
    name   string
    getter FoodNameGetter // declare function
}

pizza := Food{
    name: "Pizza",
    getter: func(name string) string { // declare function body
        return "This is " + name + "."
    },
}
  1. 结构体比较

如果类型和值相同,就等于。

package main

import "fmt"

type Teacher struct {
    name string
}

type Student struct {
    name string
}

func main() {
    s1 := Student{"John"}
    s2 := Student{"John"}
    fmt.Println(s1 == s2) // true

    // invalid operation: s1 == t1 (mismatched types Student and Teacher)
    // t1 := Teacher{"John"}
    // fmt.Println(s1 == t1)
}

参考资料与拓展阅读

Go 几个特殊用法

2020-12-18

点后直接括号

  1. type assertion 类型断言
  2. type switch 类型判断

Golang 是强类型的语言,这两种语法都是只对 interface{} 有效。

package main

import "fmt"

func test(value interface{}) {
    switch value.(type) {
    case string:
        fmt.Printf("%#v\n", value)
    }
}

func test2(value interface{}) {
    v1, ok := value.([]byte)
    fmt.Printf("%#v, %#v\n", v1, ok)

    v2, ok := value.(string)
    fmt.Printf("%#v, %#v\n", v2, ok)
}

func main() {
    a := "abc"
    test(a)
    test2(a)
}

Golang 数组操作

2020-12-15

声明

# array
[length]Type
[length]Type{v1, v2, ..., vn}
[...]Type{v1, v2, ..., vn}

# slice
[]Type
[]Type{v1, v2, ..., vn}
make([]Type, length)
make([]Type, length, capacity)

我想尝试动态创建数组(通过 arrLen 变量),没有找到方法,可能这就是静态类型语言吧。
所以,数组必须在写代码的时候就明确长度。否则就应该用切片。

此外,数组应该算是值类型。赋值的时候,会完全复制一份,传参也是一样。

Slice 等于数组指针 + 长度 + 容量。

package main

import "fmt"

func main() {
    var a []int
    fmt.Printf("%#v \t%d %d\n", a, len(a), cap(a)) // []int(nil) 0 0

    b := []int{1, 2, 3}
    fmt.Printf("%#v \t%d %d\n", b, len(b), cap(b)) // []int{1, 2, 3} 3 3

    var c [3]int
    fmt.Printf("%#v \t%d %d\n", c, len(c), cap(c)) // [3]int{0, 0, 0} 3 3

    d := [...]int{1, 2, 3}
    fmt.Printf("%#v \t%d %d\n", d, len(d), cap(d)) // [3]int{1, 2, 3} 3 3

    d2 := [...]int{3: 100}
    fmt.Printf("%#v \t%d %d\n", d2, len(d2), cap(d2)) // [4]int{0, 0, 0, 100} 4 4

    e := d[:]
    fmt.Printf("%#v \t%d %d\n", e, len(e), cap(e)) // []int{1, 2, 3} 3 3

    // 动态创建切片
    f := make([]int, 3, 10)
    fmt.Printf("%#v \t%d %d\n", f, len(f), cap(f)) // []int{0, 0, 0} 3 10

    // new 返回指针
    g := new([]int)
    fmt.Printf("%#v \t%d %d\n", g, len(*g), cap(*g)) // &[]int(nil) 0 0

    h := new([3]int)
    fmt.Printf("%#v \t%d %d\n", h, len(*h), cap(*h)) // &[]int{0, 0, 0} 3 3

    type User struct {
        Username string
        Password string
    }
    users := []User{
        {"a", "pass1"},
        {"b", "pass2"},  // 这样分行写的话,不能省略这个逗号
    }
    fmt.Printf("%+v \t%d %d\n", users, len(users), cap(users))
    // [{Username:a Password:pass1} {Username:b Password:pass2}] 2 2
}

索引

a[n]
a[n:m]
a[n:]
a[:m]
a[:]

// 索引为负数
// invalid argument: index -1 (constant of type int) must not be negative

// 索引越界
// invalid argument: array index 10 out of bounds [0:5]

遍历

for i := 0; i < len(arr); i++ {
    val := arr[i]
    // ...
}

for i, val := range arrayVar {
    // ...
}

// 如果只有一个变量接收遍历的值,那么这个变量将是 index
// 这个地方总是容易写错,要小心
for i := range arrayVar {
    val := arrayVar[i]
    // ...
}

复制

s1 := []int{1, 3, 6}
s2 := append([]int{}, s1...)
fmt.Printf("%#v %p\n", s1, s1)
fmt.Printf("%#v %p\n", s2, s2)

s3 := make([]int, len(s1))
copy(s3, s1)
fmt.Printf("%#v %p\n", s3, s3)

注意:copy 复制内容的长度以 src,dst 中较小的长度为准。

删除

a := []int{1, 2, 3, 4, 5, 6, 7}
// del a[3]
a = append(a[:3], a[4:]...)

插入

// 在尾部插入一个
a = append(a, ele)

// 在尾部插入一个数组或切片
a = append(a, arr...)

// copy 也是一种方法
a := [10]int{1, 2, 3}
b := []int{4, 5, 6}
copy(a[3:], b)

// WRONG!
a := []int{1, 2, 3, 5, 6, 7}
tmp := a[:3]
tmp = append(tmp, 4)
fmt.Println(a)  // [1 2 3 4 6 7]

func insert(slice []int, index int, num int) []int {
    rest_len := len(slice) - index
    tmp := make([]int, rest_len, len(slice)+1)
    copy(tmp, slice[:index])
    tmp[index] = num
    tmp = append(tmp, slice[index:]...)
    return tmp
}

弹出

数组长度固定无法执行“弹出”操作,但是可以删除其中的一个节点。

nums := []int{1, 2, 3, 4}
first := nums[0]
nums = nums[1:]
last := nums[len(nums) - 1]
nums := nums[:len(nums) - 1]

合并

package main

import "fmt"

func main() {
    a := []int{1, 2, 3}
    b := []int{1, 2, 3}
    c := [3]int{4, 5, 6}
    d := [3]int{4, 5, 6}

    // 切片合并
    e := append(a, b...)
    fmt.Printf("%#v, %#v, %#v\n", a, b, e)

    f := append(c[:], d[:]...)
    fmt.Printf("%#v, %#v, %#v\n", c, d, f)

    g := [6]int{}
    for i, v := range a {
        g[i] = v
    }
    length := len(a)
    for i, v := range a {
        g[i+length] = v
    }
    fmt.Printf("%#v\n", g)

    h := [6]int{}
    // func copy(dst, src []Type) int
    copy(h[:], a)
    fmt.Printf("%#v\n", h)
    copy(h[3:], a)
    fmt.Printf("%#v\n", h)
}

排序

package main

import (
    "fmt"
    "sort"
)

func main() {
    nums := []int{9, 5, 2, 7, 1}
    sort.Ints(nums)
    fmt.Println(nums)
}
  • sort.Strings
  • sort.Float64s

godoc 命令

2020-12-11
godoc -http=:6060 -index -play -timestamps -v

# 如果在 go 模块目录执行,会列出本地依赖包的文档
# using module mode; GOMOD=xxx.mod

go doc fmt
go doc fmt.Println
go doc fmt Println
go doc -src fmt Println

# 查看本地包文档
go doc github.com/astaxie/beego
go doc github.com/astaxie/beego Listen
go doc -all github.com/astaxie/bee

PS: 关于 Go 项目文档

  1. 紧挨者 package, const, type, func 等关键字的注释

问题

C:\Users\admin>godoc -http=:6060 -index -play -timestamps -v
'godoc' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

新版本不再自带 godoc 工具,需要另外安装:

go install golang.org/x/tools/cmd/godoc@latest

Go 运算符

2020-12-09
  • 算术运算符 Arithmetic Operators
  • + - * / %
  • ++ --
  • 比较运算符 Comparison Operators
  • > < == != >= <=
  • 逻辑运算符 Logical Operators
  • && || !
  • 按位运算符 Bitwise Operators
  • & 按位与 bitwise AND
  • | 按位或 bitwise OR
  • ^ 按位取反 bitwise NOT / 按位异或 bitwise XOR
  • 注意:其他很多语言都是采用 ~ 表示取反
  • &^ bit clear (AND NOT)
  • << 左移,>> 右移
  • 赋值运算符 Assignment Operators
  • = 以及算术运算赋值,位运算赋值
  • 其他运算符 Misc Operators
  • * 指针,& 取地址,<- 通道接收

Operator precedence

| 优先级 | 运算符 |
| ------ | ------------------------------ | ----- | --- |
| 5 | * / % << >> & &^ |
| 4 | + - | ^ |
| 3 | 关系运算符 |
| 2 | && |
| 1 | | | |

示例

package main

import "fmt"

func main() {
    var a uint8 = 0b_0011_1100 // 60
    var b uint8 = 0b_0000_1111 // 15

    fmt.Printf("      a %08b (%d)\n", a, a)
    fmt.Printf("      b %08b (%d)\n", b, b)
    fmt.Println()

    fmt.Printf("    NOT %08b 非(NOT a)\n", (^a))
    fmt.Println()

    fmt.Printf("    AND %08b 与\n", (a & b))
    fmt.Printf("     OR %08b 或\n", (a | b))
    fmt.Printf("    XOR %08b 异或\n", (a ^ b))
    fmt.Println()

    fmt.Printf("   NAND %08b 与非\n", ^(a & b))
    fmt.Printf("    NOR %08b 或非\n", ^(a | b))
    fmt.Printf("   XNOR %08b 同或(异或非)\n", ^(a ^ b))
    fmt.Println()

    fmt.Printf("AND NOT %08b BitClear\n", (a &^ b))
    // fmt.Printf("AND NOT %08b BitClear\n", (a & (^b)))

    // 格式化工具会将 ^ 和右操作数放在一起
    // 这一点和 &^ 不同,应该是由于 Golang Spec 中,将 &^ 当成一个操作符
    // 本质上,没有什么区别,都是先按位取反,再按位与或
    fmt.Printf(" OR NOT %08b Useless\n", (a | ^b))
    // fmt.Printf(" OR NOT %08b Useless\n", (a | (^b)))
}
//       a 00111100 (60)
//       b 00001111 (15)

//     NOT 11000011 非(NOT a)

//     AND 00001100 与
//      OR 00111111 或
//     XOR 00110011 异或

//    NAND 11110011 与非
//     NOR 11000000 或非
//    XNOR 11001100 同或(异或非)

// AND NOT 00110000 BitClear
//  OR NOT 11111100 Useless

参考资料与拓展阅读

Golang strings.Builder

2020-12-08

https://github.com/golang/go/blob/master/src/strings/builder.go

主要的作用是频繁拼接字符串,相比字符串拼接操作符(+)或者 fmt.SPrintf 效率更高。

实例

package main

import (
    "fmt"
    "strings"
)

func main() {
    var builder strings.Builder
    builder.WriteString("Hello")
    builder.WriteString(", ")
    builder.WriteString("World!")
    result := builder.String()
    fmt.Println(result)
}

方法

  • func (b *Builder) String() string
  • func (b *Builder) Len() int { return len(b.buf)
  • func (b *Builder) Cap() int { return cap(b.buf)
  • func (b *Builder) Reset() 内容重置
  • func (b *Builder) Grow(n int) 预分配空间,正确使用可以提升程序执行效率
  • func (b *Builder) Write(p []byte) (int, error)
  • func (b *Builder) WriteByte(c byte) error
  • func (b *Builder) WriteRune(r rune) (int, error)
  • func (b *Builder) WriteString(s string) (int, error)

源码

实际上就是针对 []byte 的一个封装。

// A Builder is used to efficiently build a string using Write methods.
// It minimizes memory copying. The zero value is ready to use.
// Do not copy a non-zero Builder.
type Builder struct {
    addr *Builder // of receiver, to detect copies by value
    buf  []byte
}

func (b *Builder) copyCheck() {
    if b.addr == nil {
        // This hack works around a failing of Go's escape analysis
        // that was causing b to escape and be heap allocated.
        // See issue 23382.
        // TODO: once issue 7921 is fixed, this should be reverted to
        // just "b.addr = b".
        b.addr = (*Builder)(noescape(unsafe.Pointer(b)))
    } else if b.addr != b {
        panic("strings: illegal use of non-zero Builder copied by value")
    }
}

// WriteString appends the contents of s to b's buffer.
// It returns the length of s and a nil error.
func (b *Builder) WriteString(s string) (int, error) {
    b.copyCheck()
    b.buf = append(b.buf, s...)
    return len(s), nil
}
  • addr 指向自己的指针,不知道干什么用
  • buf 是 buffer,缓冲区,用于存储 build 出来的字符串
  • 通过缓冲区做存储,避免频繁创建字符串对象,减少内存分配和垃圾回收

性能测试

BenchmarkStrPlus-20             100000000               11.11 ns/op            0 B/op          0 allocs/op
BenchmarkSprintf-20             12129922               101.5 ns/op            48 B/op          3 allocs/op
BenchmarkStrJoin-20             45257742                24.47 ns/op           16 B/op          1 allocs/op
BenchmarkStrBuilder-20          38868284                36.31 ns/op           24 B/op          2 allocs/op
BenchmarkByteBuf-20             22016934                53.34 ns/op           80 B/op          2 allocs/op
BenchmarkByteSlice-20           31495318                36.13 ns/op           24 B/op          2 allocs/op
BenchmarkByteSlice2-20          39563612                32.18 ns/op           24 B/op          2 allocs/op

BenchmarkStrPlusBatch-20         7331364               170.0 ns/op           112 B/op          6 allocs/op
BenchmarkSprintfBatch-20         1481492               823.2 ns/op           328 B/op         20 allocs/op
BenchmarkStrJoinBatch-20        19598844                59.78 ns/op           32 B/op          1 allocs/op
BenchmarkStrBuilderBatch-20     13560961                87.39 ns/op           56 B/op          3 allocs/op
BenchmarkByteBufBatch-20        10693280                97.61 ns/op           96 B/op          2 allocs/op
BenchmarkByteSliceBatch-20      12115166                95.27 ns/op           56 B/op          3 allocs/op
BenchmarkByteSlice2Batch-20     13136418                90.53 ns/op           56 B/op          3 allocs/op

fmt.Sprintf 用来做字符串拼接的话,性能总是最差。
此外,如果只是简单的两个字符串相加,直接加号拼接性能最好。
否则就根据情况,选用其他方案比较好。

Golang Bytes 相关操作

2020-12-08

byte 实际上是 uint8 的别名,[]byte 也就是 uint8 切片。

常见操作

package main

import (
    "bytes"
    "encoding/hex"
    "fmt"
    "strconv"
)

func main() {
    // 1. 转换
    str1 := "HELLO WORLD"
    bytes0 := []byte(str1) // string to bytes
    str2 := string(bytes0) // bytes to string
    fmt.Printf("%#v\n", bytes0)
    // []byte{0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x20, 0x57, 0x4f, 0x52, 0x4c, 0x44}
    fmt.Println(str1, bytes0, str2)
    // HELLO WORLD [72 69 76 76 79 32 87 79 82 76 68] HELLO WORLD

    // 2. 连接
    bytes1 := []byte("HELLO ")
    bytes2 := []byte("WORLD")
    bytes3 := append(bytes1, bytes2...)
    fmt.Println(bytes3)
    // [72 69 76 76 79 32 87 79 82 76 68]

    // 3. 拷贝
    bytes4 := make([]byte, len(bytes3))
    copy(bytes4, bytes3)
    fmt.Println(bytes4)
    // [72 69 76 76 79 32 87 79 82 76 68]

    // 4. 长度和容量
    fmt.Println(len(bytes4), cap(bytes4)) // 11 11

    // 5. 截取
    bytes5 := bytes4[7:10]
    fmt.Println(bytes5) // [79 82 76]

    // 6. 比较
    bytes6 := []byte("HELLO WORLD")
    fmt.Println(bytes.Equal(bytes4, bytes6)) // true

    // 7. 遍历
    for i := 0; i < len(bytes6); i++ {
        fmt.Printf("%d ", bytes6[i])
    }
    fmt.Println()
    // 72 69 76 76 79 32 87 79 82 76 68

    // 8. 转化为数字
    bytes7 := []byte("12345")
    num, _ := strconv.Atoi(string(bytes7))
    fmt.Println(num) // 12345

    // 9. 转化为16进制字符串
    bytes8 := []byte("HELLO WORLD")
    hexStr := hex.EncodeToString(bytes8)
    fmt.Println(hexStr) // 48454c4c4f20574f524c44
}

输出

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func main() {
    buf := new(bytes.Buffer) // *bytes.Buffer
    // func (b *Buffer) WriteString(s string) (n int, err error)
    buf.WriteString("HELLO ")
    buf.WriteString("WORLD")

    fmt.Println(string(buf.Bytes()))
    fmt.Println(buf.String()) // 相同

    // ========================================

    w := os.Stdout // *os.File
    // func (f *File) Write(b []byte) (n int, err error)
    // func (f *File) WriteString(s string) (n int, err error)
    w.WriteString("HELLO ")

    n, err := io.WriteString(w, "WORLD\n")
    if err != nil {
        panic(err)
    }
    fmt.Printf("n: %d\n", n)
}

利用 reflect 实现 bytes / string 转换

参考:https://www.sobyte.net/post/2022-01/go-string-bytes/

func String2Bytes(s string) []byte {
    sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
    bh := reflect.SliceHeader{
        Data: sh.Data,
        Len:  sh.Len,
        Cap:  sh.Len,
    }
    return *(*[]byte)(unsafe.Pointer(&bh))
}

func Bytes2String(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

Golang 字符串 string

2020-12-08
package main

func main() {
    a := "hello 世界"
    fmt.Printf("%#v (%d)\n", a, len(a))
    // "hello 世界" (12)

    // 按 rune ForRange 循环
    for k, v := range a {
        fmt.Printf("%#4v. %#6v (%T)\n", k, v, v)
    }
    // 按 byte 索引取值
    fmt.Printf("a[0]: %#6v (%T)\n", a[0], a[0])
    fmt.Printf("a[6]: %#6v (%T)\n", a[6], a[6])
    //    0.    104 (int32)
    //    1.    101 (int32)
    //    2.    108 (int32)
    //    3.    108 (int32)
    //    4.    111 (int32)
    //    5.     32 (int32)
    //    6.  19990 (int32)
    //    9.  30028 (int32)
    // a[0]:   0x68 (uint8)
    // a[6]:   0xe4 (uint8)

    b := []byte(a)
    fmt.Printf("%#v\n", b)
    // []byte{0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c}

    c := []rune(a)
    fmt.Printf("%#v\n", c)
    // []int32{104, 101, 108, 108, 111, 32, 19990, 30028}
}
  • len(s)
  • strings.Join(s1, s2) string 连接字符串
  • strings.ContainsRune(s, rune) bool
  • strings.Contains(s, substr) bool 子串包含判断
    注意:任何字符串都包含空字符串
  • strings.ContainsAny(s, chars string) bool 字符包含判断
  • strings.Index(s, substr) int 定位(Rabin-Karp 算法)
  • strings.Count(s, substr) int 字符计算(Rabin-Karp 算法)
    注意:任何字符串包含 n + 1 个空字符串
  • strings.HasPrefix(s, substr) bool startswith
  • strings.HasSuffix(s, substr) bool endswith
  • strings.Compare(s1, s2) 大于 1 / 小于 -1 / 等于 0
  • strings.Repeat(s, num) string 替换子串
  • strings.Replace(s, substr, replacement, num) string
  • strings.EqualFold(s1, s2) bool 忽略大小写等于判断
  • strings.Fields(s) 用空白字符(空格、换行、tab)将字符串切割成字串
  • strings.Split(s, sep string) []string 切割字符串
  • strings.SplitAfter(s, sep string) []string 切割字符串(包含分隔符)
  • strings.SplitAfterN(s, sep string, n int) []string
  • strings.SplitN(s, sep string, n int) []string

参考 Golang strings 包。

字符串连接:

  • +, +=
  • fmt.Sprintf
  • strings.Join
  • bytes.Buffer
var b bytes.Buffer
b.WriteString("hello")
b.WriteString(" world")
fmt.Println(b.String())
  • strings.Builder
var sb strings.Builder
sb.WriteString("hello")
sb.WriteString(" world")
fmt.Println(sb.String())

Golang: 正则表达式

2020-12-06

Compile 系列

func Compile(expr string) (*Regexp, error)
func CompilePOSIX(expr string) (*Regexp, error)
func MustCompile(str string) *Regexp
func MustCompilePOSIX(str string) *Regexp

函数名称中的 Must 表示:如果正则错误,直接 panic

Match 系列

func (re *Regexp) Match(b []byte) bool
func (re *Regexp) MatchReader(r io.RuneReader) bool
func (re *Regexp) MatchString(s string) bool

Find 系列

func (re *Regexp) Find(b []byte) []byte
func (re *Regexp) FindAll(b []byte, n int) [][]byte
func (re *Regexp) FindAllIndex(b []byte, n int) [][]int
func (re *Regexp) FindAllString(s string, n int) []string
func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte
func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int
func (re *Regexp) FindIndex(b []byte) (loc []int)
func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)
func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int
func (re *Regexp) FindString(s string) string
func (re *Regexp) FindStringIndex(s string) (loc []int)
func (re *Regexp) FindStringSubmatch(s string) []string
func (re *Regexp) FindStringSubmatchIndex(s string) []int
func (re *Regexp) FindSubmatch(b []byte) [][]byte
func (re *Regexp) FindSubmatchIndex(b []byte) []int

其实好记,Find(All)?(String)?(Submatch)?(Index)? 一组合就有 16 种了,再加上两个 FindReader 方法。

Replace 系列

func (re *Regexp) ReplaceAll(src, repl []byte) []byte
func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
func (re *Regexp) ReplaceAllString(src, repl string) string
func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string

其他

func (re *Regexp) Copy() *Regexp // DEPRECATED
func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
func (re *Regexp) LiteralPrefix() (prefix string, complete bool)
func (re *Regexp) Longest()
func (re *Regexp) NumSubexp() int
func (re *Regexp) Split(s string, n int) []string
func (re *Regexp) String() string
func (re *Regexp) SubexpIndex(name string) int
func (re *Regexp) SubexpNames() []string

四个封装方法

func Match(pattern string, b []byte) (matched bool, err error)
func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
func MatchString(pattern string, s string) (matched bool, err error)
func QuoteMeta(s string) string

示例

func main() {
    text := "Hello, 2021! The year 2020 was great, but 2021 will be even better."

    pattern := `\b\d{4}\b` // 匹配四个数字的单词

    regex, err := regexp.Compile(pattern)
    if err != nil {
        fmt.Println("Error compiling regex:", err)
        return
    }

    matches := regex.FindAllString(text, -1)
    for _, match := range matches {
        fmt.Println(match)
    }
}

Output:

2021
2020
2021

Golang:new 和 make

2020-12-05
$ go doc builtin.new
package builtin // import "builtin"

func new(Type) *Type
    The new built-in function allocates memory. The first argument is a type,
    not a value, and the value returned is a pointer to a newly allocated zero
    value of that type.

$ go doc builtin.make
package builtin // import "builtin"

func make(t Type, size ...IntegerType) Type
    The make built-in function allocates and initializes an object of type
    slice, map, or chan (only). Like new, the first argument is a type, not a
    value. Unlike new, make's return type is the same as the type of its
    argument, not a pointer to it. The specification of the result depends on
    the type:

        Slice: The size specifies the length. The capacity of the slice is
        equal to its length. A second integer argument may be provided to
        specify a different capacity; it must be no smaller than the
        length. For example, make([]int, 0, 10) allocates an underlying array
        of size 10 and returns a slice of length 0 and capacity 10 that is
        backed by this underlying array.
        Map: An empty map is allocated with enough space to hold the
        specified number of elements. The size may be omitted, in which case
        a small starting size is allocated.
        Channel: The channel's buffer is initialized with the specified
        buffer capacity. If zero, or the size is omitted, the channel is
        unbuffered.
  • func new(Type) *Type
  • func make(t Type, size ...IntegerType) Type

new 和 make 的区别

  1. new 没有类型限制,make 只能用来分配和初始化 slice,map,chan。
  2. new 返回指针,make 返回引用(引用类型的值)。
  3. new 会将分配的空间置零(对应类型的零值),make 则可以类型初始化,比如 slice 的长度和容量。
package main

import "fmt"

type User struct {
    Name string
}

type Addr struct{}

func main() {
    user1 := new(User)
    user2 := new(User)
    fmt.Printf("%#v (%p) %d\n", user1, user1, &user1)
    fmt.Printf("%#v (%p) %d\n", user2, user2, &user2)
    fmt.Printf("user1 == user2 : %#v\n", user1 == user2)

    addr1 := new(Addr)
    addr2 := new(Addr)
    fmt.Printf("%#v (%p) %d\n", addr1, addr1, &addr1)
    fmt.Printf("%#v (%p) %d\n", addr2, addr2, &addr2)
    fmt.Printf("addr1 == addr2 : %#v\n", addr1 == addr2)
}
&main.User{Name:""} (0xc00006a250) 824633745448
&main.User{Name:""} (0xc00006a260) 824633745456
user1 == user2 : false
&main.Addr{} (0xf61438) 824633745472
&main.Addr{} (0xf61438) 824633745480
addr1 == addr2 : true

注意上面这一点,空 struct 多次 new 出的指针完全相同。暂时没有想明白这样设计的好处。

Go 关键字

2020-12-05

25 个关键字

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var

声明 (4)

  1. var 变量
  2. const 常量
  3. type 类型
  4. func 函数

并发相关 (3)

  1. go 并发
  2. chan 信道
  3. select 分支

类型 (3)

  1. interface 接口
  2. map 映射
  3. struct 结构体

流程控制 (3 + 4 + 6)

  1. defer 延迟执行
  2. goto 跳转
  3. return 返回

循环 (4)

  1. for
  2. continue
  3. break
  4. range 用于读取 slice、map、channel 数据

分支 (6)

  1. if
  2. else
  3. switch
  4. case
  5. default
  6. fallthrough

包 (2)

  1. package
  2. import

39 个预定义标识符

Types:
    any bool byte comparable
    complex64 complex128 error float32 float64
    int int8 int16 int32 int64 rune string
    uint uint8 uint16 uint32 uint64 uintptr

Constants:
    true false iota

Zero value:
    nil

Functions:
    append cap close complex copy delete imag len
    make new panic print println real recover

值 (4)

  1. true
  2. false
  3. iota
  4. nil

类型 (20 + 2)

int (10)

  1. int
  2. int8
  3. int16
  4. int32
  5. int64
  6. uint
  7. uint8
  8. uint16
  9. uint32
  10. uint64

complex (2)

  1. complex64
  2. complex128

float (2)

  1. float32
  2. float64

字符与字符串 (3)

  1. byte => uint8
  2. rune => int32
  3. string

泛型相关 (2) Go1.18+

  1. any
  2. comparable

其他 (3)

  1. bool
  2. uintptr 指针
  3. error 一个内置的 interface

Builtin 函数 (15)

  1. append
  2. delete
  3. close

  4. cap

  5. len

  6. copy

  7. make

  8. new

  9. panic

  10. recover

  11. print

  12. println

  13. real

  14. imag
  15. complex

Go 模板

2020-12-01

fmt.Sprintf 字符串格式化

tpl := `[%s] Your verify code is %s.`
s := fmt.Sprintf(tpl, "Markjour", "1234")
println(s)

os.Expand 变量替换

tpl := `[${sign}] Your verify code is ${code}.`
params := map[string]string{"sign": "Markjour", "code": "1234"}
println(os.Expand(tpl, func(k string) string { return params[k] }))

text/template 和 html/template

这两个就可以处理复杂的情况,嵌套模板,控制语句都支持。

package main

import (
    "os"
    "text/template"
)

func main() {
    tpl := `[{{.sign}}] Your verify code is {{.code}}.`
    t := template.New("just-a-name")
    t, _ = t.Parse(tpl)
    params := map[string]string{"sign": "Markjour", "code": "1234"}
    t.Execute(os.Stdout, params)
}

附:strings.Map / bytes.Map 提供单个字符的替换

func Map(mapping func(rune) rune, s string) string
package main

import (
    "fmt"
    "strings"
)

const A = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \n"
const B = "N'|&4:@ j{BI+Y!H/Q_iR\\FM}$moLe?#X\"WCE3S,8(r1f%T.;6DbaG]y`q~ltJxu-k2gA\nvhnd=)*s7Z5p^OK[V0z>9<UcwP"

func main() {
    encrypt := func(r rune) rune {
        if !strings.ContainsRune(A, r) {
            return 0
        }
        return rune(B[strings.IndexRune(A, r)])
    }
    decrypt := func(r rune) rune {
        if !strings.ContainsRune(B, r) {
            return 0
        }
        return rune(A[strings.IndexRune(B, r)])
    }

    raw := "Life was like a box of chocolate, you never know what you're gonna get."
    fmt.Println(raw)

    encrypted := strings.Map(encrypt, raw)
    fmt.Println(encrypted)
    // 3j:4wFN_wIjB4wNw'!Mw!:w| !|!INi4dw}!RwY4\4QwBY!FwF Niw}!RAQ4w@!YYNw@4i)

    decrypted := strings.Map(decrypt, encrypted)
    fmt.Println(decrypted)
}

参考资料与拓展阅读

Golang: cannot assign to struct field xxx in map

2020-11-20
package main

import (
    "fmt"
)

type Person struct {
    FirstName string
    LastName  string
}

func main() {
    // 准备 =========================
    people := make(map[int]Person)
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
    }
    people[1] = person

    // 报错:cannot assign to struct field people[1].FirstName in map
    // people[1].FirstName = "Jim"

    // 方式 1
    p := people[1]
    p.FirstName = "Alice"
    people[1] = p
    fmt.Println(people)
    // map[1:{Alice Doe}]
    fmt.Println(people[1])
    // {Alice Doe}

    // if p, ok := people[1]; ok {
    //  p.Field = 5
    //  people[1] = p
    // }

    // 方式 2
    people2 := make(map[int]*Person)
    people2[1] = &person
    people2[1].FirstName = "Adam"
    fmt.Println(people2)
    // map[1:0xc000060020]
    fmt.Println(people2[1])
    // &{Adam Doe}
}

总之,不能直接通过 key 找到 value(struct),然后修改其中的一个字段。

Golang 数据类型

2020-10-31

基础类型:

  • Boolean types (bool)
  • Numeric types
  • String types (string)

复合类型:

  • Array types ([len]Type)
  • Slice types ([]Type)
  • Struct types (struct)
  • Map types (map[KeyType]ValueType{})

特殊类型:

  • Pointer types (*Type) 指针
  • Function types (func) 函数
  • Interface types (interface) 接口
  • Channel types (chan) 通道

引用类型

基础类型 + Array + Struct 不是引用类型,其他几种(Slice + Map + Pointer + Function + Interface + Channel)都是引用类型,函数传参的时候需要记住这一点。

数值

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

// 实现相关:
uint     either 32 or 64 bits
int      same size as uint
uintptr  an unsigned integer large enough to store the uninterpreted bits of a pointer value

声明

var foo int

var foo int = 1

foo := 1

const foo = 1

const foo int = 1

注意:只有基础类型可以声明为常量。

Golang 速查表

2020-06-26

1. 环境配置与基础语法

  • 目标:搭建开发环境,掌握基本语法和编程逻辑。
  • 内容:
    • 安装 Go 版本(推荐 Go 1.21+)及 IDE(如 VS Code + Go 插件、IntelliJ IDEA)。
    • 变量与数据类型(整型、浮点型、布尔型、字符串、数组、切片、字典)。
    • 运算符(算术、关系、逻辑、位运算)。
    • 流程控制(if-else、for、switch、goto)。
    • 函数与方法(函数定义、参数传递、返回值、闭包)。
  • 练习:
    • 编写计算器、斐波那契数列生成器。
    • 实现一个简易的 Todo List 管理工具。

2. 面向对象与结构体

  • 目标:理解 Golang 的 OOP 模型。
  • 内容:
    • 结构体(struct)的定义与初始化。
    • 方法(Method)的绑定(值接收者 vs 指针接收者)。
    • 接口(interface)与类型断言。
    • 组合(Composition)代替继承。
  • 练习:
    • 设计一个动物 kingdom,包含不同动物的行为(如 Dog 吠叫、Bird 飞翔)。
    • 实现一个简单的电商商品库存管理系统。

3. 并发与 Goroutine

  • 目标:掌握 Golang 的并发编程模型。
  • 内容:
    • Goroutine 的启动与停止(go func())。
    • Channel 的使用(阻塞、非阻塞、缓冲区)。
    • select 语句实现多路复用。
    • sync.Mutex 和 atomic 包(锁与原子操作)。
  • 练习:
    • 实现一个多线程的 Web 服务器,处理并发请求。
    • 模拟生产者-消费者问题,使用 Channel 通信。

4. 标准库实战

  • 目标:熟悉 Golang 核心库,快速开发实际应用。
  • 内容:
    • 网络编程:net/http(REST API)、net/url(URL 解析)。
    • 数据处理:encoding/json/xml(序列化/反序列化)、sort/math(常用算法)。
    • 文件 I/O:os/path/filepath(文件操作)、io/ioutil(批量读写)。
    • 模板引擎:html/template(生成动态 HTML)。
  • 项目:
    • 构建一个 RESTful API(用户管理、文章发布)。
    • 开发一个命令行工具(如文件压缩/解压、天气查询)。

5. 微服务与框架

  • 目标:掌握企业级开发模式与流行框架。
  • 内容:
    • 微服务架构(服务拆分、API 网关、配置中心)。
    • 使用框架:Gin(轻量级 HTTP 框架)、Echo、Beego。
    • 分布式工具:etcd(键值存储)、Consul(服务发现)。
    • 容器化与 Docker(部署 Go 应用)。
  • 项目:
    • 设计一个电商系统,包含用户服务、订单服务、支付服务。
    • 实现一个实时聊天室(WebSocket + Goroutine)。

6. 数据库与 ORM

  • 目标:连接数据库并高效操作。
  • 内容:
    • SQL 数据库驱动(database/sql + PostgreSQL/MySQL)。
    • ORM 工具:GORM、sqlx。
    • NoSQL 支持(MongoDB + mgo 包)。
  • 项目:
    • 开发一个博客系统(支持 MySQL 存储、标签分类)。
    • 实现一个用户登录注册系统(JWT 认证 + Redis 会话)。

7. 工程化实践

8. 性能与调优

  • 目标:提升代码性能与稳定性。
  • 内容:
    • 性能分析工具:pprof、trace。
    • 优化技巧:减少内存分配、利用缓存、并发优化。
    • 错误处理与日志(log 包、zap 日志库)。
  • 实战:
    • 分析高并发场景下的性能瓶颈(如百万级请求处理)。
    • 重构代码,优化响应时间与资源占用。