doubiao1734 2017-12-31 04:16
浏览 49
已采纳

将数据从客户端发送到服务器-REST Web服务

I am developing a client-server application using RESTful web services.

I want to ask for user input on the client and send it to the server and use that name in the rest of my program but I cannot send the name to the server properly.

Below is a part of my program:

Client:

func main() {
       //getting input
        fmt.Println("Please enter your name: ")
        reader := bufio.NewReader(os.Stdin)
        myName, _ := reader.ReadString('
')

        client := &http.Client{
            CheckRedirect: nil,
        }
        reply, err := http.NewRequest("GET", "http://localhost:8080/", nil)
        reply.Header.Add("username", myName)
        client.Do(reply)
        if err != nil {
            fmt.Println(err)
        }

Server:

func CreateClient(w http.ResponseWriter, r *http.Request) {

    clientName := r.Header.Get("username")
    fmt.Println(clientName, "---------")//it's empty
    cli := &Client{
        currentRoom:   nil, //starts as nil because the user is not initally in a room
        outputChannel: make(chan string),
        name:          clientName,
    }
    Members = append(Members, cli)

    reply := cli.name

    fmt.Fprintf(w, reply)
}

on the client side, reply (reply.Header.Add("username", myName)) has the user name in the header but on the server side clientName (clientName := r.Header.Get("username")) is empty so the rest of my program won't run.

My problem is that I cannot send the user input to the server and take it back on the client side.

Can someone tell me how I can solve the problem?

  • 写回答

1条回答 默认 最新

  • dongping5230 2017-12-31 04:59
    关注

    You may want to have a look at http query string. Wikipedia

    Sending the username.

    req := http.NewRequest("GET","localhost:8080",nil)
    q:=req.URL.Query()
    q.Add("username",myName)
    req.URL.RawQuery = q.Encode()
    Resp,err:=http. Client{}.Do(req)
    

    Recieving the username:

    clientName := r.URL.Query()["username"][0]
    

    Note that if your are going to do the same with password or any other sensitive data, please do some research on how to make it secure and DO NOT copy this code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)