Simple example of web input/output

Can someone show me a simple working example of how to get simple user input on the web and display it back, using http/net?
For example, do the following only on the web:
fmt.Print("Enter text: ")
var input string
fmt.Scanln(&input)
fmt.Print(input)

Hello.
I made a simple example of login. He, if you be logged show the values.

Main.go:

package main

import (
	"html/template"
	"log"
	"net/http"
)

//Login Struct
type Login struct {
	Name string
	Pass string
}

//Login Example - Hello Guys - By Vitor Brunoo

var tpl *template.Template

func login(w http.ResponseWriter, req *http.Request) {

	if req.Method == http.MethodPost {

		login := req.FormValue("login")
		pass := req.FormValue("pass")

		if login == "admin" && pass == "admin" {
			var l Login

			l.Name = req.FormValue("login")
			l.Pass = req.FormValue("pass")

			err := tpl.ExecuteTemplate(w, "login.gohtml", l)
			if err != nil {
				http.Error(w, err.Error(), 500)
				log.Fatalln(err)
			}
			return
		}

	}
	err := tpl.ExecuteTemplate(w, "login.gohtml", nil)
	if err != nil {
		http.Error(w, err.Error(), 500)
		log.Fatalln(err)
	}

}

func init() {
	tpl = template.Must(template.ParseFiles("login.gohtml"))
}

func main() {
	http.HandleFunc("/", login)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Login.gohtml

 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8"/>
     <title>Login Exemple - Using template</title>
 </head>
 <body>
     {{if .}}
     <p> Hello {{.Name}} </p>
     <script>
        alert("Login done successfully");
     </script>
     {{end}}
     {{if not .}}
     <form method="POST">
        <input type='text' name='login'>
        <input type='password' name='pass'>
        <input type='submit' value='GO' >
     </form>
    {{end}}
</body>
 </html>

Thank you very much!
It’s rare that I see an example that actually works.
I copied it into my google cloud console, deployed it and it worked!

1 Like

I really appreciate you sending a working example! I know it’s a lot to ask
but could you possibly reply with the same code with comments describing
with the different portions do?

Do you want to talk about skype, whatsapp or something to get your questions answered? More eazy

That would be good; I work M-F, 8 to 5 (sometimes get off earlier than 5).
What times might work for you?

What’s your timezone? I’m in -3UTC Work 8 to 6

I’m eastern, so it’s almost 5pm now

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.