Ramu Mangalarapu
Posted on January 8, 2022
Hi,
Today I am going to write simple tutorial about reading file in Golang.
Let's say you want to read json file, you can read using golang os ReadFile.
The json file we are reading is same as in our golang code file.
user.json
{
"id": "0000001",
"name": "user",
"email": "user.email.com",
"phoneNumber": "+0001"
}
main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
)
// User is sample object
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PhoneNumber string `json:"phoneNumber"`
}
func main() {
// provide the file path to read from
b, err := os.ReadFile("user.json")
if err != nil {
log.Fatalf("Failed to read file: %v\n", err)
}
// where to store the file contents
var u User
json.NewDecoder(bytes.NewBuffer(b)).Decode(&u)
// printing the file contents or use it for
// other purposes.
fmt.Printf("%#v", u)
}
This way can de-serialize to our native Golang types and use them like passing it other functions or doing some computation on it.
Thank you.
💖 💪 🙅 🚩
Ramu Mangalarapu
Posted on January 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.