2023-08-19 17:44:34 +03:00
|
|
|
// Package main ...
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
2023-08-19 18:15:42 +03:00
|
|
|
"mime"
|
2023-08-19 17:44:34 +03:00
|
|
|
"net/http"
|
|
|
|
"os"
|
2023-08-19 18:15:42 +03:00
|
|
|
"path"
|
2023-08-19 17:44:34 +03:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"git.mills.io/prologic/pages-server/gitea"
|
|
|
|
)
|
|
|
|
|
|
|
|
// GiteaHandler ...
|
|
|
|
type GiteaHandler struct {
|
|
|
|
Client *gitea.Client
|
|
|
|
|
2023-11-13 09:25:14 +03:00
|
|
|
Server string
|
|
|
|
Domain string
|
|
|
|
Token string
|
|
|
|
DomainsMap map[string]string
|
2023-08-19 17:44:34 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Init ...
|
|
|
|
func (h *GiteaHandler) Init() error {
|
|
|
|
var err error
|
|
|
|
h.Client, err = gitea.NewClient(h.Server, h.Token, h.Domain)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP ...
|
|
|
|
func (h *GiteaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2023-11-13 09:25:14 +03:00
|
|
|
// use domain from the map
|
|
|
|
if mapped, ok := h.DomainsMap[r.Host]; ok {
|
|
|
|
r.Host = mapped
|
|
|
|
}
|
2023-08-19 17:44:34 +03:00
|
|
|
// remove the domain if it's set (works fine if it's empty)
|
|
|
|
user := strings.TrimRight(strings.TrimSuffix(r.Host, h.Domain), ".")
|
|
|
|
log.Printf("user: %s", user)
|
|
|
|
|
|
|
|
f, err := h.Client.Open(user, r.URL.Path)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, fmt.Sprintf("error resource not found: %s", err.Error()), http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-08-19 18:15:42 +03:00
|
|
|
extension := path.Ext(r.URL.Path)
|
|
|
|
mimeType := mime.TypeByExtension(extension)
|
|
|
|
w.Header().Add("content-type", mimeType)
|
|
|
|
|
2023-08-19 17:44:34 +03:00
|
|
|
if _, err := io.Copy(w, f); err != nil {
|
|
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2023-11-13 09:25:14 +03:00
|
|
|
domainsMap := map[string]string{}
|
|
|
|
items := strings.Split(os.Getenv("DOMAINS_MAP"), ";")
|
|
|
|
for _, item := range items {
|
|
|
|
itemParts := strings.Split(item, ":")
|
|
|
|
if len(itemParts) == 2 {
|
|
|
|
domainsMap[itemParts[0]] = itemParts[1]
|
|
|
|
}
|
|
|
|
}
|
2023-08-19 17:44:34 +03:00
|
|
|
handler := &GiteaHandler{
|
2023-11-13 09:25:14 +03:00
|
|
|
Domain: os.Getenv("DOMAIN"),
|
|
|
|
Server: os.Getenv("GITEA_URL"),
|
|
|
|
Token: os.Getenv("GITEA_TOKEN"),
|
|
|
|
DomainsMap: domainsMap,
|
2023-08-19 17:44:34 +03:00
|
|
|
}
|
|
|
|
if err := handler.Init(); err != nil {
|
|
|
|
log.Fatalf("error initializing handler: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := http.ListenAndServe("0.0.0.0:8000", handler); err != nil {
|
|
|
|
log.Fatalf("error running server: %s", err)
|
|
|
|
}
|
|
|
|
}
|