Updated:

17 minute read

개요

Go는 코드 주석을 통한 자동 문서화를 언어 차원에서 지원합니다.

주요 특징:

  • 주석 기반 문서화: 별도 파일 불필요
  • go doc 도구: 터미널에서 문서 조회
  • godoc 서버: 웹 기반 문서 브라우징
  • pkg.go.dev: 공개 패키지 자동 문서화
  • Examples: 실행 가능한 예제 코드
  • Markdown 지원: Go 1.19+에서 제한적 지원
  • 자동 링크: 타입/함수 자동 연결

문서화 주석 작성

1. 패키지 문서화

// Package calculator provides basic arithmetic operations.
//
// This package implements addition, subtraction, multiplication,
// and division operations for integers and floating-point numbers.
//
// Example usage:
//
//	result := calculator.Add(2, 3)
//	fmt.Println(result) // Output: 5
package calculator

규칙:

  • 패키지 선언 바로 위에 작성
  • // Package <name> 형식으로 시작
  • 빈 줄로 단락 구분
  • 들여쓰기 4칸: 코드 블록

여러 파일이 있는 경우:

// doc.go - 패키지 문서 전용 파일 (권장)
/*
Package calculator provides basic arithmetic operations.

This package implements addition, subtraction, multiplication,
and division operations for integers and floating-point numbers.

# Quick Start

    import "github.com/user/calculator"
    
    func main() {
        result := calculator.Add(2, 3)
        fmt.Println(result)
    }

# Features

- Integer arithmetic
- Floating-point arithmetic
- Error handling for division by zero
*/
package calculator

2. 함수 문서화

// Add returns the sum of two integers.
//
// It performs simple addition without overflow checking.
// For overflow-safe addition, use math/big package.
func Add(a, b int) int {
    return a + b
}

// Divide divides a by b and returns the quotient.
//
// It returns an error if b is zero.
//
// Example:
//
//	result, err := Divide(10, 2)
//	if err != nil {
//	    log.Fatal(err)
//	}
//	fmt.Println(result) // 5
func Divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

규칙:

  • 함수명으로 시작
  • 동작과 반환값 설명
  • 에러 조건 명시
  • 들여쓰기로 코드 예제 포함

3. 타입 문서화

// Calculator represents a stateful calculator.
//
// It maintains a running total and supports chaining operations.
type Calculator struct {
    // Total is the current accumulated value.
    // It is updated after each operation.
    Total float64
    
    // history stores the operation history (unexported)
    history []string
}

// Operation represents a calculator operation.
//
// Valid operations are: "add", "subtract", "multiply", "divide".
type Operation string

const (
    // OperationAdd represents addition.
    OperationAdd Operation = "add"
    
    // OperationSubtract represents subtraction.
    OperationSubtract Operation = "subtract"
    
    // OperationMultiply represents multiplication.
    OperationMultiply Operation = "multiply"
    
    // OperationDivide represents division.
    OperationDivide Operation = "divide"
)

4. 메서드 문서화

// Add adds the given value to the calculator's total.
//
// It returns the calculator itself to allow method chaining.
//
// Example:
//
//	calc := &Calculator{}
//	calc.Add(5).Multiply(2).Subtract(3)
//	fmt.Println(calc.Total) // 7
func (c *Calculator) Add(value float64) *Calculator {
    c.Total += value
    c.history = append(c.history, fmt.Sprintf("add %.2f", value))
    return c
}

// Reset resets the calculator to its initial state.
//
// This clears the total and operation history.
func (c *Calculator) Reset() {
    c.Total = 0
    c.history = nil
}

5. 변수와 상수 문서화

// DefaultPrecision is the default decimal precision for calculations.
const DefaultPrecision = 2

// MaxValue is the maximum allowed value for calculations.
var MaxValue = math.MaxFloat64

// Common errors returned by calculator operations.
var (
    // ErrDivisionByZero is returned when dividing by zero.
    ErrDivisionByZero = errors.New("division by zero")
    
    // ErrOverflow is returned when a calculation overflows.
    ErrOverflow = errors.New("calculation overflow")
    
    // ErrInvalidOperation is returned for unsupported operations.
    ErrInvalidOperation = errors.New("invalid operation")
)

go doc 명령어

1. 기본 사용법

# 패키지 문서 보기
go doc fmt
go doc encoding/json
go doc github.com/user/mypackage

# 특정 심볼 보기
go doc fmt.Println
go doc json.Marshal
go doc http.Server

