← history for internal/handler/handle_raw.go
4e7342aeinternal/handler/handle_raw.go65 lines⬡ raw↓ download
 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
/**
 * AltGit - altgit
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Paolo Lulli <kevwe.com>
 * @copyright Paolo Lulli 2026
 */

package handler

import (
    "altgit/internal/config"
    "altgit/internal/gitrepo"
    "altgit/internal/rendering"
    "fmt"
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"
)

// HandleRaw GET /:repo/raw?path=<f>&hash=<h>[&dl=1]
func HandleRaw(cfg config.AltGitConfiguration) gin.HandlerFunc {
    return func(c *gin.Context) {
        _, rp, ok := rendering.ResolveRepo(cfg, c.Param("repo"))
        if !ok {
            return
        }
        path := c.Query("path")
        hash := c.Query("hash")
        if path == "" || hash == "" {
            c.String(http.StatusBadRequest, "missing path or hash")
            return
        }
        content, _, err := gitrepo.FileAtCommit(rp, hash, path)
        if err != nil {
            c.String(http.StatusNotFound, "file not found at that revision: %s", err.Error())
            return
        }

        ct := "text/plain; charset=utf-8"
        lower := strings.ToLower(path)
        switch {
        case strings.HasSuffix(lower, ".html") || strings.HasSuffix(lower, ".htm"):
            ct = "text/html; charset=utf-8"
        case strings.HasSuffix(lower, ".json"):
            ct = "application/json"
        case strings.HasSuffix(lower, ".xml"):
            ct = "application/xml"
        case strings.HasSuffix(lower, ".css"):
            ct = "text/css; charset=utf-8"
        case strings.HasSuffix(lower, ".js") || strings.HasSuffix(lower, ".ts"):
            ct = "text/javascript; charset=utf-8"
        }

        c.Header("Content-Type", ct)
        if c.Query("dl") == "1" {
            filename := path[strings.LastIndex(path, "/")+1:]
            c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
        }
        c.String(http.StatusOK, content)
    }
}