How to read API document

The Go Programming Language Packages

name 說明
archive 檔案相關
.tar:檔案壓縮
.zip:對zip文件讀寫操作
bufio
builtin 預先聲明定義
bytes []bytes 操作
compass 解壓縮
.bzip2
.flate
.gzip
.lzw
.zlib
container 容器 : heap, list, ring
.heap:提供對實現了heap interface類型的操作
.list:實作 doubly linked list
.ring:實作 circular lists
crypto 加密
database 資料庫操作
.sql:提供SQL資料庫的通用介面
.sql/driver:提供被sql使用的資料庫驅動實作的interface
debug
encoding 編碼格式轉換
errors 異常處理
expvar 為公告變量提供一個標準interface, ex:計數器
flag 命令列標籤解析
fmt 輸入與輸出
go
hash hash interface
html HTML 文本轉換
image 基礎的2-D圖片庫
index .index/suffixarray:通過使用内存中suffix array實現了對數時間的子字串搜索
io io interface
log 紀錄資料
math 基礎數學方法
mime MIME 規範
net 網路IO interface
os 跨平台的interface
path 路徑相關
reflect 映射處理
regexp 正規表達式
runtime 與Go運行時, 系統相互的操作
sort 排序
strconv 字串類型轉換
strings 字串處理
sync 同步
syscall 針對底層原始系統操作的interface
testing 自動化測試
text .scanner:解析utf8編碼的文本
.tabwriter:轉換文本中的標籤檔
time 測量與顯示時間
unicode 測試 Unicode 性質
unsafe 繞過 go 安全程序類型的操作

strings 字串處理 參考資料

內容 說明
func Contains(s, substr string) bool 判斷字串 s 中是否包含字串substr
func ContainsAny(s, chars string) bool 判斷字串s 中是否存在 chars 中的任一字
func ContainRune(s string, r rune) bool 判斷字串s 中是否存在 字符 r
func Count(s, sep string) int 返回字串s中 sep 出現的個數
func Index(s, sep string) int 返回sep 在s中第一次出現的位置, 不存在返回-1
func LastIndex(s, sep string) int 返回sep 在s中最後一次出現的位置, 不存在-1
func IndexRune(s string, r rune) int 返回字符r 在字串s中第一次出現的位置
func IndexAny(s, chars string) int 返回s中第一次出現chars字串任一字的位置
func LastIndexAny(s, chars string) int 返回s中最後一次出現chars字串任一字的位置
func HasPrefix(s, substr string) bool 判斷s是否以substr 開頭
func HasSuffix(s, substr string) bool 判斷s是否以substr 結尾
func Split(s, sep string) []string 以sep做為s的分隔符
func SplitN(s, sep string, n int) []string 以sep作為s的分隔符, 最多分切成n部分, n=0 retunr nil, n < 0, 不限制個數
func Fields(s string) []string 以連續空白符作為分隔, 結果中不包含空白字符
func Join(a []string, sep string) string 用sep作為a的分隔符, 將a依序轉出成字串
func Repeat(s string, count int) string 將s連續coun次連接成一個新字串
func ToUpper(s string) string 轉大寫
func ToLower(s string) string 轉小寫
func Trim(s string, cutset string) string 刪除s頭尾符合cutset的字串
func Replace(s, old, new string, n int) string 將s 中的old替換成new

io Input/Output 讀寫資料 參考資料

  • 定義的 function不多, 大部分都是使用interface
  • 主要的兩個interface 是 Reader and Writer io提供了函式 ReadFull, 可將r中的data讀出來放到buf供其他程式處理

    func ReadFull(r Reader, buf []byte) (n int, err error)
    

    以下是Reader的定義

    type Reader interface {
      Read(p []byte) (n int, err error)
    }
    

    只要物件實現了Read的方法就可以被ReadFull讀取了

  • io 提供的nterface
    Reader : 用來輸出資料

      type Reader interface {
          Read(p []byte) (n int, err error)
      }
    

    Writer : 用來寫入資料

      type Writer interface {
          Write(p []byte) (n int, err error)
      }
    

    Closer : 用來關閉資料

      type Closer interface {
          Close() error
      }
    

    Seeker : 用來移動資料的讀寫指針

      type Seeker interface {
      Seek(offset int64, whence int) (ret int64, err error)
      }
    

    ReadFrom : 用來讀出r中的資料

      type ReaderFrom interface {
          ReadFrom(r Reader) (n int64, err error)
      }
    

    WriterTo : 將資料寫入w中

      type WriterTo interface {
          WriteTo(w Writer) (n int64, err error)
      }
    
  • io 提供的函式

    WriteString : 將字串s寫到w中

    func WriteString(w Writer, s string) (n int, err error)
    

    ReadAtLeast : 從r中讀取資料到buf, 至少讀取min的字串

    func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error
    

    Copy 從src中複製資料到dst, 直到所有資料複製完成

    func Copy(dst Writer, src Reader) (written int64, err error)
    

    CopyN : 從src中讀取n個字節的資料到dst

    func CopyN(dst Writer, src Reader, n int64) (written int64, err error)
    

