Generate TypeScript interfaces from Go structs/interfaces - useful for JSON RPC

bel

Generate TypeScript interfaces from Go structs/interfaces - useful for JSON RPC

Go Report Card GoDoc gocover.run Stability: Active

Open in Gitpod

bel is used in production in https://gitpod.io.

Getting started

bel is easy to use. There are two steps involved: extract the Typescript information, and generate the Typescript code.

package main

import (
    "github.com/32leaves/bel"
)

type Demo struct {
    Foo string `json:"foo,omitempty"`
    Bar uint32
    Baz struct {
        FirstField  bool
        SecondField *string
    }
}

func main() {
    ts, err := bel.Extract(Demo{})
    if err != nil {
        panic(err)
    }

    err = bel.Render(ts)
    if err != nil {
        panic(err)
    }
}

produces something akin to (sans formatting):

export interface Demo {
    foo?: string
    Bar: number
    Baz: {
        FirstField: boolean
        SecondField: string
    }
}

Converting interfaces

You can also convert Golang interfaces to TypeScript interfaces. This is particularly handy for JSON RPC:

package main

import (
    "os"
    "github.com/32leaves/bel"
)

type DemoService interface {
    SayHello(name, msg string) (string, error)
}

func main() {
    ts, err := bel.Extract((*DemoService)(nil))
    if err != nil {
        panic(err)
    }

    err = bel.Render(ts)
    if err != nil {
        panic(err)
    }
}

produces something akin to (sans formatting):

export interface DemoService {
    SayHello(arg0: string, arg1: string): string
}

Advanced Usage

You can try all the examples mentioned below in Gitpod.

FollowStructs

Follow structs enable the transitive generation of types. See examples/embed-structs.go.

would produce code for the interface UserService, as well as the struct it refers to AddUserRequest, and User because it's referenced by AddUserRequest. Without FollowStructs we'd simply refer to the types by name, but would not generate code for them.

SortAlphabetically

SortAlphabetically sorts all types and their members by alphabetical order. This produces more deterministic/stable output, which is great for making things comparable across pull requests. See examples/sort-alphabetically.go.

EmbedStructs

Embed structs is similar to FollowStructs except that it produces a single canonical type for each structure. Whenever one struct references another, that reference is resolved and the definition of the other is embedded. See examples/embed-structs.go.

NameAnonStructs

NameAnonStructs is kind of the opposite of EmbedStructs. When we encounter a nested anonymous struct, we make give this previously anonymous structure a name and refer to it using this name. See examples/name-anon-structs.go.

CustomNamer

CustomNamer enables full control over the TypeScript type names. This is handy to enforce a custom coding guideline, or to add a prefix/suffix to the generated type names. See examples/custom-namer.go.

Enums

See examples/enums.go.

Go famously does not have enums, but rather type aliases and consts. Using reflection alone there is no way to obtain a comprehensive list of type values, as the linker might optimize and remove some. bel supports the extraction of enums by parsing the Go source code. Note that this is merely a heuristic and may fail in your case. If it does not work, bel falls back to the underlying type.

Enums can be generated as TypeScript enum or as sum types. Use the bel.GenerateEnumsAsSumTypes flag to change this behaviour.

Code Generation

See examples/code-generation.go.

When generating the TypeScript code you might want to wrap everything in a namespace. To that end bel.GenerateNamespace("myNamespaceName") can be used.

By default bel adds a comment to the files it generates. You can influcence this comment (and any other code that comes before the generated code) using bel.GeneratePreamble and bel.GenerateAdditionalPreamble.

You can configure the io.Writer that bel uses using bel.GenerateOutputTo.

Contributing

All contributions/PR/issue/beer are welcome ❤️ .

It's easiest to work with bel using Gitpod: Open in Gitpod

Owner
Christian Weichel
Working on @gitpod-io and werft
Christian Weichel
Similar Resources

A lightweight (simplistic) JSON format log analyzer for Nginx.

A lightweight (simplistic) JSON format log analyzer for Nginx.

Nginx-JSON-Log-Analyzer README English | 中文 What is it Nginx-JSON-Log-Analyzer is a lightweight (simplistic) JSON format log analyzer, used to analyze

Nov 29, 2022

alog is a dependency free, zero/minimum memory allocation JSON logger with extensions

alog is a dependency free, zero/minimum memory allocation JSON logger with extensions

