91 lines
1.8 KiB
Go
91 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
c, err := NewConfig()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
s := &http.Server{
|
|
Addr: fmt.Sprintf(":%d", c.Port),
|
|
Handler: c,
|
|
}
|
|
foo := s.ListenAndServe
|
|
if c.Cert.CRT != "" {
|
|
foo = func() error {
|
|
return s.ListenAndServeTLS(c.Cert.CRT, c.Cert.Key)
|
|
}
|
|
}
|
|
log.Printf("listening on %v...", s.Addr)
|
|
if err := foo(); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func (c Config) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodOptions {
|
|
cors(w)
|
|
return
|
|
}
|
|
|
|
if r.URL.Scheme == "https" {
|
|
w.Header().Set("X-Forwarded-Proto", "https")
|
|
}
|
|
|
|
if c.handleAdmin(w, r) {
|
|
return
|
|
}
|
|
|
|
if !c.basicAuth(w, r) {
|
|
return
|
|
}
|
|
|
|
http.Error(w, "not yet", http.StatusNotImplemented)
|
|
}
|
|
|
|
func cors(w http.ResponseWriter) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Headers", "X-Auth-Token, content-type, Content-Type")
|
|
w.Header().Set("Content-Length", "0")
|
|
w.Header().Set("Content-Type", "text/plain")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, TRACE, PATCH, HEAD, DELETE")
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (c Config) endpoint(r *http.Request) string {
|
|
return strings.Split(r.Host, ".")[0]
|
|
}
|
|
|
|
func (c Config) handleAdmin(w http.ResponseWriter, r *http.Request) bool {
|
|
switch c.endpoint(r) {
|
|
case "_":
|
|
panic("not impl: list")
|
|
case "home":
|
|
panic("not impl: home")
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (c Config) basicAuth(w http.ResponseWriter, r *http.Request) bool {
|
|
basicAuth := c.Endpoints[c.endpoint(r)].BasicAuth
|
|
if noAuth := basicAuth == ""; noAuth {
|
|
return true
|
|
}
|
|
|
|
u, p, _ := r.BasicAuth()
|
|
if fmt.Sprintf("%s:%s", u, p) != basicAuth {
|
|
w.Header().Set("WWW-Authenticate", "Basic")
|
|
http.Error(w, "unexpected basic auth", http.StatusUnauthorized)
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|