From f0ca6e40e3cf93ed55e85701fd5676617b24fc19 Mon Sep 17 00:00:00 2001 From: truongtop1 Date: Sun, 15 Dec 2024 19:04:08 +0700 Subject: [PATCH] chore: update shared function --- console.go | 12 ++- date.go | 132 +----------------------- date_test.go | 185 --------------------------------- docs/docs/receipts/api.md | 72 ++++++------- docs/docs/receipts/console.md | 16 +-- docs/docs/receipts/random.md | 39 ++++--- function.go | 3 +- math.go | 96 ----------------- math_test.go | 13 +++ public/count.svg | 8 +- samples/console.go | 16 +-- shared.go | 130 ++++++++++++++++++++--- time.go | 136 +++++++++++++++++++++++++ time_test.go | 187 ++++++++++++++++++++++++++++++++++ 14 files changed, 546 insertions(+), 499 deletions(-) create mode 100644 math_test.go create mode 100644 time.go create mode 100644 time_test.go diff --git a/console.go b/console.go index c1fbf99..a2d8ba5 100644 --- a/console.go +++ b/console.go @@ -36,8 +36,16 @@ func Cls() { Cmd("clear", "cls") } -func PrintColor[T int | int8 | int16 | int32 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64 | string](color string, chain T) { - fmt.Printf("%s%v\n", color, chain) +func OutputColor[T int | int8 | int16 | int32 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64 | string](color string, output T) { + fmt.Printf("%s%v%s", color, output, DEFAULT_CONSOLE) +} + +func OutputSuccess(output string) { + println(GREEN_CONSOLE + output + DEFAULT_CONSOLE) +} + +func OutputError(output string, err string) { + println(RED_CONSOLE + err + DEFAULT_CONSOLE) } func Banner(font IFontBannerType, s string) { diff --git a/date.go b/date.go index 8285d62..49d2ddd 100644 --- a/date.go +++ b/date.go @@ -1,12 +1,6 @@ package gouse -import ( - "fmt" - "strconv" - "time" -) - -/* Date formats */ +import "time" func format(input interface{}, format string) string { var t time.Time @@ -106,127 +100,3 @@ func UTCDate(date ...interface{}) string { return format(date[0].(time.Time), "Jan 2, 2006 at 3:04pm (MST)") } } - -/* Time formats */ - -func Second() int { - return time.Now().Second() -} - -func Minute() int { - return time.Now().Minute() -} - -func Hour() int { - return time.Now().Hour() -} - -func Day() int { - return time.Now().Day() -} - -func Month() int { - return int(time.Now().Month()) -} - -func Year() int { - return time.Now().Year() -} - -func Weekday() int { - return int(time.Now().Weekday()) -} - -func Unix() int64 { - return time.Now().Unix() -} - -func UnixMilli() int64 { - return time.Now().UnixNano() / int64(time.Millisecond) -} - -func UnixMicro() int64 { - return time.Now().UnixNano() / int64(time.Microsecond) -} - -func UnixNano() int64 { - return time.Now().UnixNano() -} - -func UnixMilliToTime(milli int64) time.Time { - return time.Unix(0, milli*int64(time.Millisecond)) -} - -func UnixMicroToTime(micro int64) time.Time { - return time.Unix(0, micro*int64(time.Microsecond)) -} - -func UnixNanoToTime(nano int64) time.Time { - return time.Unix(0, nano) -} - -/* Clock format */ - -func formatTime(t time.Time) string { - hour := t.Hour() - minute := t.Minute() - second := t.Second() - - hourStr := strconv.Itoa(hour) - minuteStr := strconv.Itoa(minute) - secondStr := strconv.Itoa(second) - - if hour < 10 { - hourStr = fmt.Sprintf("0%s", hourStr) - } - if minute < 10 { - minuteStr = fmt.Sprintf("0%s", minuteStr) - } - if second < 10 { - secondStr = fmt.Sprintf("0%s", secondStr) - } - - return fmt.Sprintf("%s:%s:%s", hourStr, minuteStr, secondStr) -} - -func TerminalClock() { - msgTime := make(chan time.Time) - - go func() { - for { - time.Sleep(1 * time.Second) - msgTime <- time.Now() - } - }() - - for t := range msgTime { - Cls() - fmt.Println(formatTime(t)) - } -} - -/* Utilities */ - -func ToSecond(second int) time.Duration { - return time.Duration(second) * time.Second -} - -func ToMinute(minute int) time.Duration { - return time.Duration(minute) * time.Minute -} - -func ToHour(hour int) time.Duration { - return time.Duration(hour) * time.Hour -} - -func SleepSecond(second int) { - time.Sleep(ToSecond(second)) -} - -func SleepMinute(minute int) { - time.Sleep(ToMinute(minute)) -} - -func SleepHour(hour int) { - time.Sleep(ToHour(hour)) -} diff --git a/date_test.go b/date_test.go index 824bed3..34076c0 100644 --- a/date_test.go +++ b/date_test.go @@ -5,8 +5,6 @@ import ( "time" ) -/* Testing date formats */ - func TestISODate(t *testing.T) { now := time.Now() if ISODate() != now.Format("2006-01-02T15:04:05.999Z") { @@ -67,186 +65,3 @@ func TestUTCDate(t *testing.T) { t.Error("UTC() should return today's date in UTC format") } } - -/* Testing time formats */ - -func TestSecond(t *testing.T) { - if Second() != time.Now().Second() { - t.Error("Second() != time.Now().Second()") - } -} - -func TestMinute(t *testing.T) { - if Minute() != time.Now().Minute() { - t.Error("Minute() != time.Now().Minute()") - } -} - -func TestHour(t *testing.T) { - if Hour() != time.Now().Hour() { - t.Error("Hour() != time.Now().Hour()") - } -} - -func TestDay(t *testing.T) { - if Day() != time.Now().Day() { - t.Error("Day() != time.Now().Day()") - } -} - -func TestMonth(t *testing.T) { - if Month() != int(time.Now().Month()) { - t.Error("Month() != int(time.Now().Month())") - } -} - -func TestYear(t *testing.T) { - if Year() != time.Now().Year() { - t.Error("Year() != time.Now().Year()") - } -} - -func TestWeekday(t *testing.T) { - if Weekday() != int(time.Now().Weekday()) { - t.Error("Weekday() != int(time.Now().Weekday())") - } -} - -func TestUnix(t *testing.T) { - if Unix() != time.Now().Unix() { - t.Error("Unix() != time.Now().Unix()") - } -} - -func TestUnixMilli(t *testing.T) { - if UnixMilli() != time.Now().UnixNano()/int64(time.Millisecond) { - t.Error("UnixMilli() != time.Now().UnixNano()/int64(time.Millisecond)") - } -} - -func TestUnixMicro(t *testing.T) { - result := UnixMicro() - currentTime := time.Now().UnixNano() / int64(time.Microsecond) - - acceptableRange := int64(1000) // 1 millisecond in microseconds - - if result < currentTime-acceptableRange || result > currentTime+acceptableRange { - t.Errorf("UnixMicro() result %d is not within an acceptable range of current time %d", result, currentTime) - } -} - -func TestUnixNano(t *testing.T) { - result := UnixNano() - currentTime := time.Now().UnixNano() - - acceptableRange := int64(1000000000) // 1 second in nanoseconds - - if result < currentTime-acceptableRange || result > currentTime+acceptableRange { - t.Errorf("UnixNano() result %d is not within an acceptable range of current time %d", result, currentTime) - } -} - -func TestUnixMilliToTime(t *testing.T) { - if UnixMilliToTime(0) != time.Unix(0, 0) { - t.Error("UnixMilliToTime(0) != time.Unix(0, 0)") - } -} - -func TestUnixMicroToTime(t *testing.T) { - if UnixMicroToTime(0) != time.Unix(0, 0) { - t.Error("UnixMicroToTime(0) != time.Unix(0, 0)") - } -} - -func TestUnixNanoToTime(t *testing.T) { - if UnixNanoToTime(0) != time.Unix(0, 0) { - t.Error("UnixNanoToTime(0) != time.Unix(0, 0)") - } -} - -func TestFormatTime(t *testing.T) { - tests := []struct { - name string - input time.Time - expected string - }{ - { - name: "Single digit hour, minute, and second", - input: time.Date(2024, 2, 4, 5, 6, 7, 0, time.UTC), - expected: "05:06:07", - }, - { - name: "Double digit hour, minute, and second", - input: time.Date(2024, 2, 4, 15, 16, 17, 0, time.UTC), - expected: "15:16:17", - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - result := formatTime(tc.input) - if result != tc.expected { - t.Errorf("Expected %s, but got %s", tc.expected, result) - } - }) - } -} - -/* Testing utilities */ - -func TestToSecond(t *testing.T) { - second := 1 - expected := time.Duration(second) * time.Second - actual := ToSecond(second) - if expected != actual { - t.Errorf(DESC_TEST, expected, actual) - } -} - -func TestToMinute(t *testing.T) { - minute := 1 - expected := time.Duration(minute) * time.Minute - actual := ToMinute(minute) - if expected != actual { - t.Errorf(DESC_TEST, expected, actual) - } -} - -func TestToHour(t *testing.T) { - hour := 1 - expected := time.Duration(hour) * time.Hour - actual := ToHour(hour) - if expected != actual { - t.Errorf(DESC_TEST, expected, actual) - } -} - -func TestSleepSecond(t *testing.T) { - nowSecond := time.Now().Second() - second := 1 - SleepSecond(second) - if nowSecond == time.Now().Second() { - t.Errorf("Expected %v but it got %v", nowSecond+second, time.Now().Second()) - } -} - -// skip this test because it will take a long time -// func TestSleepMinute(t *testing.T) { -// nowMinute := time.Now().Minute() -// minute := 1 - -// SleepMinute(minute) -// if nowMinute == time.Now().Minute() { -// t.Errorf("Expected %v but it got %v", nowMinute+minute, time.Now().Minute()) -// } -// } - -// skip this test because it will take a long time -// func TestSleepHour(t *testing.T) { -// nowHour := time.Now().Hour() -// hour := 1 -// SleepHour(hour) -// if nowHour == time.Now().Hour() { -// t.Errorf("Expected %v but it got %v", nowHour+hour, time.Now().Hour()) -// } -// } diff --git a/docs/docs/receipts/api.md b/docs/docs/receipts/api.md index 635288c..afc252c 100644 --- a/docs/docs/receipts/api.md +++ b/docs/docs/receipts/api.md @@ -4,7 +4,9 @@ ```go import ( - "time" "github.com/thuongtruong109/gouse" ) + "time" + "github.com/thuongtruong109/gouse" +) ``` ## 1. Api loadbalancer @@ -12,42 +14,44 @@ import ( Description: Load balancer with health check
Input params: (ILbConfig.ProxyPort, ILbConfig.Backends)
```go -func ApiLoadbalancer() { - lbCfg := gouse.ILbConfig{ - ProxyPort: "8080", - Backends: []gouse.IBackend{ - { - URL: "http://localhost:8081", - IsDead: false, - }, - { - URL: "http://localhost:8082", - IsDead: false, - }, - { - URL: "http://localhost:8083", - IsDead: false, - }, - }, - } - - // gouse.HealthCheck() // Enable health check (optional) - gouse.LoadBalancer(lbCfg.ProxyPort, lbCfg.Backends) -} ``` +func ApiLoadbalancer() { + lbCfg := gouse.ILbConfig{ + ProxyPort: "8080", + Backends: []gouse.IBackend{ + { + URL: "http://localhost:8081", + IsDead: false, + }, + { + URL: "http://localhost:8082", + IsDead: false, + }, + { + URL: "http://localhost:8083", + IsDead: false, + }, + }, + } + + // gouse.HealthCheck() // Enable health check (optional) + gouse.LoadBalancer(lbCfg.ProxyPort, lbCfg.Backends) +} +``` ## 2. Api graceful shutdown Description: Graceful shutdown for API server
Input params: (IGracefulShutdown)
```go -func ApiGracefulShutdown() { - gs := gouse.IGracefulShutdown{ - Port: "3000", - StartMsg: "Starting server at port http://localhost:3000", - ShutdownMsg: "Shutting down server...", - SleepTimout: 5 * time.Second, - HeaderTimeout: 5 * time.Second, - } - - gs.GracefulShutdown() -} ``` +func ApiGracefulShutdown() { + gs := gouse.IGracefulShutdown{ + Port: "3000", + StartMsg: "Starting server at port http://localhost:3000", + ShutdownMsg: "Shutting down server...", + SleepTimout: 5 * time.Second, + HeaderTimeout: 5 * time.Second, + } + + gs.GracefulShutdown() +} +``` diff --git a/docs/docs/receipts/console.md b/docs/docs/receipts/console.md index 8cf2e5e..87c7ef1 100644 --- a/docs/docs/receipts/console.md +++ b/docs/docs/receipts/console.md @@ -54,14 +54,14 @@ func ConsoleClear() { ```go func ConsoleWithColor() { - gouse.PrintColor(gouse.DEFAULT_FG, "this is default") - gouse.PrintColor(gouse.WHITE_FG, "this is white") - gouse.PrintColor(gouse.RED_FG, "this is red") - gouse.PrintColor(gouse.GREEN_FG, "this is green") - gouse.PrintColor(gouse.YELLOW_FG, "this is yellow") - gouse.PrintColor(gouse.BLUE_FG, "this is blue") - gouse.PrintColor(gouse.MAGENTA_FG, "this is magenta") - gouse.PrintColor(gouse.CYAN_FG, "this is cyan") + gouse.OutputColor(gouse.DEFAULT_CONSOLE, "this is default") + gouse.OutputColor(gouse.WHITE_CONSOLE, "this is white") + gouse.OutputColor(gouse.RED_CONSOLE, "this is red") + gouse.OutputColor(gouse.GREEN_CONSOLE, "this is green") + gouse.OutputColor(gouse.YELLOW_CONSOLE, "this is yellow") + gouse.OutputColor(gouse.BLUE_CONSOLE, "this is blue") + gouse.OutputColor(gouse.MAGENTA_CONSOLE, "this is magenta") + gouse.OutputColor(gouse.CYAN_CONSOLE, "this is cyan") } ``` diff --git a/docs/docs/receipts/random.md b/docs/docs/receipts/random.md index d84eafa..694f630 100644 --- a/docs/docs/receipts/random.md +++ b/docs/docs/receipts/random.md @@ -4,7 +4,9 @@ ```go import ( - "fmt" "github.com/thuongtruong109/gouse" ) + "fmt" + "github.com/thuongtruong109/gouse" +) ``` ## 1. Random number @@ -12,42 +14,47 @@ import ( Description: Return a random number between min and max
Input params: (min, max int)
```go -func RandomNumber() { - fmt.Println(gouse.RandNum(1, 100)) -} ``` +func RandomNumber() { + fmt.Println(gouse.RandNum(1, 100)) +} +``` ## 2. Random i d Description: Return a random id (string) with current timestamp
```go -func RandomID() { - fmt.Println(gouse.RandID()) -} ``` +func RandomID() { + fmt.Println(gouse.RandID()) +} +``` ## 3. Random string Description: Return a random string with n characters length
Input params: (length int)
```go -func RandomString() { - fmt.Println(gouse.RandStr(10)) -} ``` +func RandomString() { + fmt.Println(gouse.RandStr(10)) +} +``` ## 4. Random digit Description: Return a random digit number with n characters length
Input params: (length int)
```go -func RandomDigit() { - fmt.Println(gouse.RandDigit(10)) -} ``` +func RandomDigit() { + fmt.Println(gouse.RandDigit(10)) +} +``` ## 5. Random u u i d Description: Return a random UUID (format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
```go -func RandomUUID() { - fmt.Println(gouse.UUID()) -} ``` +func RandomUUID() { + fmt.Println(gouse.UUID()) +} +``` diff --git a/function.go b/function.go index e8e3a8d..1abc37d 100644 --- a/function.go +++ b/function.go @@ -147,6 +147,5 @@ func IntervalFunc(fn func(), timeout int) { func RunTimeFunc(startTime time.Time, task func()) time.Duration { task() - elapsedTime := float64(time.Since(startTime).Seconds() * 1000) - return time.Duration(elapsedTime) + return DiffTimeNow(startTime) } diff --git a/math.go b/math.go index bddfd90..6100add 100644 --- a/math.go +++ b/math.go @@ -72,102 +72,6 @@ func Time(distance, speed float64) float64 { return DivideF(distance, speed) } -// func Density(mass, volume int) int { -// return Divide(mass, volume) -// } - -// func DensityF(mass, volume float64) float64 { -// return DivideF(mass, volume) -// } - -// func Pressure(force, area int) int { -// return Divide(force, area) -// } - -// func PressureF(force, area float64) float64 { -// return DivideF(force, area) -// } - -// func Work(force, distance int) int { -// return Multi(force, distance) -// } - -// func WorkF(force, distance float64) float64 { -// return MultiF(force, distance) -// } - -// func Power(work, time int) int { -// return Divide(work, time) -// } - -// func PowerF(work, time float64) float64 { -// return DivideF(work, time) -// } - -// func Momentum(mass, velocity int) int { -// return Multi(mass, velocity) -// } - -// func MomentumF(mass, velocity float64) float64 { -// return MultiF(mass, velocity) -// } - -// func Acceleration(velocity, time int) int { -// return Divide(velocity, time) -// } - -// func AccelerationF(velocity, time float64) float64 { -// return DivideF(velocity, time) -// } - -// func Force(mass, acceleration int) int { -// return Multi(mass, acceleration) -// } - -// func ForceF(mass, acceleration float64) float64 { -// return MultiF(mass, acceleration) -// } - -// func Weight(mass, gravity int) int { -// return Multi(mass, gravity) -// } - -// func WeightF(mass, gravity float64) float64 { -// return MultiF(mass, gravity) -// } - -// func MomentumForce(momentum, time int) int { -// return Divide(momentum, time) -// } - -// func MomentumForceF(momentum, time float64) float64 { -// return DivideF(momentum, time) -// } - -// func MomentumVelocity(momentum, mass int) int { -// return Divide(momentum, mass) -// } - -// func MomentumVelocityF(momentum, mass float64) float64 { -// return DivideF(momentum, mass) -// } - -// func MomentumMass(momentum, velocity int) int { -// return Divide(momentum, velocity) -// } - -// func MomentumMassF(momentum, velocity float64) float64 { -// return DivideF(momentum, velocity) -// } - -// func MomentumTime(momentum, force int) int { -// return Divide(momentum, force) -// } - -// func MomentumTimeF(momentum, force float64) float64 { -// return DivideF(momentum, force) -// } - /* Functions */ func Abs(num int) int { diff --git a/math_test.go b/math_test.go new file mode 100644 index 0000000..b61c193 --- /dev/null +++ b/math_test.go @@ -0,0 +1,13 @@ +package gouse + +import ( + "testing" +) + +/*Testing for formulas*/ +func TestLog(t *testing.T) { + result := Log(10, 10) + if result != 1 { + t.Errorf("Log() = %d; want 1", result) + } +} diff --git a/public/count.svg b/public/count.svg index 451f22b..fcdb2b3 100644 --- a/public/count.svg +++ b/public/count.svg @@ -1,5 +1,5 @@ - - 391 functions + + 371 functions @@ -13,7 +13,7 @@ - - 391 functions + + 371 functions diff --git a/samples/console.go b/samples/console.go index 5ab8792..da0339c 100644 --- a/samples/console.go +++ b/samples/console.go @@ -38,14 +38,14 @@ func ConsoleClear() { } func ConsoleWithColor() { - gouse.PrintColor(gouse.DEFAULT_FG, "this is default") - gouse.PrintColor(gouse.WHITE_FG, "this is white") - gouse.PrintColor(gouse.RED_FG, "this is red") - gouse.PrintColor(gouse.GREEN_FG, "this is green") - gouse.PrintColor(gouse.YELLOW_FG, "this is yellow") - gouse.PrintColor(gouse.BLUE_FG, "this is blue") - gouse.PrintColor(gouse.MAGENTA_FG, "this is magenta") - gouse.PrintColor(gouse.CYAN_FG, "this is cyan") + gouse.OutputColor(gouse.DEFAULT_CONSOLE, "this is default") + gouse.OutputColor(gouse.WHITE_CONSOLE, "this is white") + gouse.OutputColor(gouse.RED_CONSOLE, "this is red") + gouse.OutputColor(gouse.GREEN_CONSOLE, "this is green") + gouse.OutputColor(gouse.YELLOW_CONSOLE, "this is yellow") + gouse.OutputColor(gouse.BLUE_CONSOLE, "this is blue") + gouse.OutputColor(gouse.MAGENTA_CONSOLE, "this is magenta") + gouse.OutputColor(gouse.CYAN_CONSOLE, "this is cyan") } func ConsoleBanner() { diff --git a/shared.go b/shared.go index 74b0e02..ab4b8fa 100644 --- a/shared.go +++ b/shared.go @@ -7,20 +7,20 @@ type ITest struct { WantErr bool } -// These maybe not supported by all terminals const ( - DEFAULT_FG string = "\033[0m" - RED_FG string = "\033[31m" - GREEN_FG string = "\033[32m" - YELLOW_FG string = "\033[33m" - PURPLE_FG string = "\033[34m" - PINK_FG string = "\033[35m" - CYAN_FG string = "\033[36m" - WHITE_FG string = "\033[97m" - ORANGE_FG string = "\033[38;5;208m" - BLUE_FG string = "\033[38;5;27m" - MAGENTA_FG string = "\033[38;5;13m" - Gray string = "\033[37m" + // These maybe not supported by all terminals + DEFAULT_CONSOLE string = "\033[0m" + RED_CONSOLE string = "\033[31m" + GREEN_CONSOLE string = "\033[32m" + YELLOW_CONSOLE string = "\033[33m" + PURPLE_CONSOLE string = "\033[34m" + PINK_CONSOLE string = "\033[35m" + CYAN_CONSOLE string = "\033[36m" + WHITE_CONSOLE string = "\033[97m" + ORANGE_CONSOLE string = "\033[38;5;208m" + BLUE_CONSOLE string = "\033[38;5;27m" + MAGENTA_CONSOLE string = "\033[38;5;13m" + GRAY_CONSOLE string = "\033[37m" ) // const ( @@ -49,6 +49,110 @@ const ( PhoneReg = `^\+\d{1,2}\s?\(\d{1,4}\)\s?\d{1,6}-\d{1,6}$` ) +const ( + DESC_CREATE_FAILED string = "create failed" + DESC_GET_FAILED string = "get failed" + DESC_UPDATE_FAILED string = "update failed" + DESC_DELETE_FAILED string = "delete failed" + + DESC_CREATE_SUCCESS string = "create successfully" + DESC_GET_SUCCESS string = "get successfully" + DESC_UPDATE_SUCCESS string = "update successfully" + DESC_DELETE_SUCCESS string = "delete successfully" + + DESC_NOT_FOUND_DATA string = "not found data" + DESC_EMPTY_DATA string = "empty data" + DESC_INVALID_DATA string = "invalid data" +) + +// const ( +// STATUS_OK string = "OK" +// STATUS_CREATED string = "Created" +// STATUS_ACCEPTED string = "Accepted" +// STATUS_NO_CONTENT string = "No Content" +// STATUS_RESET_CONTENT string = "Reset Content" +// STATUS_PARTIAL_CONTENT string = "Partial Content" +// STATUS_MOVED_PERMANENT string = "Moved Permanently" +// STATUS_FOUND string = "Found" +// STATUS_SEE_OTHER string = "See Other" +// STATUS_NOT_MODIFIED string = "Not Modified" +// STATUS_USE_PROXY string = "Use Proxy" +// STATUS_TEMP_REDIRECT string = "Temporary Redirect" + +// STATUS_BAD_REQUEST string = "Bad Request" +// STATUS_UNAUTHORIZED string = "Unauthorized" +// STATUS_FORBIDDEN string = "Forbidden" +// STATUS_NOT_FOUND string = "Not Found" +// STATUS_METHOD_NOT_ALLOWED string = "Method Not Allowed" +// STATUS_NOT_ACCEPTABLE string = "Not Acceptable" +// STATUS_PROXY_AUTH_REQUIRED string = "Proxy Authentication Required" +// STATUS_REQUEST_TIMEOUT string = "Request Timeout" +// STATUS_CONFLICT string = "Conflict" +// STATUS_GONE string = "Gone" +// STATUS_LENGTH_REQUIRED string = "Length Required" +// STATUS_PRECONDITION_FAILED string = "Precondition Failed" +// STATUS_REQUEST_ENTITY_LARGE string = "Request Entity Too Large" +// STATUS_REQUEST_URI_LARGE string = "Request-URI Too Large" +// STATUS_UNSUPPORTED_MEDIA string = "Unsupported Media Type" +// STATUS_REQUEST_RANGE_INVALID string = "Requested Range Not Satisfiable" +// STATUS_EXPECTATION_FAILED string = "Expectation Failed" + +// STATUS_INTERNAL_SERVER_ERROR string = "Internal Server Error" +// STATUS_NOT_IMPLEMENTED string = "Not Implemented" +// STATUS_BAD_GATEWAY string = "Bad Gateway" +// STATUS_SERVICE_UNAVAILABLE string = "Service Unavailable" +// STATUS_GATEWAY_TIMEOUT string = "Gateway Timeout" + +// STATUS_CONTINUE string = "Continue" +// STATUS_SWITCHING_PROTOCOL string = "Switching Protocols" +// STATUS_PROCESSING string = "Processing" +// STATUS_EARLY_HINTS string = "Early Hints" +// ) + +// const ( +// STATUS_CONTINUE_CODE int = 100 +// STATUS_SWITCHING_PROTOCOL_CODE int = 101 +// STATUS_PROCESSING_CODE int = 102 +// STATUS_EARLY_HINTS_CODE int = 103 + +// STATUS_OK_CODE int = 200 +// STATUS_CREATED_CODE int = 201 +// STATUS_ACCEPTED_CODE int = 202 +// STATUS_NO_CONTENT_CODE int = 204 +// STATUS_RESET_CONTENT_CODE int = 205 +// STATUS_PARTIAL_CONTENT_CODE int = 206 +// STATUS_MOVED_PERMANENT_CODE int = 301 +// STATUS_FOUND_CODE int = 302 +// STATUS_SEE_OTHER_CODE int = 303 +// STATUS_NOT_MODIFIED_CODE int = 304 +// STATUS_USE_PROXY_CODE int = 305 +// STATUS_TEMP_REDIRECT_CODE int = 307 + +// STATUS_BAD_REQUEST_CODE int = 400 +// STATUS_UNAUTHORIZED_CODE int = 401 +// STATUS_FORBIDDEN_CODE int = 403 +// STATUS_NOT_FOUND_CODE int = 404 +// STATUS_METHOD_NOT_ALLOWED_CODE int = 405 +// STATUS_NOT_ACCEPTABLE_CODE int = 406 +// STATUS_PROXY_AUTH_REQUIRED_CODE int = 407 +// STATUS_REQUEST_TIMEOUT_CODE int = 408 +// STATUS_CONFLICT_CODE int = 409 +// STATUS_GONE_CODE int = 410 +// STATUS_LENGTH_REQUIRED_CODE int = 411 +// STATUS_PRECONDITION_FAILED_CODE int = 412 +// STATUS_REQUEST_ENTITY_LARGE_CODE int = 413 +// STATUS_REQUEST_URI_LARGE_CODE int = 414 +// STATUS_UNSUPPORTED_MEDIA_CODE int = 415 +// STATUS_REQUEST_RANGE_INVALID_CODE int = 416 +// STATUS_EXPECTATION_FAILED_CODE int = 417 + +// STATUS_INTERNAL_SERVER_ERROR_CODE int = 500 +// STATUS_NOT_IMPLEMENTED_CODE int = 501 +// STATUS_BAD_GATEWAY_CODE int = 502 +// STATUS_SERVICE_UNAVAILABLE_CODE int = 503 +// STATUS_GATEWAY_TIMEOUT_CODE int = 504 +// ) + type IFontBannerType map[string][3]string var DOUBLE_ALPHA = IFontBannerType{ diff --git a/time.go b/time.go new file mode 100644 index 0000000..5d9138b --- /dev/null +++ b/time.go @@ -0,0 +1,136 @@ +package gouse + +import ( + "fmt" + "strconv" + "time" +) + +func Second() int { + return time.Now().Second() +} + +func Minute() int { + return time.Now().Minute() +} + +func Hour() int { + return time.Now().Hour() +} + +func Day() int { + return time.Now().Day() +} + +func Month() int { + return int(time.Now().Month()) +} + +func Year() int { + return time.Now().Year() +} + +func Weekday() int { + return int(time.Now().Weekday()) +} + +func Unix() int64 { + return time.Now().Unix() +} + +func UnixMilli() int64 { + return time.Now().UnixNano() / int64(time.Millisecond) +} + +func UnixMicro() int64 { + return time.Now().UnixNano() / int64(time.Microsecond) +} + +func UnixNano() int64 { + return time.Now().UnixNano() +} + +func UnixMilliToTime(milli int64) time.Time { + return time.Unix(0, milli*int64(time.Millisecond)) +} + +func UnixMicroToTime(micro int64) time.Time { + return time.Unix(0, micro*int64(time.Microsecond)) +} + +func UnixNanoToTime(nano int64) time.Time { + return time.Unix(0, nano) +} + +func ToSecond(second int) time.Duration { + return time.Duration(second) * time.Second +} + +func ToMinute(minute int) time.Duration { + return time.Duration(minute) * time.Minute +} + +func ToHour(hour int) time.Duration { + return time.Duration(hour) * time.Hour +} + +func SleepSecond(second int) { + time.Sleep(ToSecond(second)) +} + +func SleepMinute(minute int) { + time.Sleep(ToMinute(minute)) +} + +func SleepHour(hour int) { + time.Sleep(ToHour(hour)) +} + +/* Clock format */ + +func formatTime(t time.Time) string { + hour := t.Hour() + minute := t.Minute() + second := t.Second() + + hourStr := strconv.Itoa(hour) + minuteStr := strconv.Itoa(minute) + secondStr := strconv.Itoa(second) + + if hour < 10 { + hourStr = fmt.Sprintf("0%s", hourStr) + } + if minute < 10 { + minuteStr = fmt.Sprintf("0%s", minuteStr) + } + if second < 10 { + secondStr = fmt.Sprintf("0%s", secondStr) + } + + return fmt.Sprintf("%s:%s:%s", hourStr, minuteStr, secondStr) +} + +func TerminalClock() { + msgTime := make(chan time.Time) + + go func() { + for { + time.Sleep(1 * time.Second) + msgTime <- time.Now() + } + }() + + for t := range msgTime { + Cls() + fmt.Println(formatTime(t)) + } +} + +func DiffTime(t1, t2 time.Time) time.Duration { + return t2.Sub(t1) +} + +func DiffTimeNow(startTime time.Time) time.Duration { + elapsedTime := float64(time.Since(startTime).Seconds() * 1000) + return time.Duration(elapsedTime) +} diff --git a/time_test.go b/time_test.go new file mode 100644 index 0000000..62f05ee --- /dev/null +++ b/time_test.go @@ -0,0 +1,187 @@ +package gouse + +import ( + "testing" + "time" +) + +func TestSecond(t *testing.T) { + if Second() != time.Now().Second() { + t.Error("Second() != time.Now().Second()") + } +} + +func TestMinute(t *testing.T) { + if Minute() != time.Now().Minute() { + t.Error("Minute() != time.Now().Minute()") + } +} + +func TestHour(t *testing.T) { + if Hour() != time.Now().Hour() { + t.Error("Hour() != time.Now().Hour()") + } +} + +func TestDay(t *testing.T) { + if Day() != time.Now().Day() { + t.Error("Day() != time.Now().Day()") + } +} + +func TestMonth(t *testing.T) { + if Month() != int(time.Now().Month()) { + t.Error("Month() != int(time.Now().Month())") + } +} + +func TestYear(t *testing.T) { + if Year() != time.Now().Year() { + t.Error("Year() != time.Now().Year()") + } +} + +func TestWeekday(t *testing.T) { + if Weekday() != int(time.Now().Weekday()) { + t.Error("Weekday() != int(time.Now().Weekday())") + } +} + +func TestUnix(t *testing.T) { + if Unix() != time.Now().Unix() { + t.Error("Unix() != time.Now().Unix()") + } +} + +func TestUnixMilli(t *testing.T) { + if UnixMilli() != time.Now().UnixNano()/int64(time.Millisecond) { + t.Error("UnixMilli() != time.Now().UnixNano()/int64(time.Millisecond)") + } +} + +func TestUnixMicro(t *testing.T) { + result := UnixMicro() + currentTime := time.Now().UnixNano() / int64(time.Microsecond) + + acceptableRange := int64(1000) // 1 millisecond in microseconds + + if result < currentTime-acceptableRange || result > currentTime+acceptableRange { + t.Errorf("UnixMicro() result %d is not within an acceptable range of current time %d", result, currentTime) + } +} + +func TestUnixNano(t *testing.T) { + result := UnixNano() + currentTime := time.Now().UnixNano() + + acceptableRange := int64(1000000000) // 1 second in nanoseconds + + if result < currentTime-acceptableRange || result > currentTime+acceptableRange { + t.Errorf("UnixNano() result %d is not within an acceptable range of current time %d", result, currentTime) + } +} + +func TestUnixMilliToTime(t *testing.T) { + if UnixMilliToTime(0) != time.Unix(0, 0) { + t.Error("UnixMilliToTime(0) != time.Unix(0, 0)") + } +} + +func TestUnixMicroToTime(t *testing.T) { + if UnixMicroToTime(0) != time.Unix(0, 0) { + t.Error("UnixMicroToTime(0) != time.Unix(0, 0)") + } +} + +func TestUnixNanoToTime(t *testing.T) { + if UnixNanoToTime(0) != time.Unix(0, 0) { + t.Error("UnixNanoToTime(0) != time.Unix(0, 0)") + } +} + +func TestFormatTime(t *testing.T) { + tests := []struct { + name string + input time.Time + expected string + }{ + { + name: "Single digit hour, minute, and second", + input: time.Date(2024, 2, 4, 5, 6, 7, 0, time.UTC), + expected: "05:06:07", + }, + { + name: "Double digit hour, minute, and second", + input: time.Date(2024, 2, 4, 15, 16, 17, 0, time.UTC), + expected: "15:16:17", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + result := formatTime(tc.input) + if result != tc.expected { + t.Errorf("Expected %s, but got %s", tc.expected, result) + } + }) + } +} + +/* Testing utilities */ + +func TestToSecond(t *testing.T) { + second := 1 + expected := time.Duration(second) * time.Second + actual := ToSecond(second) + if expected != actual { + t.Errorf(DESC_TEST, expected, actual) + } +} + +func TestToMinute(t *testing.T) { + minute := 1 + expected := time.Duration(minute) * time.Minute + actual := ToMinute(minute) + if expected != actual { + t.Errorf(DESC_TEST, expected, actual) + } +} + +func TestToHour(t *testing.T) { + hour := 1 + expected := time.Duration(hour) * time.Hour + actual := ToHour(hour) + if expected != actual { + t.Errorf(DESC_TEST, expected, actual) + } +} + +func TestSleepSecond(t *testing.T) { + nowSecond := time.Now().Second() + second := 1 + SleepSecond(second) + if nowSecond == time.Now().Second() { + t.Errorf("Expected %v but it got %v", nowSecond+second, time.Now().Second()) + } +} + +// skip this test because it will take a long time +// func TestSleepMinute(t *testing.T) { +// nowMinute := time.Now().Minute() +// minute := 1 + +// SleepMinute(minute) +// if nowMinute == time.Now().Minute() { +// t.Errorf("Expected %v but it got %v", nowMinute+minute, time.Now().Minute()) +// } +// } + +// skip this test because it will take a long time +// func TestSleepHour(t *testing.T) { +// nowHour := time.Now().Hour() +// hour := 1 +// SleepHour(hour) +// if nowHour == time.Now().Hour() { +// t.Errorf("Expected %v but it got %v", nowHour+hour, time.Now().Hour()) +// } +// }