# 메서드 보기
go doc http.Server.ListenAndServe

# 현재 디렉토리 패키지
go doc
go doc Add

2. 옵션

# 모든 문서 출력 (unexported 포함)
go doc -all

# unexported 심볼 포함
go doc -u

# 짧은 형식 (원라인)
go doc -short fmt

# 소스 코드 위치 표시
go doc -src fmt.Println

# 특정 심볼만
go doc -cmd fmt.Println

3. 출력 예제

$ go doc fmt.Printf
package fmt // import "fmt"

func Printf(format string, a ...any) (n int, err error)
    Printf formats according to a format specifier and writes to standard
    output. It returns the number of bytes written and any write error
    encountered.
$ go doc -short json
Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v any) error
NewDecoder(r io.Reader) *Decoder
NewEncoder(w io.Writer) *Encoder
...

godoc 서버

1. 로컬 서버 실행

# godoc 설치 (Go 1.12+)
go install golang.org/x/tools/cmd/godoc@latest

# 서버 시작
godoc -http=:6060

# 브라우저에서 열기
# http://localhost:6060

# 특정 경로만
godoc -http=:6060 -goroot=/path/to/project

2. pkgsite (현대적 대안)

# pkgsite 설치
go install golang.org/x/pkgsite/cmd/pkgsite@latest

# 서버 시작
pkgsite -http=:8080

# 브라우저에서 열기
# http://localhost:8080

3. 프로젝트 문서 보기

# 현재 모듈 문서화
cd /path/to/your/project
godoc -http=:6060

# http://localhost:6060/pkg/your-module-path/

Example 함수

1. 기본 Example

// example_test.go
package calculator_test

import (
    "fmt"
    "yourmodule/calculator"
)

func ExampleAdd() {
    result := calculator.Add(2, 3)
    fmt.Println(result)
    // Output: 5
}

func ExampleDivide() {
    result, err := calculator.Divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(result)
    // Output: 5
}

규칙:

  • Example 접두사 사용
  • // Output: 주석으로 출력 검증
  • go test 시 자동 실행 및 검증
  • godoc에 자동 포함

2. 타입별 Example

// 함수 예제
func ExampleAdd() {
    fmt.Println(calculator.Add(2, 3))
    // Output: 5
}

// 타입 예제
func ExampleCalculator() {
    calc := &calculator.Calculator{}
    calc.Add(5)
    fmt.Println(calc.Total)
    // Output: 5
}

// 메서드 예제
func ExampleCalculator_Add() {
    calc := &calculator.Calculator{}
    calc.Add(5).Add(3)
    fmt.Println(calc.Total)
    // Output: 8
}

// 메서드 체이닝 예제
func ExampleCalculator_Add_chaining() {
    calc := &calculator.Calculator{}
    calc.Add(5).Multiply(2).Subtract(3)
    fmt.Println(calc.Total)
    // Output: 7
}

3. 복잡한 Output

func ExamplePrintMap() {
    m := map[string]int{"a": 1, "b": 2}
    for k, v := range m {
        fmt.Printf("%s=%d\n", k, v)
    }
    // Unordered output:
    // a=1
    // b=2
}

func ExampleMultiLine() {
    fmt.Println("Line 1")
    fmt.Println("Line 2")
    fmt.Println("Line 3")
    // Output:
    // Line 1
    // Line 2
    // Line 3
}

4. Example without Output

func ExampleServer() {
    // 출력이 없거나 검증하지 않는 예제
    server := http.Server{
        Addr:    ":8080",
        Handler: http.DefaultServeMux,
    }
    _ = server
    // 문서화 목적으로만 사용
}

5. 전체 파일 Example

// example_full_test.go
package calculator_test

import (
    "fmt"
    "yourmodule/calculator"
)

func Example() {
    // 패키지 전체 예제
    calc := &calculator.Calculator{}
    
    calc.Add(10)
    calc.Multiply(2)
    calc.Subtract(5)
    
    fmt.Printf("Result: %.0f\n", calc.Total)
    // Output: Result: 15
}

func Example_advanced() {
    // 추가 패키지 예제
    calc := calculator.New()
    
    result, _ := calc.
        Add(5).
        Multiply(2).
        Divide(2).
        GetTotal()
    
    fmt.Printf("%.0f\n", result)
    // Output: 5
}

문서화 포맷팅

1. 단락과 제목 (Go 1.19+)

