ts fixes, better stderr and stdout handling

This commit is contained in:
Jan Halfar 2016-07-01 18:02:47 +02:00
parent 395af28344
commit 0d1b229b46
8 changed files with 88 additions and 111 deletions

View File

@ -15,7 +15,7 @@ import (
func jsonDump(v interface{}) {
jsonBytes, err := json.MarshalIndent(v, "", " ")
fmt.Println(err, string(jsonBytes))
fmt.Fprintln(os.Stderr, err, string(jsonBytes))
}
func usage() {
fmt.Println("Usage")
@ -27,7 +27,7 @@ func main() {
flag.Parse()
if len(*flagTsModule) == 0 {
fmt.Println("missing ts module")
fmt.Fprintln(os.Stderr, "missing ts module")
}
args := flag.Args()
@ -39,33 +39,40 @@ func main() {
goPath := os.Getenv("GOPATH")
if len(goPath) == 0 {
fmt.Println("GOPATH not set")
fmt.Fprintln(os.Stderr, "GOPATH not set")
os.Exit(1)
}
longPackageName := args[0]
longPackageNameParts := strings.Split(longPackageName, "/")
goFilename := path.Join(goPath, "src", longPackageName, "gotsrpc.go")
_, err := os.Stat(goFilename)
if err == nil {
fmt.Fprintln(os.Stderr, "removing existing", goFilename)
os.Remove(goFilename)
}
packageName := longPackageNameParts[len(longPackageNameParts)-1]
services, structs, err := gotsrpc.Read(goPath, longPackageName, args[1:])
if err != nil {
fmt.Println("an error occured", err)
fmt.Fprintln(os.Stderr, "an error occured", err)
os.Exit(2)
}
jsonDump(services)
jsonDump(structs)
//jsonDump(services)
//jsonDump(structs)
ts, err := gotsrpc.RenderTypeScript(services, structs, *flagTsModule)
if err != nil {
fmt.Println("could not generate ts code", err)
fmt.Fprintln(os.Stderr, "could not generate ts code", err)
os.Exit(3)
}
fmt.Println(ts)
gocode, goerr := gotsrpc.RenderGo(services, packageName)
if goerr != nil {
fmt.Println("could not generate go code", goerr)
fmt.Fprintln(os.Stderr, "could not generate go code", goerr)
os.Exit(4)
}
@ -73,15 +80,14 @@ func main() {
if formattingError == nil {
gocode = string(formattedGoBytes)
} else {
fmt.Println("could not format go code", formattingError)
fmt.Fprintln(os.Stderr, "could not format go code", formattingError)
}
writeErr := ioutil.WriteFile(goFilename, []byte(gocode), 0644)
if writeErr != nil {
fmt.Println("could not write go source to file", writeErr)
fmt.Fprintln(os.Stderr, "could not write go source to file", writeErr)
os.Exit(5)
}
fmt.Println(goFilename, gocode)
//fmt.Println(goFilename, gocode)
//gotsrpc.ReadFile("/Users/jan/go/src/github.com/foomo/gotsrpc/demo/demo.go", []string{"Service"})
}

View File

@ -6,6 +6,53 @@ import (
"net/http"
)
type ServiceGoTSRPCProxy struct {
EndPoint string
service *Service
}
func NewServiceGoTSRPCProxy(service *Service, endpoint string) *ServiceGoTSRPCProxy {
return &ServiceGoTSRPCProxy{
EndPoint: endpoint,
service: service,
}
}
// ServeHTTP exposes your service
func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
gotsrpc.ErrorMethodNotAllowed(w)
return
}
var args []interface{}
switch gotsrpc.GetCalledFunc(r, p.EndPoint) {
case "Hello":
args = []interface{}{""}
err := gotsrpc.LoadArgs(args, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
helloReply, helloErr := p.service.Hello(args[0].(string))
gotsrpc.Reply([]interface{}{helloReply, helloErr}, w)
return
case "NothingInNothinOut":
p.service.NothingInNothinOut()
gotsrpc.Reply([]interface{}{}, w)
return
case "ExtractAddress":
args = []interface{}{&Person{}}
err := gotsrpc.LoadArgs(args, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
extractAddressAddr, extractAddressE := p.service.ExtractAddress(args[0].(*Person))
gotsrpc.Reply([]interface{}{extractAddressAddr, extractAddressE}, w)
return
}
}
type FooGoTSRPCProxy struct {
EndPoint string
service *Foo
@ -38,50 +85,3 @@ func (p *FooGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
}
type ServiceGoTSRPCProxy struct {
EndPoint string
service *Service
}
func NewServiceGoTSRPCProxy(service *Service, endpoint string) *ServiceGoTSRPCProxy {
return &ServiceGoTSRPCProxy{
EndPoint: endpoint,
service: service,
}
}
// ServeHTTP exposes your service
func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
gotsrpc.ErrorMethodNotAllowed(w)
return
}
var args []interface{}
switch gotsrpc.GetCalledFunc(r, p.EndPoint) {
case "ExtractAddress":
args = []interface{}{&Person{}}
err := gotsrpc.LoadArgs(args, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
extractAddressAddr, extractAddressE := p.service.ExtractAddress(args[0].(*Person))
gotsrpc.Reply([]interface{}{extractAddressAddr, extractAddressE}, w)
return
case "Hello":
args = []interface{}{""}
err := gotsrpc.LoadArgs(args, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
helloReply, helloErr := p.service.Hello(args[0].(string))
gotsrpc.Reply([]interface{}{helloReply, helloErr}, w)
return
case "NothingInNothinOut":
p.service.NothingInNothinOut()
gotsrpc.Reply([]interface{}{}, w)
return
}
}

View File

@ -1,40 +1 @@
package demo_test
import (
"net/http"
"github.com/foomo/gotsrpc"
)
type ServiceGoTSRPCProxy struct {
EndPoint string
service *Service
}
func NewServiceGoTSRPCProxy(service *Service, endpoint string) *ServiceGoTSRPCProxy {
return &ServiceGoTSRPCProxy{
EndPoint: endpoint,
service: service,
}
}
func (sp *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
gotsrpc.ErrorMethodNotAllowed(w)
return
}
switch gotsrpc.GetCalledFunc(r, sp.EndPoint) {
case "Hello":
args := []interface{}{""}
err := gotsrpc.LoadArgs(args, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
helloReply, helloErr := sp.service.Hello(args[0].(string))
gotsrpc.Reply([]interface{}{helloReply, helloErr}, w)
return
default:
gotsrpc.ErrorFuncNotFound(w)
}
}

9
go.go
View File

@ -87,18 +87,25 @@ func renderServiceProxies(services []*Service, packageName string, g *code) erro
g.l(`
type ` + proxyName + ` struct {
EndPoint string
allowOrigin []string
service *` + service.Name + `
}
func New` + proxyName + `(service *` + service.Name + `, endpoint string) *` + proxyName + ` {
func New` + proxyName + `(service *` + service.Name + `, endpoint string, allowOrigin []string) *` + proxyName + ` {
return &` + proxyName + `{
EndPoint: endpoint,
allowOrigin : allowOrigin,
service: service,
}
}
// ServeHTTP exposes your service
func (p *` + proxyName + `) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, origin := range p.allowOrigin {
w.Header().Add("Access-Control-Allow-Origin", origin)
}
if r.Method != "POST" {
gotsrpc.ErrorMethodNotAllowed(w)
return

View File

@ -70,7 +70,7 @@ func parsePackage(goPath string, packageName string) (pkg *ast.Package, err erro
strippedPackageName := packageNameParts[len(packageNameParts)-1]
foundPackages := []string{}
for pkgName, pkg := range pkgs {
fmt.Println("pkgName", pkgName)
//fmt.Println("pkgName", pkgName)
if pkgName == strippedPackageName {
return pkg, nil
}

View File

@ -2,7 +2,6 @@ package gotsrpc
import (
"errors"
"fmt"
"go/ast"
"reflect"
)
@ -27,7 +26,7 @@ func readServiceFile(file *ast.File, services []*Service) error {
starExpr := firstReceiverField.Type.(*ast.StarExpr)
if "*ast.Ident" == reflect.ValueOf(starExpr.X).Type().String() {
ident := starExpr.X.(*ast.Ident)
fmt.Println(" on sth:", ident.Name)
trace(" on sth:", ident.Name)
service, ok := findService(ident.Name)

View File

@ -3,6 +3,7 @@ package gotsrpc
import (
"fmt"
"go/ast"
"os"
"reflect"
"strings"
)
@ -23,7 +24,7 @@ func readStructs(pkg *ast.Package) (structs map[string]*Struct, err error) {
func trace(args ...interface{}) {
if ReaderTrace {
fmt.Println(args...)
fmt.Fprintln(os.Stderr, args...)
}
}
@ -128,7 +129,7 @@ func readAstArrayType(v *Value, arrayType *ast.ArrayType) {
case "*ast.StarExpr":
readAstStarExpr(v, arrayType.Elt.(*ast.StarExpr))
default:
fmt.Println("array type elt", reflect.ValueOf(arrayType.Elt).Type().String())
trace("array type elt", reflect.ValueOf(arrayType.Elt).Type().String())
}
}
@ -155,7 +156,7 @@ func readAstSelectorExpr(v *Value, selectorExpr *ast.SelectorExpr) {
Name: selectorExpr.Sel.Name,
}
default:
fmt.Println("selectorExpr.Sel !?", selectorExpr.X, reflect.ValueOf(selectorExpr.X).Type().String())
trace("selectorExpr.Sel !?", selectorExpr.X, reflect.ValueOf(selectorExpr.X).Type().String())
}
}
@ -183,7 +184,7 @@ func (v *Value) loadExpr(expr ast.Expr) {
}
readAstMapType(v.Array.Value.Map, fieldArray.Elt.(*ast.MapType))
default:
fmt.Println("---------------------> array of", reflect.ValueOf(fieldArray.Elt).Type().String())
trace("---------------------> array of", reflect.ValueOf(fieldArray.Elt).Type().String())
}
case "*ast.Ident":
fieldIdent := expr.(*ast.Ident)
@ -240,9 +241,9 @@ func readFieldList(fieldList []*ast.Field) (fields []*Field) {
}
func extractStructs(file *ast.File, structs map[string]*Struct) error {
for _, imp := range file.Imports {
fmt.Println("import", imp.Name, imp.Path)
}
//for _, imp := range file.Imports {
// fmt.Println("import", imp.Name, imp.Path)
//}
for name, obj := range file.Scope.Objects {
//fmt.Println(name, obj.Kind, obj.Data)
if obj.Kind == ast.Typ && obj.Decl != nil {

View File

@ -35,6 +35,9 @@ func (v *Value) tsType() string {
func renderStruct(str *Struct, ts *code) error {
ts.l("export interface " + str.Name + " {").ind(1)
for _, f := range str.Fields {
if f.JSONInfo != nil && f.JSONInfo.Ignore {
continue
}
ts.app(f.tsName())
if f.Value.IsPtr {
ts.app("?")
@ -88,11 +91,11 @@ func renderService(service *Service, ts *code) error {
if len(args) > 0 {
ts.app(", ")
}
ts.app("success(" + strings.Join(retArgs, ", ") + ") => void")
ts.app("success:(" + strings.Join(retArgs, ", ") + ") => void")
ts.app(", err:(request:XMLHttpRequest) => void) {").nl()
ts.ind(1)
// generic framework call
ts.l("GoTSRPC.call(this.endPoint, \"" + method.Name + "\"), [" + strings.Join(callArgs, ", ") + "], success, err);")
ts.l("GoTSRPC.call(this.endPoint, \"" + method.Name + "\", [" + strings.Join(callArgs, ", ") + "], success, err);")
ts.ind(-1)
ts.app("}")
ts.nl()