Skip to content

[WASM] How can I perform a set of crud REST api with tinygo ? #4131

Open
@SkydersZ

Description

@SkydersZ

Discussed in https://github.com/orgs/tinygo-org/discussions/4127

Originally posted by SkydersZ February 13, 2024
I'm currently working on a personal project. Notably to discover the possibilities of Web Assembly and Tinygo.

I have a small project which use vanilla.js and a simple index.html containing a button. When I click on the button, it execute my wasm module method getBookById which is exposed through my index.js file.

I have partially succeed in requesting an endpoint of my localhost backend server.

main.go (front) :

package main

import (
	"fmt"
	"net/http"
	"strconv"
)

// Call the backend server
//
//export getBookByID
func getBookByID(id int) {
	resp, err := http.Get("http://localhost:3001/books/" + strconv.Itoa(id))
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
	if resp != nil {
		fmt.Println(resp)
	} else {
		fmt.Println("Received nil response from server")
	}
}

func main() {
	println("Go wasm module is called")
}

main.go (back) :

// books slice to seed data records
var books = []book{
	{ID: "1", Title: "Sample title 1", Author: "Joe"},
	{ID: "2", Title: "Sample title 2", Author: "Michael"},
	{ID: "3", Title: "Sample title 3", Author: "John"},
}

// ....
// Return a Book by it's id
func getBookByID(c *gin.Context) {
	id := c.Param("id")

	for _, a := range books {
		if a.ID == id {
			c.IndentedJSON(http.StatusOK, a)
			return
		}
	}
	c.IndentedJSON(http.StatusNotFound, gin.H{"message": "book not found"})
}

I have the following log in my backend running with gin :
[GIN] 2024/02/13 - 16:49:15 | 200 | 476.625µs | 127.0.0.1 | GET "/books/1"

And I can see in the browser "network" section, the response status from the server (200 OK)
response content:

{
    "id": "1",
    "title": "Sample title 1",
    "author": "Joe"
}

But in my browser console, I have the following error :

panic: runtime error: nil pointer dereference
main.wasm:0x55925 Uncaught (in promise) RuntimeError: unreachable
    at runtime.runtimePanicAt (main.wasm:0x55925)
    at runtime.nilPanic (main.wasm:0x775f)
    at runtime.chanSelect (main.wasm:0x71087)
    at interface:{RoundTrip:func:{pointer:named:net/http.Request}{pointer:named:net/http.Response,named:error}}.RoundTrip$invoke (main.wasm:0x1d5856)
    at getBookByID (main.wasm:0x202e02)
    at getBookByID.command_export (main.wasm:0x204c70)
    at getBookById (index.js:40:50)
    at async HTMLButtonElement.<anonymous> ((index):161:24)

Is it due to a bad return type format ? Do I need to return my json as a string ?

Or should I use syscall/js to do an http call ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    wasmWebAssembly

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions