45 lines
853 B
Go
Raw Normal View History

2023-04-20 08:13:19 +09:00
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"time"
"github.com/syumai/workers"
"github.com/syumai/workers/cloudflare"
"github.com/syumai/workers/cloudflare/fetch"
)
func handler(w http.ResponseWriter, req *http.Request) {
2024-04-17 00:56:47 +09:00
cloudflare.PassThroughOnException()
2023-04-20 08:13:19 +09:00
// logging after responding
2024-04-17 00:56:47 +09:00
cloudflare.WaitUntil(func() {
2023-04-20 08:13:19 +09:00
for i := 0; i < 5; i++ {
time.Sleep(time.Second)
}
fmt.Println("5-second task completed")
})
// panic if x-error header has provided
if req.Header.Get("x-error") != "" {
panic("error")
}
// responds with origin server
fc := fetch.NewClient()
proxy := httputil.ReverseProxy{
2023-05-28 13:06:16 +09:00
Transport: fc.HTTPClient(fetch.RedirectModeManual).Transport,
2023-04-20 08:13:19 +09:00
Director: func(r *http.Request) {
r.URL = req.URL
},
}
proxy.ServeHTTP(w, req)
}
func main() {
workers.Serve(http.HandlerFunc(handler))
}