From e22082d15215a7115e2d1732518ad61cd72a3792 Mon Sep 17 00:00:00 2001 From: whysman Date: Fri, 25 Apr 2025 01:28:05 -0400 Subject: [PATCH 1/3] zip code lookup api, mongo conn, viper config, cleaning --- config.yaml | 7 ++- go.mod | 28 ++++++++++- go.sum | 110 ++++++++++++++++++++++++++++++++++++----- main.go | 140 +++++++++++++++++++++++++++++++--------------------- 4 files changed, 215 insertions(+), 70 deletions(-) diff --git a/config.yaml b/config.yaml index 7517127..8b64063 100644 --- a/config.yaml +++ b/config.yaml @@ -1,3 +1,8 @@ redis: host: localhost - port: 6379 \ No newline at end of file + port: 6379 +mongo: + host: localhost + port: 27017 + user: example + pass: example \ No newline at end of file diff --git a/go.mod b/go.mod index cdac06b..40d5c10 100644 --- a/go.mod +++ b/go.mod @@ -6,10 +6,34 @@ require ( github.com/go-redis/redis/v8 v8.11.5 github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 - gopkg.in/yaml.v2 v2.4.0 + github.com/spf13/viper v1.20.1 + go.mongodb.org/mongo-driver v1.17.3 ) require ( - github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/fsnotify/fsnotify v1.8.0 // indirect + github.com/go-viper/mapstructure/v2 v2.2.1 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/klauspost/compress v1.16.7 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/sagikazarmark/locafero v0.7.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.12.0 // indirect + github.com/spf13/cast v1.7.1 // indirect + github.com/spf13/pflag v1.0.6 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + golang.org/x/crypto v0.32.0 // indirect + golang.org/x/sync v0.10.0 // indirect + golang.org/x/sys v0.29.0 // indirect + golang.org/x/text v0.21.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 3270a05..ba5b797 100644 --- a/go.sum +++ b/go.sum @@ -1,30 +1,118 @@ -github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= -github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= +github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= +github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= +github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= +github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781 h1:DzZ89McO9/gWPsQXS/FVKAlG02ZjaQ6AlZRBimEYOd0= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +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/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo= +github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs= +github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4= +github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= +github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= +github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ= +go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= +golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 62dcbc1..1760190 100644 --- a/main.go +++ b/main.go @@ -14,7 +14,10 @@ import ( "github.com/go-redis/redis/v8" "github.com/gorilla/mux" "github.com/gorilla/websocket" - "gopkg.in/yaml.v2" + "github.com/spf13/viper" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" ) var ( @@ -41,6 +44,12 @@ type Config struct { Host string `yaml:"host"` Port string `yaml:"port"` } + Mongo struct { + Host string `yaml:"host"` + Port string `yaml:"port"` + User string `yaml:"user"` + Pass string `yaml:"pass"` + } } type Client struct { @@ -54,34 +63,29 @@ type Server struct { mu sync.Mutex } -func getConfig(configPath string) (*Config, error) { - // Create config structure - config := &Config{} +type MongoConn struct { + conn *mongo.Client +} - // Open config file - file, err := os.Open(configPath) - if err != nil { - return nil, err +func getConfig(configPath string) (Config, error) { + viper.SetConfigName("config") // name of config file (without extension) + viper.SetConfigType("yaml") + viper.AddConfigPath(".") // optionally look for config in the working directory + err := viper.ReadInConfig() // Find and read the config file + if err != nil { // Handle errors reading the config file + panic(fmt.Errorf("fatal error config file: %w", err)) } - defer func(file *os.File) { - err := file.Close() - if err != nil { + var config Config - } - }(file) - - // Init new YAML decode - d := yaml.NewDecoder(file) - - // Start YAML decoding from file - if err := d.Decode(&config); err != nil { - return nil, err + err = viper.Unmarshal(&config) + if err != nil { + log.Fatalf("unable to decode into struct, %v", err) } return config, nil } -func loadConfig() *Config { +func loadConfig() Config { cfg, err := getConfig("config.yaml") if err != nil { log.Fatal(err) @@ -108,6 +112,22 @@ func newServer() *Server { } } +func newMongo(cfg Config) *MongoConn { + credential := options.Credential{ + Username: cfg.Mongo.User, + Password: cfg.Mongo.Pass, + } + clientOpts := options.Client().ApplyURI("mongodb://" + cfg.Mongo.Host + ":" + cfg.Mongo.Port).SetAuth(credential) + client, err := mongo.Connect(ctx, clientOpts) + //mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")) + if err != nil { + log.Fatal(err) + } + return &MongoConn{ + conn: client, + } +} + func (s *Server) addClient(client *Client) { s.mu.Lock() defer s.mu.Unlock() @@ -328,39 +348,44 @@ func setState(w http.ResponseWriter, r *http.Request, s *Server) { w.WriteHeader(http.StatusOK) } -/* - func updateState(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed) - return - } - allRecords, err := fetchAllRecords() - if err != nil { - log.Printf("Error fetching records: %v", err) - http.Error(w, "Failed to fetch records", http.StatusInternalServerError) - return - } - - var messages []Message - for _, record := range allRecords { - var message Message - err := json.Unmarshal([]byte(record), &message) - if err != nil { - log.Printf("Error unmarshalling record: %v", err) - http.Error(w, "Failed to parse records", http.StatusInternalServerError) - return - } - messages = append(messages, message) - } - - w.Header().Set("Content-Type", "application/json") - err = json.NewEncoder(w).Encode(messages) - if err != nil { - log.Printf("Error encoding response: %v", err) - http.Error(w, "Failed to encode response", http.StatusInternalServerError) - } +func getLocByZip(w http.ResponseWriter, r *http.Request, mongo *MongoConn) { + var request struct { + Zip string `json:"Zip"` } -*/ + err := json.NewDecoder(r.Body).Decode(&request) + + if r.Method != http.MethodPost { + http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) + return + } + + if err != nil { + http.Error(w, "Invalid JSON format", http.StatusBadRequest) + } + fmt.Println(request) + if request.Zip == "" { + fmt.Println("Missing or empty zip field") + http.Error(w, "Missing or empty zip field", http.StatusBadRequest) + return + } + var result struct { + Location struct { + Coordinates []float64 `bson:"coordinates"` + } `bson:"location"` + } + err = mongo.conn.Database("geodb").Collection("zipcodes"). + FindOne(ctx, bson.M{"zip": request.Zip}).Decode(&result) + if err != nil { + http.Error(w, "Failed to find zip field", http.StatusInternalServerError) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + err = json.NewEncoder(w).Encode(result.Location.Coordinates) + if err != nil { + http.Error(w, "Failed to encode response", http.StatusInternalServerError) + } +} + func enableCORS(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") // Allow all origins @@ -378,8 +403,9 @@ func enableCORS(next http.Handler) http.Handler { } func main() { - initRedis(*loadConfig()) - + config := loadConfig() + initRedis(config) + mongoConn := newMongo(config) server := newServer() router := mux.NewRouter() @@ -389,7 +415,9 @@ func main() { router.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) { setState(w, r, server) }).Methods("POST") - //router.HandleFunc("/update", updateState).Methods("GET") + router.HandleFunc("/zipLookup", func(w http.ResponseWriter, r *http.Request) { + getLocByZip(w, r, mongoConn) + }).Methods("POST") corsRouter := enableCORS(router) // Start server and other necessary goroutines From 974fc95f2d107c3b0686b9cecbf7ed246eed3a0a Mon Sep 17 00:00:00 2001 From: whysman Date: Mon, 28 Apr 2025 00:10:56 -0400 Subject: [PATCH 2/3] added park lookup api --- main.go | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 1760190..cf87bb0 100644 --- a/main.go +++ b/main.go @@ -16,6 +16,7 @@ import ( "github.com/gorilla/websocket" "github.com/spf13/viper" "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) @@ -353,15 +354,13 @@ func getLocByZip(w http.ResponseWriter, r *http.Request, mongo *MongoConn) { Zip string `json:"Zip"` } err := json.NewDecoder(r.Body).Decode(&request) - + if err != nil { + http.Error(w, "Invalid JSON format", http.StatusBadRequest) + } if r.Method != http.MethodPost { http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) return } - - if err != nil { - http.Error(w, "Invalid JSON format", http.StatusBadRequest) - } fmt.Println(request) if request.Zip == "" { fmt.Println("Missing or empty zip field") @@ -386,6 +385,69 @@ func getLocByZip(w http.ResponseWriter, r *http.Request, mongo *MongoConn) { } } +func parkLookup(w http.ResponseWriter, r *http.Request, mongo *MongoConn) { + var request struct { + Lat float32 `json:"Lat"` + Lon float32 `json:"Lon"` + Dist float32 `json:"Dist"` + } + err := json.NewDecoder(r.Body).Decode(&request) + if err != nil { + http.Error(w, "Cannot decode request", http.StatusBadRequest) + } + if r.Method != http.MethodPost { + http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) + return + } + log.Println(request.Lat, request.Lon, request.Dist) + + cursor, err := mongo.conn.Database("geodb").Collection("parks"). + Find(ctx, bson.D{{"location", bson.D{{"$near", bson.D{{"$geometry", bson.D{ + {"type", "Point"}, {"coordinates", bson.A{request.Lat, request.Lon}}}}, + {"$minDistance", 0}, {"$maxDistance", request.Dist * 1609.344}}}}}}) + if err != nil { + http.Error(w, "Failed to find parks", http.StatusInternalServerError) + } + if cursor.Err() != nil { + http.Error(w, "Failed to find parks", http.StatusInternalServerError) + } + type Result struct { + Id primitive.ObjectID `bson:"_id"` + Name string `json:"name"` + Address string `json:"address"` + City string `json:"city"` + State string `json:"state"` + Zip string `json:"zip"` + Location struct { + Coordinates []float64 `json:"coordinates"` + } `json:"location"` + } + var totalResult []Result + if cursor.RemainingBatchLength() > 0 { + log.Printf("Found %d parks", cursor.RemainingBatchLength()) + + for cursor.Next(ctx) { + var result Result + log.Printf(cursor.Current.String()) + if err := cursor.Decode(&result); err != nil { + log.Fatal(err) + } + fmt.Printf("%+v\n", result) + totalResult = append(totalResult, result) + } + if err := cursor.Err(); err != nil { + log.Fatal(err) + } + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + err = json.NewEncoder(w).Encode(totalResult) + if err != nil { + http.Error(w, "Failed to encode response", http.StatusInternalServerError) + } + +} + func enableCORS(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") // Allow all origins @@ -418,6 +480,9 @@ func main() { router.HandleFunc("/zipLookup", func(w http.ResponseWriter, r *http.Request) { getLocByZip(w, r, mongoConn) }).Methods("POST") + router.HandleFunc("/parkLookup", func(w http.ResponseWriter, r *http.Request) { + parkLookup(w, r, mongoConn) + }).Methods("POST") corsRouter := enableCORS(router) // Start server and other necessary goroutines From 1908134133628a69d277d06727efae29c5c4b037 Mon Sep 17 00:00:00 2001 From: whysman Date: Mon, 28 Apr 2025 23:15:03 -0400 Subject: [PATCH 3/3] cursor nil check, cleaning --- main.go | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/main.go b/main.go index cf87bb0..963b3ad 100644 --- a/main.go +++ b/main.go @@ -68,7 +68,7 @@ type MongoConn struct { conn *mongo.Client } -func getConfig(configPath string) (Config, error) { +func getConfig() (Config, error) { viper.SetConfigName("config") // name of config file (without extension) viper.SetConfigType("yaml") viper.AddConfigPath(".") // optionally look for config in the working directory @@ -87,7 +87,7 @@ func getConfig(configPath string) (Config, error) { } func loadConfig() Config { - cfg, err := getConfig("config.yaml") + cfg, err := getConfig() if err != nil { log.Fatal(err) } @@ -114,11 +114,15 @@ func newServer() *Server { } func newMongo(cfg Config) *MongoConn { - credential := options.Credential{ - Username: cfg.Mongo.User, - Password: cfg.Mongo.Pass, + clientOpts := options.Client().ApplyURI("mongodb://" + cfg.Mongo.Host + ":" + cfg.Mongo.Port) + if !(cfg.Mongo.User == "" && cfg.Mongo.Pass == "") { + log.Println("WARNING: MongoDB user/pass is set") + credential := options.Credential{ + Username: cfg.Mongo.User, + Password: cfg.Mongo.Pass, + } + clientOpts.SetAuth(credential) } - clientOpts := options.Client().ApplyURI("mongodb://" + cfg.Mongo.Host + ":" + cfg.Mongo.Port).SetAuth(credential) client, err := mongo.Connect(ctx, clientOpts) //mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { @@ -391,9 +395,9 @@ func parkLookup(w http.ResponseWriter, r *http.Request, mongo *MongoConn) { Lon float32 `json:"Lon"` Dist float32 `json:"Dist"` } - err := json.NewDecoder(r.Body).Decode(&request) - if err != nil { + if json.NewDecoder(r.Body).Decode(&request) != nil { http.Error(w, "Cannot decode request", http.StatusBadRequest) + return } if r.Method != http.MethodPost { http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) @@ -405,10 +409,7 @@ func parkLookup(w http.ResponseWriter, r *http.Request, mongo *MongoConn) { Find(ctx, bson.D{{"location", bson.D{{"$near", bson.D{{"$geometry", bson.D{ {"type", "Point"}, {"coordinates", bson.A{request.Lat, request.Lon}}}}, {"$minDistance", 0}, {"$maxDistance", request.Dist * 1609.344}}}}}}) - if err != nil { - http.Error(w, "Failed to find parks", http.StatusInternalServerError) - } - if cursor.Err() != nil { + if err != nil || cursor.Err() != nil { http.Error(w, "Failed to find parks", http.StatusInternalServerError) } type Result struct { @@ -423,12 +424,13 @@ func parkLookup(w http.ResponseWriter, r *http.Request, mongo *MongoConn) { } `json:"location"` } var totalResult []Result - if cursor.RemainingBatchLength() > 0 { + + if cursor != nil && cursor.RemainingBatchLength() > 0 { log.Printf("Found %d parks", cursor.RemainingBatchLength()) for cursor.Next(ctx) { var result Result - log.Printf(cursor.Current.String()) + //log.Printf(cursor.Current.String()) if err := cursor.Decode(&result); err != nil { log.Fatal(err) }