Executing javascript code within a golang environment

Is it possible to include JavaScript code within Go code?

package main

import (
    "fmt"
    "net/http"
)
func work(w http.ResponseWriter, r *http.Request){
    fmt.Printf("<script>console.log('javascript working')</script>")

}

func main() {
    http.HandleFunc("/", work)
    http.ListenAndServe(":4000", nil)
}

After running this code in the browser and checking the console window, there doesn't seem to be any output. Is there a way to execute JavaScript within Go code? It seems challenging to use Ajax with Golang.

Answer №1

This is a straightforward piece of JavaScript embedded in Go code:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    hello := "hello yu bn"
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, `<html>
            <head>
            </head>
            <body>
            <h1>Go Timer (ticks every second!)</h1>
            <div id="output"></div>
            <script type="text/javascript">
            console.log("`+hello+`");
            </script>
            </body>
            </html>`)
    })
    http.ListenAndServe(":9000", nil)
}

It's pretty cool! Make sure to check the browser console for any output!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Get into a Nested Class in JavaScript

I'm struggling to articulate my question, but I know there's a solution out there. I have profile cards in HTML, each with the class "card" containing two numbers. My goal is to display a progress bar specific to the % relationship of these numbe ...

What steps are involved in installing Angular 2 through NPM?

Currently, I am in the process of setting up my personal local development environment for an Angular 2 application without utilizing the QuickStart seed mentioned on the official Angular 2 website or the Angular CLI due to the surplus files that come with ...

Need to update React textarea with value that is currently set as readonly

In my React application, I have a textarea that is populated with a specific value. My goal is to allow this textarea to be updated and then submit the form in order to update the corresponding row in the database. <textarea id="description" className= ...

Triggering callback once all AJAX requests have finished

loadInfo: function(){ var jsonCounter = 0, room = ['room1','room2','room3'], dates = [], prices = [] $.each(booking.rooms, function(key, room_name) { $.getJSON('/get_info.php?room= ...

Arranging ajax json information using php

Recently, I encountered an issue while working with a flot area chart for statistical data over the years. Everything was functioning smoothly with static data, but now I am facing difficulties in fetching data from MySQL and formatting it correctly as JSO ...

What are the steps to resolving an Unhandled promise rejection error in a Node.js application?

I encountered an error message that I need help resolving: I am faced with an unhandled promise rejection. This issue likely occurred due to throwing inside an async function without a catch block, or rejecting a promise without handling it using .catch( ...

Applying inline css transition style using a string distorts the original value. Strange

I have a CSS file that specifies a transition property as follows (vendor prefixes excluded for brevity): transition: opacity 1s; Now, I want to tweak the transition-delay property of each element using JavaScript to create a stagger effect. Here's h ...

Convert SVG to image using a personalized icon font

I'm facing a challenge that I hope someone can assist me with: My objective is to save an inline SVG as a PNG image. The issue arises from the fact that the SVG contains foreignObject elements with webfont icons (including Fontawesome and custom one ...

How can I confirm in Lodash whether all properties in an array are equal even without a property to exclude?

Consider the following array of employee data: var service = [{ AssignedEmployeeInternalID: "8000000011", AssignedEmployeeUUID: "00000000-0001-1EE1-82C1-8379F1C4462E", BillableIndicator: true, BusinessPartnerFormattedName: ...

Edgeshelper failing to update mesh positions

I want to create a custom colored box with different colored edges. To accomplish this, I'm using the following code to generate the box and its edges. I've encapsulated both elements within an object3D since there will be multiple objects in the ...

Ways to specify an array type with unique elements that all have the same generic type as the rest?

Recently I've been dedicated to enhancing my open-source library, but I've run into a puzzling issue that has me stumped. Let's take a look at the code snippet: In my setup, I have an array containing functions designed for transformations ...

Angular controller within dynamically loaded content using Ajax

I am facing an issue with loading files via Ajax and applying Angular in my project. Here is the link to the Plunker where you can see the problem: http://plnkr.co/MxXzlenAuGcDy8iljKYX The problem I am encountering is that the content of sidebar.html loa ...

Is using "move(-1)" considered incorrect in an AngularJS expression?

Encountering this error message: [$parse:ueoe] Unexpected end of expression: move( When using this snippet of code: <button type="button" ng-click="move(-1)" tabindex="-1"> Could there be a syntax issue with move(-1) in AngularJS? On a side note, ...

Key code problem - Struggling to block the entry of the % symbol

On my HTML page, I have an input text field that should only accept number keys and left/right arrow on the keyboard. I attempted to implement this using JavaScript, but encountered a problem. <input onkeypress="return allowNumberOnly(event)" /> fu ...

When I press the right arrow key, the cursor vanishes into thin air

A content editable div contains HTML elements such as spans and plain text. View fiddle .ing-tag_0{ color:white; background-color: blue; } <div value="" id="step_input_0" name="step" placeholder="Tell us about step 1" class="input stepbox step ...

Calling JavascriptInterface in an H5 environment is not permitted

Utilizing the power of vue, I created an immersive h5 page within the application framework. The seamless connection between the page and the app relies on the use of window.JSInterface for communication. My current challenge lies in invoking the JSInterfa ...

utilizing a message collector for configuring embed fields

I'm currently working on a message collector feature that collects data to use in an embed's title, description, and color. My goal is to have each value correspond to a different aspect of the embed. However, I've encountered some challenge ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

The error message [jsonFlickrApi is not defined] in JavaScript is indicating that the

Upon calling a FLickrAPI, the returned xmlhttp.responseText appears as follows: jsonFlickrApi({"photos":{"page":1, "pages":200, "perpage":100, "total":"19934", "photo":[{"id":"7315581986", "owner":"62691288@N00", "secret":"504915125a", "server":"7090", ...