mapi
This repo is a collection of tools that I put together to be more efficient when building APIs. So far, here’s a list of dependencies I’m using:
Requirements
- Go 1.15 or higher. We aim to support the latest supported versions of go.
- MongoDB 4 and higher.
Disclaimer
We do not recommend using this repo for production code, so please be careful where you use this.
Installation
go get github.com/opposite-bracket/mapi
Example
To get started with a project, all you need to do is the following:
NOTE: replace github.com/opposite-bracket/myapi
with
your own.
mkdir ~/go/src/github.com/opposite-bracket/myapi
go mod init github.com/opposite-bracket/myapi
cd myapi
package main
import (
"github.com/opposite-bracket/mapi"
"log"
"net/http"
)
// HomeResponse contains data associated to home response
type HomeResponse struct {
Message string `json:"message"`
}
func main() {
mapi.Api.AddRoute(
"/",
http.MethodGet,
"HOME",
func(context *mapi.RequestContext) {
context.JSON(http.StatusOK, HomeResponse{
"Hello world",
})
})
err := mapi.Api.Start()
if nil != err {
log.Fatal("Failed to start server", err)
}
}
File structure
Here’s how i’m recommending we structure the app
apis
|
++ about.go
|
++ api2.go
|
...
myapi.go
in each api file, you can find a set of API endpoints. For example (about.go
):
package api
import (
"github.com/opposite-bracket/mapi"
"log"
"net/http"
)
type HealthResponse struct {
EnvInfo string `json:"env"`
}
func Health(context *mapi.RequestContext) {
log.Print("Checking env health")
context.JSON(http.StatusOK, HealthResponse{
EnvInfo: context.GetEnvStatus(),
})
}
// REGISTRY
func RegisterHealthRoutes() {
mapi.Api.AddRoute("/v1/_health", http.MethodGet, "HEALTH_EP", Health)
}
Your myapi.go
(main file) should look like this:
package main
import (
"github.com/opposite-bracket/mapi"
"github.com/opposite-bracket/usemapi/api"
"log"
)
// HomeResponse contains data associated to home response
type HomeResponse struct {
Message string `json:"message"`
}
func main() {
err := mapi.Api.Start()
api.RegisterHealthRoutes()
if nil != err {
log.Fatal("Failed to start server", err)
}
}
License
this code is licensed under the MIT license.