加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang之web编程入门

发布时间:2020-12-16 18:37:33 所属栏目:大数据 来源:网络整理
导读:golang之web编程入门示例,聊聊数行,简单理解。 package mainimport ("fmt""html/template""log""net/http""strings")func sayhelloName(w http.ResponseWriter,r *http.Request) {r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request b

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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读