io/ioutil Input / Output 參考資料

  • 提供的函式

    ReadAll : 讀取 r中所有的資料

    func ReadAll(r io.Reader) ([]byte, error)
    

    ReadFile : 讀取文件中的所有資料

    func ReadFile(filename string) ([]byte, error)
    

    WriteFile : 向文件filename 寫入data

    func WriteFile(filename string, data []byte, perm os.FileMode) error
    

    ReadDir : 讀取 dirname 中所有的目錄和文件

    func ReadDir(dirname string) ([]os.FileInfo, error)
    

os Files & Folders 檔案&資料夾操作

  • 提供的函式

    Create : 建立一個檔案

    func Create(name string) (file *File, err error)
    

    OpenFile : 打開檔案, 可以指定權限和打開的方式

    func OpenFile(name string, flag int, perm FileMode) (file *File, err error)要
    

    Open : 打開檔案

    func Open(name string) (file *File, err error)
    

    Close : 關閉檔案

    func (f *File) Close() error
    

    Stat : 取得檔案的結構描述

    func Stat(name string) (fi FileInfo, err error)
    

    Chdir : 修改工作目錄

    func (f *File) Chdir() error
    

    Getwd : 取得當前目錄

    func Getwd() (dir string, err error)
    

errors 錯誤訊息

  • 自訂回傳錯誤訊息的方法 :

      package main
    
      import "errors"
    
      func main() {
        err := errors.New("error message")
      }
    

container/list List

  • list 是一個 doubly-linked list
  • 是一種資料結構
  • 提供的函式 :

    New : 返回一個初始化list

    func New() *List
    

    Back : 取得list最後一個元素

    func (l *List) Back() *Element
    

    Front : 取得 list 第一個元素

    func (l *List) Front() *Element
    

    Init : 初始化或者清除list

    func (l *List) Init() *List
    

    Len : 取得list 長度

    func (l *List) Len() int
    

    MoveAfter : 將元素e 移動到mark之後

    func (l *List) MoveAfter(e, mark *Element)
    

    MoveBefore : 將元素e 移動到mark之前

    func (l *List) MoveBefore(e, mark *Element)
    

    MoveToBack : 將元素e移動到list尾端

    func (l *List) MoveToBack(e *Element)
    

    MoveToFront : 將元素e移動到list起點

    func (l *List) MoveToFront(e *Element)
    

    PushBack : 在list 尾端插入v, 並返回該元素

    func (l *List) PushBack(v interface{}) *Element
    

    PushBackList : 在list尾端插入另一個list

    func (l *List) PushBackList(other *List)
    

    PushFront: 在list 起點插入v, 並返回該元素

    func (l *List) PushFront(v interface{})
    

    PushFrontList : 在list起點插入另一個list

    func (l *List) PushFrontList(other *List)
    

    Remove : 移除元素 e , 並返回e的值

    func (l *List) Remove(e *Element) interface{}
    

sort 排序

  • 會依照資料內容自動選擇較有效率的排序方式
  • 定義了三個interface :

    Len : 爲集合內元素的總數

    func Len() int
    

    Less : 如果index爲i的元素小于index爲j的元素,則返回true,否則返回false

    Less(i, j int) bool
    

    Swap : 交換索引爲 i 和 j 的元素

    Swap(i, j int)
    

hash Hashes & Cryptography

  • Hash functions in Go are broken into two categories: cryptographic and non-cryptographic.
  • non-cryptographic hash functions :
    • hash/adler32
    • hash/crc32
    • hash/crc64
    • hash/fnc

