1 回答
TA贡献1995条经验 获得超2个赞
在这里,我清理了你的代码。现在测试应该更容易编写
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"time"
)
// Data struct which contains
// an array of users
type Data struct {
Users []User `json:"users"`
}
// User struct which contains the first + last name and the birthdate
type User struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Date string `json:"date"`
}
func IsLeapYear(date time.Time) bool {
return date.Day()%400 == 0 || (date.Day()%4 == 0 && date.Day()%100 != 0)
}
func parseDate(date string) time.Time {
parsedDate, err := time.Parse("2006/01/02", date)
if err != nil {
parsedDate, err = time.Parse("2006-01-02", date)
if err != nil {
log.Fatal("unsupported date format:", err)
}
}
return parsedDate
}
func CheckBirthdateOf(user User) {
date := parseDate(user.Date)
fmt.Println("User Date: " + user.Date)
fmt.Println("User First Name: " + user.FirstName)
fmt.Println("User Last Name: " + user.LastName)
if IsLeapYear(date) {
fmt.Println(user.Date, "is a Leap Year ✨ ✨ ✨")
if date.Day() == time.Now().Day() {
fmt.Println("TODAY IS YOUR BIRTHDAY AND A Leap YEAR, Happy birthday !!!🎉 🎉 🍾 🍾 ")
} else {
fmt.Println("TODAY IS NOT YOUR BIRTHDAY, but it's a leap year..!!! 👍 👍 👍 ")
}
} else {
fmt.Println(user.Date, " is Not a Leap Year 💥 💥 💥 ")
fmt.Println("Your Date is neither a leap year nor your birthday..!!! 😔😔😔")
}
fmt.Println("")
}
func main() {
jsonFile, err := os.Open("users.json")
if err != nil {
panic(err)
}
fmt.Println("Successfully Opened users_data.json")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var usersData Data
json.Unmarshal(byteValue, &usersData)
for _, user := range usersData.Users {
CheckBirthdateOf(user)
}
}
- 1 回答
- 0 关注
- 64 浏览
添加回答
举报