从登录名到服务器将用户名存储在数组中

时间:2018-11-19 23:56:14

标签: javascript html arrays angularjs go

我有一个小型Go Web服务器,可以在用户登录时向其显示数据。我要解决的问题是仅当特定用户登录时使网页仅显示某些信息。例如,当管理员登录时,将有一个仅管理员项的列表,他们可以在网上看到页。

我遇到的问题是由于某种原因,我的Go代码没有将用户名存储在我正在调用的数组中,所以当我将其传递给JavaScript时,它为空。

这是我苦苦挣扎的代码的三个主要部分:

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

请注意,这是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>

同样,我只希望管理员登录时显示该div,而Go需要将用户名发送到javascript进行验证。通过在Go中添加调试行并启动服务器,我得到了这一点:

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

因此很显然usernameArray为空,不确定我做错了什么。谁能告诉我为什么authHandler中的usernameArray为空?

1 个答案:

答案 0 :(得分:1)

首先,我可以看到您在没有GET查询参数的情况下向服务器发送了j_username请求,因此您无法在服务器端读取j_username

第二个usernameArray是空片,在解析j_username时失败。尝试呼叫index out of range时发生错误usernameArray[0]

您应使用GET之类的j_username发送/getAuth?j_username=admin请求,并修改服务器中的代码。

    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)