《Go Web编程实战派--从入门到精通》的随笔笔记
第二章 Go Web 开发基础
2.1第一个Go Web 程序
package mainimport ("fmt""net/http"
)func hello(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Hello World")
}
func main() {server := &http.Server{Addr: "0.0.0.0:80",}http.HandleFunc("/", hello)server.ListenAndServe()
}
访问浏览器的127.0.0.1:80
接下来我们通过Go语言来创建GET、POST、PUT、DELETE这4种类型的窖户端请求,来初步了解害户端的创建方法.
创建GET请求
package mainimport ("fmt""io/ioutil""net/http"
)func main() {resp, err := http.Get("https://www.baidu.com")if err != nil {fmt.Println("err", err)}closer := resp.Bodybytes, err := ioutil.ReadAll(closer)fmt.Println(string(bytes))
}
通过上面的代码可以获得百度首页的HTML文档
创建POST请求
package mainimport ("bytes""fmt""io/ioutil""net/http"
)func main() {url := "https://www.shirdon.com/comment/add"body := "{\"userId\":1,\"articleId\":1,\"comment\":\"这是一条评论\"}"response, err := http.Post(url, "application/x-www-form-urlencoded", bytes.NewBufferString(body))if err != nil {fmt.Println("err", err)}b, err := ioutil.ReadAll(response.Body)fmt.Println(string(b))
}