在下面的程序中我有两个路由器。其中一个在公共接入点上工作localhost:3000并充当公共接入点。它还可以将带有数据的请求发送到localhost:8000正在处理数据的另一个本地地址。第二个路由器正在工作localhost:8000并处理第一个路由器的处理请求。
第一路由器向第二使用功能发送带有上下文的请求http.NewRequestWithContext()。该值将被添加到上下文中,并且上下文将被添加到请求中。当请求到达第二个路由器时,它没有之前添加的值。
有些东西(例如错误处理)没有被编写,以便不在这里发布代码墙。
package main
import (
"bytes"
"context"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func main() {
go func() {
err := http.ListenAndServe(
"localhost:3000",
GetDataAndSolve(),
)
if err != nil {
panic(err)
}
}()
go func() {
err := http.ListenAndServe( // in GetDataAndSolve() we send requests
"localhost:8000", // with data for processing
InternalService(),
)
if err != nil {
panic(err)
}
}()
// interrupt := make(chan os.Signal, 1)
// signal.Notify(interrupt, syscall.SIGTERM, syscall.SIGINT) …Run Code Online (Sandbox Code Playgroud)