• 
      
    Web Service
    1
    package main
    2
    3
    import (
    4
        "io"
    5
        "net/http"
    6
    )
    7
    8
    const (
    9
        REPO = "repo"       // repo where the file is located
    10
        ID = "id"           // a sha in Git, nodeid in Mercurial, etc.
    11
    )
    12
    13
    // Sends a response containing the file blob, if it exists
    14
    // Currently uses request params - to change to path params?
    15
    // i.e. /file/repo/id instead of
    16
    //      /file?repo=repo1&id=sha1sha
    17
    func GetFile(w http.ResponseWriter, r *http.Request) {
    18
        repoName := r.URL.Query().Get(REPO)
    19
        id := r.URL.Query().Get(ID)
    20
    21
        if len(repoName) != 0 && len(id) != 0 {
    22
            //GetRepository(repoName).GetFile(id)
    23
            repo := GetRepository(repoName)
    24
            w.Header().Set("Content-Type", "application/octet-stream")
    25
            w.Write(repo.GetFile(id))
    26
        }
    27
    }
    28
    29
    // Sends a true or false response depending on whether the file exists
    30
    // Currently uses request params - to change to path params?
    31
    // i.e. /file/repo/name/id instead of
    32
    //      /file?repo=repo1&id=sha1
    33
    func FileExists(w http.ResponseWriter, r *http.Request) {
    34
        repoName := r.URL.Query().Get(REPO)
    35
        id := r.URL.Query().Get(ID)
    36
    37
        if len(repoName) != 0 && len(id) != 0 {
    38
            repo := GetRepository(repoName)
    39
            exists := repo.GetFileExists(id)
    40
    41
            w.Header().Set("Content-Type", "application/octet-stream")
    42
            if exists {
    43
                io.WriteString(w, "true")
    44
            } else {
    45
                io.WriteString(w, "false")
    46
            }
    47
        }
    48
    }
    49
    50
    // Handles all the URL routing
    51
    func Route() {
    52
        http.HandleFunc("/file", GetFile)
    53
        http.HandleFunc("/exists", FileExists)
    54
    }