master
Paulo Simão 2021-09-07 13:15:32 -03:00
parent cfb43ba21d
commit 5893ad898b
6 changed files with 91 additions and 256 deletions

View File

@ -3,6 +3,7 @@ package lib
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"log"
"os" "os"
) )
@ -50,18 +51,34 @@ func processGoClientOutput(f string) error {
} }
WNL("package %s", api.Namespace) WNL("package %s", api.Namespace)
for k, v := range api.UsedImportsFunctions {
log.Printf("Adding import from funcions: %s => %s", k, v)
WNL(`import "%s"`, k)
}
for k, v := range api.UsedImportsTypes {
log.Printf("Adding import from types: %s => %s", k, v)
WNL(`import "%s"`, k)
}
WNL(`import ( WNL(`import (
"bytes" "bytes"
"errors" "errors"
"io/ioutil" "io/ioutil"
"encoding/json" "encoding/json"
"net/http" "net/http"
"time"
) )
var Basepath string = "" var Basepath string = ""
var Host string = "" var Host string = ""
var ExtraHeaders map[string]string = make(map[string]string) var ExtraHeaders map[string]string = make(map[string]string)
var cli *http.Client
func SetCli(nc *http.Client) {
cli = nc
}
func invoke(m string, path string, bodyo interface{}) (*json.Decoder, error) { func invoke(m string, path string, bodyo interface{}) (*json.Decoder, error) {
b := &bytes.Buffer{} b := &bytes.Buffer{}
err := json.NewEncoder(b).Encode(bodyo) err := json.NewEncoder(b).Encode(bodyo)
@ -81,14 +98,12 @@ func invoke(m string, path string, bodyo interface{}) (*json.Decoder, error) {
req.Header.Set(k, v) req.Header.Set(k, v)
} }
cli := http.Client{}
res, err := cli.Do(req) res, err := cli.Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer res.Body.Close()
if res.StatusCode >= 400 { if res.StatusCode >= 400 {
bs, err := ioutil.ReadAll(res.Body) bs, err := ioutil.ReadAll(res.Body)
@ -111,7 +126,7 @@ func invoke(m string, path string, bodyo interface{}) (*json.Decoder, error) {
W("[]") W("[]")
} }
if f.Map { if f.Map {
W("map[%s]%s", f.Mapkey, f.Mapval) WNL("map[%s]%s", f.Mapkey, f.Mapval)
} else { } else {
WNL(f.Type) WNL(f.Type)
} }

View File

@ -9,13 +9,22 @@ import (
func processGoServerOutput(f string) error { func processGoServerOutput(f string) error {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
W := func(s string, p ...interface{}) { //W := func(s string, p ...interface{}) {
buf.WriteString(fmt.Sprintf(s, p...)) // buf.WriteString(fmt.Sprintf(s, p...))
} //}
WNL := func(s string, p ...interface{}) { WNL := func(s string, p ...interface{}) {
buf.WriteString(fmt.Sprintf(s+"\n", p...)) buf.WriteString(fmt.Sprintf(s+"\n", p...))
} }
ResImplType := func(v *APIParamType) string {
ret := ""
if !v.IsArray || v.Ispointer {
ret = ret + "&"
}
ret += v.Typename + "{}"
return ret
}
WNL("package %s", api.Namespace) WNL("package %s", api.Namespace)
WNL(`import ( WNL(`import (
"context" "context"
@ -25,17 +34,17 @@ func processGoServerOutput(f string) error {
)`) )`)
for k := range api.UsedImportsFunctions { for k := range api.UsedImportsFunctions {
W(`import "%s"`, k) WNL(`import "%s"`, k)
} }
WNL(`type API struct { WNL(`type API struct {
Mux *http.ServeMux Mux *http.ServeMux
Perms map[string]string Perms map[string]string
} }
func (a *API) GetPerm(r *http.Request) string { func (a *API) GetPerm(r *http.Request) string {
return a.Perms[r.Method+"_"+strings.Split(r.RequestURI, "?")[0]] return a.Perms[r.Method+"_"+strings.Split(r.RequestURI, "?")[0]]
} }
`) `)
WNL(`func Init() *API{ WNL(`func Init() *API{
@ -61,18 +70,17 @@ func processGoServerOutput(f string) error {
} else { } else {
WNL(` h_%s(w,r)`, v1.Method.Name) WNL(` h_%s(w,r)`, v1.Method.Name)
} }
WNL(` default:
http.Error(w,"Method not allowed",500)`)
WNL(` }`)
} }
WNL(` })`)
WNL(` default:
http.Error(w,"Method not allowed",500)
}`)
} }
WNL(` })`)
WNL(` return ret WNL(` return ret
} }`)
`)
for _, v := range api.Methods { for _, v := range api.Methods {
WNL(`func h_%s(w http.ResponseWriter, r *http.Request) { WNL(`func h_%s(w http.ResponseWriter, r *http.Request) {
@ -80,15 +88,7 @@ func processGoServerOutput(f string) error {
ctx = context.WithValue(r.Context(), "REQ", r) ctx = context.WithValue(r.Context(), "REQ", r)
ctx = context.WithValue(ctx, "RES", w)`, v.Name) ctx = context.WithValue(ctx, "RES", w)`, v.Name)
W(" var req ") WNL(" req := %s", ResImplType(v.ReqType))
if v.ReqType.IsArray {
W("[]")
}
if v.ReqType.Ispointer {
W("*")
}
WNL(v.ReqType.Typename)
WNL(` if r.Method!=http.MethodGet && r.Method!=http.MethodHead {`) WNL(` if r.Method!=http.MethodGet && r.Method!=http.MethodHead {`)

View File

@ -1,7 +1,14 @@
package main package main
import "go.digitalcircle.com.br/tools/apigen/lib" import (
"fmt"
"go.digitalcircle.com.br/tools/apigen/lib"
"os"
)
var Ver string = "Tue Sep 7 12:38:32 -03 2021"
func main() { func main() {
os.Stdout.WriteString(fmt.Sprintf("Version: %s\n", Ver))
lib.Run() lib.Run()
} }

View File

@ -1,72 +0,0 @@
package goapi
import (
"github.com/gin-gonic/gin"
)
import "crypto"
var perms map[string]string
func init() {
perms = make(map[string]string)
perms["POST_/someapi"] = "ASD"
perms["DELETE_/someapi"] = "ASD"
perms["GET_/someapi"] = "ASD"
perms["PUT_/someapi"] = "ASD"
}
func GetPerm(c *gin.Context) string {
perm, ok := perms[c.Request.Method+"_"+c.Request.URL.Path]
if !ok {
return ""
}
return perm
}
func Build(r *gin.Engine) *gin.Engine {
r.DELETE("/someapi", func(c *gin.Context) {
var req *crypto.Hash
c.BindJSON(req)
res, err := SomeAPI2(c.Request.Context(), req)
if err != nil {
c.Error(err)
}
c.JSON(200, res)
})
r.GET("/someapi", func(c *gin.Context) {
var req string
c.BindJSON(&req)
res, err := SomeGET(c.Request.Context(), req)
if err != nil {
c.Error(err)
}
c.JSON(200, res)
})
r.POST("/someapi", func(c *gin.Context) {
var req string
c.BindJSON(&req)
res, err := SomeAPI(c.Request.Context(), req)
if err != nil {
c.Error(err)
}
c.JSON(200, res)
})
r.PUT("/someapi", func(c *gin.Context) {
var req string
c.BindJSON(&req)
res, err := SomePUT(c.Request.Context(), req)
if err != nil {
c.Error(err)
}
c.JSON(200, res)
})
return r
}

View File

@ -25,42 +25,43 @@ type AStr struct {
@PERM: ASD @PERM: ASD
@VERB: POST @VERB: POST
*/ */
func SomeAPI(ctx context.Context, s string) (out string, err error) { func SomeAPI(ctx context.Context, s *AStr) (out *AStr, err error) {
print("Got:" + s) //print("Got:" + s)
out = time.Now().String() + " - Hey Ya!" //out = time.Now().String() + " - Hey Ya!"
return return
} }
/* //
@API ///*
@PATH: /someapi //@API
@PERM: ASD //@PATH: /someapi
@VERB: GET //@PERM: ASD
*/ //@VERB: GET
func SomeGET(ctx context.Context, s string) (out string, err error) { //*/
print("Got:" + s) //func SomeGET(ctx context.Context, s string) (out string, err error) {
out = time.Now().String() + " - Hey Ya!" // print("Got:" + s)
return // out = time.Now().String() + " - Hey Ya!"
} // return
//}
/* //
@API ///*
@PATH: /someapi //@API
@PERM: ASD //@PATH: /someapi
@VERB: PUT //@PERM: ASD
*/ //@VERB: PUT
func SomePUT(ctx context.Context, s string) (out string, err error) { //*/
print("Got:" + s) //func SomePUT(ctx context.Context, s string) (out string, err error) {
out = time.Now().String() + " - Hey Ya!" // print("Got:" + s)
return // out = time.Now().String() + " - Hey Ya!"
} // return
//}
/* //
@API ///*
@PATH: /someapi //@API
@PERM: ASD //@PATH: /someapi
@VERB: DELETE //@PERM: ASD
*/ //@VERB: DELETE
func SomeAPI2(ctx context.Context, s *crypto.Hash) ([]string, error) { //*/
return nil, nil //func SomeAPI2(ctx context.Context, s *crypto.Hash) ([]string, error) {
} // return nil, nil
//}

View File

@ -1,116 +0,0 @@
package gocli
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"time"
)
var Basepath string = ""
var Host string = ""
var ExtraHeaders map[string]string = make(map[string]string)
func invoke(m string, path string, bodyo interface{}) (*json.Decoder, error) {
b := &bytes.Buffer{}
err := json.NewEncoder(b).Encode(bodyo)
if err != nil {
return nil, err
}
body := bytes.NewReader(b.Bytes())
req, err := http.NewRequest(m, Host+Basepath+path, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-type", "application/json")
for k, v := range ExtraHeaders {
req.Header.Set(k, v)
}
cli := http.Client{}
res, err := cli.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode >= 400 {
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
return nil, errors.New(string(bs))
}
ret := json.NewDecoder(res.Body)
return ret, nil
}
type ARequestStruct struct {
C time.Time `json:"c"`
D string `json:"d"`
A string `json:"a"`
B int64 `json:"b"`
}
type AResponseStruct struct {
A string `json:"a"`
B int64 `json:"b"`
C time.Time `json:"c"`
D string `json:"d"`
}
type AStr struct {
A string `json:"a"`
B []string `json:"b"`
}
type AStr2 struct {
X string `json:"x"`
Y []string `json:"y"`
Z []AStr `json:"z"`
W map[string]AStr `json:"w"`
}
func SomeAPI3(req *AStr) (res []*AStr, err error) {
var dec *json.Decoder
dec, err = invoke("POST", "/someapi3", req)
if err != nil {
return
}
ret := []*AStr{}
err = dec.Decode(&ret)
if err != nil {
return nil, err
}
return ret, err
}
func SomeAPI(req *AStr) (res []*AStr, err error) {
var dec *json.Decoder
dec, err = invoke("PUT", "/someapi", req)
if err != nil {
return
}
ret := []*AStr{}
err = dec.Decode(&ret)
if err != nil {
return nil, err
}
return ret, err
}
func SomeAPI2(req *AStr) (res []*AStr, err error) {
var dec *json.Decoder
dec, err = invoke("POST", "/someapi", req)
if err != nil {
return
}
ret := []*AStr{}
err = dec.Decode(&ret)
if err != nil {
return nil, err
}
return ret, err
}