54 lines
1.1 KiB
Go
Raw Normal View History

2022-05-20 00:28:02 +09:00
package main
import (
2022-06-09 01:19:25 +09:00
"io"
"log"
2022-05-20 00:28:02 +09:00
"net/http"
2022-08-05 23:10:04 +09:00
"github.com/syumai/tinyutil/httputil"
2022-05-20 00:28:02 +09:00
"github.com/syumai/workers"
)
const (
userName = "user"
userPassword = "password"
)
func authenticate(req *http.Request) bool {
username, password, ok := req.BasicAuth()
return ok && username == userName && password == userPassword
}
2022-06-09 01:19:25 +09:00
func handleError(w http.ResponseWriter, status int, msg string) {
w.WriteHeader(status)
w.Write([]byte(msg + "\n"))
}
2022-05-20 00:28:02 +09:00
func handleRequest(w http.ResponseWriter, req *http.Request) {
if !authenticate(req) {
w.Header().Add("WWW-Authenticate", `Basic realm="login is required"`)
2022-06-09 01:19:25 +09:00
handleError(w, http.StatusUnauthorized, "Unauthorized")
return
}
u := *req.URL
u.Scheme = "https"
u.Host = "syum.ai"
2022-08-05 23:10:04 +09:00
resp, err := httputil.Get(u.String())
2022-06-09 01:19:25 +09:00
if err != nil {
handleError(w, http.StatusInternalServerError, "Internal Error")
log.Printf("failed to execute proxy request: %v\n", err)
2022-05-20 00:28:02 +09:00
return
}
2022-06-09 01:33:04 +09:00
for k, values := range resp.Header {
for _, v := range values {
w.Header().Add(k, v)
}
}
2022-06-09 01:19:25 +09:00
defer resp.Body.Close()
io.Copy(w, resp.Body)
2022-05-20 00:28:02 +09:00
}
func main() {
workers.Serve(http.HandlerFunc(handleRequest))
}