Golang : Submit web forms without browser by http.PostForm example
Writing this tutorial on how to submit a web form without using a browser. We submit web forms almost every time when we go online, such as login form, sign up form or purchasing order form. All these are done with a browser and require human input.
In this tutorial, we will learn how to post form input with Golang and get the status to see if the submission is successful or otherwise. For demonstration purpose, a server program will wait for input from client program and a client program will submit the login data to the server program. If the submission is successful, the server program prints out the accepted input from the client.
First, run this server program and prepare to accept submission from a client program.
loginserver.go
package main
import (
"fmt"
"html/template"
"log"
"net/http"
)
const logUserPage = `<html><body>
{{if .LoginError}}<p style="color:red">Either username or password is not in our record! Sign Up?</p>{{end}}
<form method="post" action="/login">
{{if .Username}}
<p><b>{{.Username}}</b>, you're already logged in! <a href="/logout">Logout!</a></p>
{{else}}
<label>Username:</label>
<input type="text" name="Username"><br>
<label>Password:</label>
<input type="password" name="Password">
<input type="submit" name="Login" value="Let me in!">
{{end}}
</form>
</body></html>`
var logUserTemplate = template.Must(template.New("").Parse(logUserPage))
func LoginPageHandler(w http.ResponseWriter, r *http.Request) {
conditionsMap := map[string]interface{}{}
// verify username and password
if r.FormValue("Password") != "" && r.FormValue("Username") != "" {
username := r.FormValue("Username")
password := r.FormValue("Password")
log.Println("Logged in :", username)
log.Println("With password :", password)
conditionsMap["Username"] = username
conditionsMap["LoginError"] = false
}
if err := logUserTemplate.Execute(w, conditionsMap); err != nil {
log.Println(err)
}
}
func main() {
fmt.Println("Server started, submit web forms to localhost:8080/login")
http.HandleFunc("/login", LoginPageHandler)
http.ListenAndServe(":8080", nil)
}
Execute
go run loginserver.go &
Next, run this client program. NOTE: Remember, the client must have the matching form variable names in order to execute a successful submission. The names should be case sensitive.
submitwebform.go
package main
import (
"fmt"
"net/http"
"net/url"
)
func main() {
username := "adamng"
password := "theultimatepassword"
loginURL := "http://localhost:8080/login"
urlData := url.Values{}
urlData.Set("Username", username)
urlData.Set("Password", password)
resp, err := http.PostForm(loginURL, urlData)
if err != nil {
fmt.Println(err)
}
fmt.Println("Status : ", resp.Status)
fmt.Println("Header: ", resp.Header)
fmt.Println("Body: ", resp.Body)
}
Output from server program upon receiving correct login input:
Server started, submit web forms to localhost:8080/login
2017/08/30 16:07:56 Logged in : adamng
2017/08/30 16:07:56 With password : theultimatepassword
Happy coding!
References:
https://www.socketloop.com/references/golang-net-http-postform-function-example
See also : Golang : Login and logout a user after password verification and redirect example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.9k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+17.9k Golang : Get path name to current directory or folder
+7.8k Swift : Convert (cast) Character to Integer?
+13k Golang : reCAPTCHA example
+10k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+8.4k Golang : Get final balance from bit coin address example
+11.4k Golang : Detect user location with HTML5 geo-location
+11.1k Golang : Handle API query by curl with Gorilla Queries example
+8.3k Golang : Find duplicate files with filepath.Walk
+6.8k Golang : Of hash table and hash map
+6.4k Get Facebook friends working in same company
+8.4k Golang : GMail API create and send draft with simple upload attachment example