简体   繁体   中英

inconsistent behaviour of javascript (particlesJS)

I am trying to make a login page with work. Below is the body of main html page (only body is shown to keep things concise):

<body>
    <div class="container">
        <div id="login-box">
            <div class="controls">
                <input type="text" name="username" placeholder="Username" class="form-control" />
                <input type="text" name="username" placeholder="Password" class="form-control" />
                <button type="button" class="btn btn-default btn-block btn-custom">Login</button>
            </div>  <!-- /.controls -->
        </div>   <!-- /#login-box -->
    </div>    <!-- /.container -->

    <div id="particles-js"></div>
    <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"> </script>

    <script>
    particlesJS.load('particles-js', 'particles.json', function() {
        console.log('callback - particles.js config loaded');
    });
    </script>

</body>

In addition to this I have a css and particles.json static files.

Everything works when I execute it on a web browser with apache2 as web server.

Then I take the exact same files and use it in a Golang program:

func main(){
    templates := template.Must(template.ParseFiles("../../templates/index.html"))
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
        if err:= templates.ExecuteTemplate(w, "index.html", nil) ; err != nil{
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
        //fmt.Fprintf(w, "Welcome to Gopherland")
    })
    http.Handle("/css/", http.FileServer(http.Dir("style")))
    http.Handle("/js/", http.FileServer(http.Dir("style")))
    http.ListenAndServe(":5000", nil)
}

and it fails to parse particles.json file:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

No other compile time or run time error is thrown by Go. This error appears in browser console. I have checked the validity of particles.json file.

Can someone help please?

Contents of particles.json:

{
  "particles": {
    "number": {
      "value": 80,
      "density": {
        "enable": true,
        "value_area": 800
      }
    },
    "color": {
      "value": "#ffffff"
    },
    "shape": {
      "type": "circle",
      "stroke": {
        "width": 0,
        "color": "#000000"
      },
      "polygon": {
        "nb_sides": 5
      },
      "image": {
        "width": 100,
        "height": 100
      }
    },
    "opacity": {
      "value": 0.5,
      "random": false,
      "anim": {
        "enable": false,
        "speed": 1,
        "opacity_min": 0.1,
        "sync": false
      }
    },
    "size": {
      "value": 5,
      "random": true,
      "anim": {
        "enable": false,
        "speed": 40,
        "size_min": 0.1,
        "sync": false
      }
    },
    "line_linked": {
      "enable": true,
      "distance": 150,
      "color": "#ffffff",
      "opacity": 0.4,
      "width": 1
    },
    "move": {
      "enable": true,
      "speed": 6,
      "direction": "none",
      "random": false,
      "straight": false,
      "out_mode": "out",
      "attract": {
        "enable": false,
        "rotateX": 600,
        "rotateY": 1200
      }
    }
  },
  "interactivity": {
    "detect_on": "canvas",
    "events": {
      "onhover": {
        "enable": true,
        "mode": "repulse"
      },
      "onclick": {
        "enable": true,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 400,
        "line_linked": {
          "opacity": 1
        }
      },
      "bubble": {
        "distance": 400,
        "size": 40,
        "duration": 2,
        "opacity": 8,
        "speed": 3
      },
      "repulse": {
        "distance": 200
      },
      "push": {
        "particles_nb": 4
      },
      "remove": {
        "particles_nb": 2
      }
    }
  },
  "retina_detect": true,
  "config_demo": {
    "hide_card": false,
    "background_color": "#b61924",
    "background_image": "",
    "background_position": "50% 50%",
    "background_repeat": "no-repeat",
    "background_size": "cover"
  }
}

http.HandleFunc("/", is matching anything that doesn't match elsewhere, it's essentially a catch all as the ServeMux documentation states:

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.

Since it is trying to load particles.json , and there is no better match, it is loading your index page.

You need to add another route, something like:

http.HandleFunc("/particles.json", func(w http.ResponseWriter, r *http.Request) {
   http.ServeFile(w, r, "./path/to/particles.json")
})

Thanks for your invaluable comments. I did try every options suggested above but couldn't make the program to work until I figured out that I had a silly misconception (due to lack of knowledge of course) that " / " in: *http.HandleFunc(" / ", func(w http.ResponseWriter, r http.Request) is the root of my project folder ie the folder under which I had my ./src, ./bin, ./style/css/ and ./style/js/

However, that wasn't the case. I modified the code to this:

func main () {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
        http.ServeFile(w, r, r.URL.Path)
    })
    http.ListenAndServe(":5000" , nil)
}

compiled and ran. Only to find that if I don't pass any path it was listing the "root" filesystem's contents like, /bin, /home. This was enough for me to understand that Go code is considering "/" filesystem's root and NOT project's root folder. I then updated absolute path of css and json file in my index.html and boom... It worked!

Thanks again for your help. It did help me a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM