Leverage Go programming language to extract data from a file and utilize it in rendering with

While many articles discuss using Go Arrays with Javascript, I am working on something unique. My goal is to read a configuration file using Go, which has server-side access, and incorporate it into a javascript function that will be rendered with the template. This approach helps avoid hard coding values in the JavaScript:

My objective is to move away from manually specifying prefixes in the code and instead store them in a separate file, eliminating the need for recompilation every time a prefix needs to be added:

javaString += "function isValidPrefix() {"
javaString += "forbidden_prefixes = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\" ];"
... more javascript ...
javaString += "}"

Therefore, I attempted the following:

var configArr []string
configArr = LoadFile("/conf.dat")

javaString += "forbidden_prefixes = [];"

 for _, eachline := range configArr {
    javaString += "forbidden_prefixes.push(\" + eachline + \");"
    fmt.Println(eachline)
}

Although eachLine prints out correctly within the loop, forbidden_prefixes contains only one element + eachLine +. This seems to trigger a syntax error, and even when attempting to retrieve the DOM element's value for comparison, the web console indicates that the element does not exist. Previously, everything functioned correctly with hardcoded values. Am I making an error, or is this approach simply unattainable?

Answer №1

Construct a new string utilizing hardcoded values instead of the designated variable. Give this a shot:

    updatedString += fmt.Sprintf("required_values.push(\"%s\");",eachline)

Answer №2

The source of the problem lies in the syntax you used. By escaping the quotes, the + operators have become part of the string itself. Here are a couple of solutions to resolve this issue:

javaString += "forbidden_prefixes.push(\"" + eachline + "\");"

Alternatively,

javaString += fmt.Sprintf("forbidden_prefixes.push(%q);", eachline)

%q will enclose the replaced value with quotes.

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

Processing custom jQuery AJAX function callback in JavaScript

My jQuery code seems to be causing some trouble. (function () { function fetchContent(page) { $.ajax({ url: "/backend/index.php/frontend/pull_page/", type: "POST", data: {page: page}, success: fu ...

Error encountered: Unexpected token found in JSX while attempting to integrate the react-simple-typewriter component

Exploring the realm of creating a portfolio website through practice and experimenting with various animations. I've been diving into this particular document, https://www.npmjs.com/package/react-simple-typewriter, and conducting online research to g ...

What is the process for constructing a regular expression (regex) in JavaScript to validate an id?

My validation requirements are relatively straightforward, but as someone who is new to regex, I am in need of quick assistance. The format should be either 1234567890 or 123456-7890, allowing for any number ranging from 0 to 9 and a total character length ...

Three.js: Apply a single color to a mesh shaderMaterial until a specific point is reached

I am struggling to grasp the concept of Three.js shaders. My goal is to apply a color to a mesh, but only up to a specific point. Here is my progress so far. I want the green color to "stop" at 50% of the mesh height For the remaining part of the mesh (ab ...

convert CSV data into an array

My goal is to convert a CSV file into an array where the header serves as the key. However, when I try to insert this script into a database, it ends up overriding the previous row in the CSV file and only the last value gets stored in the database. I sus ...

Obtaining data from an external ng-repeat element

My list contains items that are being repeated using ng-repeat details. I want to be able to hover over one of the li elements and have the background of a div called background (which is outside of the ng-repeat) change to the url of the corresponding d ...

Randomly selecting an element from an array as the default option in vue.js

I am working on a neat little tool to learn vue.js where users can find out the time it takes to travel from one location to another: Codepen It's functioning fairly well at the moment, but I want to include a random value from each array when the pa ...

a user-friendly database solution for storing data in HTML 5 and Google Drive

Greetings, I am currently faced with the following dilemma: As I work on my angular 2 application, I find myself needing to save certain data. Personally, I have a preference for saving data in JSON format. Here is the scenario: Imagine a todo list where ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

Nodejs script designed to efficiently download all files from an FTP server to a local directory before seamlessly transferring them to another FTP folder

I am currently facing a challenge in downloading all files from a specific folder on an FTP site. The folder, named "IN" (as demonstrated in the example code), contains several .csv files. The requirements for this task are: Download all CSV files presen ...

What methods does MaterialUI utilize to achieve this?

Have you checked out the autocomplete feature in their component? You can find it here: https://mui.com/material-ui/react-autocomplete/ I noticed that after clicking on a suggestion in the dropdown, the input box retains its focus. How do they achieve thi ...

What is the best way to generate hyperlinks for hidden content controlled by a show/hide javascript function?

I am interested in creating links to hidden content using a show/hide JavaScript. Within the hidden content, there are three divs containing videos and text that I would like to link to. For example, linking to the "example" div as shown below. The links d ...

Issue with Vue custom range slider where cursor position is not accurately displayed

I recently developed a unique input range slider using Vue.js. While most aspects of the slider are functioning correctly, I have encountered an issue with the cursor position not aligning properly while sliding the range slider. Ideally, the cursor shou ...

What is the process for reverting Node.js from version 16 LTS back to 14 LTS?

Looking for help to downgrade my Node.js version from 16 to 14 for a project. I want to avoid conflicts and errors during the process. Any tips or guidance would be appreciated! Currently working on Windows platform. Thanks in advance. ...

I am currently searching for a method to display the content of a URL from an external source. While I have successfully managed to print the title accurately, I am now

I have stripped down most of the elements from my initial code to demonstrate how it is currently functioning. I've successfully implemented a feature that fetches the webview title, but now I am looking to expand it to showcase more of the HTML conte ...

Creating a Node.js application using Express requires careful consideration of file structure and communication methods

Struggling to pass login form credentials to existing JavaScript files for logic and info retrieval. Login page contains a form with POST method. main.js handles the login: main.js module.exports = { returnSessionToken: function(success, error) { ...

When I tried to use the zoom-in feature in Cropper.js, I encountered some issues with the centered cropped image

I am encountering an issue with Cropper.js. My goal is to zoom in on the image while cropping, ensuring that the crop box remains centered as I drag and modify it. Additionally, after cropping a piece of the image, that cropped portion should also be cente ...

Convert a prototype code to jQuery using AJAX syntax

Seeking advice on my code syntax as I transition from Prototype to jQuery. I currently have both frameworks running simultaneously and aim to streamline all scripts into jQuery for improved page load efficiency and speed. Migrating from Prototype to jQue ...

Unit Testing in AngularJS - leveraging multiple mocks and providers for comprehensive coverage

As I dive into unit testing for my Angular application, I find myself pondering the best way to organize the tests folder. My project was initialized using the yeoman angular generator, which comes equipped with Jasmine and Karma out of the box. Let' ...

Using the $ sign to choose a subdocument in mongoose

Here is the structure of my document: "event": { "attendants": { "seekers": [ { "$oid": "5bcdabd27e51de001576d289" }, { "$oid": "5bc9b39c1a48dd0d7d521924" } ...