This commit is contained in:
kenneth 2023-12-25 11:15:27 +08:00
parent d41908ded5
commit 887c5bc859
4 changed files with 23 additions and 7 deletions

1
go.mod
View File

@ -5,6 +5,7 @@ go 1.21.5
require (
github.com/gorilla/mux v1.8.1
github.com/itchyny/base58-go v0.2.1
github.com/joho/godotenv v1.5.1
github.com/redis/go-redis/v9 v9.3.1
github.com/stretchr/testify v1.8.4
)

2
go.sum
View File

@ -12,6 +12,8 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/itchyny/base58-go v0.2.1 h1:wtnhAVdOcW3WuHEASmGHMms4juOB8yEpj/KJxlB57+k=
github.com/itchyny/base58-go v0.2.1/go.mod h1:BNvrKeAtWNSca1GohNbyhfff9/v0IrZjzWCAGeAvZZE=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.3.1 h1:KqdY8U+3X6z+iACvumCNxnoluToB+9Me+TvyFa21Mds=

19
main.go
View File

@ -6,14 +6,21 @@ import (
"net/http"
"os"
"os/signal"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"github.com/zhang2092/go-url-shortener/handler"
"github.com/zhang2092/go-url-shortener/store"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatalf("failed to load env: %v", err)
}
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
@ -23,10 +30,16 @@ func main() {
router.HandleFunc("/create-short-url", handler.CreateShortUrl).Methods(http.MethodPost)
router.HandleFunc("/{shortUrl}", handler.HandleShortUrlRedirect).Methods(http.MethodGet)
store.InitializeStore()
addr := os.Getenv("REDIS_ADDR")
password := os.Getenv("REDIS_PASSWORD")
db, err := strconv.Atoi(os.Getenv("REDIS_DB"))
if err != nil {
log.Fatalf("failed to get redis db index: %v", err)
}
store.InitializeStore(addr, password, db)
srv := &http.Server{
Addr: "0.0.0.0:9090",
Addr: "0.0.0.0:" + os.Getenv("SERVER_PORT"),
Handler: router,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
@ -34,7 +47,7 @@ func main() {
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Printf("failed to start server on :9000, err: %v", err)
log.Printf("failed to start server on :"+os.Getenv("SERVER_PORT")+", err: %v", err)
}
}()

View File

@ -20,11 +20,11 @@ var (
const CacheDuration = 6 * time.Hour
func InitializeStore() {
func InitializeStore(addr string, password string, db int) {
redisClient := redis.NewClient(&redis.Options{
Addr: "localhost:6378",
Password: "secret",
DB: 0,
Addr: addr,
Password: password,
DB: db,
})
pong, err := redisClient.Ping(ctx).Result()