2015-02-11 14 views
17

我在Go中編寫了一個REST API,使用不代表單個時間點的日期。在golang沒有時間的情況下使用日期的慣用方式是什麼?

它是JSON數據以「2006-01-02」格式進出服務器,數據使用DATE列與mysql數據庫交談。

我試過的一件事是創建一個嵌入時間的結構,並實現JSON和SQL轉換接口實現,以便能夠正確地與端點進行交互,同時仍然有Time方法可用於日期數學和格式化。例如:

package localdate 

import (
    "time" 
    "encoding/json" 
    "database/sql/driver" 
) 

type LocalDate struct { 
    time.Time 
} 

func NewLocalDate(year int, month time.Month, day int) LocalDate { 
    time := time.Date(year, month, day, 0, 0, 0, 0, time.UTC) 
    return LocalDate{Time: time} 
} 

const LocalDateFormat = "2006-01-02" // yyyy-mm-dd 

func (ld *LocalDate) UnmarshalJSON(data []byte) error { 
    // parse and set the ld.Time variable 
} 

func (ld *LocalDate) MarshalJSON() ([]byte, error) { 
    return json.Marshal(ld.Format(LocalDateFormat)) 
} 

// sql.Scanner implementation to convert a time.Time column to a LocalDate 
func (ld *LocalDate) Scan(value interface{}) error {} 

// sql/driver.Valuer implementation to go from LocalDate -> time.Time 
func (ld *LocalDate) Value() (driver.Value, error) {} 

// used to convert a LocalDate into something we can plug into a query 
// we could just use ld.Time, but that would send '2015-01-01 00:00:00 +0000 UTC' 
// instead of '2015-01-01' for the DATE query parameter. (Which works for mysql, but is officially invalid SQL) 
func (ld *LocalDate) SqlDate() string { 
    return ld.Format(LocalDateFormat) 
} 

然後其他結構可以是這種類型,並獲得90%的代表日期類型在我的問題域。

上面的代碼有效,但我覺得我正在對抗Go電流。所以,對於該語言的退伍軍人有幾個問題:

您是否認爲這段代碼會導致比它節省更多的痛苦?
如果是這樣,你會推薦什麼樣的風格?

+0

你能在「日期細說那不代表一個單一的時間點「?他們是範圍? – thwd 2015-02-11 06:55:11

+0

對不起,我使用複數形式來表示一般的日期......對於這種情況,我一次只能處理一個日期。 – 2015-02-11 17:37:50

+5

你也可以在 'type LocalDate time.Time'上定義你的方法 如果你不需要嵌入 – metakeule 2015-02-12 16:28:58

回答

相關問題