model.*Booking.UnmarshalJSON   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nop 1
dl 0
loc 24
rs 9.55
c 0
b 0
f 0
1
package model
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"time"
7
)
8
9
// year-month-day
10
const DateFormat = "2006-01-02"
11
12
type Booking struct {
13
	Id        int       `json:"booking_id" db:"id"`
14
	RoomId    int       `json:"-" db:"room_id"`
15
	DateStart time.Time `json:"date_start" db:"date_start"`
16
	DateEnd   time.Time `json:"date_end" db:"date_end"`
17
}
18
19
func (b *Booking) MarshalJSON() ([]byte, error) {
20
	return json.Marshal(&struct {
21
		Id        int    `json:"booking_id"`
22
		DateStart string `json:"date_start"`
23
		DateEnd   string `json:"date_end"`
24
	}{
25
		Id:        b.Id,
26
		DateStart: b.DateStart.Format(DateFormat),
27
		DateEnd:   b.DateEnd.Format(DateFormat),
28
	})
29
}
30
31
func (b *Booking) UnmarshalJSON(data []byte) error {
32
	var buffer struct {
33
		RoomId    int    `json:"room_id"`
34
		DateStart string `json:"date_start"`
35
		DateEnd   string `json:"date_end"`
36
	}
37
	if err := json.Unmarshal(data, &buffer); err != nil {
38
		return err
39
	}
40
41
	dateStart, err := time.Parse(DateFormat, buffer.DateStart)
42
	if err != nil {
43
		return errors.New("bad date_start")
44
	}
45
	dateEnd, err := time.Parse(DateFormat, buffer.DateEnd)
46
	if err != nil {
47
		return errors.New("bad date_end")
48
	}
49
50
	b.RoomId = buffer.RoomId
51
	b.DateStart = dateStart
52
	b.DateEnd = dateEnd
53
54
	return nil
55
}
56