golang.org/x/build@v0.0.0-20240506185731-218518f32b70/cmd/coordinator/modproxy.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build linux || darwin 6 7 package main 8 9 import ( 10 "io" 11 "log" 12 "net/http" 13 ) 14 15 func listenAndServeInternalModuleProxy() { 16 err := http.ListenAndServe(":8123", http.HandlerFunc(proxyModuleCache)) 17 log.Fatalf("error running internal module proxy: %v", err) 18 } 19 20 // proxyModuleCache proxies requests to https://proxy.golang.org/ 21 func proxyModuleCache(w http.ResponseWriter, r *http.Request) { 22 proxyURL(w, r, "https://proxy.golang.org") 23 } 24 25 func proxyURL(w http.ResponseWriter, r *http.Request, baseURL string) { 26 outReq, err := http.NewRequest("GET", baseURL+r.RequestURI, nil) 27 if err != nil { 28 http.Error(w, "invalid URL", http.StatusBadRequest) 29 return 30 } 31 outReq = outReq.WithContext(r.Context()) 32 outReq.Header = r.Header.Clone() 33 res, err := http.DefaultClient.Do(outReq) 34 if err != nil { 35 http.Error(w, err.Error(), http.StatusInternalServerError) 36 return 37 } 38 defer res.Body.Close() 39 for k, vv := range res.Header { 40 for _, v := range vv { 41 w.Header().Add(k, v) 42 } 43 } 44 if res.StatusCode/100 != 2 && res.StatusCode != 410 { 45 log.Printf("modproxy: proxying HTTP %s response from backend for %s, %s %s", res.Status, r.RemoteAddr, r.Method, r.RequestURI) 46 } 47 48 w.WriteHeader(res.StatusCode) 49 io.Copy(w, res.Body) 50 }