golang之web编程入门

戈巴英
2023-12-01

golang之web编程入门示例,聊聊数行,简单理解。

package main

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

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request body)
	//注意:如果没有调用ParseForm方法,下面无法获取表单的数据
	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)
		fmt.Println("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello wow!") //这个写入到w的是输出到客户端的
}
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		t, _ := template.ParseFiles("login.html")
		t.Execute(w, nil)
	} else {
		r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request body)
		//请求的是登陆数据,那么执行登陆的逻辑判断
		fmt.Println("username:", r.Form["username"])
		fmt.Println("password:", r.Form["password"])
		fmt.Fprintf(w, "Hello %s!", r.Form["username"]) //这个写入到w的是输出到客户端的
	}
}
func main() {
	var err error
	http.HandleFunc("/", sayhelloName)      //设置访问的路由
	http.HandleFunc("/login", login)        //设置访问的路由
	err = http.ListenAndServe(":9090", nil) //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

go编程之路由器函数:

package main

import (
	"fmt"
	"net/http"
)

type MyMux struct {
}

//设置路由器
func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		sayhelloName(w, r)
		return
	}
	http.NotFound(w, r)
	return
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello gerryyang, version 2!\n")
}

func main() {
	mux := &MyMux{}
	http.ListenAndServe(":9090", mux)
}



 类似资料: