Store username in array from login to server











up vote
0
down vote

favorite












I have a small Go web-server that displays data to users as they login. The problem I'm trying to achieve is to have the web-page only show certain information when a specific user logs in. For example, when admin logs in there would be a list of admin-only items that they can see on the web-page.



The problem I'm having is for some reason my Go code isn't storing the username in the array that I'm calling, so when I pass it over to the JavaScript it is blank.



Here are the 3 main parts of the code that I'm struggling with:



main.go



package main

import "fmt"

func authHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
usernameArray, hasUsername := r.PostForm["j_username"]

//This line added for debugging purposes
log.Println("username:", usernameArray[0])

if hasUsername {
fmt.Fprintf(w, "%s", usernameArray[0])
}
}

func main() {
http.HandleFunc("/getAuth", authHandler)
}




javascript.js



Note that this is AngularJS



$scope.init = function() {
checkAuthentication();
};

checkAuthentication = function() {
$http.get("/getAuth").then(
function(response) {
var username = response.data;

console.log(username): //Added for debugging purposes

if (username === "admin") {
$scope.showAdminOnlyItems = true;
}
});
}




main.html



<div id="admin-only-items" ng-show="showAdminOnlyItems">
<hr style="border:1px solid">
<p style="text-align: center">admin only: </p>
<div id="adminOnlyButtom">
<button class="button" data-ng-click="doSomething()">Do something</button>
</div>
</div>


Again, I only want that div to show up when admin logs in, and Go needs to send the username over to the javascript to verify that. By adding the debugging line in Go and starting the server up, I get this:



2018/11/19 16:28:42 http: panic serving 10.240.49.238:59621: runtime error: 
index out of range
goroutine 26 [running]:
net/http.(*conn).serve.func1(0xc42009f720)
C:/Go/src/net/http/server.go:1726 +0xd0
panic(0x79f820, 0xe17940)
C:/Go/src/runtime/panic.go:502 +0x229
main.authHandler(0xc56220, 0xc420135180, 0xc4207a3500)
D:/src/main.go:346 +0x1d8


So it's clear that the usernameArray is empty, not sure what I did wrong. Can anyone help tell me why the usernameArray is empty in authHandler?










share|improve this question




















  • 1




    You should check for error value returned from r.ParseForm() and use r.PostFormValue() instead.
    – Pie 'Oh' Pah
    Nov 20 at 0:30






  • 2




    Also note that r.PostFormValue() would be for a PUT, PATCH, or POST. You're sending an http GET method, which is not expended to send any data.
    – Slotheroo
    Nov 20 at 0:32










  • How are you sending request data to Go in the first place? The javascript code only send GET request with no data.
    – Pie 'Oh' Pah
    Nov 20 at 1:02















up vote
0
down vote

favorite












I have a small Go web-server that displays data to users as they login. The problem I'm trying to achieve is to have the web-page only show certain information when a specific user logs in. For example, when admin logs in there would be a list of admin-only items that they can see on the web-page.



The problem I'm having is for some reason my Go code isn't storing the username in the array that I'm calling, so when I pass it over to the JavaScript it is blank.



Here are the 3 main parts of the code that I'm struggling with:



main.go



package main

import "fmt"

func authHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
usernameArray, hasUsername := r.PostForm["j_username"]

//This line added for debugging purposes
log.Println("username:", usernameArray[0])

if hasUsername {
fmt.Fprintf(w, "%s", usernameArray[0])
}
}

func main() {
http.HandleFunc("/getAuth", authHandler)
}




javascript.js



Note that this is AngularJS



$scope.init = function() {
checkAuthentication();
};

checkAuthentication = function() {
$http.get("/getAuth").then(
function(response) {
var username = response.data;

console.log(username): //Added for debugging purposes

if (username === "admin") {
$scope.showAdminOnlyItems = true;
}
});
}




main.html



<div id="admin-only-items" ng-show="showAdminOnlyItems">
<hr style="border:1px solid">
<p style="text-align: center">admin only: </p>
<div id="adminOnlyButtom">
<button class="button" data-ng-click="doSomething()">Do something</button>
</div>
</div>


Again, I only want that div to show up when admin logs in, and Go needs to send the username over to the javascript to verify that. By adding the debugging line in Go and starting the server up, I get this:



2018/11/19 16:28:42 http: panic serving 10.240.49.238:59621: runtime error: 
index out of range
goroutine 26 [running]:
net/http.(*conn).serve.func1(0xc42009f720)
C:/Go/src/net/http/server.go:1726 +0xd0
panic(0x79f820, 0xe17940)
C:/Go/src/runtime/panic.go:502 +0x229
main.authHandler(0xc56220, 0xc420135180, 0xc4207a3500)
D:/src/main.go:346 +0x1d8


So it's clear that the usernameArray is empty, not sure what I did wrong. Can anyone help tell me why the usernameArray is empty in authHandler?










