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
+23.1k Golang : Calculate time different
+7.4k Golang : Of hash table and hash map
+5k Javascript : How to get width and height of a div?
+8.2k Golang : Randomize letters from a string example
+12.8k Golang : Pass database connection to function called from another package and HTTP Handler
+37.8k Golang : Comparing date or timestamp
+5.4k PHP : Hide PHP version information from curl
+10k Golang : Translate language with language package example
+18.1k Golang : Get all upper case or lower case characters from string example
+10.4k Golang : Detect number of faces or vehicles in a photo
+18.9k Unmarshal/Load CSV record into struct in Go
+4.9k JavaScript: Add marker function on Google Map