Skip to content

Commit

Permalink
Basic CRUD handlers and services.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jyothis-P committed May 29, 2024
1 parent 18a306d commit 2f52625
Show file tree
Hide file tree
Showing 10 changed files with 483 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DATABASE_URI=mongodb://localhost:27017
DATABASE_NAME=mydb
Empty file added README.md
Empty file.
39 changes: 39 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package grf

import (
"context"
"log"
"os"
"time"

"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func SetupDatabase() (*mongo.Database, func(), error) {
connectionString, dbname := GetDBDetails()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(connectionString))

disconnect := func() {
cancel()
if err := client.Disconnect(ctx); err != nil {
panic(err)
}
}
db := client.Database(dbname)

return db, disconnect, err
}

func GetDBDetails() (uri, dbname string) {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}

uri = os.Getenv("DATABASE_URI")
dbname = os.Getenv("DATABASE_NAME")
return
}
2 changes: 2 additions & 0 deletions example/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DATABASE_URI=mongodb://localhost:27017
DATABASE_NAME=mydb
74 changes: 74 additions & 0 deletions example/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package main

import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"

grf "github.com/Jyothis-P/go-rest-framework"
"github.com/gorilla/mux"
)

// Create a model
// Make sure to give json and bson structs as necessary.
type Todo struct {
Title string `json:"title" bson:"title"`
Completed bool `json:"completed" bson:"completed"`
}

func main() {

// Setup database.
db, cancel, err := grf.SetupDatabase()
defer cancel()
if err != nil {
log.Println("Error setting up the database.", err)
return
}

// Create App context.
appContext := grf.Ctx{
DB: db,
}

// Create a router.
r := mux.NewRouter().StrictSlash(true)

// Register routes for the model.
grf.RegisterCRUDRoutes[Todo]("/todo", r, &appContext)

// Set up server.
const PORT string = "8001"
srv := &http.Server{
Addr: "0.0.0.0:" + PORT,
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r,
}

// Start the server.

go func() {
log.Println("Starting web server on " + PORT)
if err := srv.ListenAndServe(); err != nil {
log.Println("Error with the web server.")
log.Println(err)
}
}()

// Graceful shutdown of the server in case of os interrupts.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c

ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()

srv.Shutdown(ctx)
log.Println("Shutting down.")
os.Exit(0)
}
19 changes: 19 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
module github.com/Jyothis-P/go-rest-framework

go 1.22.3

require (
github.com/gorilla/mux v1.8.1
github.com/joho/godotenv v1.5.1
go.mongodb.org/mongo-driver v1.15.0
)

require (
github.com/golang/snappy v0.0.1 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // 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-20181117223130-1be2e3e5546d // indirect
golang.org/x/crypto v0.17.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/text v0.14.0 // indirect
)
56 changes: 56 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
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/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/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
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-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mongodb.org/mongo-driver v1.15.0 h1:rJCKC8eEliewXjZGf0ddURtl7tTVy1TK3bfl0gkUSLc=
go.mongodb.org/mongo-driver v1.15.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c=
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.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
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/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.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/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-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/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.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
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=
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=
24 changes: 24 additions & 0 deletions grf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package grf

import (
"net/http"

"go.mongodb.org/mongo-driver/mongo"
)

// Application Context struct. This is made available to your handler functions as a parameter.
// Handy for keeping values like database connections.
type Ctx struct {
DB *mongo.Database
}

// An adapter for handler functions with an added app context passed in.
// Implements http.Handler.
type H struct {
*Ctx
Fn func(*Ctx, http.ResponseWriter, *http.Request)
}

func (appHandler H) ServeHTTP(w http.ResponseWriter, r *http.Request) {
appHandler.Fn(appHandler.Ctx, w, r)
}
150 changes: 150 additions & 0 deletions handlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package grf

import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"

"github.com/gorilla/mux"
)

