CRUD Operations Using GOA Framework — Part I
Build your api’s using GOA framework
Before we begin let’s understand what is GOA ?
- Goa is framework for developing API’s and microservices in Go.
- Goa completely relies on code generation which reduces the need for repetitive coding.
- Goa is design based framework, having said that “Design is the single source of truth” and from which both design and docs are derived.
- You can find more detailed information here
Moving on let’s get started ….
NOTE: Part-I
just includes adding services for adding records and showing the added records!
Create a new project under your home directory
mkdir -p book/designcd bookgo mod init book
Next make sure the Goa module is installed and up-to-date:
go get -u goa.design/goa/v3
go get -u goa.design/goa/v3/...
Now let’s start with design to create a record of book and list all the books
Create and open the file $HOME/book/design/design.go
and paste the following code …
Further let’s create and add type for book, open the file $HOME/book/design/type.go
and paste the following code
Now let’s write methods for create and list by updating the design.go
file
Now as we have the design for our service let’s run the goa gen
command to generated the code. Since our design package was created under the book
module the command line is
goa gen book/design
The generated file should look like this
gen
├── book
│ ├── client.go
│ ├── endpoints.go
│ ├── service.go
│ └── views
│ └── view.go
└── http
├── book
│ ├── client
│ │ ├── client.go
│ │ ├── cli.go
│ │ ├── encode_decode.go
│ │ ├── paths.go
│ │ └── types.go
│ └── server
│ ├── encode_decode.go
│ ├── paths.go
│ ├── server.go
│ └── types.go
├── cli
│ └── book
│ └── cli.go
├── openapi3.json
├── openapi3.yaml
├── openapi.json
└── openapi.yaml
We can now run the goa example
command to generate a basic implementation of the service along with buildable server files that spins up goroutines to start a HTTP.
goa example book/design
The goa example
command creates the following files
├── book.go
├── cmd
│ ├── book
│ │ ├── http.go
│ │ └── main.go
│ └── book-cli
│ ├── http.go
│ └── main.go
The auto-generated book.go
file would be similar to
Edit the file book.go
and implement the create
and list
method. Copy and replace the following code in book.go
The generated server are built and run as follows:
go build ./cmd/book
# Run the server./book[bookapi] 18:02:39 HTTP "Create" mounted on POST /
[bookapi] 18:02:39 HTTP "List" mounted on GET /books
[bookapi] 18:02:39 HTTP server listening on "localhost:8000"
Let’s add a record using Postman by making a POST
api call
To list the records of books one can simply make an api call with method GET
as follows
Let’s create services for updating and deleting in Part-II
You can find the source code here