handleFunc和handle

一、handle案例

1、main.go如下,http访问:127.0.0.1:9990/static/mytest.txt

package main

import (
	"net/http"
)

func main(){

	addr :=":9990"
        //www目录和main文件在同一级,查找www目录下的static文件下的mytest.txt文件
	http.Handle("/static/",http.FileServer(http.Dir("./www")))

	http.ListenAndServe(addr,nil)
}

2、handle接口如下:

func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }

第二个参数是Handler这个接口, 这个接口有一个ServeHTTP()的方法

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

所以这个方法使用的时候需要自己去定义struct实现这个Handler接口。  

package main
 
import (
	"net/http"
	"log"
)
 
type httpServer struct {
}
 
func (server httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(r.URL.Path))
}
 
func main() {
	var server httpServer
	http.Handle("/", server)
	log.Fatal(http.ListenAndServe("localhost:9000", nil))
}
 
ServeHTTP(w http.ResponseWriter, r *http.Request)返回结果方式有:
第一种:w.Write([]byte(r.URL.Path))
func (server httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(r.URL.Path))
}

第二种:fmt.Fprintln

func (server httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "你好世界!!!")

}

二、handlefunc案例

package main

import (
	"net/http"
	"log"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(r.URL.Path))
	})
	log.Fatal(http.ListenAndServe("localhost:9000", nil))
}

r *http.Request返回值分析

r.Method    //返回请求方法
r.URL        //返回请求url
r.Proto      //返回请求协议

请求:http://127.0.0.1:9000/?a=5&b=6
r.ParseForm //解析
r.Form //返回请求的数据a,b

等价于r.FormValue

三、http上传文件

1、上传文件

http.HandleFunc("/form-data/", func(w http.ResponseWriter, r *http.Request) {
          r.ParseMultipartForm(10*1024*1024)
          fmt.Println(r.MultipartForm.File)
          for k,fileHeaders := range r.MultipartForm.File {
              fmt.Println("file",k)
              for idx,fileHeader :=range fileHeaders {
              fmt.Printtln(idx,fileHeader.Filename,fileHeader.Header,fileHeader.Size)
                if file,err :=fileHeader.Open();err ==nil{
                   defer file.Close()
                   io.Copy(os.Stdout,file)
                   fmt.Println()
           }
        }
}

}

 2、输出文件内容

http.HandleFunc("/form-data/", func(w http.ResponseWriter, r *http.Request) {
	f,fh,_ :=r.FormFile("a")
	fmt.Println(fh.Filename,fh.Header,fh.Size)
	io.Copy(os.Stdout,f)
	fmt.Println()

	f,fh,_ =r.FormFile("a")
	fmt.Println(fh.Filename,fh.Header,fh.Size)
	io.Copy(os.Stdout,f)
	fmt.Println()
}

 四、重定向跳转URL

func main() {

	http.HandleFunc("/redirect/", func(w http.ResponseWriter, r *http.Request) {
		//重定向跳转到 /home/
		http.Redirect(w, r, "/home/", http.StatusFound)

	})

	http.HandleFunc("/home/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "home")

	})

	log.Fatal(http.ListenAndServe("localhost:9099", nil))
}

 五、客户端访问请求

例子1、书写服务端

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(r.URL.Path))
		fmt.Println(r.Method)    //返回请求方法
		fmt.Println(r.URL)        //返回请求url
		fmt.Println(r.Proto)      //返回请求协议<br><br>请求:http://127.0.0.1:9000/?a=5&b=6<br>r.ParseForm
		fmt.Fprintln(w,time.Now())
	})
	log.Fatal(http.ListenAndServe("localhost:9000", nil))
}

书写客户端

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main(){
	url :="http://127.0.0.1:9000/"
	resp,err :=http.Get(url)
	if err !=nil{
		log.Fatal(err.Error())
	}

	fmt.Println(resp.Proto)
	fmt.Println(resp.StatusCode)
	fmt.Println(resp.Header)

	io.Copy(os.Stdout,resp.Body)

}

 例子2、书写服务端

package main

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

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(r.URL.Path))

		fmt.Fprintln(w,time.Now())
		r.ParseForm()

		//接收来自客户端的请求
		fmt.Println(r.Form.Get("a"))
		fmt.Println(r.Form.Get("b"))
	})
	log.Fatal(http.ListenAndServe("localhost:9000", nil))
}

书写客户端,通过get类型向http://127.0.0.1:9000/?a=1&b=2"提交数据

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main(){
	url :="http://127.0.0.1:9000/?a=1&b=2"
	resp,err :=http.Get(url)
	if err !=nil{
		log.Fatal(err.Error())
	}

	fmt.Println(resp.Proto)
	fmt.Println(resp.StatusCode)
	fmt.Println(resp.Header)

	io.Copy(os.Stdout,resp.Body)

}

六、post提交数据 

提交数据格式   http://127.0.0.1:9000/form?name=小明

1、书写服务端

package main

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

func main() {
	http.HandleFunc("/form", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		
		fmt.Println(r.PostFormValue("name"))
		fmt.Println(r.PostFormValue("sex"))
		//返回一个map
		fmt.Println(r.Form)
	})
	log.Fatal(http.ListenAndServe("localhost:9000", nil))
}

2、客户端发送请求,postman测试

原文地址:https://www.cnblogs.com/wuchangblog/p/14920987.html