kok
kok (pronounced keɪ-oʊ-keɪ) is a toolkit of Go kit.
Zen
- Embrace the Clean Architecture for non-trivial applications.
- Just write code for your business logic, generate everything else.
- Implement the service once, consume it in various ways (in-process function call or RPC).
Features
-
Code Generation Tool
- Endpoint
- Transport
- HTTP
- HTTP Server
- HTTP Client
- HTTP Test
- OAS-v2 Documentation
- gRPC
-
Useful Packages
- appx: Application framework for HTTP and CRON applications (a wrapper of appx).
- prometheus: Prometheus metrics utilities.
- trace: A thin wrapper of x/net/trace for Go kit.
- werror: Classified business errors.
Installation
$ go install github.com/RussellLuo/kok/cmd/kokgen@latest
Usage
$ kokgen -h
kokgen [flags] source-file interface-name
-flat
whether to use flat layout (default true)
-fmt
whether to make code formatted (default true)
-old
whether to use the old annotation syntax
-out string
output directory (default ".")
-snake
whether to use snake-case for default names (default true)
-test string
the YAML file that provides test-cases for HTTP (default "./http.test.yaml")
-trace
whether to enable tracing
Quick Start
HTTP
NOTE: The following code is located in helloworld.
-
Define the interface
type Service interface {
SayHello(ctx context.Context, name string) (message string, err error)
}
-
Implement the service
type Greeter struct{}
func (g *Greeter) SayHello(ctx context.Context, name string) (string, error) {
return "Hello " + name, nil
}
-
Add HTTP annotations
type Service interface {
//kok:op POST /messages
SayHello(ctx context.Context, name string) (message string, err error)
}
-
Generate the HTTP code
$ cd examples/helloworld
$ kokgen ./service.go Service
-
Consume the service
Run the HTTP server:
$ go run cmd/main.go
2020/09/15 18:06:22 transport=HTTP addr=:8080
Consume by HTTPie:
$ http POST :8080/messages name=Tracey
HTTP/1.1 200 OK
Content-Length: 27
Content-Type: application/json; charset=utf-8
Date: Tue, 15 Sep 2020 10:06:34 GMT
{
"message": "Hello Tracey"
}
-
See the OAS documentation
(Click to expand)
$ http GET :8080/api
HTTP/1.1 200 OK
Content-Length: 848
Content-Type: text/plain; charset=utf-8
Date: Tue, 15 Sep 2020 10:08:24 GMT
swagger: "2.0"
info:
title: "No Title"
version: "0.0.0"
description: "Service is used for saying hello."
license:
name: "MIT"
host: "example.com"
basePath: "/"
schemes:
- "https"
consumes:
- "application/json"
produces:
- "application/json"
paths:
/messages:
post:
description: "SayHello says hello to the given name."
operationId: "SayHello"
parameters:
- name: body
in: body
schema:
$ref: "#/definitions/SayHelloRequestBody"
produces:
- application/json; charset=utf-8
responses:
200:
description: ""
schema:
$ref: "#/definitions/SayHelloResponse"
definitions:
SayHelloRequestBody:
type: object
properties:
name:
type: string
SayHelloResponse:
type: object
properties:
message:
type: string
gRPC
NOTE: The following code is located in helloworldgrpc.
-
Define the interface
type Service interface {
SayHello(ctx context.Context, name string) (message string, err error)
}
-
Implement the service
type Greeter struct{}
func (g *Greeter) SayHello(ctx context.Context, name string) (string, error) {
return "Hello " + name, nil
}
-
Add gRPC annotations
type Service interface {
//kok:grpc
SayHello(ctx context.Context, name string) (message string, err error)
}
-
Generate the gRPC code
$ cd examples/helloworldgrpc
$ kokgen ./service.go Service
-
Consume the service
Run the gRPC server:
$ go run cmd/main.go
2020/09/15 18:06:22 transport=HTTP addr=:8080
Consume by grpcurl:
$ grpcurl -plaintext -d '{"name": "Tracey"}' :8080 pb.Service/SayHello
{
"message": "Hello Tracey"
}
See more examples here.
HTTP
Annotations
Define the HTTP request operation
Old syntax (DEPRECATED)
-
Key: @kok(op)
-
Value: <method> <pattern>
- method: The request method
- pattern: The request URL
- NOTE: All variables in pattern will automatically be bound to their corresponding method arguments (matches by name in lower camel case), as path parameters, if the variables are not yet specified as path parameters explicitly by
@kok(param)
.
-
Example:
type Service interface {
// @kok(op): DELETE /users/{id}
DeleteUser(ctx context.Context, id int) (err error)
}
// HTTP request:
// $ http DELETE /users/101
Directive //kok:op
Syntax
//kok:op <method> <pattern>
Arguments
- method: The request method.
- pattern: The request URL.
- NOTE: All variables in pattern will automatically be bound to their corresponding method arguments (match by names in lower camel case), as path parameters, if these variables have not yet been specified explicitly by
//kok:param
.
Examples
type Service interface {
//kok:op DELETE /users/{id}
DeleteUser(ctx context.Context, id int) (err error)
}
// HTTP request:
// $ http DELETE /users/101
Define the HTTP request parameters
Old syntax (DEPRECATED)
- Key:
@kok(param)
- Value:
<argName> < in:<in>,name:<name>,required:<required>
- argName: The name of the method argument.
- Argument aggregation: By specifying the same argName, multiple request parameters (each one is of basic type or repeated basic type) can be aggregated into one method argument (of any type).
- You do not need to repeat the argName, only the first one is required.
- Blank identifier: By specifying the argName with a double underscore prefix
__
, the corresponding request parameter(s) will not be mapped to any method argument. See here for more details.
- in:
- path: The method argument is sourced from a path parameter.
- Optional: All variables in pattern will automatically be bound to their corresponding method arguments (matches by name in lower camel case), as path parameters.
- query: The method argument is sourced from a query parameter.
- To receive values from a multi-valued query parameter, the method argument can be defined as a slice of basic type.
- header: The method argument is sourced from a header parameter.
- cookie: The method argument is sourced from a cookie parameter.
- request: The method argument is sourced from a property of Go's http.Request.
- This is a special case, and only one property
RemoteAddr
is available now.
- Note that parameters located in request have no relationship with OAS.
- name: The name of the corresponding request parameter.
- Optional: Defaults to argName (snake-case, or lower-camel-case if
-snake=false
) if not specified.
- descr: The OAS description of the corresponding request parameter.
- Optional: Defaults to
""
if not specified.
- required: Determines whether this parameter is mandatory.
- Optional: Defaults to
false
, if not specified.
- If the parameter location is path, this property will be set to
true
internally, whether it's specified or not.
- Example:
-
Bind request parameters to simple arguments:
type Service interface {
// @kok(op): PUT /users/{id}
// @kok(param): name < in:header,name:X-User-Name
UpdateUser(ctx context.Context, id int, name string) (err error)
}
// HTTP request:
// $ http PUT /users/101 X-User-Name:tracey
-
Bind multiple request parameters to a struct according to tags:
type User struct {
ID int `kok:"path.id"`
Name string `kok:"query.name"`
Age int `kok:"header.X-User-Age"`
}
type Service interface {
// @kok(op): PUT /users/{id}
// @kok(param): user
UpdateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http PUT /users/101?name=tracey X-User-Age:1
-
Bind multiple query parameters to a struct with no tags:
type User struct {
Name string
Age int
Hobbies []string
}
type Service interface {
// @kok(op): POST /users
// @kok(param): user
CreateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http POST /users?Name=tracey&Age=1&Hobbies=music&Hobbies=sport
-
Argument aggregation:
type Service interface {
// @kok(op): POST /logs
// @kok(param): ip < in:header,name:X-Forwarded-For
// @kok(param): ip < in:request,name:RemoteAddr
Log(ctx context.Context, ip net.IP) (err error)
}
// The equivalent annotations.
type Service interface {
// @kok(op): POST /logs
// @kok(param): ip < in:header,name:X-Forwarded-For
// @kok(param): < in:request,name:RemoteAddr
Log(ctx context.Context, ip net.IP) (err error)
}
// You must customize the decoding of `ip` later (conventionally in another file named `codec.go`).
// See examples in the `Encoding and decoding` section.
// HTTP request:
// $ http POST /logs
Directive //kok:param
Syntax
//kok:param <argName> [<parameter> [, <parameter2> [, ...]]]
If multiple method arguments are involved, you may need to apply multiple bindings. This can be done by adding a new //kok:param
directive, or by appending the binding to the end of the last //kok:param
directive in a semicolon-separated list.
Arguments
- argName: The name of the method argument.
- Argument aggregation: By specifying multiple
<parameter>
s in a comma-separated list, multiple request parameters (each one is of basic type or repeated basic type) can be aggregated into one method argument (of any type).
- Blank identifier: By specifying the argName with a double underscore prefix
__
, the corresponding request parameter(s) will not be mapped to any method argument. See here for more details.
- parameter: The definition of a single request parameter, to which the method argument will be mapped.
- Syntax:
in=<in> name=<name> required=<required> type=<type> descr=<descr>
- Options:
- in:
- path: The request parameter is a path parameter.
- Optional: All variables in pattern will automatically be bound to their corresponding method arguments (match by names in lower camel case), as path parameters.
- query: The request parameter is a query parameter.
- To receive values from a multi-valued query parameter, the method argument can be defined as a slice of basic type.
- header: The request parameter is a header parameter.
- To receive values from a multi-valued header parameter, the method argument can be defined as a slice of basic type.
- cookie: The request parameter is a cookie parameter.
- request: The request parameter is a property of Go's http.Request.
- This is a special case, and only one property
RemoteAddr
is available now.
- Note that parameters located in request have no relationship with OAS.
- name: The name of the request parameter.
- Optional: Defaults to argName (snake-case, or lower-camel-case if
-snake=false
) if not specified.
- required: Determines whether this parameter is mandatory.
- Optional: Defaults to
false
, if not specified.
- If the parameter location is path, this property will be set to
true
internally, whether it's specified or not.
- type: The OAS type of the request parameter.
- Optional: Defaults to the type of the method argument, if not specified.
- descr: The OAS description of the request parameter.
- Optional: Defaults to
""
, if not specified.
Examples
-
Bind request parameters to simple arguments:
type Service interface {
//kok:op PUT /users/{id}
//kok:param name in=header name=X-User-Name
UpdateUser(ctx context.Context, id int, name string) (err error)
}
// HTTP request:
// $ http PUT /users/101 X-User-Name:tracey
-
Bind multiple request parameters to a struct according to tags:
type User struct {
ID int `kok:"in=path"` // name defaults to snake case `id`
Name string `kok:"in=query"` // name defaults to snake case `name`
Age int `kok:"in=header name=X-User-Age"`
}
type Service interface {
//kok:op PUT /users/{id}
//kok:param user
UpdateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http PUT /users/101?name=tracey X-User-Age:1
-
Bind multiple query parameters to a struct with no tags:
type User struct {
Name string // equivalent to `kok:"in=query name=name"`
Age int // equivalent to `kok:"in=query name=age"`
Hobbies []string // equivalent to `kok:"in=query name=hobbies"`
}
type Service interface {
//kok:op POST /users
//kok:param user
CreateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http POST /users?name=tracey&age=1&hobbies=music&hobbies=sport
-
Argument aggregation:
type Service interface {
//kok:op POST /logs
//kok:param ip in=header name=X-Forwarded-For, in=request name=RemoteAddr
Log(ctx context.Context, ip net.IP) (err error)
}
// The equivalent annotations =>
// (using backslash-continued annotations)
type Service interface {
//kok:op POST /logs
//kok:param ip in=header name=X-Forwarded-For, \
// in=request name=RemoteAddr
Log(ctx context.Context, ip net.IP) (err error)
}
// You must customize the decoding of `ip` later (conventionally in another file named `codec.go`).
// See a runnable example in examples/usersvc.
// HTTP request:
// $ http POST /logs
-
Multiple bindings in a single //kok:param
:
type Service interface {
//kok:op POST /users
//kok:param name; age; ip in=header name=X-Forwarded-For, in=request name=RemoteAddr
CreateUser(ctx context.Context, name string, age int, ip net.IP) (err error)
}
// The equivalent annotations =>
// (using backslash-continued annotations)
type Service interface {
//kok:op POST /users
//kok:param name; \
// age; \
// ip in=header name=X-Forwarded-For, in=request name=RemoteAddr
CreateUser(ctx context.Context, name string, age int, ip net.IP) (err error)
}
// HTTP request:
// $ http POST /users?name=tracey&age=1
Define the HTTP request body
Old syntax (DEPRECATED)
- Key:
@kok(body)
- Value:
<field>
or body:<field>,name:<argName>=<name>,descr:<argName>=<descr>
- field: The name of the method argument whose value is mapped to the HTTP request body.
- Optional: When omitted, a struct containing all the arguments, which are not located in path/query/header, will automatically be mapped to the HTTP request body.
- The special name
-
can be used, to define that there is no HTTP request body. As a result, every argument, which is not located in path/query/header, will automatically be mapped to one or more query parameters.
- argName: The name of the method argument to be manipulated.
- name: The name of the corresponding request parameter.
- Optional: Defaults to argName (snake-case, or lower-camel-case if
-snake=false
) if not specified.
- descr: The OAS description of the corresponding request parameter.
- Optional: Defaults to
""
, if not specified.
- Example:
-
Omitted:
type Service interface {
// @kok(op): POST /users
CreateUser(ctx context.Context, name string, age int) (err error)
}
// HTTP request:
// $ http POST /users name=tracey age=1
-
Specified as a normal argument:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Service interface {
// @kok(op): POST /users
// @kok(body): user
CreateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http POST /users name=tracey age=1
-
Specified as -
:
type User struct {
Name string `kok:"name"`
Age int `kok:"age"`
Hobbies []string `kok:"hobby"`
}
type Service interface {
// @kok(op): POST /users
// @kok(body): -
CreateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http POST /users?name=tracey&age=1&hobby=music&hobby=sport
Directive //kok:body
Syntax
//kok:body <field>
or
//kok:body <manipulation> [; <manipulation2> [; ...]]
Arguments
- field: The name of the method argument whose value is mapped to the HTTP request body.
- Optional: When omitted, a struct containing all the arguments, which are not located in path/query/header, will automatically be mapped to the HTTP request body.
- The special name
-
can be used, to define that there is no HTTP request body. As a result, every argument, which is not located in path/query/header, will automatically be mapped to one or more query parameters.
- manipulation:
- Syntax:
<argName> name=<name> type=<type> descr=<descr>
- Options:
- argName: The name of the method argument to be manipulated.
- name: The name of the request parameter.
- Optional: Defaults to argName (snake-case, or lower-camel-case if
-snake=false
) if not specified.
- type: The OAS type of the request parameter.
- Optional: Defaults to the type of the method argument, if not specified.
- descr: The OAS description of the request parameter.
- Optional: Defaults to
""
, if not specified.
Examples
-
Omitted:
type Service interface {
//kok:op POST /users
CreateUser(ctx context.Context, name string, age int) (err error)
}
// HTTP request:
// $ http POST /users name=tracey age=1
-
Specified as a normal argument:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Service interface {
//kok:op POST /users
//kok:body user
CreateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http POST /users name=tracey age=1
-
Specified as -
:
type User struct {
Name string
Age int
Hobbies []string `kok:"name=hobby"`
}
type Service interface {
//kok:op POST /users
//kok:body -
CreateUser(ctx context.Context, user User) (err error)
}
// HTTP request:
// $ http POST /users?name=tracey&age=1&hobby=music&hobby=sport
-
Manipulation:
type Service interface {
//kok:op POST /users
//kok:body age name=user_age type=string descr=The-user-age
CreateUser(ctx context.Context, name string, age int) (err error)
}
// HTTP request:
// $ http POST /users name=tracey user_age=1
Define the success HTTP response
Old syntax (DEPRECATED)
-
Key: @kok(success)
-
Value: statusCode:<statusCode>,body:<body>
- statusCode: The status code of the success HTTP response.
- Optional: Defaults to 200 if not specified.
- body: The name of the response field whose value is mapped to the HTTP response body.
- Optional: When omitted, a struct containing all the results (except error) will automatically be mapped to the HTTP response body.
-
Example:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Service interface {
// @kok(op): POST /users
// @kok(success): statusCode:201,body:user
CreateUser(ctx context.Context) (user User, err error)
}
Directive //kok:success
Syntax
//kok:success statusCode=<statusCode> body=<body> manip=`<manipulation> [; <manipulation2> [; ...]]`
Arguments
- statusCode: The status code of the success HTTP response.
- Optional: Defaults to
200
, if not specified.
- body: The name of the response field whose value is mapped to the HTTP response body.
- Optional: When omitted, a struct containing all the results (except error) will automatically be mapped to the HTTP response body.
- manipulation:
- Syntax:
<argName> name=<name> type=<type> descr=<descr>
- Not supported yet.
Examples
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Service interface {
//kok:op POST /users
//kok:success statusCode=201 body=user
CreateUser(ctx context.Context) (user User, err error)
}
Old syntax (DEPRECATED)
-
Key: @kok(oas)
-
Value: <property>:<value>
<property>
: The property to set. Supported properties:
- docsPath: The URL path to the OAS documentation itself.
- Optional: Defaults to
"/api"
if not specified.
- title: The
title
field of Info Object, see Basic Structure.
- Optional: Defaults to
"No Title"
if not specified.
- version: The
version
field of Info Object, see Basic Structure.
- Optional: Defaults to
"0.0.0"
if not specified.
- description: The
description
field of Info Object, see Basic Structure.
- Unavailable: Automatically extracted from the Go documentation of the interface definition.
- basePath: The
basePath
property, see API Host and Base URL.
- tags: A list of tags (comma-separated), see Grouping Operations With Tags.
<value>
: The value of the property.
-
Example:
// This is the API documentation of User.
// @kok(oas): docsPath:/api-docs
// @kok(oas): title:User API
// @kok(oas): version:1.0.0
// @kok(oas): basePath:/v1
// @kok(oas): tags:user
type Service interface {
// @kok(op): POST /users
CreateUser(ctx context.Context, name string, age int) (err error)
}
Directive //kok:oas
Syntax
//kok:oas <property>=<value>
Arguments
- property: The property to set. Supported properties:
- docsPath: The URL path to the OAS documentation itself.
- Optional: Defaults to
"/api"
if not specified.
- title: The
title
field of Info Object, see Basic Structure.
- Optional: Defaults to
"No Title"
if not specified.
- version: The
version
field of Info Object, see Basic Structure.
- Optional: Defaults to
"0.0.0"
if not specified.
- description: The
description
field of Info Object, see Basic Structure.
- Unavailable: Automatically extracted from the Go documentation of the interface definition.
- basePath: The
basePath
property, see API Host and Base URL.
- tags: A list of tags (comma-separated), see Grouping Operations With Tags.
- value: The value of the property.
Examples
// This is the API documentation of User.
//kok:oas docsPath=/api-docs
//kok:oas title=User-API
//kok:oas version=1.0.0
//kok:oas basePath=/v1
//kok:oas tags=user
type Service interface {
//kok:op POST /users
CreateUser(ctx context.Context, name string, age int) (err error)
}
Define the annotation alias
Old syntax (DEPRECATED)
-
Key: @kok(alias)
-
Value: <name>=`<value>`
<name>
: The name of the alias.
<value>
: The string value that the alias represents.
-
Example:
type Service interface {
// @kok(op): POST /users
// @kok(param): operatorID < in:header,name:Authorization,required:true
CreateUser(ctx context.Context, operatorID int) (err error)
// @kok(op): DELETE /users/{id}
// @kok(param): operatorID < in:header,name:Authorization,required:true
DeleteUser(ctx context.Context, id, operatorID int) (err error)
}
// The equivalent annotations =>
// @kok(alias): opID=`operatorID < in:header,name:Authorization,required:true`
type Service interface {
// @kok(op): POST /users
// @kok(param): $opID
CreateUser(ctx context.Context, operatorID int) (err error)
// @kok(op): DELETE /users/{id}
// @kok(param): $opID
DeleteUser(ctx context.Context, id, operatorID int) (err error)
}
Directive //kok:alias
Syntax
//kok:alias <name>=`<value>`
Arguments
- name: The name of the alias.
- value: The string value that the alias represents.
Examples
type Service interface {
//kok:op POST /users
//kok:param operatorID in=header name=Authorization required=true
CreateUser(ctx context.Context, operatorID int) (err error)
//kok:op DELETE /users/{id}
//kok:param operatorID in=header name=Authorization required=true
DeleteUser(ctx context.Context, id, operatorID int) (err error)
}
// The equivalent annotations =>
//kok:alias opID=`operatorID in=header name=Authorization required=true`
type Service interface {
//kok:op POST /users
//kok:param $opID
CreateUser(ctx context.Context, operatorID int) (err error)
//kok:op DELETE /users/{id}
//kok:param $opID
DeleteUser(ctx context.Context, id, operatorID int) (err error)
}
Encoding and decoding
See the HTTP Codec interface.
Also see here for examples.
OAS Schema
See the OAS Schema interface.
gRPC
Annotations
Old syntax (DEPRECATED)
- Key:
@kok(grpc)
- Value:
request:<request>,response:<response>
- request: The name of the method argument whose value is mapped to the gRPC request.
- Optional: When omitted, a struct containing all the arguments (except context.Context) will automatically be mapped to the gRPC request.
- response: The name of the method result whose value is mapped to the gRPC response.
- Optional: When omitted, a struct containing all the results (except error) will automatically be mapped to the gRPC response.
- Example:
-
Omitted:
type Service interface {
// @kok(grpc)
CreateUser(ctx context.Context, name string, age int) (err error)
}
// gRPC request:
// $ grpcurl -d '{"name": "tracey", "age": 1}' ... pb.Service/CreateUser
-
Specified:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Service interface {
// @kok(grpc): request:user
CreateUser(ctx context.Context, user User) (err error)
}
// gRPC request:
// $ grpcurl -d '{"name": "tracey", "age": 1}' ... pb.Service/CreateUser
Directive //kok:grpc
Syntax
//kok:grpc request=<request> response=<response>
Arguments
- request: The name of the method argument, whose value will be mapped to the gRPC request.
- Optional: When omitted, a struct containing all the arguments (except context.Context) will automatically be mapped to the gRPC request.
- response: The name of the method result, whose value will be mapped to the gRPC response.
- Optional: When omitted, a struct containing all the results (except error) will automatically be mapped to the gRPC response.
Examples
-
Omitted:
type Service interface {
//kok:grpc
CreateUser(ctx context.Context, name string, age int) (err error)
}
// gRPC request:
// $ grpcurl -d '{"name": "tracey", "age": 1}' ... pb.Service/CreateUser
-
Specified:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Service interface {
//kok:grpc request=user
CreateUser(ctx context.Context, user User) (err error)
}
// gRPC request:
// $ grpcurl -d '{"name": "tracey", "age": 1}' ... pb.Service/CreateUser
Documentation
Checkout the Godoc.
License
MIT