获得徽章 0
Go 管道的用法
一个简单的使用方法如下
func boring(msg string, c chan string) {
for i := 0; ; i++ {
// 发送信息给管道 (hannel / chan)
// 同时,它也在等待管道的消费者消费完成
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}
func main() {
c := make(chan string) // 初始化一个管道
go boring("boring!", c)
for i := 0; i < 5; i++ {
// `<-c` 等待 `boring` 方法给它发送值,如果一直没有收到,那么会被阻塞在这一步
fmt.Printf("You say: %q\n", <-c)
}
fmt.Println("You're boring. I'm leaving")
} #青训营 x 字节后端训练营#
一个简单的使用方法如下
func boring(msg string, c chan string) {
for i := 0; ; i++ {
// 发送信息给管道 (hannel / chan)
// 同时,它也在等待管道的消费者消费完成
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}
func main() {
c := make(chan string) // 初始化一个管道
go boring("boring!", c)
for i := 0; i < 5; i++ {
// `<-c` 等待 `boring` 方法给它发送值,如果一直没有收到,那么会被阻塞在这一步
fmt.Printf("You say: %q\n", <-c)
}
fmt.Println("You're boring. I'm leaving")
} #青训营 x 字节后端训练营#
展开
评论
点赞
#青训营 x 字节后端训练营# func main() {
fmt.Println("Starting the server ...")
helloHandler := handler.NewHelloHandler()
http.Handle("/hello", helloHandler)
// 创建服务器,ListenAndServe若服务器宕机,会返回异常
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
package handler
import (
"bytes"
"fmt"
"net/http"
)
type HelloHandler struct {
m map[string]string
}
func NewHelloHandler() *HelloHandler {
return &HelloHandler{m: make(map[string]string)}
}
// 回声服务器,返回接受的body,
// 实现Handler接口
func (h HelloHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
b := request.Body
buf := bytes.Buffer{}
buf.ReadFrom(b)
b.Close()
s := buf.String()
fmt.Printf("get request: \nMethod:%s\n%s\n%s\n", request.Method, request.RequestURI, s)
writer.Write(buf.Bytes())
}
路由拦截下来后才能得知请求方法
我们需要手动处理io,
读取io后body需要手动映射到实例中,
链接上的参数需要我们手动使用正则取下来
路由分组问题,比如 /test/t /test/t2
返回值需要我们手动处理为[]byte类型
fmt.Println("Starting the server ...")
helloHandler := handler.NewHelloHandler()
http.Handle("/hello", helloHandler)
// 创建服务器,ListenAndServe若服务器宕机,会返回异常
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
package handler
import (
"bytes"
"fmt"
"net/http"
)
type HelloHandler struct {
m map[string]string
}
func NewHelloHandler() *HelloHandler {
return &HelloHandler{m: make(map[string]string)}
}
// 回声服务器,返回接受的body,
// 实现Handler接口
func (h HelloHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
b := request.Body
buf := bytes.Buffer{}
buf.ReadFrom(b)
b.Close()
s := buf.String()
fmt.Printf("get request: \nMethod:%s\n%s\n%s\n", request.Method, request.RequestURI, s)
writer.Write(buf.Bytes())
}
路由拦截下来后才能得知请求方法
我们需要手动处理io,
读取io后body需要手动映射到实例中,
链接上的参数需要我们手动使用正则取下来
路由分组问题,比如 /test/t /test/t2
返回值需要我们手动处理为[]byte类型
展开
评论
点赞