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.

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

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集