wttr.in/cmd/srv.go

94 lines
1.8 KiB
Go
Raw Normal View History

package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"time"
2020-05-30 16:14:17 +00:00
lru "github.com/hashicorp/golang-lru"
)
2020-05-30 16:14:17 +00:00
const uplinkSrvAddr = "127.0.0.1:9002"
const uplinkTimeout = 30
const prefetchInterval = 300
const lruCacheSize = 12800
// plainTextAgents contains signatures of the plain-text agents
var plainTextAgents = []string{
"curl",
"httpie",
"lwp-request",
"wget",
"python-httpx",
"python-requests",
"openbsd ftp",
"powershell",
"fetch",
"aiohttp",
"http_get",
2022-03-26 18:24:23 +00:00
"xh",
}
var lruCache *lru.Cache
2020-05-30 16:14:17 +00:00
type responseWithHeader struct {
InProgress bool // true if the request is being processed
Expires time.Time // expiration time of the cache entry
Body []byte
Header http.Header
StatusCode int // e.g. 200
}
func init() {
var err error
2020-05-30 16:14:17 +00:00
lruCache, err = lru.New(lruCacheSize)
if err != nil {
panic(err)
}
dialer := &net.Dialer{
2020-05-30 16:14:17 +00:00
Timeout: uplinkTimeout * time.Second,
KeepAlive: uplinkTimeout * time.Second,
DualStack: true,
}
2020-05-30 16:14:17 +00:00
http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
return dialer.DialContext(ctx, network, uplinkSrvAddr)
}
2020-05-30 16:14:17 +00:00
initPeakHandling()
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func main() {
2022-11-19 18:20:35 +00:00
logger := NewRequestLogger(
Conf.Logging.AccessLog,
time.Duration(Conf.Logging.Interval)*time.Second)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
2022-11-19 18:20:35 +00:00
if err := logger.Log(r); err != nil {
log.Println(err)
}
2020-05-30 16:14:17 +00:00
// printStat()
response := processRequest(r)
copyHeader(w.Header(), response.Header)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(response.StatusCode)
w.Write(response.Body)
})
2022-11-19 18:34:11 +00:00
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", Conf.Server.PortHTTP), nil))
}