Skip to content

Commit a54ad80

Browse files
committed
feat: working api route to postgres nd strategy implementation
1 parent 96f477d commit a54ad80

File tree

8 files changed

+131
-24
lines changed

8 files changed

+131
-24
lines changed

bin/air

7.84 MB
Binary file not shown.

go.mod

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,22 @@ module github.com/syntaxsdev/mercury
22

33
go 1.22.7
44

5+
require (
6+
github.com/go-chi/chi/v5 v5.2.0
7+
github.com/redis/go-redis/v9 v9.7.0
8+
go.mongodb.org/mongo-driver v1.17.1
9+
go.mongodb.org/mongo-driver/v2 v2.0.0
10+
)
11+
512
require (
613
github.com/cespare/xxhash/v2 v2.2.0 // indirect
714
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
8-
github.com/go-chi/chi/v5 v5.2.0 // indirect
9-
github.com/golang-migrate/migrate/v4 v4.18.1 // indirect
1015
github.com/golang/snappy v0.0.4 // indirect
11-
github.com/hashicorp/errwrap v1.1.0 // indirect
12-
github.com/hashicorp/go-multierror v1.1.1 // indirect
1316
github.com/klauspost/compress v1.17.11 // indirect
14-
github.com/redis/go-redis/v9 v9.7.0 // indirect
1517
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
1618
github.com/xdg-go/scram v1.1.2 // indirect
1719
github.com/xdg-go/stringprep v1.0.4 // indirect
1820
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
19-
go.mongodb.org/mongo-driver/v2 v2.0.0 // indirect
20-
go.uber.org/atomic v1.11.0 // indirect
2121
golang.org/x/crypto v0.31.0 // indirect
2222
golang.org/x/sync v0.10.0 // indirect
2323
golang.org/x/text v0.21.0 // indirect

go.sum

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
1+
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
2+
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
3+
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
4+
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
15
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
26
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
7+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
38
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
49
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
510
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
611
github.com/go-chi/chi/v5 v5.2.0 h1:Aj1EtB0qR2Rdo2dG4O94RIU35w2lvQSj6BRA4+qwFL0=
712
github.com/go-chi/chi/v5 v5.2.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
8-
github.com/golang-migrate/migrate/v4 v4.18.1 h1:JML/k+t4tpHCpQTCAD62Nu43NUFzHY4CV3uAuvHGC+Y=
9-
github.com/golang-migrate/migrate/v4 v4.18.1/go.mod h1:HAX6m3sQgcdO81tdjn5exv20+3Kb13cmGli1hrD6hks=
1013
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
1114
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
12-
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
13-
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
14-
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
15-
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
16-
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
15+
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
16+
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
1717
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
1818
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
19-
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
2019
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
2120
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
2221
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
@@ -28,10 +27,10 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi
2827
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
2928
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
3029
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
30+
go.mongodb.org/mongo-driver v1.17.1 h1:Wic5cJIwJgSpBhe3lx3+/RybR5PiYRMpVFgO7cOHyIM=
31+
go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4=
3132
go.mongodb.org/mongo-driver/v2 v2.0.0 h1:Jfd7XpdZa9yk3eY774bO7SWVb30noLSirL9nKTpavhI=
3233
go.mongodb.org/mongo-driver/v2 v2.0.0/go.mod h1:nSjmNq4JUstE8IRZKTktLgMHM4F1fccL6HGX1yh+8RA=
33-
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
34-
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
3534
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
3635
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
3736
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=

internal/handlers/helpers.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package handlers
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
7+
"github.com/syntaxsdev/mercury/models"
8+
)
9+
10+
func WriteHttp(w http.ResponseWriter, code int, message string, data interface{}) error {
11+
w.Header().Set("Content-Type", "application/json")
12+
w.WriteHeader(code)
13+
err := json.NewEncoder(w).Encode(models.Response{Message: message, Code: code, Data: data})
14+
if err != nil {
15+
return err
16+
}
17+
return nil
18+
}

internal/handlers/strategy.go

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,82 @@ package handlers
22

33
import (
44
"encoding/json"
5+
"log"
56
"net/http"
67

78
"github.com/syntaxsdev/mercury/internal/services"
89
"github.com/syntaxsdev/mercury/models"
10+
"go.mongodb.org/mongo-driver/bson"
911
)
1012

1113
// Get All Strategies
1214
func GetAllStrategies(w http.ResponseWriter, r *http.Request, f *services.Factory) {
15+
var results []interface{}
16+
var payload map[string]interface{}
17+
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
18+
payload = nil
19+
}
20+
21+
if payload != nil {
22+
err := f.MongoService.First("strategies", bson.M(payload), &results)
23+
if err == nil && results == nil {
24+
WriteHttp(w, http.StatusNotFound, "Nothing was found with the supplied filter", nil)
25+
return
26+
} else if err == nil {
27+
log.Println("Here")
28+
WriteHttp(w, http.StatusOK, "Successfully fetched all strategies by filter", results)
29+
}
30+
log.Println("Here", err)
31+
}
32+
err := f.MongoService.All("strategies", bson.M{}, &results)
33+
if err != nil {
34+
http.Error(w, "Could not retrieve strategies.", http.StatusInternalServerError)
35+
return
36+
}
37+
code := http.StatusOK
38+
WriteHttp(w, code, "Successfully fetched all strategies", results)
1339

1440
}
1541