share|improve this question




















  • 1




    You should check for error value returned from r.ParseForm() and use r.PostFormValue() instead.
    – Pie 'Oh' Pah
    Nov 20 at 0:30






  • 2




    Also note that r.PostFormValue() would be for a PUT, PATCH, or POST. You're sending an http GET method, which is not expended to send any data.
    – Slotheroo
    Nov 20 at 0:32










  • How are you sending request data to Go in the first place? The javascript code only send GET request with no data.
    – Pie 'Oh' Pah
    Nov 20 at 1:02













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a small Go web-server that displays data to users as they login. The problem I'm trying to achieve is to have the web-page only show certain information when a specific user logs in. For example, when admin logs in there would be a list of admin-only items that they can see on the web-page.



The problem I'm having is for some reason my Go code isn't storing the username in the array that I'm calling, so when I pass it over to the JavaScript it is blank.



Here are the 3 main parts of the code that I'm struggling with:



main.go



package main

import "fmt"

func authHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
usernameArray, hasUsername := r.PostForm["j_username"]

//This line added for debugging purposes
log.Println("username:", usernameArray[0])

if hasUsername {
fmt.Fprintf(w, "%s", usernameArray[0])
}
}

func main() {
http.HandleFunc("/getAuth", authHandler)
}




javascript.js



Note that this is AngularJS



$scope.init = function() {
checkAuthentication();
};

checkAuthentication = function() {
$http.get("/getAuth").then(
function(response) {
var username = response.data;

console.log(username): //Added for debugging purposes

if (username === "admin") {
$scope.showAdminOnlyItems = true;
}
});
}




main.html



<div id="admin-only-items" ng-show="showAdminOnlyItems">
<hr style="border:1px solid">
<p style="text-align: center">admin only: </p>
<div id="adminOnlyButtom">
<button class="button" data-ng-click="doSomething()">Do something</button>
</div>
</div>


Again, I only want that div to show up when admin logs in, and Go needs to send the username over to the javascript to verify that. By adding the debugging line in Go and starting the server up, I get this:



2018/11/19 16:28:42 http: panic serving 10.240.49.238:59621: runtime error: 
index out of range
goroutine 26 [running]:
net/http.(*conn).serve.func1(0xc42009f720)
C:/Go/src/net/http/server.go:1726 +0xd0
panic(0x79f820, 0xe17940)
C:/Go/src/runtime/panic.go:502 +0x229
main.authHandler(0xc56220, 0xc420135180, 0xc4207a3500)
D:/src/main.go:346 +0x1d8


So it's clear that the usernameArray is empty, not sure what I did wrong. Can anyone help tell me why the usernameArray is empty in authHandler?










share|improve this question















I have a small Go web-server that displays data to users as they login. The problem I'm trying to achieve is to have the web-page only show certain information when a specific user logs in. For example, when admin logs in there would be a list of admin-only items that they can see on the web-page.



The problem I'm having is for some reason my Go code isn't storing the username in the array that I'm calling, so when I pass it over to the JavaScript it is blank.



Here are the 3 main parts of the code that I'm struggling with:



main.go



package main

import "fmt"

func authHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
usernameArray, hasUsername := r.PostForm["j_username"]

//This line added for debugging purposes
log.Println("username:", usernameArray[0])

if hasUsername {
fmt.Fprintf(w, "%s", usernameArray[0])
}
}

func main() {
http.HandleFunc("/getAuth", authHandler)
}




javascript.js



Note that this is AngularJS



$scope.init = function() {
checkAuthentication();
};

checkAuthentication = function() {
$http.get("/getAuth").then(
function(response) {
var username = response.data;

console.log(username): //Added for debugging purposes

if (username === "admin") {
$scope.showAdminOnlyItems = true;
}
});
}




main.html



<div id="admin-only-items" ng-show="showAdminOnlyItems">
<hr style="border:1px solid">
<p style="text-align: center">admin only: </p>
<div id="adminOnlyButtom">
<button class="button" data-ng-click="doSomething()">Do something</button>
</div>
</div>


Again, I only want that div to show up when admin logs in, and Go needs to send the username over to the javascript to verify that. By adding the debugging line in Go and starting the server up, I get this:



2018/11/19 16:28:42 http: panic serving 10.240.49.238:59621: runtime error: 
index out of range
goroutine 26 [running]:
net/http.(*conn).serve.func1(0xc42009f720)
C:/Go/src/net/http/server.go:1726 +0xd0
panic(0x79f820, 0xe17940)
C:/Go/src/runtime/panic.go:502 +0x229
main.authHandler(0xc56220, 0xc420135180, 0xc4207a3500)
D:/src/main.go:346 +0x1d8


So it's clear that the usernameArray is empty, not sure what I did wrong. Can anyone help tell me why the usernameArray is empty in authHandler?







javascript html arrays angularjs go






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 7:51









Flimzy

36.6k96496




36.6k96496










asked Nov 19 at 23:56









WitchKing17

7810




