Hello everyone, my name is Xie Wei, I am a programmer.

I’ve combed through some of the libraries and received some comments, most of which point to one question: why comb through these innocuous libraries?

Well, it does look like a simple library comb. The main reason: The Back End Engineer Walkthrough series, which started from scratch and got to this point in the tutorial, looked like it needed to be more difficult. Follow up and improve. Another reason, in fact, is to tell beginners that a lot of the built-in library code organization, code writing means learning, borrowing, reference.

I prepared this one, so I’d better put it on the air.

The core is simple: know the basic syntax of Go, use the built-in time library, and get most of it.

Outline:

  • Holiday API

Recently, the project needs to use the holidays stipulated by the state, so we need to obtain these data. There are many ways to get this data:

  • For example, the more stupid way: search engines, manual sorting
  • Use some free and open third-party holiday apis: unstable, although this data does not need to be used frequently
  • Use some paid third-party holiday apis: paid

So in a concise way, write such a holiday library.

Requirements:

  • Simple features
  • Simple API

1. Data acquisition

The data source needs to be reliable, so look for official notification sources.

For example, The General Office of the State Council issued a notice on some holidays in 2018

The general way, is web data capture, parsing out the data.

That’s the first step, get the data; Of course, there are many websites where you can find this information, but here are just examples.

2. Define the structure

What is the most important information we need to know about the holidays?

  • The name of the
  • schedule

Based on this, the structure can be designed as follows:

type OneCollection struct {
	Start  string `json:"start"`
	End    string `json:"end"`
	ChName string `json:"ch_name"`
	EnName string `json:"en_name"`}Copy the code

Include:

  • Chinese name
  • English names
  • The start time
  • The end of time

About the holiday name, the national legal festivals are so several: New Year’s Day, Spring Festival, Qingming, Dragon Boat Festival, labor, Mid-Autumn festival, National Day

Take a page from many of the built-in libraries: this fixed data processing can be done using enumerated types:

const (
	NewYearDay = iota
	SpringFestivalDay
	TombSweepingDay
	LaborDay
	DragonBoatFestivalDay
	NationalDay
	MidAutumnFestivalDay
)

var ChHolidays = [...]string{
	"New Year's day"."Spring Festival"."Qingming Festival".Labor Day."Dragon Boat Festival"."Mid-Autumn Festival"."National Day",}var EnHolidays = [...]string{
	"New Year\\'s Day"."Spring Festival"."Tomb-sweeping Day"."Labour Day"."Dragon Boat Festival"."Mid-autumn Festival"."National Day",}Copy the code

This processing is common in built-in libraries: for example, the time type of time base unit month: January, February, March, etc

3. Historical data

Based on the above analysis, to build this simple library, to organize historical holidays, select data from 2010 to 2019.

/ / one yeartype YearCollection struct {
	Data []OneCollection `json:"data"'} // n yearstype CollectionYearHistory struct {
	Data [][]OneCollection `json:"data"`} / / data from 2010 to 2019 - year - old func FetchCollectionYearHistory CollectionYearHistory () {return CollectionYearHistory{
		Data: [][]OneCollection{
			holiday2019,
			holiday2018,
			holiday2017,
			holiday2016,
			holiday2015,
			holiday2014,
			holiday2013,
			holiday2012,
			holiday2011,
			holiday2010,
		},
	}
}

Copy the code

4. Build the API

  • Choose good naming
  • Choose a good data return format
- FetchAll
- FetchByChName(year int, name string)
- FetchByEnName(year int, name string)
- FetchByMonth(year int, month int)
- FetchByYear(year int)
- FetchMonthHolidayCount(year int, month int)
- FetchYearHolidayCount(year int)
- IsHoliday
- IsWeekDay
- IsWorkDay

Copy the code

It is designed this way because it is common for projects to do something like this:

  • Get all historical data
  • Get historical data for a certain year
  • Obtain historical data for a month
  • Number of days off in a month in a year
  • Count the number of days off in a year
  • Determine if a date is a holiday
  • Determine if a date is a weekend
  • Determine if a date is a working day

Based on these requirements, the API above was built

Taking several apis as examples, how to implement the detailed operation?

  • FetchByYear(year int): FetchByYear is obtained from historical data
// FetchByYear get holidays by year in china
func FetchByYear(year int) []history.OneCollection {
	var index int
	nowYear, _, _ := time.Now().Date()
	if year > nowYear+1 {
		return nil
	}
	index = nowYear + 1 - year
	return history.FetchCollectionYearHistory().Data[index]

}
Copy the code
  • FetchByMonth: FetchByMonth is obtained from historical data of a certain year
func FetchByMonth(year int, month int) []history.OneCollection {
	if month < 1 || month > 12 {
		return nil

	}
	collections := FetchByYear(year)
	var data []history.OneCollection
	for _, collection := range collections {
		collectionTime, _ := time.Parse("2006/01/02", collection.End)
		if int(collectionTime.Month()) == month {
			data = append(data, collection)
		}
	}
	return data
}
Copy the code
  • IsHoliday: Whether the target can be hit in historical data
func IsHoliday(value string) bool {
	collectionTime, err := time.Parse("2006/01/02", value)
	iferr ! = nil {return false
	}
	nowYear, _, _ := time.Now().Date()
	if collectionTime.Year() > nowYear+1 {
		return false
	}
	collections := FetchByYear(collectionTime.Year())
	for _, collection := range collections {
		startDate, _ := getDate(collection.Start)
		endDate, _ := getDate(collection.End)
		if collectionTime.Unix() >= startDate.Unix() && collectionTime.Unix() <= endDate.Unix() {
			return true}}return false

}
Copy the code
  • IsWeekDay: not a holiday or weekday
// IsWeekDay: judge date is week day or not
func IsWeekDay(value string) bool {
	return! IsWorkDay(value) && ! IsHoliday(value) }Copy the code
  • Holidays is for information only

< note >

Based on the above concept, there are many gadgets that can be written:

Such as:

  • Get ancient Poetry
  • Given a date, judge the constellations
  • Given an ID card, determine whether it is valid, which region it belongs to, etc
  • Given an IP address, give the geographical location
  • Given a Chinese, give English or pinyin
  • Given a word, explain its Chinese meaning…

After < >