Server
package main
import (
"net/http"
"os"
"io"
)
func main() {
http.HandleFunc("/",handle)
http.ListenAndServe("127.0.0.1:8005",nil)
}
func handle(w http.ResponseWriter,r *http.Request) {
url:=r.URL.String()
fp,err:=os.Open("/Users/zmx/go/180726/src/main"+url)
if err!=nil {
w.Write([]byte(err.Error()))
return
}
defer fp.Close()
buf:=make([]byte,4096)
for {
n,err:=fp.Read(buf)
if err==io.EOF {
break
}
w.Write(buf[:n])
}
}
Client
package main
import (
"net/http"
"fmt"
"io"
)
func main() {
resp,err:=http.Get("http://127.0.0.1:8005/index.go")
if err!=nil {
fmt.Print(err)
return
}
defer resp.Body.Close()
fmt.Println(resp.Status)
fmt.Println(resp.StatusCode)
fmt.Println(resp.Body)
fmt.Println(resp.Header)
buf:=make([]byte,4096)
for {
n,err:=resp.Body.Read(buf)
fmt.Print(string(buf[:n]))
if err!=nil {
if err==io.EOF {
break
} else {
fmt.Print(err)
}
}
}
}
有疑问加站长微信联系(非本文作者)