一、从Http开始
1.简单的http服务器
/**
一种写法
**/
package main
import (
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter ,req *http.Request){
log.Println(req.Method +":"+req.RequestURI)
fmt.Fprintf(w,"hello %s" ,req.URL.Path)
}
func main() {
http.HandleFunc("/",index)
//err := http.ListenAndServe("127.0.0.1:8080",nil) 也可以
err := http.ListenAndServe("0.0.0.0:8080",nil)
if err!=nil {
log.Fatalln(err.Error())
}
}
/**
另一种写法
**/
package main
import (
"fmt"
"log"
"net/http"
)
type httpHandle struct{
}
func (http httpHandle) ServeHTTP(w http.ResponseWriter ,req *http.Request){
log.Println(req.Method +":"+req.RequestURI)
fmt.Fprintf(w,"hello %s %s" ,req.URL.Path,req.URL.Path[1:])
}
func main() {
handle := httpHandle{}
err := http.ListenAndServe("127.0.0.1:8080",handle)
if err != nil {
log.Fatalln(err.Error())
}
}
2.简单的http的客户端
package main
import (
"fmt"
"net/http"
)
func main() {
client := http.Client{}
rsp,err:=client.Get("<http://localhost:8080/hello>")
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Printf("%s",rsp.Status)
}