14

I am working in Go. Following code to handle the client request.

package main

import (
    "net/http"
    "fmt"
 )

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<html><head><script>function createGroup(){var xmlhttp,number = document.getElementById('phoneNumber').value,email = document.getElementById('emailId').value; var values = {}; values.number = phoneNumber; values.email= emailId; if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}else{xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');}xmlhttp.open('POST','createGroup',true);xmlhttp.send(values.toString());}</script></head><body><h1>Group</h1><input type='text' name='phoneNumber' id='phoneNumber'/><input type='email' id='emailId' name='emailId'/><button onClick='createGroup()'>Create Group</button></body></html>")
 })
 http.HandleFunc("/createGroup",func(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r)
    //Try to get the user information
 })
 panic(http.ListenAndServe(":8080", nil))
}

Note

Client: Contains two text box to get the phone number, email and createGroup button.

  1. If user clicks the createGroup, Post request of /createGroup is triggered using ajax.

  2. createGroup request is handled in server(Go)

Problem

How to get the phone number and email in server side?

I have printed the request in /createGroup handler but values are missing.

Output: &{POST /createGroup HTTP/1.1 1 1 map[Accept:[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8] Accept-Encoding:[gzip, deflate] Content-Length:[15] Content-Type:[text/plain; charset=UTF-8] Connection:[keep-alive] Pragma:[no-cache] Cache-Control:[no-cache] User-Agent:[Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0] Accept-Language:[en-US,en;q=0.5] Referer:[http://localhost:8080/]] 0xc200099ac0 15 [] false localhost:8080 map[] map[] <nil> map[] 127.0.0.1:59523 /createGroup <nil>}

Any help will be grateful.

1
  • Can you format html in example? Commented Feb 15, 2017 at 7:21

1 Answer 1

25

Use ParseForm and r.FormValue, for example :

http.HandleFunc("/createGroup",func(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    fmt.Println(r.Form)
    fmt.Println(r.FormValue("email"))
})
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Thanks it is working, Note: In front-end i used form submission instead of ajax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.