// Package mypackage provides utilities.
//
// # Overview
//
// This package includes several utilities for common tasks.
//
// # Features
//
// - Feature 1
// - Feature 2
// - Feature 3
//
// # Installation
//
//	go get github.com/user/mypackage
//
// # Quick Start
//
// Create a new instance:
//
//	obj := mypackage.New()
//	obj.DoSomething()
package mypackage

2. 코드 블록

// ProcessData processes the input data.
//
// Example usage:
//
//	data := []int{1, 2, 3, 4, 5}
//	result := ProcessData(data)
//	for _, v := range result {
//	    fmt.Println(v)
//	}
//
// The function returns a new slice without modifying the input.
func ProcessData(data []int) []int {
    // implementation
}

3. 링크

// Server implements an HTTP server.
//
// It uses the standard library's http.Server internally.
// See http.Server for configuration options.
//
// Related types: Client, Handler, Request, Response.
type Server struct {
    // ...
}

4. 리스트

// ParseConfig parses the configuration file.
//
// Supported formats:
//   - JSON (.json)
//   - YAML (.yaml, .yml)
//   - TOML (.toml)
//   - INI (.ini)
//
// The parser automatically detects the format based on file extension.
func ParseConfig(filename string) (*Config, error) {
    // ...
}

5. 경고와 노트

// DeleteAll removes all data from the database.
//
// WARNING: This operation is irreversible!
//
// It is recommended to create a backup before calling this function.
//
// Note: This function requires admin privileges.
func DeleteAll() error {
    // ...
}

pkg.go.dev

1. 자동 문서화

공개 저장소의 Go 모듈은 자동으로 pkg.go.dev에 문서화됩니다.

URL 형식:

https://pkg.go.dev/github.com/user/repo
https://pkg.go.dev/github.com/user/repo/pkg/subpackage
https://pkg.go.dev/github.com/user/repo@v1.2.3

2. README 통합

<!-- README.md -->
# My Package

