Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: updated go version, removed duplicated code, more idiomatic approach #2

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
commit-message:
prefix: "deps"
open-pull-requests-limit: 10
55 changes: 55 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
run:
# Default concurrency is an available CPU number
concurrency: 4

# Include test files or not, default is true
tests: true

# Settings of specific linters
linters-settings:
gocyclo:
min-complexity: 20

linters:
# do not use `enable-all`: it's deprecated and will be removed soon.
disable-all: true
enable:
- asasalint
- asciicheck
- bidichk
- bodyclose
- dogsled
- durationcheck
- errcheck
- errchkjson
- forbidigo
- gocognit
- gocritic
- godox
- gofmt
- gofumpt
- goimports
- goprintffuncname
- gosimple
- govet
- ineffassign
- misspell
- nakedret
- nestif
- nilerr
- nonamedreturns
- prealloc
- predeclared
- revive
- staticcheck
- stylecheck
- tenv
- typecheck
- unconvert
- unparam
- unused
- usestdlibvars
- whitespace

issues:
max-same-issues: 0
33 changes: 32 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ func main() {
// {"response":{"original_input":{"phrase":"hello"}}}
```

To generate OpenAPI/Swagger schema:
## OpenAPI/Swagger

**To generate OpenAPI/Swagger schema:**

```go
myRouter := fastapi.NewRouter()
Expand All @@ -62,4 +64,33 @@ jsonBytes, _ := json.MarshalIndent(swagger, "", " ")
fmt.Println(string(jsonBytes))
```

**To serve OpenAPI/Swagger schema:**

```go
r := gin.Default()

// Use Router for handling API requests and generating OpenAPI definition
myRouter := fastapi.NewRouter()
myRouter.AddCall("/echo", EchoHandler)

r.POST("/api/*path", myRouter.GinHandler) // must have *path parameter

swagger := myRouter.EmitOpenAPIDefinition()
swagger.Info.Title = "My awesome API"
jsonBytes, _ := json.MarshalIndent(swagger, "", " ")
fmt.Println(string(jsonBytes))

// Serve Swagger JSON
r.GET("/swagger.json", func(c *gin.Context) {
c.Data(http.StatusOK, "application/json", jsonBytes)
})

// Serve Swagger UI
r.Static("/swagger-ui", "./swaggerui")

r.Run()
```

You can check [the example](examples/) for more details about serving Swagger.

<img src="https://user-images.githubusercontent.com/677093/146807480-be53b3fb-6de8-451f-8373-e8d6da54a032.png" width="400px" height="auto">
5 changes: 3 additions & 2 deletions emit_openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
openapi "github.com/go-openapi/spec"
)

func (r *Router) EmitOpenAPIDefinition() openapi.Swagger {
func (router *Router) EmitOpenAPIDefinition() openapi.Swagger {
sw := openapi.Swagger{}
sw.Swagger = "2.0"
sw.Info = &openapi.Info{}
Expand All @@ -20,10 +20,11 @@ func (r *Router) EmitOpenAPIDefinition() openapi.Swagger {
sw.Definitions = make(map[string]openapi.Schema)

definitionTypes := make(map[string]reflect.Type)
for path, handlerFuncPtr := range r.routesMap {
for path, handlerFuncPtr := range router.routes {
handlerType := reflect.TypeOf(handlerFuncPtr)
inputType := handlerType.In(1)
definitionTypes[inputType.Name()] = inputType

for i := 0; i < inputType.NumField(); i++ {
field := inputType.Field(i)
if field.Type.Kind() == reflect.Struct {
Expand Down
21 changes: 11 additions & 10 deletions emit_openapi_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package fastapi

import (
"github.com/gin-gonic/gin"
"testing"

"github.com/gin-gonic/gin"
)

type InnerStruct struct {
Expand All @@ -27,22 +28,22 @@ type Out struct {
Output string `json:"output"`
}

func RequestHandler(ctx *gin.Context, in In) (out Out, err error) {
return
func RequestHandler(_ *gin.Context, _ In) (Out, error) {
return Out{}, nil
}

func RequestHandlerTwo(ctx *gin.Context, in In2) (out Out, err error) {
return
func RequestHandlerTwo(_ *gin.Context, _ In2) (Out, error) {
return Out{}, nil
}

func TestOpenAPIDefinition(t *testing.T) {
myRouter := NewRouter()
myRouter.AddCall("/ping", RequestHandler)
myRouter.AddCall("/pong", RequestHandlerTwo)
sw := myRouter.EmitOpenAPIDefinition()
openAPIRouter := NewRouter()
openAPIRouter.AddCall("/ping", RequestHandler)
openAPIRouter.AddCall("/pong", RequestHandlerTwo)
sw := openAPIRouter.EmitOpenAPIDefinition()

if len(sw.Paths.Paths) != 2 {
t.Fatal("Wrong number of pathes")
t.Fatal("Wrong number of paths")
}

if len(sw.Definitions) != 4 {
Expand Down
52 changes: 52 additions & 0 deletions examples/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package examples

import (
"encoding/json"
"fmt"
"net/http"

"github.com/gin-gonic/gin"
"github.com/sashabaranov/go-fastapi"
)

type EchoInput struct {
Phrase string `json:"phrase"`
}

type EchoOutput struct {
OriginalInput EchoInput `json:"original_input"`
}

func EchoHandler(ctx *gin.Context, in EchoInput) (out EchoOutput, err error) {
out.OriginalInput = in
return
}

func main() {
r := gin.Default()

// Use Router for handling API requests and generating OpenAPI definition
myRouter := fastapi.NewRouter()
myRouter.AddCall("/echo", EchoHandler)

r.POST("/api/*path", myRouter.GinHandler) // must have *path parameter

swagger := myRouter.EmitOpenAPIDefinition()
swagger.Info.Title = "My awesome API"
jsonBytes, _ := json.MarshalIndent(swagger, "", " ")
fmt.Println(string(jsonBytes))

// Serve Swagger JSON
r.GET("/swagger.json", func(c *gin.Context) {
c.Data(http.StatusOK, "application/json", jsonBytes)
})

// Serve Swagger UI
r.Static("/swagger-ui", "./swaggerui")

r.Run()
}

// Try it:
// $ curl -H "Content-Type: application/json" -X POST --data '{"phrase": "hello"}' localhost:8080/api/echo
// {"response":{"original_input":{"phrase":"hello"}}}
53 changes: 53 additions & 0 deletions examples/swaggerui/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/swagger-ui.css" >
<link rel="icon" type="image/png" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/favicon-16x16.png" sizes="16x16" />
<style>
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}

body {
margin:0;
background: #fafafa;
}
</style>
</head>

<body>
<div id="swagger-ui"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/swagger-ui-bundle.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout"
})
// End Swagger UI call region

window.ui = ui
}
</script>
</body>
</html>
80 changes: 35 additions & 45 deletions fastapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,64 +8,55 @@ import (
"github.com/gin-gonic/gin"
)

type Router struct {
routesMap map[string]interface{}
}
func (router *Router) GinHandler(ctx *gin.Context) {
path := ctx.Param("path")
log.Print(path)

func NewRouter() *Router {
return &Router{
routesMap: make(map[string]interface{}),
handlerFuncPtr, present := router.routes[path]
if !present {
respondWithError(ctx, http.StatusNotFound, "handler not found")
return
}
}

func (r *Router) AddCall(path string, handler interface{}) {
handlerType := reflect.TypeOf(handler)

if handlerType.NumIn() != 2 {
panic("Wrong number of arguments")
}
if handlerType.NumOut() != 2 {
panic("Wrong number of return values")
inputVal, err := bindInput(ctx, handlerFuncPtr)
if err != nil {
respondWithError(ctx, http.StatusBadRequest, "invalid request")
return
}

ginCtxType := reflect.TypeOf(&gin.Context{})
if !handlerType.In(0).ConvertibleTo(ginCtxType) {
panic("First argument should be *gin.Context!")
}
// fmt.Println(handlerType.In(1).Kind() == reflect.Struct)
if handlerType.In(1).Kind() != reflect.Struct {
panic("Second argument must be a struct")
outputVal, err := callHandler(ctx, handlerFuncPtr, inputVal)
if err != nil {
respondWithError(ctx, http.StatusInternalServerError, err)
return
}

errorInterface := reflect.TypeOf((*error)(nil)).Elem()
if !handlerType.Out(1).Implements(errorInterface) {
panic("Second return value should be an error")
}
if handlerType.Out(0).Kind() != reflect.Struct {
panic("First return value be a struct")
}
ctx.JSON(http.StatusOK, gin.H{
"response": outputVal.Interface(),
})
}

r.routesMap[path] = handler
func (router *Router) GetRoutes() map[string]interface{} {
return router.routes
}

func (r *Router) GinHandler(c *gin.Context) {
path := c.Param("path")
log.Print(path)
handlerFuncPtr, present := r.routesMap[path]
if !present {
c.JSON(http.StatusNotFound, gin.H{"error": "handler not found"})
return
}
func respondWithError(ctx *gin.Context, code int, message interface{}) {
ctx.JSON(code, gin.H{
"error": message,
"code": code,
})
}

func bindInput(ctx *gin.Context, handlerFuncPtr interface{}) (interface{}, error) {
handlerType := reflect.TypeOf(handlerFuncPtr)
inputType := handlerType.In(1)
inputVal := reflect.New(inputType).Interface()
err := c.BindJSON(inputVal)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
if err := ctx.BindJSON(inputVal); err != nil {
return nil, err
}
return inputVal, nil
}

func callHandler(c *gin.Context, handlerFuncPtr interface{}, inputVal interface{}) (reflect.Value, error) {
toCall := reflect.ValueOf(handlerFuncPtr)
outputVal := toCall.Call(
[]reflect.Value{
Expand All @@ -76,9 +67,8 @@ func (r *Router) GinHandler(c *gin.Context) {

returnedErr := outputVal[1].Interface()
if returnedErr != nil || !outputVal[1].IsNil() {
c.JSON(http.StatusInternalServerError, gin.H{"error": returnedErr})
return
return reflect.Value{}, returnedErr.(error)
}

c.JSON(http.StatusOK, gin.H{"response": outputVal[0].Interface()})
return outputVal[0], nil
}
Loading