The go language implementation handles form input

  • 2020-05-27 05:55:36
  • OfStack

login.html


<html>
<head><title></title></head>
<body>
    <form action="http://localhost:9090/login" method="post">
        User name: <input type="text" name="username">
        The secret   Code: <input type="text" name="password">
        <input type="submit" value=" The login ">
    </form>
</body>
</html>

main.go


package main
import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strings"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
    // parsing url Passed parameter
    r.ParseForm()
    // Print the information on the server side
    fmt.Println(r.Form)
    fmt.Println("path", r.URL.Path)
    fmt.Println("Scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        // join() Method is used to put all the elements in an array 1 String.
        // The element is separated by the specified delimiter
        fmt.Println("val:", strings.Join(v, ""))
    }
    // Output to the client
    fmt.Fprintf(w, "hello astaxie!")
}
func login(w http.ResponseWriter, r *http.Request) {
    fmt.Println("method:", r.Method)
    if r.Method == "GET" {
        t, _ := template.ParseFiles("login.html")
        // Execute parse template
        // func (t *Template) Execute(wr io.Writer, data interface{}) error {
        t.Execute(w, nil)
    } else {
        r.ParseForm()
        fmt.Println("username:", r.Form["username"])
        fmt.Println("password:", r.Form["password"])
    }
}
func main() {
    // Set access route
    http.HandleFunc("/", sayHelloName)
    http.HandleFunc("/login", login)
    // Set the listening port
    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Fatal("ListenAndserve:", err)
    }
}

That's all for this article, I hope you enjoy it.


Related articles: