2021-09-06 11:27:54 +00:00
|
|
|
# API Gen
|
2021-04-02 14:40:28 +00:00
|
|
|
API Generator
|
2021-09-06 11:27:54 +00:00
|
|
|
|
|
|
|
API Generator works on top of Go code and comments. Instead of generating openapi and from there deriving your code,
|
|
|
|
you can code 1st, and reduce the amount of effort at refactoring / improving your code in case of changes or improvements.
|
|
|
|
|
|
|
|
How it works:
|
|
|
|
|
|
|
|
Create a GO package with the business logic to be exposed:
|
|
|
|
|
|
|
|
```go
|
|
|
|
/*
|
|
|
|
@API
|
|
|
|
@PATH: /someapi
|
|
|
|
@PERM: ASD
|
|
|
|
@VERB: POST
|
|
|
|
*/
|
|
|
|
func SomeAPI(ctx context.Context, s string) (out string, err error) {
|
|
|
|
print("Got:" + s)
|
|
|
|
out = time.Now().String() + " - Hey Ya!"
|
|
|
|
return
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
Note the follwoing on the above API:
|
|
|
|
|
|
|
|
1 - Method has a context as 1st parameter
|
|
|
|
2 - Method has a string as 2nd parameter
|
|
|
|
3 - Method returns a string and an error
|
|
|
|
|
|
|
|
1st Rule of API Methods:
|
|
|
|
|
|
|
|
1 - Always recive context and an interface as parameters in
|
|
|
|
2 - Always return interface and error
|
|
|
|
|
|
|
|
Also note the comments just above the Method, this is used as meta programming,
|
|
|
|
binding the method do the API impl.
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
|
|
/*@API*/
|
|
|
|
type AStr struct {
|
|
|
|
Country string
|
|
|
|
City string
|
|
|
|
HouseNumber int64
|
|
|
|
IsCondo bool
|
|
|
|
SomeWeirdTest string `json:"SUPERCALIFRAGILISPEALIDOUX"`
|
|
|
|
Recursive map[string]AStr
|
|
|
|
Arrofpstr []string `json:"arrofpstr,omitempty"`
|
|
|
|
When time.Time
|
|
|
|
Some crypto.Decrypter
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
For datastructures you may need to use as params in or out - you may use similar approach:
|
|
|
|
|
|
|
|
Mark them with the comment `@API` and they will be also exported.
|
|
|
|
|
|
|
|
Once your code is ready, call apigen fromt the command line with the following alternatives:
|
|
|
|
|
|
|
|
1 - goserver: Provides API Server using standard lib router
|
|
|
|
2 - gin: Provives API Server using Gin
|
|
|
|
3 - gocli: Creates Go Client for the API
|
|
|
|
4 - ts: Creates typescript client for the API
|
|
|
|
5 - pycli: Creates python client for the API
|
|
|
|
|
|
|
|
See apigen -h for further details
|