[![Go Reference](https://pkg.go.dev/badge/github.com/user/mypackage.svg)](https://pkg.go.dev/github.com/user/mypackage)
[![Go Report Card](https://goreportcard.com/badge/github.com/user/mypackage)](https://goreportcard.com/report/github.com/user/mypackage)

Package mypackage provides ...

## Installation

```bash
go get github.com/user/mypackage

Quick Start

import "github.com/user/mypackage"

func main() {
    // Usage example
}

## 3. 배지 추가

```markdown
[![Go Reference](https://pkg.go.dev/badge/github.com/user/mypackage.svg)](https://pkg.go.dev/github.com/user/mypackage)

4. 문서 갱신

# pkg.go.dev는 자동으로 갱신되지만, 수동으로 요청 가능
# 1. pkg.go.dev에서 패키지 검색
# 2. "Request" 버튼 클릭

# 또는 프록시를 통해 갱신
go get github.com/user/mypackage@latest

베스트 프랙티스

1. 문서화 체크리스트

패키지 수준:

  • 패키지 목적 명확히 설명
  • 주요 기능 나열
  • 사용 예제 포함
  • 설치 방법 제공

함수/메서드:

  • 동작 설명
  • 파라미터 설명 (명확하지 않은 경우)
  • 반환값 설명
  • 에러 조건 명시
  • 예제 코드 (복잡한 경우)

타입:

  • 타입의 목적
  • 제로값 동작
  • 동시성 안전성 여부
  • 사용 예제

2. 좋은 문서 예시

// Package httputil provides HTTP utility functions.
//
// This package extends the standard net/http package with
// commonly-needed functionality for building HTTP clients and servers.
//
// # Features
//
//   - Retry logic with exponential backoff
//   - Request/response logging
//   - Timeout handling
//   - Circuit breaker pattern
//
// # Example
//
//	client := httputil.NewClient(
//	    httputil.WithTimeout(30 * time.Second),
//	    httputil.WithRetry(3),
//	)
//	
//	resp, err := client.Get("https://api.example.com/data")
//	if err != nil {
//	    log.Fatal(err)
//	}
//	defer resp.Body.Close()
package httputil

// Client is an HTTP client with retry and timeout capabilities.
//
// It wraps the standard http.Client and adds:
//   - Automatic retries with exponential backoff
//   - Request timeouts
//   - Circuit breaker protection
//
// Client is safe for concurrent use by multiple goroutines.
//
// The zero value is usable with default settings but it's recommended
// to use NewClient for customization.
type Client struct {
    client  *http.Client
    retries int
    timeout time.Duration
}

// NewClient creates a new HTTP client with the given options.
//
// If no options are provided, default settings are used:
//   - Timeout: 30 seconds
//   - Retries: 3
//   - Backoff: exponential with jitter
//
// Example:
//
//	client := NewClient(
//	    WithTimeout(10 * time.Second),
//	    WithRetry(5),
//	)
func NewClient(opts ...Option) *Client {
    // implementation
}

// Get performs a GET request to the specified URL.
//
// It automatically retries on temporary failures and follows redirects
// up to a maximum of 10 times.
//
// Returns an error if:
//   - The URL is invalid
//   - All retry attempts fail
//   - The request times out
//   - The context is cancelled
//
// The caller is responsible for closing the response body.
//
// Example:
//
//	resp, err := client.Get("https://api.example.com/users/123")
//	if err != nil {
//	    return err
//	}
//	defer resp.Body.Close()
//	
//	var user User
//	if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
//	    return err
//	}
func (c *Client) Get(url string) (*http.Response, error) {
    // implementation
}

3. 명명 규칙

// ✅ 좋은 함수명 (자명함)
func (db *DB) Close() error
func (s *Server) Start() error
func NewClient() *Client

// ❌ 나쁜 함수명 (문서 필수)
func (db *DB) DoIt() error  // 무엇을 하는가?
func Process(data []byte) ([]byte, error)  // 어떻게 처리하는가?

4. 버전 정보

// Package mylib provides data processing utilities.
//
// # Compatibility
//
// This package requires Go 1.18 or later due to the use of generics.
//
// # Versioning
//
// This package follows semantic versioning (https://semver.org/).
// Breaking changes will increment the major version.
package mylib

const (
    // Version is the current version of the package.
    Version = "v2.1.0"
)

실전 예제

1. 완전한 패키지 문서화

// doc.go
/*
Package calculator provides basic and advanced arithmetic operations.

# Overview

Calculator supports both simple operations (add, subtract, multiply, divide)
and advanced functions (power, square root, trigonometry).

# Installation

	go get github.com/example/calculator

# Quick Start

	import "github.com/example/calculator"
	
	func main() {
		// Basic operations
		result := calculator.Add(2, 3)
		fmt.Println(result) // 5
		
		// Stateful calculator
		calc := calculator.New()
		calc.Add(10).Multiply(2).Subtract(5)
		fmt.Printf("Total: %.0f\n", calc.Total) // 15
	}

# Features

  - Basic arithmetic: Add, Subtract, Multiply, Divide
  - Advanced math: Power, Sqrt, Sin, Cos, Tan
  - Stateful calculator with method chaining
  - Precision control for floating-point operations
  - Error handling for invalid operations

# Concurrency

All functions in this package are safe for concurrent use.
The Calculator type uses internal locking to ensure thread-safety.

# Performance

Basic operations are implemented using native Go operators and have
O(1) complexity. Advanced operations use the math package.

For high-precision calculations, consider using the math/big package.
*/
package calculator
// calculator.go
package calculator

import (
    "errors"
    "math"
    "sync"
)

// Add returns the sum of a and b.
func Add(a, b float64) float64 {
    return a + b
}

// Subtract returns the difference of a and b.
func Subtract(a, b float64) float64 {
    return a - b
}

// Multiply returns the product of a and b.
func Multiply(a, b float64) float64 {
    return a * b
}

// Divide returns the quotient of a divided by b.
//
// It returns ErrDivisionByZero if b is zero.
func Divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, ErrDivisionByZero
    }
    return a / b, nil
}

// Calculator represents a stateful calculator.
//
// It maintains a running total and supports method chaining.
// Calculator is safe for concurrent use.
type Calculator struct {
    mu    sync.RWMutex
    total float64
}

// New creates a new Calculator with zero initial value.
func New() *Calculator {
    return &Calculator{}
}

// Add adds v to the current total and returns the calculator.
//
// Example:
//
//	calc := New()
//	calc.Add(5).Add(3)
//	fmt.Println(calc.Total()) // 8
func (c *Calculator) Add(v float64) *Calculator {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.total += v
    return c
}

// Total returns the current total.
func (c *Calculator) Total() float64 {
    c.mu.RLock()
    defer c.mu.RUnlock()
    return c.total
}

// ErrDivisionByZero is returned when attempting to divide by zero.
var ErrDivisionByZero = errors.New("division by zero")
// example_test.go
package calculator_test

import (
    "fmt"
    "github.com/example/calculator"
)

func ExampleAdd() {
    result := calculator.Add(2, 3)
    fmt.Println(result)
    // Output: 5
}

func ExampleDivide() {
    result, err := calculator.Divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(result)
    // Output: 5
}

func ExampleDivide_zero() {
    _, err := calculator.Divide(10, 0)
    fmt.Println(err)
    // Output: division by zero
}

func ExampleCalculator() {
    calc := calculator.New()
    calc.Add(5).Add(3).Subtract(2)
    fmt.Println(calc.Total())
    // Output: 6
}

func ExampleCalculator_Add() {
    calc := calculator.New()
    calc.Add(10)
    fmt.Printf("%.0f\n", calc.Total())
    // Output: 10
}

func Example() {
    // Basic usage
    sum := calculator.Add(2, 3)
    fmt.Println("Sum:", sum)
    
    // Stateful calculator
    calc := calculator.New()
    calc.Add(10).Multiply(2)
    fmt.Println("Total:", calc.Total())
    
    // Output:
    // Sum: 5
    // Total: 20
}

2. API 패키지 문서화

// Package api provides RESTful API handlers.
//
// # Overview
//
// This package implements HTTP handlers for the application's REST API.
// All handlers follow RESTful conventions and return JSON responses.
//
// # Authentication
//
// Most endpoints require authentication via JWT tokens.
// Include the token in the Authorization header:
//
//	Authorization: Bearer <token>
//
// # Error Handling
//
// All errors are returned in a consistent JSON format:
//
//	{
//	    "error": "error message",
//	    "code": "ERROR_CODE",
//	    "status": 400
//	}
//
// # Rate Limiting
//
// API requests are rate-limited to 100 requests per minute per IP.
// Rate limit information is included in response headers:
//
//	X-RateLimit-Limit: 100
//	X-RateLimit-Remaining: 95
//	X-RateLimit-Reset: 1234567890
package api

// Handler implements HTTP handlers for the API.
//
// It should be created using NewHandler with required dependencies.
// Handler is safe for concurrent use.
type Handler struct {
    db     *database.DB
    cache  *cache.Cache
    logger *log.Logger
}

// NewHandler creates a new API handler.
//
// It requires a database connection, cache client, and logger.
// Returns an error if any dependency is nil.
//
// Example:
//
//	handler, err := api.NewHandler(db, cache, logger)
//	if err != nil {
//	    log.Fatal(err)
//	}
//	
//	http.Handle("/api/", handler)
func NewHandler(db *database.DB, cache *cache.Cache, logger *log.Logger) (*Handler, error) {
    // implementation
}

일반적인 실수

1. 불완전한 문서

// ❌ 나쁜 예
// Add adds numbers
func Add(a, b int) int {
    return a + b
}

// ✅ 좋은 예
// Add returns the sum of a and b.
//
// It performs simple integer addition without overflow checking.
// For overflow-safe addition, use math/big.Int.
func Add(a, b int) int {
    return a + b
}

2. 자명한 주석

// ❌ 나쁜 예 (주석이 코드와 중복)
// SetName sets the name
func (u *User) SetName(name string) {
    u.Name = name
}

// ✅ 좋은 예 (추가 정보 제공)
// SetName updates the user's display name.
//
// The name is validated and trimmed of whitespace.
// Returns ErrInvalidName if the name is empty or too long.
func (u *User) SetName(name string) error {
    name = strings.TrimSpace(name)
    if name == "" || len(name) > 100 {
        return ErrInvalidName
    }
    u.Name = name
    return nil
}

3. 잘못된 Example Output

// ❌ 나쁜 예 (Output이 실제와 다름)
func ExampleAdd() {
    fmt.Println(Add(2, 3))
    // Output: 6  // 실제는 5
}
// go test 시 실패!

// ✅ 좋은 예
func ExampleAdd() {
    fmt.Println(Add(2, 3))
    // Output: 5
}

4. 형식 오류

// ❌ 나쁜 예 (코드 블록 들여쓰기 부족)
// Example:
// result := Add(2, 3)
// fmt.Println(result)

// ✅ 좋은 예 (탭 또는 4칸 들여쓰기)
// Example:
//
//	result := Add(2, 3)
//	fmt.Println(result)

5. 미완성 문장

// ❌ 나쁜 예
// returns the user
func GetUser(id int) *User {
    // ...
}

// ✅ 좋은 예 (완전한 문장)
// GetUser returns the user with the given ID.
//
// It returns nil if the user is not found.
func GetUser(id int) *User {
    // ...
}

6. 내부 구현 노출

// ❌ 나쁜 예 (내부 구현 상세)
// ProcessData uses a red-black tree internally
// to sort the data and then applies a bubble sort
// algorithm for final ordering...
func ProcessData(data []int) []int {
    // ...
}

// ✅ 좋은 예 (외부 동작에 집중)
// ProcessData sorts and deduplicates the input data.
//
// It returns a new slice without modifying the input.
// The time complexity is O(n log n).
func ProcessData(data []int) []int {
    // ...
}

7. Deprecated 함수 표시 누락

// ❌ 나쁜 예
func OldFunction() {
    // ...
}

// ✅ 좋은 예
// OldFunction is deprecated. Use NewFunction instead.
//
// Deprecated: This function will be removed in v2.0.
// Use NewFunction which provides better performance
// and additional features.
func OldFunction() {
    // ...
}

도구와 자동화

1. golint

# golint 설치
go install golang.org/x/lint/golint@latest

# 문서 검사
golint ./...

# 출력 예시:
# calculator.go:10:1: comment on exported function Add should be of the form "Add ..."
# calculator.go:20:1: exported type Calculator should have comment or be unexported

2. godocdown (Markdown 생성)

# godocdown 설치
go install github.com/robertkrimen/godocdown/godocdown@latest

# Markdown 생성
godocdown > API.md
godocdown -template=template.md > API.md

3. CI/CD 통합

# .github/workflows/docs.yml
name: Documentation

on: [push, pull_request]

jobs:
  docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.21'
      
      - name: Install tools
        run: |
          go install golang.org/x/lint/golint@latest
          go install golang.org/x/tools/cmd/godoc@latest
      
      - name: Check documentation
        run: |
          golint -set_exit_status ./...
      
      - name: Test examples
        run: |
          go test -run Example
      
      - name: Generate docs
        run: |
          godoc -http=:6060 &
          sleep 2
          curl http://localhost:6060/pkg/yourmodule/ > docs.html
      
      - name: Upload docs
        uses: actions/upload-artifact@v3
        with:
          name: documentation
          path: docs.html

4. pre-commit hook

#!/bin/sh
# .git/hooks/pre-commit

# 문서 검사
golint ./... | grep -q "comment on exported" && {
    echo "Error: Missing or incorrect documentation"
    echo "Run: golint ./..."
    exit 1
}

# Example 테스트
go test -run Example || {
    echo "Error: Example tests failed"
    exit 1
}

exit 0

고급 기법

1. 조건부 문서

//go:build linux
// +build linux

// Package sysutil provides Linux-specific system utilities.
//
// This package is only available on Linux systems.
// For cross-platform utilities, see the os package.
package sysutil

2. 내부 패키지 문서화

// Package internal provides internal utilities.
//
// This is an internal package and should not be imported
// by external code. The API is subject to change without notice.
//
// Internal packages cannot be imported by code outside
// the parent package or module.
package internal

3. 문서 템플릿

// template.go

// Package {{.PackageName}} provides {{.Description}}.
//
// # Overview
//
// {{.Overview}}
//
// # Installation
//
//	go get {{.ImportPath}}
//
// # Quick Start
//
//	{{.QuickStart}}
//
// # Features
//
// {{range .Features}}
//   - {{.}}
// {{end}}
package template

4. 다국어 문서

// Package i18n provides internationalization support.
//
// # English
//
// This package provides utilities for translating applications
// into multiple languages.
//
// # 한국어
//
// 이 패키지는 애플리케이션을 여러 언어로 번역하는 유틸리티를 제공합니다.
//
// # 日本語
//
// このパッケージは、アプリケーションを複数の言語に翻訳するための
// ユーティリティを提供します。
package i18n

정리

  • 주석 기반: 코드와 함께 문서 관리
  • go doc: 터미널에서 빠른 조회
  • godoc/pkgsite: 웹 기반 브라우징
  • Examples: 실행 가능한 문서, 자동 테스트
  • pkg.go.dev: 공개 패키지 자동 문서화
  • 포맷팅: 제목, 코드 블록, 리스트, 링크
  • 규칙: 함수명으로 시작, 완전한 문장, 명확한 설명
  • 실수: 불완전한 문서, 자명한 주석, 형식 오류
  • 도구: golint, godocdown, CI/CD 통합
  • 베스트: 체크리스트, 예제 포함, 버전 정보
  • 원칙: 사용자 관점에서 작성, 외부 동작에 집중