在下面的程序中,我有两个路由器。一个在公共接入点工作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)
// <-interrupt // just a cool way to close the program, uncomment if you need it
}
func GetDataAndSolve() http.Handler {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/tasks/str", func(rw http.ResponseWriter, r *http.Request) {
// receiving data for processing...
taskCtx := context.WithValue(r.Context(), "str", "strVar") // the value is being
postReq, err := http.NewRequestWithContext( // stored to context
taskCtx, // context is being given to request
"POST",
"http://localhost:8000/tasks/solution",
bytes.NewBuffer([]byte("something")),
)
postReq.Header.Set("Content-Type", "application/json") // specifying for endpoint
if err != nil { // what we are sending
return
}
}
冉冉说
素胚勾勒不出你
随时随地看视频慕课网APP
相关分类