Golang学习笔记-简单的Go Web程序

Go Web程序

package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
)

func http_server_say_hello(w http.ResponseWriter, r *http.Request) {
    
    
	_ = r.ParseForm() 	//解析参数
	fmt.Println(r.Form)
	fmt.Println("Path: ", r.URL.Path)
	fmt.Println("Host: ", r.Host)

	for k,v:=range r.Form{
    
    
		fmt.Println("key:",k)
		fmt.Println("val:", strings.Join(v,""))
	}
	//写入到w的是输出到客户端的内容
	_,_ = fmt.Fprintf(w,"Hello Web, %s!", r.Form.Get("name"))


}

func main(){
    
    
	fmt.Printf("Running in main ...")

	http.HandleFunc("/",http_server_say_hello)	//设置访问的路由
	err := http.ListenAndServe(":8080",nil)	//设置监听的端口
	if err != nil{
    
    
		log.Fatal("ListenAndServe:",err)
	}
	//在浏览器中打开:http://localhost:8080/hello?name=lyk
}

登录功能

//login.tpl文件
<html>
<head>
    <title>控制台登录</title>
</head>
<body>
<form action="/login" method="post">
    用户名:<input type="text" name="username"/>
    密码:<input type="text" name="password"/>
    <input type="submit" value="登录"/>
</form>
</body>
</html>
package main

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

func login(w http.ResponseWriter, r *http.Request){
    
    
	fmt.Println("method:", r.Method)
	if r.Method == "GET"{
    
    
		t,_ := template.ParseFiles("login.tpl")
		log.Println(t.Execute(w, nil))
	}else {
    
    
		_ = r.ParseForm()
		fmt.Println("username:",r.Form["username"])
		fmt.Println("password:",r.Form["password"])
		if pwd := r.Form.Get("password");pwd == "123456"{
    
    
			fmt.Fprintf(w,"欢迎登录, Hello %s!",r.Form.Get("username"))
		}else {
    
    
			fmt.Fprintf(w, "密码错误,请重新输入!")
		}

	}
}

func login_function_caller()  {
    
    
	http.HandleFunc("/login", login)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
    
    
		log.Fatal("ListenAndServe:",err)
	}
}

func main(){
    
    
	fmt.Printf("Running in main ...")
	login_function_caller()
}

结果

登录界面
登录成功

猜你喜欢

转载自blog.csdn.net/qq_40904479/article/details/106505548