0

i'm currently trying to send variables (in this case a struct array into the JS variable Data) to my website. In Addition i want to read a String out of my TextField and trigger a Function with it as parameter. My question is, how to get/recieve/send the variable from Go/Javascript? For now it doesnt even call the fillChoiceBox() function. I set it as onClick Function but nothing happens. A Code Example would be very nice.

Here my Golang code:

//Klimakammer struct
type klimakammer struct {
    Name        string `json:"name"`
    Hersteller  string `json:"hersteller"`
    IP          string `json:"ip"`
    SollTemp    string `json:"solltemp"`
    IstTemp     string `json:"isttemp"`
    SollFcht    string `json:"sollfcht"`
    IstFcht     string `json:"istfcht"`
    kammerstart bool
    kammerstop  bool
}

//Ct01 Klimakammern erstellen
var Ct01 = klimakammer{"ct01", "weiss", "10.0.62.22", "", "", "", "", false, true}

//Kammern - Fill Klimakammer Array
var Kammern = []klimakammer{
    Ct01,
}

func main() {

    fs := http.FileServer(http.Dir("./static/"))
    http.Handle("/", fs)

    http.ListenAndServe(":8080", nil)

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        buff, _ := json.Marshal(&Kammern)
        fmt.Fprintln(w, string(buff))
    })

}

and my JS-Code:

function fillChoiceBox() {

   **//That was my first try (But it never found the URL "/getKammer"):**
 // $.ajax({
 //     url: "http://localhost:8080/getKammer",
 //     method: "GET",
 //     function(data) {
 //         var $dropdown = $("#Kammer");
 //         for( i=0; i <= data.length; i++) {
 //               $dropdown.append($("<option />").val(data[i]).text(this.name));
 //               $("#getKammer").prop('disabled', true);
 //         }
 //     },
 //  })
            var i;
            var $dropdown = $("#Kammer");
            for( i=0; i <= data.length; i++) {
            $dropdown.append($("<option />").val(data[i]));
            }
            $("#getKammer").prop('disabled', true);
  }
9
  • Calling HandleFunc after ListenAndServe makes no sense. Commented Jun 10, 2020 at 6:12
  • Calling HandleFunc/Handle more than once with the same pattern will panic (currently your code doesn't panic because the second call is not reached thanks to ListenAndServe). Commented Jun 10, 2020 at 6:13
  • okay thanks and how to send the data to JS? Commented Jun 10, 2020 at 6:18
  • and as i said my previous try was with /getKammer but the developerConsole of Chrome said that /getKammer is not there Commented Jun 10, 2020 at 6:20
  • Use a separate endpoint, using "/" is not a requirement, you can substitute it with whatever else (within reason). Commented Jun 10, 2020 at 6:21

1 Answer 1

1

Here is a sample code to send and get data from a typical Go Server. Before implementing, I would suggest going through this blog about writing web applications with Go.

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type Foo struct {
    Field1 string `json:"field1"`
    Field2 int    `json:"field2"`
}

func main() {
    http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
        var f Foo
        if err := json.NewDecoder(r.Body).Decode(&f); err != nil {
            panic(err)
        }
        defer r.Body.Close()

        log.Println("foo: ", f)
        w.WriteHeader(http.StatusOK)
    })

    http.HandleFunc("/bar", func(w http.ResponseWriter, _ *http.Request) {
        f := Foo{"bar", 20}
        w.Header().Set("Content-Type", "application/json")
        if err := json.NewEncoder(w).Encode(&f); err != nil {
            panic(err)
        }
    })

    panic(http.ListenAndServe(":3030", nil))
}

/*
JS Code to post data:

$.ajax({
    url: "http://localhost:3030/foo",
    method: "POST",
    data: JSON.stringify({field1:"foo",field2:10}),
    success: function() {
        console.log('done');
    }
})

JS Code to get data:

$.ajax({
    url: "http://localhost:3030/bar",
    method: "GET",
    success: function(data) {
        console.log(data);
    }
})
*/
Sign up to request clarification or add additional context in comments.

1 Comment

Like @mkopriva mentioned in the comments, its still important for you to understand the basics of a go web server. ListenAndServe is a blocking call. This means, your program will not proceed beyond that. So in your original question http.HandleFunc("/" is unreachable code. Please read through the blog I linked to get a better understanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.