Search code examples
restgorestful-url

Sending data from client to server - REST webservice


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('\n')

        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?


Solution

  • 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.