Mkdoc | go tool to wasm

Time:2021-2-23

cause

Some time ago, I wrote an API document generation tool mkdoc, because I didn’t rely on go cli like swag go. Later, I wondered if I could compile it into wasm and put it on the web page, so that we could easily deploy it and have an understanding of it.

achievements

Online experience

  • ( :

If you are interested in mkdoc, welcome fork & star

Some questions

  1. The tool uses the file system, the wasm provided by go_ exec.js File system is not implemented in
  2. Yes os.Getwd Syscall / JS has no direct support for system calls
  3. Some interaction problems between go and JS

solve

file system

In wasm_ exec.js You can see an unimplementednode fs APIThen we just need to clicknode fs APIImplement amemory filesystemCan solve the file system problem.

But it’s too troublesome to build wheels by yourself. I found the memfs Library (give the author 100). With memfs, I assign the FS provided by him to the window.fs Go will use this FS.

system call

Look first os.Getwd Source code of

// Getwd returns a rooted path name corresponding to the
// current directory. If the current directory can be
// reached via multiple paths (due to symbolic links),
// Getwd may return any one of them.
func Getwd() (dir string, err error) {
    if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
        return syscall.Getwd()
    }

    // Clumsy but widespread kludge:
    // if $PWD is set and matches ".", use it.
    dot, err := statNolog(".")
    if err != nil {
        return "", err
    }
    dir = Getenv("PWD")
    if len(dir) > 0 && dir[0] == '/' {
        d, err := statNolog(dir)
        if err == nil && SameFile(dot, d) {
            return dir, nil
        }
    }

If it is found, it will check the PWD environment variable. If it is found, it is the current PWD environment variable$PWDThe value of $pwd is used directly,
So add a set env when starting to solve the problem of incorrect directory of getwd.

func initJS() {
    //...
    os.Setenv("PWD", "/")
}

interactive

Here’s a story about go log.Println Binding to JS console.log The other way is to look at the document.

func (c *ConsoleWriter) Write(p []byte) (n int, err error) {
    js.Global().Get("console").Call("log", string(p))
    return len(p), nil
}

func (c *ConsoleWriter) Log(s string) {
    c.Write([]byte(s))
}

var console = new(ConsoleWriter)

func initJS() {
    log.SetOutput(console)
    // ...
}

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]