wttr.in/cmd/srv.go

70 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
"context"
"log"
"net"
"net/http"
"time"
2020-05-30 18:14:17 +02:00
lru "github.com/hashicorp/golang-lru"
)
2020-05-30 18:14:17 +02:00
const uplinkSrvAddr = "127.0.0.1:9002"
const uplinkTimeout = 30
const prefetchInterval = 300
const lruCacheSize = 12800
var lruCache *lru.Cache
2020-05-30 18:14:17 +02: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 18:14:17 +02:00
lruCache, err = lru.New(lruCacheSize)
if err != nil {
panic(err)
}
dialer := &net.Dialer{
2020-05-30 18:14:17 +02:00
Timeout: uplinkTimeout * time.Second,
KeepAlive: uplinkTimeout * time.Second,
DualStack: true,
}
2020-05-30 18:14:17 +02:00
http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
return dialer.DialContext(ctx, network, uplinkSrvAddr)
}
2020-05-30 18:14:17 +02:00
initPeakHandling()
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
2020-05-30 18:14:17 +02: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)
})
2020-05-30 18:14:17 +02:00
log.Fatal(http.ListenAndServe(":8082", nil))
}