7810








  • 1




    You should check for error value returned from r.ParseForm() and use r.PostFormValue() instead.
    – Pie 'Oh' Pah
    Nov 20 at 0:30






  • 2




    Also note that r.PostFormValue() would be for a PUT, PATCH, or POST. You're sending an http GET method, which is not expended to send any data.
    – Slotheroo
    Nov 20 at 0:32










  • How are you sending request data to Go in the first place? The javascript code only send GET request with no data.
    – Pie 'Oh' Pah
    Nov 20 at 1:02














  • 1




    You should check for error value returned from r.ParseForm() and use r.PostFormValue() instead.
    – Pie 'Oh' Pah
    Nov 20 at 0:30






  • 2




    Also note that r.PostFormValue() would be for a PUT, PATCH, or POST. You're sending an http GET method, which is not expended to send any data.
    – Slotheroo
    Nov 20 at 0:32










  • How are you sending request data to Go in the first place? The javascript code only send GET request with no data.
    – Pie 'Oh' Pah
    Nov 20 at 1:02








1




1




You should check for error value returned from r.ParseForm() and use r.PostFormValue() instead.
– Pie 'Oh' Pah
Nov 20 at 0:30




You should check for error value returned from r.ParseForm() and use r.PostFormValue() instead.
– Pie 'Oh' Pah
Nov 20 at 0:30




2




2




Also note that r.PostFormValue() would be for a PUT, PATCH, or POST. You're sending an http GET method, which is not expended to send any data.
– Slotheroo
Nov 20 at 0:32




Also note that r.PostFormValue() would be for a PUT, PATCH, or POST. You're sending an http GET method, which is not expended to send any data.
– Slotheroo
Nov 20 at 0:32












How are you sending request data to Go in the first place? The javascript code only send GET request with no data.
– Pie 'Oh' Pah
Nov 20 at 1:02




How are you sending request data to Go in the first place? The javascript code only send GET request with no data.
– Pie 'Oh' Pah
Nov 20 at 1:02












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










The first, I can see that you send GET request to server without j_username query param therefore you can not read j_username on server side.



The second, usernameArray is empty slice which is failing while parse j_username. Error index out of range occur when you try to call usernameArray[0].



You should send GET request with j_username like that /getAuth?j_username=admin and modify code from server.



    usernameArray, hasUsername := r.URL.Query()["j_username"]
//This line added for debugging purposes
log.Println("debug here :", usernameArray)

if hasUsername {
fmt.Fprintf(w, "%s", usernameArray[0])
return
}

// Send an error message to client
http.Error(w, `missing username`, 500)





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384331%2fstore-username-in-array-from-login-to-server%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    The first, I can see that you send GET request to server without j_username query param therefore you can not read j_username on server side.



    The second, usernameArray is empty slice which is failing while parse j_username. Error index out of range occur when you try to call usernameArray[0].



    You should send GET request with j_username like that /getAuth?j_username=admin and modify code from server.



        usernameArray, hasUsername := r.URL.Query()["j_username"]
    //This line added for debugging purposes
    log.Println("debug here :", usernameArray)

    if hasUsername {
    fmt.Fprintf(w, "%s", usernameArray[0])
    return
    }

    // Send an error message to client
    http.Error(w, `missing username`, 500)





    share|improve this answer

























      up vote
      1
      down vote



      accepted










      The first, I can see that you send GET request to server without j_username query param therefore you can not read j_username on server side.



      The second, usernameArray is empty slice which is failing while parse j_username. Error index out of range occur when you try to call usernameArray[0].



      You should send GET request with j_username like that /getAuth?j_username=admin and modify code from server.



          usernameArray, hasUsername := r.URL.Query()["j_username"]
      //This line added for debugging purposes
      log.Println("debug here :", usernameArray)

      if hasUsername {
      fmt.Fprintf(w, "%s", usernameArray[0])
      return
      }

      // Send an error message to client
      http.Error(w, `missing username`, 500)





      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        The first, I can see that you send GET request to server without j_username query param therefore you can not read j_username on server side.



        The second, usernameArray is empty slice which is failing while parse j_username. Error index out of range occur when you try to call usernameArray[0].



        You should send GET request with j_username like that /getAuth?j_username=admin and modify code from server.



            usernameArray, hasUsername := r.URL.Query()["j_username"]
        //This line added for debugging purposes
        log.Println("debug here :", usernameArray)

        if hasUsername {
        fmt.Fprintf(w, "%s", usernameArray[0])
        return
        }

        // Send an error message to client
        http.Error(w, `missing username`, 500)





        share|improve this answer












        The first, I can see that you send GET request to server without j_username query param therefore you can not read j_username on server side.



        The second, usernameArray is empty slice which is failing while parse j_username. Error index out of range occur when you try to call usernameArray[0].



        You should send GET request with j_username like that /getAuth?j_username=admin and modify code from server.



            usernameArray, hasUsername := r.URL.Query()["j_username"]
        //This line added for debugging purposes
        log.Println("debug here :", usernameArray)

        if hasUsername {
        fmt.Fprintf(w, "%s", usernameArray[0])
        return
        }

        // Send an error message to client
        http.Error(w, `missing username`, 500)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 2:16









        KibGzr

        1,091510




        1,091510






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384331%2fstore-username-in-array-from-login-to-server%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Wiesbaden

            Marschland

            Dieringhausen