Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use go-chi for handling routes #11

Merged
merged 21 commits into from
Dec 26, 2021
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ import (
"log"
"net/http"
"os"
"github.com/SimplQ/simplQ-golang/internal/mux"

"github.com/SimplQ/simplQ-golang/internal/mux"
)

func main() {
routes := mux.InitalizeRoutes()

listenAddr := ":8080"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Moved variable down to be closer to where it's required.

if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok {
listenAddr = ":" + val
}

mux.InitalizeRoutes()

log.Printf("About to listen on %s. Go to https://127.0.0.1%s/", listenAddr, listenAddr)
log.Fatal(http.ListenAndServe(listenAddr, nil))
log.Printf("About to listen on %s. Go to http://127.0.0.1%s/", listenAddr, listenAddr)
log.Fatal(http.ListenAndServe(listenAddr, routes))
}
17 changes: 17 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
module github.com/SimplQ/simplQ-golang

go 1.17

require go.mongodb.org/mongo-driver v1.8.1

require (
github.com/go-chi/chi/v5 v5.0.7 // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.0.2 // indirect
github.com/xdg-go/stringprep v1.0.2 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f // indirect
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect
golang.org/x/text v0.3.5 // indirect
)
58 changes: 58 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
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/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8=
github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
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.0.2 h1:akYIkZ28e6A96dkWNJQu3nmCzH3YfwMPQExUYDaRv7w=
github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs=
github.com/xdg-go/stringprep v1.0.2 h1:6iq84/ryjjeRmMJwxutI51F2GIPlP5BfTvXHeYjyhBc=
github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
go.mongodb.org/mongo-driver v1.8.1 h1:OZE4Wni/SJlrcmSIBRYNzunX5TKxjrTS4jKSnA99oKU=
go.mongodb.org/mongo-driver v1.8.1/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f h1:aZp0e2vLN4MToVqnjNEYEtrEA8RH8U8FN1CU7JgqsPU=
golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/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-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
92 changes: 92 additions & 0 deletions internal/datastore/mongo_store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package datastore

import (
"context"
"log"
"os"

"github.com/SimplQ/simplQ-golang/internal/models"

"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

// A Structure with Collections frequently used and a pointer to the client
type MongoDB struct {
Client *mongo.Client
Queue *mongo.Collection
Token *mongo.Collection
}

var mongodb MongoDB

func NewMongoDB() *MongoDB {
// Use local mongodb instance if env variable not set
uri := "mongodb://localhost:27017/?maxPoolSize=20&w=majority"

if val, ok := os.LookupEnv("MONGO_URI"); ok {
uri = val
}

log.Println("Connecting to MongoDB...")

client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))

if err != nil {
log.Fatal(err)
}

new_mongodb := MongoDB {
client,
client.Database("simplq").Collection("queue"),
client.Database("simplq").Collection("token"),
}

log.Println("Successfully connected to MongoDB!")

return &new_mongodb
}

func (mongodb MongoDB) CreateQueue(queue models.Queue) models.QueueId {
// Set id to empty so its generated by mongoDB
queue.Id = ""

result, err := mongodb.Queue.InsertOne(context.TODO(), queue)

if err != nil {
log.Fatal(err)
}

stringId := result.InsertedID.(primitive.ObjectID).Hex()

return models.QueueId(stringId)
}

func (mongodb MongoDB) ReadQueue(models.QueueId) models.Queue {
panic("Not implemented")
}

func (mongodb MongoDB) PauseQueue(models.QueueId) {
panic("Not implemented")
}

func (mongodb MongoDB) ResumeQueue(models.QueueId) {
panic("Not implemented")
}

func (mongodb MongoDB) DeleteQueue(models.QueueId) {
panic("Not implemented")
}

func (mongodb MongoDB) AddTokenToQueue(models.QueueId, models.Token) {
panic("Not implemented")
}

func (mongodb MongoDB) ReadToken(models.TokenId) {
panic("Not implemented")
}

func (mongodb MongoDB) RemoveToken(models.TokenId) {
panic("Not implemented")
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package persistence
package datastore

import (
"github.com/SimplQ/simplQ-golang/internal/models"
)
import "github.com/SimplQ/simplQ-golang/internal/models"

type QueueStore interface {
// Create a new queue and return the queue ID.
Expand All @@ -29,3 +27,5 @@ type QueueStore interface {
// Delete token
RemoveToken(models.TokenId)
}

var Store QueueStore = NewMongoDB()
43 changes: 43 additions & 0 deletions internal/handler/queue.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package handler

import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"

"github.com/SimplQ/simplQ-golang/internal/datastore"
"github.com/SimplQ/simplQ-golang/internal/models"
)

func GetQueue(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "GET Queue not implemented")
}

func CreateQueue(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)

var q models.Queue
err := decoder.Decode(&q)

if err != nil {
panic(err)
}

// Initialize values
// Only consider queue name from the body of the request
q.CreationTime = time.Now()
q.IsDeleted = false
q.IsPaused = false
q.Tokens = make([]models.Token, 0)

log.Print("Create Queue: ")
log.Println(q)

insertedId := datastore.Store.CreateQueue(q)

log.Printf("Inserted %s", insertedId)

fmt.Fprintf(w, "Post queue")
}
17 changes: 9 additions & 8 deletions internal/models/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,27 @@ import (
type QueueId Id

type Queue struct {
// Unique ID for the queue.
Id QueueId
// Unique ID for the queue.
Id QueueId `bson:"_id,omitempty"`

// Name of the queue. The name is used in generating queue urls, for ex
// https://simplq.me/j/<QueueName>. The storage layer guarantees sure that
// there is only one queue by a given name.
QueueName string
QueueName string `bson:"queueName"`

// Set to true if the queue is temporarily not issuing tokens
IsPaused bool
IsPaused bool `bson:"isPaused"`

// Set to true if the queue has been deleted
IsDeleted bool
IsDeleted bool `bson:"isDeleted"`

// Tokens present in the queue.
Tokens []Token
Tokens []Token `bson:"tokens"`

// Creation time.
CreationTime time.Time
CreationTime time.Time `bson:"creationTime,omitempty"`

// Deletion time.
DeletionTime time.Time
DeletionTime time.Time `bson:"deletionTime,omitempty"`

}
27 changes: 23 additions & 4 deletions internal/mux/mux.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
package mux

import (
"net/http"
"github.com/SimplQ/simplQ-golang/internal/handler"
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"

"github.com/SimplQ/simplQ-golang/internal/handler"
)

func InitalizeRoutes() {
http.HandleFunc("/api/HttpExample", handler.Hello);
func InitalizeRoutes() chi.Router {
r := chi.NewRouter()

r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)

r.Use(middleware.Timeout(10 * time.Second))

// Routes for "queue" resource
r.Route("/queue", func(r chi.Router) {
// POST /articles
r.Post("/", handler.CreateQueue)
})

return r;
}