~blowry/sourcehut-vanity

ref: 924adc0e863c9752f9eeb96e6c7bc407d9e672cb sourcehut-vanity/vanityserver/vanityserver.go -rw-r--r-- 2.0 KiB
924adc0eBenjamin Lowry Use correct import host for submodules 1 year, 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// VanityServer implements an HTTP.Handler that redirects HTTP requests to projects hosted on sourcehut.
// Example usage:
//
//    import (
//        "net/http"
//        "ben.gmbh/sourcehut-vanity/vanityserver"
//    )
//    func main() {
//        http.ListenAndServe(port, vanityserver.VanityServer{Username: "blowry"})
//    }
//
// SPDX-License-Identifier: GPL-3.0-or-later
package vanityserver

import (
    "fmt"
    "strings"
    "net/http"
    "html/template"
)

type VanityServer struct {
    Username string
}

type templatedata struct {
    User string
    ImportHost string
    ProjectName string
    Redir string
}

const page = `<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="go-import" content="{{.ImportHost}} git https://git.sr.ht/~{{.User}}/{{.ProjectName}}">
<meta name="go-source" content="{{.ImportHost}} https://git.sr.ht/~{{.User}}/{{.ProjectName}} https://git.sr.ht/~{{.User}}/{{.ProjectName}}/tree/master{/dir} https://git.sr.ht/~{{.User}}/{{.ProjectName}}/tree/master{/dir}/{file}#L{line}">
<meta http-equiv="refresh" content="0; url={{.Redir}}">
</head>
<body>
Nothing to see here; <a href="{{.Redir}}">move along</a>.
</body>
</html>`

func (server VanityServer) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.New("page").Parse(page))
    fmt.Println("Hit: " + r.URL.Path)
    path := strings.Split(r.URL.Path, "/")
    projectname := path[1]
    baseurl := "https://git.sr.ht/~" + server.Username + "/" + projectname
    var destination string
    r.ParseForm()

    if (len(path) > 2 && path[2] != "") {
        destination = baseurl + "/tree/master/" + strings.Replace(r.URL.Path, "/" + path[1] + "/", "", 1)
    } else {
        destination = baseurl
    }
    if (r.Form.Get("go-get") == "1") { // go-get(1)
        tmpl.Execute(rw, templatedata{User: server.Username, ImportHost: r.Host + "/" + projectname, ProjectName: projectname, Redir: destination})
    } else { // Standard browser
        http.Redirect(rw, r, destination, 302)
    }
    return
}