net Servers, DNS相關

  • 提供的函式:

    InterfaceAddrs : 返回該系統網路介面地址列表

    func InterfaceAddrs() ([]Addr, error)
    

    Interfaces : 返回該系統的網路介面列表

    func Interfaces() ([]Interface, error)
    

    JoinHostPort : 將host 跟 ip合成一個網址

    func JoinHostPort(host, port string) string
    

    LookupAddr : 對該地址進行反查, 並返回映射到該地址的list列表

    func LookupAddr(addr string) (name []string, err error)
    

    LookupHost :透過本地解析器對該host進行查找, 並返回該主機位址

    func LookupHost(host string) (addrs []string, err error)
    

    LookupIP : 透過本地解析器查找host, 並返回主機ipv4, ipv6位址

    func LookupIP(host string) (addrs []IP, err error)
    

    LookupPort : 返回指定network and service 的port

    func LookupPort(network, service string) (port int, err error)
    
  • type Error

    type Error interface {
      error      //錯誤
      Timeout() bool   // Is the error a timeout? 該錯誤是時間超時錯誤嗎?
      Temporary() bool // Is the error temporary? 這個錯誤是一個臨時錯誤嗎?
    }
    

    任何實現了error介面中方法的結構都實現了net error, 主要有以下集中錯誤:

    • type AddrError :網址錯誤
      type AddrError struct {
          Err  string  //錯誤
          Addr string //地址字符串表示
      }
      
      提供的函式 :
      Error : 錯誤
      func (e *AddrError) Error() string
      
      Temporary : 判斷該錯誤是否是個臨時錯誤
      func (e *AddrError) Temporary() bool
      
      Timeout : 判斷該錯誤是否是個超時錯誤
      func (e *AddrError) Timeout() bool
      
    • type DNSConfigError : DNS 配置錯誤

      type DNSConfigError struct {
          Err error
      }
      

      提供的函式 :

          func (e *DNSConfigError) Error() string
          func (e *DNSConfigError) Temporary() bool
          func (e *DNSConfigError) Timeout() bool
      
    • type DNSError : DNS錯誤
      type DNSError struct {
      Err       string // description of the error,錯誤描述
      Name      string // name looked for,查詢 名稱
      Server    string // server used,服務
      IsTimeout bool,是否超時
      }
      
    • type InvalidAddrError 無效地址錯誤
      type InvalidAddrError string
      
    • type OpError 操作錯誤

      type OpError struct {
      
      Op string   //Op是引起錯誤的操作,如"read"或"write"
      
      Net string      //Net表示錯誤出現的網絡類型,如tcp或者udp6
      
      Addr Addr    //Addr表示錯誤出現的網絡抵制
      
      Err error    //Err表示錯誤
      }
      

      在 OpError 中大部分錯誤會包含以下錯誤

      var (
      ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
      )
      
    • type ParseError 解析錯誤
      type ParseError struct {
      Type string
      Text string
      }
      

net/http HTTP

  • 有兩個核心: Conn, ServeMux

    • Conn: goroutine
      go 在等待客戶端請求是這樣寫的 :

      c, err := srv.newConn(rw)
      if err != nil {
          continue
      }
      go c.serve()
      

      客戶端每次請求都會創建一個Conn, 這個Conn保存了這次請求的信息, 再傳給對應的Handler,
      該Handler可以讀取到對應的header, 這樣確保了每個請求的獨立性

    • ServeMux 的自定義
      其結構如下 :

      type ServeMux struct {
        mu sync.RWMutex   //锁,由于请求涉及到并发处理,因此这里需要一个锁机制
        m  map[string]muxEntry  // 路由规则,一个string对应一个mux实体,这里的string就是注册的路由表达式
        hosts bool // 是否在任意的规则中带有host信息
      }
      

      再看一下 muxEntry :

      type muxEntry struct {
        explicit bool   // 是否精确匹配
        h        Handler // 这个路由表达式对应哪个handler
        pattern  string  //匹配字符串
      }
      

      再看一下 handler :

      type Handler interface {
      ServeHTTP(ResponseWriter, *Request)  // 路由实现器
      }
      

      HandlerFunc 這個類型默認實現了ServeHTTP介面, 即調用HandlerFunc(f),
      強制類別轉換f成為了HandlerFunc類型, 這樣f就擁有了 ServeHTTP 方法

  • example

    package main
    
    import ("net/http" ; "io")
    
    func hello(res http.ResponseWriter, req *http.Request) {
      res.Header().Set(
        "Content-Type",
        "text/html",
      )
      io.WriteString(
        res,
        `<DOCTYPE html>
          <html>
          <head>
          <title>Hello World</title>
          </head>
          <body>
              Hello World!
          </body>
          </html>`,
        )
      }
      func main() {
        http.HandleFunc("/hello", hello)
        http.ListenAndServe(":9000", nil)
      }