Golang 筆記
  • Introduction
  • 安裝Golang
    • 本地編譯與安裝第三方套件
    • 第一個 GO 程式
    • export 與 import
    • 使用 go mod
  • 基本工具
  • DataBase操作
    • MySQL
    • 使用 ORM
    • MongoDB
  • 基本語法
    • Variable
    • BSON
    • JSON
    • 時間相關
    • Interface
    • Error
    • 型別
    • 字串
    • defer
    • panic, recover
    • Channel 與Goroutine
      • 讀寫鎖
      • for select 與 for range
      • UnBuffered channel 與 Buffered channel
    • Function
    • pointer
    • regExp
    • fmt
    • Make vs New
    • struct
    • Array, Slice 陣列
    • map
  • 核心模組
    • Reflect
    • File
    • Signal
    • BuiltIn
    • Sync
    • IO
    • Sort
    • http
    • crypto
    • context
  • 第三方模組
    • Dom Parser
    • gin 框架
    • Websocket
    • Iris框架
      • 讀取 Body 資料
      • 相關範例
    • Fiber 框架
    • 自動重啟 server 工具
    • go-jwt
  • 測試
  • 原始碼解析
  • 常見問題
    • 資料存取不正確
    • Data races
Powered by GitBook
On this page
  • 範例
  • IO Reader
  • IO Write
  • 對檔案的文字行進行操作

Was this helpful?

  1. 核心模組

IO

PreviousSyncNextSort

Last updated 3 years ago

Was this helpful?

包含 io 與 ioutil

範例

讀取檔案轉 JSON

package main
import (
	"os"
  "io/ioutil"
	"encoding/json"
)

func main() {
	jsonFile, err := os.Open("conf.json")
	
	if err != nil {
 	 fmt.Println(err)
	}

	defer jsonFile.Close()

	jsonStr, err := ioutil.ReadAll(jsonFile)
  if err != nil {
      log.Fatal(err)
  }
  doc := make(map[string]interface{})
  if err := json.Unmarshal(jsonStr, &doc); err != nil {
      log.Fatal(err)
  }
  fmt.Println(doc)
  fmt.Println(doc["AWS_ID"])
  fmt.Println(doc["AWS_KEY"])
  for k, v := range doc {
  	fmt.Println("%s:%s",k, v.(string))
  }
}

// map[AWS_ID:x12345123r2r4adefds AWS_KEY:test123]

// x12345123r2r4adefds
// test123

IO Reader

定義如下

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

當讀取完後會出現 io.EOF

// ErrShortWrite means that a write accepted fewer bytes than requested
// but failed to return an explicit error.
var ErrShortWrite = errors.New("short write")

// ErrShortBuffer means that a read required a longer buffer than was provided.
var ErrShortBuffer = errors.New("short buffer")

// EOF is the error returned by Read when no more input is available.
// Functions should return EOF only to signal a graceful end of input.
// If the EOF occurs unexpectedly in a structured data stream,
// the appropriate error is either ErrUnexpectedEOF or some other error
// giving more detail.
var EOF = errors.New("EOF")

// ErrUnexpectedEOF means that EOF was encountered in the
// middle of reading a fixed-size block or data structure.
var ErrUnexpectedEOF = errors.New("unexpected EOF")

// ErrNoProgress is returned by some clients of an io.Reader when
// many calls to Read have failed to return any data or error,
// usually the sign of a broken io.Reader implementation.
var ErrNoProgress = errors.New("multiple Read calls return no data or error")

許多模組包含 strings 都有接入此 Read 接口

IO Write

通常會用 for loop 來讀取與寫入,或是可用 io.copy來替代。相較於先使用 readAll 然後 fPrintf 的方式,會導致記憶體洩漏,可用 io.copy 解決。

不錯的文章可參考:

對檔案的文字行進行操作

如果要進行文字細部操作可使用 bufio 模組。

https://openhome.cc/Gossip/Go/bufio.html
Golang - 認識 io package 的原理與操作Kenny's Blog
Logo