violet/servers/http.go

74 lines
1.9 KiB
Go
Raw Normal View History

2023-04-21 03:21:46 +01:00
package servers
import (
"fmt"
"github.com/MrMelon54/violet/utils"
"github.com/julienschmidt/httprouter"
"net/http"
2023-04-21 15:49:01 +01:00
"net/url"
"time"
2023-04-21 03:21:46 +01:00
)
2023-04-21 15:49:01 +01:00
// NewHttpServer creates and runs a http server containing the public http
// endpoints for the reverse proxy.
//
// `/.well-known/acme-challenge/{token}` is used for outputting answers for
2023-06-03 19:33:06 +01:00
// acme challenges, this is used for Let's Encrypt HTTP verification.
2023-04-22 18:11:21 +01:00
func NewHttpServer(conf *Conf) *http.Server {
2023-04-21 03:21:46 +01:00
r := httprouter.New()
2023-04-21 15:49:01 +01:00
var secureExtend string
2023-04-22 18:11:21 +01:00
_, httpsPort, ok := utils.SplitDomainPort(conf.HttpsListen, 443)
if !ok {
httpsPort = 443
}
2023-04-21 15:49:01 +01:00
if httpsPort != 443 {
secureExtend = fmt.Sprintf(":%d", httpsPort)
}
// Endpoint for acme challenge outputs
2023-06-04 22:28:48 +01:00
r.GET("/.well-known/acme-challenge/:key", func(rw http.ResponseWriter, req *http.Request, params httprouter.Params) {
h := utils.GetDomainWithoutPort(req.Host)
2023-04-21 15:49:01 +01:00
2023-06-04 22:28:48 +01:00
// check if the host is valid
if !conf.Domains.IsValid(req.Host) {
utils.RespondVioletError(rw, http.StatusBadRequest, "Invalid host")
return
}
2023-04-21 16:40:26 +01:00
2023-06-04 22:28:48 +01:00
// check if the key is valid
value := conf.Acme.Get(h, params.ByName("key"))
if value == "" {
rw.WriteHeader(http.StatusNotFound)
return
2023-04-21 03:21:46 +01:00
}
2023-06-04 22:28:48 +01:00
// output response
rw.WriteHeader(http.StatusOK)
_, _ = rw.Write([]byte(value))
2023-04-21 03:21:46 +01:00
})
2023-04-21 15:49:01 +01:00
// All other paths lead here and are forwarded to HTTPS
r.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
2023-06-04 22:28:48 +01:00
h := utils.GetDomainWithoutPort(req.Host)
u := &url.URL{
Scheme: "https",
Host: h + secureExtend,
Path: req.URL.Path,
RawPath: req.URL.RawPath,
RawQuery: req.URL.RawQuery,
2023-04-21 15:49:01 +01:00
}
2023-06-04 22:28:48 +01:00
utils.FastRedirect(rw, req, u.String(), http.StatusPermanentRedirect)
2023-04-21 15:49:01 +01:00
})
// Create and run http server
2023-06-04 22:28:48 +01:00
return &http.Server{
2023-04-22 18:11:21 +01:00
Addr: conf.HttpListen,
2023-04-21 15:49:01 +01:00
Handler: r,
ReadTimeout: time.Minute,
ReadHeaderTimeout: time.Minute,
WriteTimeout: time.Minute,
IdleTimeout: time.Minute,
MaxHeaderBytes: 2500,
}
2023-04-21 03:21:46 +01:00
}