Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Passing JSON from Go (backend) to Go (frontend) via html/template. #93

Closed
@dmitshur

Description

@dmitshur

This is a question. What is a good way to get a Go struct from backend Go code to a Go func in frontend (compiled to JavaScript using GopherJS)... If I'm using html/template package.

Here are details. Suppose I have a Go struct:

package common

type Foo struct {
    Bar string
    Baz bool `json:",omitempty"`
}

And I use html/template to render a template like this:

<div>
    {{range .ManyFoos}}<div>
        <!-- I'd like to pass the Foo struct into the GoHandler func below. -->
        <span onclick="GoHandler({{.}});">{{.Bar}}</span>
    {{end}}
</div>

And the GoHandler is written in Go and compiled to JavaScript via GopherJS.

// +build js

package main

import (
    "github.com/gopherjs/gopherjs/js"
    "honnef.co/go/js/xhr"
    ".../common" // Where the Foo struct was defined.
)

// What I'd _like_ to be able to do. (Or something similarly Go-like and short...)
func GoHandler(foo common.Foo) {
    foo.Bar = foo.Bar + ... // Some logic.

    fooJson, err := json.Marshal(foo)
    if err != nil { panic(err) }

    _, err := xhr.Send("POST", "/foo", string(fooJson))
    if err != nil { panic(err) }
}

// What I'm currently doing... (It works but involves JavaScript, which I want to find a way to avoid.)
func GoHandler(foo js.Object) {
    foo.Set("Bar", foo.Get("Bar") + ...) // Some logic.

    // If I have to do this, I might as well not be writing Go code...
    fooJson = js.Global.Get("JSON").Call("stringify", foo))

    _, err := xhr.Send("POST", "/foo", string(fooJson))
    if err != nil { panic(err) }
}

func main() {
    js.Global.Set("GoHandler", GoHandler)
}

Any ideas or suggestions are appreciated. I'm new to dealing with JSON with GopherJS, so perhaps I'm missing some easy way to improve this. Or perhaps html/template cannot be used directly, and a similar package with some sort of GopherJS support would need to be created? Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions