一、golang http server
https://golangdocs.com/http-server-in-golang
python中创建一个web服务器有python -m http.server
golang中创建一个web服务器很简单。
golang中有一个叫做http的包,已经封装好了,我们接下来简单介绍下net/http包的使用。使用go 的net/http包创建一个web服务器。性能怎么样呢?或者说golang的http是如何处理并发的?
导入依赖
import “net/http”
创建一个基础的http服务器
访问一个地址,映射到一个处理函数。
package main
import (
"fmt"
"net/http"
)
func main() {
// handle route using handler function
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to new server!")
})
// listen to port
http.ListenAndServe(":5050", nil)
}
处理多个路由
其实就是多加几个HandleFunc
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to new server!")
})
http.HandleFunc("/students", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome Students!")
})
http.HandleFunc("/teachers", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome teachers!")
})
http.ListenAndServe(":5050", nil)
}
NewServeMux
NewServeMux是什么
NewServeMux vs DefaultServeMux
package main
import (
"io"
"net/http"
)
func welcome(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Welcome!")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/welcome", welcome)
http.ListenAndServe(":5050", mux)
}
二、golang http client
如果不会写也没有关系,使用postman generate golang code,快速生成代码。
http.Get
// Get is a wrapper around DefaultClient.Get.
func Get(url string) (resp *Response, err error) {
return DefaultClient.Get(url)
}
golang tips
1、go 返回值可以返回多个值,需要使用小括号括起来。
2、go里面*是什么意思?