42+
// // Get Strategy By ID
43+
// func GetStrategyByID(w http.ResponseWriter, r *http.Request, f *services.Factory) {
44+
// var result interface{}
45+
// id := chi.URLParam(r, "id")
46+
// port, err := strconv.Atoi(id)
47+
// if err != nil {
48+
// WriteHttp(w, http.StatusBadRequest, "Invalid", err)
49+
// }
50+
// // objectID, err := primitive.ObjectIDFromHex(id)
51+
// // if err != nil {
52+
// // WriteHttp(w, http.StatusBadRequest, "Invalid ID", err)
53+
// // return
54+
// // }
55+
56+
// err = f.MongoService.First("strategies", bson.M{"port": port}, &result)
57+
// if err != nil {
58+
// WriteHttp(w, http.StatusBadRequest, "Could not retrieve strategy by ID.", nil)
59+
// log.Println(err)
60+
// return
61+
// }
62+
// WriteHttp(w, http.StatusOK, "Successfully fetched strategy", result)
63+
64+
// }
65+
1666
// Create A Strategy
1767
func CreateStrategy(w http.ResponseWriter, r *http.Request, f *services.Factory) {
1868
var newStrategy models.Strategy
1969
if err := json.NewDecoder(r.Body).Decode(&newStrategy); err != nil {
20-
70+
http.Error(w, "Invalid payload", http.StatusBadRequest)
71+
return
2172
}
22-
f.MongoService.Insert("strategies", newStrategy)
73+
res, err := f.MongoService.Insert("strategies", newStrategy)
74+
if err != nil {
75+
http.Error(w, "Could not insert strategy", http.StatusInternalServerError)
76+
}
77+
78+
WriteHttp(w, http.StatusCreated, "Strategy successfully created", res)
79+
// code := http.StatusCreated
80+
// w.Header().Set("Content-Type", "application/json")
81+
// w.WriteHeader(http.StatusCreated)
82+
// json.NewEncoder(w).Encode(models.Response{Message: "Strategy successfully created", Code: code, Data: res})
2383
}

internal/services/mongo.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package services
22

33
import (
44
"context"
5+
"log"
56
"time"
67

78
"go.mongodb.org/mongo-driver/v2/mongo"
@@ -27,10 +28,18 @@ func (s *MongoService) Insert(collection string, item interface{}) (interface{},
2728

2829
func (s *MongoService) First(collection string, filter interface{}, result interface{}) error {
2930
coll := s.Client.Database(s.DatabaseName).Collection(collection)
30-
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
31+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
3132
defer cancel()
32-
33+
log.Println(filter)
34+
log.Println(collection)
3335
err := coll.FindOne(ctx, filter).Decode(result)
36+
log.Println(result)
37+
if err == mongo.ErrNoDocuments {
38+
if resultPtr, ok := result.(*interface{}); ok {
39+
*resultPtr = nil
40+
}
41+
return nil
42+
}
3443
return err
3544

3645
}

main.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,13 @@ func main() {
1717
// Get environment variables
1818
dbHost := os.Getenv("DB_HOST")
1919
dbName := os.Getenv("DB_NAME")
20+
dbUser := os.Getenv("DB_USER")
21+
dbPass := os.Getenv("DB_PASSWORD")
22+
dbPort := os.Getenv("DB_PORT")
2023

2124
// Set defaults
2225
if dbHost == "" {
23-
dbHost = "localhost:27017"
26+
dbHost = "localhost"
2427
log.Printf("INFO: No `DB_HOST` set. Defaulting to %s\n", dbHost)
2528
}
2629

@@ -29,8 +32,25 @@ func main() {
2932
log.Printf("INFO: No `DN_NAME` set. Defaulting to %s\n", dbName)
3033
}
3134

35+
if dbUser == "" {
36+
dbUser = "mercury"
37+
log.Printf("INFO: No `DB_USER` set. Defaulting to %s\n", dbUser)
38+
}
39+
40+
if dbPass == "" {
41+
dbPass = "mercury_db"
42+
log.Printf("INFO: No `DB_PASSWORD` set. Defaulting...")
43+
}
44+
45+
if dbPort == "" {
46+
dbPort = "27017"
47+
log.Printf("INFO: No `DB_USER` set. Defaulting to %s\n", dbUser)
48+
}
49+
3250
// Create MongoDB client
33-
mongo, cleanup := repositories.NewMongoClient(dbHost)
51+
connString := fmt.Sprintf("mongodb://%s:%s@%s:%s", dbUser, dbPass, dbHost, dbPort)
52+
log.Println(connString)
53+
mongo, cleanup := repositories.NewMongoClient(connString)
3454
defer cleanup()
3555
ms := services.MongoService{Client: mongo, DatabaseName: dbName}
3656

@@ -40,6 +60,7 @@ func main() {
4060
// Start Routes
4161
router := api.InitRoutes(&factory)
4262

63+
log.Printf("INFO: Starting Server... Listening on localhost:%s\n", dbPort)
4364
if err := http.ListenAndServe(":8080", router); err != nil {
4465
log.Fatalf("Serve failed to start: %v", err)
4566
}

models/strategy.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ type Strategy struct {
99

1010
type StrategyOptions struct {
1111
Active bool `json:"active"`
12-
Meta interface{} `json:"meta,omitempty"` // Any data
12+
Meta interface{} `json:"meta,omitempty"` // Any dictionary data allowed here
1313
}

0 commit comments

Comments
 (0)