Alog (c) 2020-2021 Gon Y Yi. https://gonyyi.com. MIT License Version 1.0.0 Intro Alog was built with a very simple goal in mind: Support Tagging (and

Dec 13, 2021

A simple Go JSON logger.

logger A simple JSON logger for Go. It uses a context.Context to store values which will then be logged along with each message. It is possible to rec

Jul 25, 2022

This package enables json output, level logging and so on to standard go logger.

logplug This package enables json output, level logging and so on to standard logger. Usage log.SetOutput(logplug.NewJSONPlug(os.Stderr, logplug.LogF

Dec 27, 2021

protoc-gen-grpc-gateway-ts is a Typescript client generator for the grpc-gateway project. It generates idiomatic Typescript clients that connect the web frontend and golang backend fronted by grpc-gateway.

protoc-gen-grpc-gateway-ts protoc-gen-grpc-gateway-ts is a Typescript client generator for the grpc-gateway project. It generates idiomatic Typescript

Dec 19, 2022

RPC Framework abstraction layer. Provides foundation of the RonyDesc to generate RPC server/client codes.

RonyKit RonyKit provides the abstraction layer for creating a cluster aware API server. By defining separate components for each task, you are almost

Dec 15, 2022

rpc/v2 support for JSON-RPC 2.0 Specification.

rpc rpc/v2 support for JSON-RPC 2.0 Specification. gorilla/rpc is a foundation for RPC over HTTP services, providing access to the exported methods of

Jul 4, 2021

Go library to interface with Solana JSON RPC and WebSocket interfaces

Go library to interface with Solana JSON RPC and WebSocket interfaces

Solana SDK library for Go Go library to interface with Solana JSON RPC and WebSocket interfaces. Clients for Solana native programs, Solana Program Li

Mar 2, 2022

[TOOL, CLI] - Filter and examine Go type structures, interfaces and their transitive dependencies and relationships. Export structural types as TypeScript value object or bare type representations.

typex Examine Go types and their transitive dependencies. Export results as TypeScript value objects (or types) declaration. Installation go get -u gi

Dec 6, 2022

K8s-go-structs - All k8s API Go structs

k8s-api go types Why? Its nice to have it all in a single package. . |-- pkg |

Jul 17, 2022

Examples of accepting interfaces and returning structs

Go Interfaces When I started writing tests in Go, I sometimes used interfaces to mock things in tests. Then I discovered that this is not the correct

Dec 27, 2022

Generate Typescript types from Golang source code

🎑 tygo Tygo is a tool for generating Typescript typings from Golang source files that just works. Other than reflection-based methods it preserves co

Dec 16, 2022

convert JSON of a specific format to a type structure(Typescript type or more)

json2type convert JSON of a specific format to a type structure(Typescript type or more) Quick Start CLI Install use go tool install go install github

Mar 28, 2022

Cap'n Proto library and parser for go. This is go-capnproto-1.0, and does not have rpc. See https://github.com/zombiezen/go-capnproto2 for 2.0 which has rpc and capabilities.

Version 1.0 vs 2.0 Update 2015 Sept 20: Big news! Version 2.0 of the go-bindings, authored by Ross Light, is now released and newly available! It feat

Nov 29, 2022

RPC explained by writing simple RPC framework in 300 lines of pure Golang.

Simple GoRPC Learning RPC basic building blocks by building a simple RPC framework in Golang from scratch. RPC In Simple Term Service A wants to call

Dec 17, 2022

Antenna RPC is an RPC protocol for distributed computing, it's based on QUIC and Colfer. its currently an WIP.

aRPC - Antenna Remote Procedure Call Antenna remote procedure call (aRPC) is an RPC protocol focused on distributed processing and HPC. aRPC is implem

Jun 16, 2021

Go Substrate RPC Client (GSRPC)Go Substrate RPC Client (GSRPC)

Go Substrate RPC Client (GSRPC) Substrate RPC client in Go. It provides APIs and types around Polkadot and any Substrate-based chain RPC calls. This c

Nov 11, 2021

Golang-Devnet-Interfaces - Quick example of using Scrapligo and TextFSM to parse interfaces from Devnet Sandbox

Scrapligo & TextFSM This is a simple example of using the Scrapligo library deve

Mar 7, 2022

Generate Terraform schema from Go structs

terraform-schema-gen This repository contains a CLI to generate Terraform schema out of Go structs. The generator relies on kube-openapi as an interme

Sep 13, 2022
Comments
  • Properly extract enums/const

    Properly extract enums/const

    Something like

    type Foo string
    const (
        Bar = "bar"
        Baz = "baz"
    )
    
    type UsesFoo struct {
        Field Foo
    }
    

    results in Field being extracted as type string rather than Foo. Ideally we'd have an enum Foo coming out of the extractor.

    Using Go reflection this cannot be done [1, 2]. We could however parse the Golang source and extract the const values that way.

    [1] https://stackoverflow.com/questions/33189060/is-there-a-way-to-iterate-over-constant-used-as-enum [2] https://groups.google.com/forum/#!topic/golang-nuts/M0ORoEU115o

  • Allow renaming of primitive types

    Allow renaming of primitive types

    Allows renaming primitive types. This is helpful if those types are marshalled in a non standard way.

    In our case, we had a type Timestamp int64 that we are marshalling as a string. With this change, it’s possible to customise the generated typescript type for non struct types as well.

  • Missing error check in fielpath.WalkFunc

    Missing error check in fielpath.WalkFunc

    Stacktrace:

    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x5584e9]
    
    goroutine 1 [running]:
    github.com/32leaves/bel.NewParsedSourceEnumHandler.func1(0x615603, 0x15, 0x0, 0x0, 0x653880, 0xc000100b10, 0x40, 0x5f6a00)
    	/workspace/go/pkg/mod/github.com/32leaves/[email protected]/enum.go:32 +0x49
    path/filepath.Walk(0x615603, 0x15, 0xc0001318e0, 0x0, 0x1000000006595a0)
    	/home/gitpod/go/src/path/filepath/path.go:404 +0x6a
    github.com/32leaves/bel.NewParsedSourceEnumHandler(0x615603, 0x15, 0x0, 0x0, 0x653880)
    	/workspace/go/pkg/mod/github.com/32leaves/[email protected]/enum.go:31 +0xf7
    main.main()
    	/tmp/build/gitpod-core-components-licensor-typescript--lib.b4eb6140f12b76cf914379726822bcd956b92256/ee/genapi.go:25 +0x8f
    exit status 2
    
Empleando interfaces para inyectar capas o dependencias

go-interfaces Trabajar con Interfaces facilita la inyeccion de capas, y tambien el testing de cada capa. Para desarrollar con este mecanismo es necesa

Dec 1, 2021
Changelog management tool, avoid merge conflicts and generate markdown changelogs.

chalog This is chalog, a changelog management tool. With chalog you can manage your project's changelog in a simple markdown format, split across mult

Jul 7, 2022
Parse awesome-go README file and generate a new README file with repo info.

Awesome Go Extra All data are from awesome-go and GitHub API. Audio and Music Libraries for manipulating audio. Name Description Star Open Issues Crea

Aug 11, 2022
Go-generate-cv - Simple CV generator developed in Go

go-generate-cv Simple CV generator developed in Go Milestone Have a form to fill

Jan 10, 2022
Goal is to generate logger and tracer wraps around a certain struct
Goal is to generate logger and tracer wraps around a certain struct

Goal is to generate logger and tracer wraps around a certain struct

Feb 13, 2022
Generate vector tiles for the entire planet on relatively low spec hardware.
Generate vector tiles for the entire planet on relatively low spec hardware.

Sequentially Generate Planet Mbtiles Sequentially generate and merge an entire planet.mbtiles vector tileset on low memory/power devices for free. com

Dec 21, 2022
Zero Allocation JSON Logger
Zero Allocation JSON Logger

Zero Allocation JSON Logger The zerolog package provides a fast and simple logger dedicated to JSON output. Zerolog's API is designed to provide both

Jan 1, 2023
A powerful zero-dependency json logger.

ZKits Logger Library About This package is a library of ZKits project. This is a zero-dependency standard JSON log library that supports structured JS

Dec 14, 2022
Parametrized JSON logging library in Golang which lets you obfuscate sensitive data and marshal any kind of content.
Parametrized JSON logging library in Golang which lets you obfuscate sensitive data and marshal any kind of content.

Noodlog Summary Noodlog is a Golang JSON parametrized and highly configurable logging library. It allows you to: print go structs as JSON messages; pr

Oct 27, 2022
Nginx JSON Log Analyze

Nginx-JSON-Log-Analyze Nginx Configuration log_format json_log escape=json '{"time_iso8601":"$time_iso8601",' '"remote

Nov 29, 2022