goget

Simple go get server
git clone git://git.lair.cx/goget
Log | Files | Refs

main.go (1623B)


      1 package main
      2 
      3 import (
      4 	"flag"
      5 	"html/template"
      6 	"log"
      7 	"net/http"
      8 	"os"
      9 	"strings"
     10 
     11 	_ "embed"
     12 )
     13 
     14 type TemplateData struct {
     15 	PackagePath string
     16 	ClonePath   string
     17 	SourcePath  string
     18 	ModuleName  string
     19 }
     20 
     21 var mux = http.NewServeMux()
     22 
     23 var (
     24 	flagAddr        = flag.String("addr", ":8080", "Address")
     25 	flagPackagePath = flag.String("package-path", "", "Package path")
     26 	flagClonePath   = flag.String("clone-path", "", "Clone path")
     27 	flagSourcePath  = flag.String("source-path", "", "Source path")
     28 )
     29 
     30 //go:embed template.html
     31 var templateSource []byte
     32 var tpl *template.Template
     33 
     34 func init() {
     35 	tpl = template.Must(template.New("main").Parse(string(templateSource)))
     36 }
     37 
     38 func main() {
     39 	flag.Parse()
     40 
     41 	if len(*flagPackagePath) == 0 || len(*flagClonePath) == 0 || len(*flagSourcePath) == 0 {
     42 		log.Println("invalid usage")
     43 		os.Exit(1)
     44 	}
     45 
     46 	server := &http.Server{
     47 		Addr:    *flagAddr,
     48 		Handler: http.HandlerFunc(handler),
     49 	}
     50 	log.Println("[INFO] Running on " + *flagAddr)
     51 	log.Fatal(server.ListenAndServe())
     52 }
     53 
     54 func handler(w http.ResponseWriter, r *http.Request) {
     55 	moduleName := r.URL.Path[1:]
     56 	if len(moduleName) == 0 {
     57 		w.WriteHeader(http.StatusNotFound)
     58 		w.Write([]byte("Module not found"))
     59 		return
     60 	}
     61 
     62 	if strings.ContainsRune(moduleName, '/') {
     63 		w.WriteHeader(http.StatusNotFound)
     64 		w.Write([]byte("Module not found"))
     65 		return
     66 	}
     67 
     68 	data := &TemplateData{
     69 		PackagePath: *flagPackagePath,
     70 		ClonePath:   *flagClonePath,
     71 		SourcePath:  *flagSourcePath,
     72 		ModuleName:  moduleName,
     73 	}
     74 
     75 	w.WriteHeader(200)
     76 	err := tpl.Execute(w, data)
     77 	if err != nil {
     78 		log.Printf("[EROR] template error: %s\n", err.Error())
     79 	}
     80 }