golang之web编程入门

来源:互联网 发布:数据库 pdf 编辑:程序博客网 时间:2024/04/27 19:50

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

package mainimport ("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 errorhttp.HandleFunc("/", sayhelloName)      //设置访问的路由http.HandleFunc("/login", login)        //设置访问的路由err = http.ListenAndServe(":9090", nil) //设置监听的端口if err != nil {log.Fatal("ListenAndServe: ", err)}}

go编程之路由器函数:

package mainimport ("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)}



1 0
原创粉丝点击