// Function to register the basic CRUD routes given a model.
// User can register individual routes from the generic handlers.
// Or they can use this function to generate teh default REST endpoints.
// Problem comes when it is mongodb which does not support CASCADE delete out of the box and you need a better logic for deleting.
// Maybe add an optional callback function?
// Putting a pin on it. [This can be good for atomics]
// [For objects with more complex dependencies, use the handlers you need and create the rest yourself]
func RegisterCRUDRoutes[T any](pathPrefix string, r *mux.Router, ctx *Ctx) *mux.Router {
subRouter := r.PathPrefix(pathPrefix).Subrouter()
subRouter.Handle("/", H{Ctx: ctx, Fn: GetAllHandler[T]}).Methods("GET")
subRouter.Handle("/{id}", H{Ctx: ctx, Fn: GetHandler[T]}).Methods("GET")
subRouter.Handle("/", H{Ctx: ctx, Fn: CreateHandler[T]}).Methods("POST")
subRouter.Handle("/{id}", H{Ctx: ctx, Fn: DeleteHandler[T]}).Methods("DELETE")
return subRouter
}

func GetHandler[K any](ctx *Ctx, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var object K
err := ReadOne(ctx.DB, &object, vars["id"])
if err != nil {
log.Print("Error retrieving object.")
log.Print(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
b, err := json.Marshal(object)
if err != nil {
log.Print("Error marshalling.")
log.Print(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, string(b))
}

func GetAllHandler[K any](ctx *Ctx, w http.ResponseWriter, r *http.Request) {
var objects []K
err := Read(ctx.DB, &objects)
log.Println(objects)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "Error getting all objects.")
return
}

log.Println(objects)
b, err := json.Marshal(objects)
if err != nil {
log.Print("Error marshalling.")
log.Print(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, string(b))
}

func CreateHandler[T any](ctx *Ctx, w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()

var object T
err := decoder.Decode(&object)

// Let the gatekeeping begin.
if err != nil {
log.Println("Error decoding the object from the request.")
msg, statusCode := validateJsonError(err)
http.Error(w, msg, statusCode)
log.Println(msg)
return
}

log.Println("Decoded object: ", object)

// Attempting to save the object to the db.
res, err := Create(ctx.DB, object)

if err != nil {
log.Print("Error saving object to db.")
log.Print(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Object created!, id: %s", *res)
}

func DeleteHandler[T any](ctx *Ctx, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)

// Adding additional checks in this generic function would be difficult.
// If you need more validation and dependency checking, please use a seperate handler for the same.
err := Delete[T](ctx.DB, vars["id"])
if err != nil {
http.Error(w, "Error deleting object.", http.StatusInternalServerError)
return
}

w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Object deleted.")
}

func validateJsonError(err error) (string, int) {
msg := ""
var statusCode int
var unmarshallError *json.UnmarshalTypeError
var syntaxError *json.SyntaxError
switch {
case errors.As(err, &syntaxError):
msg = fmt.Sprintf("Request body contains badly-formed JSON (at position %d)", syntaxError.Offset)
statusCode = http.StatusBadRequest
case errors.As(err, &unmarshallError):
msg = fmt.Sprintf("Request body contains an invalid value for the %q field (at position %d)", unmarshallError.Field, unmarshallError.Offset)
statusCode = http.StatusBadRequest
case errors.Is(err, io.ErrUnexpectedEOF):
msg = "Request body contains badly-formed JSON"
statusCode = http.StatusBadRequest
case strings.HasPrefix(err.Error(), "json: unknown field "):
fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
msg = fmt.Sprintf("Request body contains unknown field %s", fieldName)
statusCode = http.StatusBadRequest
case errors.Is(err, io.EOF):
msg = "Request body must not be empty"
statusCode = http.StatusBadRequest
case err.Error() == "http: request body too large":
msg = "Request body must not be larger than 1MB"
statusCode = http.StatusRequestEntityTooLarge
default:
msg = http.StatusText(http.StatusInternalServerError)
statusCode = http.StatusInternalServerError
}
return msg, statusCode
}
Loading

0 comments on commit 2f52625

Please sign in to comment.