Created
February 1, 2017 14:54
-
-
Save ppanyukov/d3fbc5d0e85569146a264a994d032b0d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See http://ppanyukov.github.io/2017/02/01/golang-with-vsts-repos.html | |
package main | |
import ( | |
"strings" | |
"fmt" | |
"os" | |
"log" | |
"net/http" | |
) | |
func handler(w http.ResponseWriter, r *http.Request) { | |
// A web server which is to make golang's `go get` tool to work with our VSTS. | |
// | |
// It basically returns an HTML with: | |
// <meta name="go-import" content="ACCOUNT/COLLECTION/REPO git https://ACCOUNT.visualstudio.com/COLLECTION/PROJECT/_git/REPO"> | |
// | |
// See also: https://github.com/kisielk/errcheck/issues/103 | |
// Make sure no leading or training slashes in path | |
url := r.URL.Path | |
url = strings.TrimPrefix(url, "/") | |
url = strings.TrimSuffix(url, "/") | |
// Expect the path to be in forms: | |
// | |
// Minimum: | |
// - ACCOUNT/COLLECTION/PROJECT/REPO | |
// | |
// Optionally also specifying a package within repo: | |
// | |
// - ACCOUNT/COLLECTION/PROJECT/REPO/PACKAGE/PACKAGE | |
pathBits := strings.Split(url, "/") | |
if len(pathBits) < 4 { | |
http.Error(w, "Repository path must be in form ACCOUNT/COLLECTION/PROJECT/REPO[/PACKAGE]", http.StatusNotFound) | |
return | |
} | |
// Construct the actual URL of the VSTS git repo | |
account := pathBits[0] | |
collection := pathBits[1] | |
project := pathBits[2] | |
repo := pathBits[3] | |
vstsUrl := fmt.Sprintf("https://%s.visualstudio.com/%s/%s/_git/%s", account, collection, project, repo) | |
// The "content" part of the <meta> tag should contain the original requested package name | |
// which we grab form URL as HOST/PATH | |
requestedPackage := fmt.Sprintf("%s%s", r.Host, r.URL.Path) | |
responseString := fmt.Sprintf(`<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> | |
<meta name="go-import" content="%s git %s"> | |
</head> | |
<body> | |
Nothing to see here! | |
</body> | |
</html>`, requestedPackage, vstsUrl) | |
w.Header().Set("Content-Type", "text/html; charset=utf-8") | |
fmt.Fprint(w, responseString) | |
return | |
} | |
func main() { | |
var port = "80" | |
// Azure PaaS port number. | |
if os.Getenv("HTTP_PLATFORM_PORT") != "" { | |
port = os.Getenv("HTTP_PLATFORM_PORT") | |
} | |
fmt.Printf("Starting server on port %s\n", port) | |
var server = http.Server{} | |
server.SetKeepAlivesEnabled(true) | |
server.Handler = http.HandlerFunc(handler) | |
server.Addr = ":" + port | |
err := server.ListenAndServe() | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment