Code Monkey home page Code Monkey logo

beego_app's People

Contributors

asu126 avatar

Stargazers

 avatar  avatar

Watchers

 avatar

beego_app's Issues

shell

shell

package main

import (
	"bytes"
	"fmt"
	//"github.com/gliderlabs/ssh"
	"io"
	// "log"
	"os"
	"os/exec"
	"sync"
)

// func (l *loggingResponseWriter) Write(data []byte) (n int, err error) {
// 	if l.status == 0 {
// 		l.WriteHeader(http.StatusOK)
// 	}
// 	n, err = l.rw.Write(data)
// 	l.written += int64(n)
// 	return n, err
// }

// var execCommand = exec.Command

// // Git subprocess helpers
// func gitCommand(gl_id string, name string, RepoPath string, args ...string) *exec.Cmd {
// 	cmd := execCommand(name, args...)
// 	// Start the command in its own process group (nice for signalling)
// 	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
// 	// Explicitly set the environment for the Git command
// 	cmd.Env = []string{
// 		fmt.Sprintf("HOME=%s", os.Getenv("HOME")),
// 		fmt.Sprintf("PATH=%s", os.Getenv("PATH")),
// 		fmt.Sprintf("LD_LIBRARY_PATH=%s", os.Getenv("LD_LIBRARY_PATH")),
// 		fmt.Sprintf("GL_ID=%s", gl_id),
// 		fmt.Sprintf("GL_PROTOCOL=http"),
// 		fmt.Sprintf("REPO_PATH=%s", RepoPath),
// 	}
// 	// If we don't do something with cmd.Stderr, Git errors will be lost
// 	cmd.Stderr = os.Stderr
// 	return cmd
// }

// func main() {
// 	var stdout bytes.Buffer
// 	cmd := exec.Command("date")
// 	cmd.Stdout = &stdout

// 	cmd.Stdout = &stdout
// 	if err := cmd.Run(); err != nil {
// 		fmt.Fprintln(os.Stderr)
// 		os.Exit(1)
// 	}

// 	// Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).
// 	fmt.Println(stdout.Len())
// 	stdout.WriteTo(os.Stdout)
// 	//return nil
// 	os.Exit(0)
// }

func main() {
	var gitCmd *exec.Cmd
	repoPath := "/home/git/gitlab-development-kit/repositories/beego/beego.git"
	gitCmd = exec.Command("git-upload-pack", repoPath)
	gitCmd.Env = os.Environ()
	var output bytes.Buffer
	gitCmd.Env = append(gitCmd.Env, "GL_PROTOCOL=ssh")
	gitCmd.Env = append(gitCmd.Env, "GL_PROTOCOL=/home/git/gitlab-development-kit/repositories/beego/beego.git")
	gitCmd.Dir = repoPath
	gitCmd.Stdin = os.Stdin
	// gitCmd.Stdout = os.Stdout
	stdout, _ := gitCmd.StdoutPipe()
	writer := io.MultiWriter(os.Stdout, &output)

	var waitGroup sync.WaitGroup
	waitGroup.Add(1)
	go func() {
		defer waitGroup.Done()
		io.Copy(writer, stdout)
	}()

	gitCmd.Stderr = os.Stderr
	if err := gitCmd.Run(); err != nil {
		fmt.Fprintln(os.Stderr)
		os.Exit(1)
	}
	waitGroup.Wait()

	//	fmt.Println(stdout.Len())
	//	stdout.WriteTo(os.Stdout)
	//return nil
	os.Exit(0)

}

fix download

package main

import (
	"compress/gzip"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path"
	"regexp"
	"strings"
)

type gitHandler struct {
	method      string
	regexp      *regexp.Regexp
	handle_func func(string, string, http.ResponseWriter, *http.Request)
	rpc         string
}

var repo_root string

var git_handlers = [...]gitHandler{
	gitHandler{"GET", regexp.MustCompile(`\A(/..*)/info/refs\z`), handle_get_info_refs, ""},
	gitHandler{"POST", regexp.MustCompile(`\A(/..*)/git-upload-pack\z`), handle_post_rpc, "git-upload-pack"},
	gitHandler{"POST", regexp.MustCompile(`\A(/..*)/git-receive-pack\z`), handle_post_rpc, "git-receive-pack"},
}

func main() {
	flag.Parse()
	repo_root = flag.Arg(0)
	log.Printf("repo_root: %s", repo_root)
	http.HandleFunc("/", git_handler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func git_handler(w http.ResponseWriter, r *http.Request) {
	log.Print(r)
	for _, g := range git_handlers {
		m := g.regexp.FindStringSubmatch(r.URL.Path)
		if r.Method == g.method && m != nil {
			g.handle_func(g.rpc, path.Join(repo_root, m[1]), w, r)
			return
		}
	}
	log.Print("Reached end of dispatch for loop")
	w.WriteHeader(404)
}

func handle_get_info_refs(_ string, path string, w http.ResponseWriter, r *http.Request) {
	rpc := r.URL.Query().Get("service")
	switch rpc {
	case "git-upload-pack", "git-receive-pack":
		w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", rpc))
		w.Header().Set("Cache-Control", "no-cache")

		if err := pktLine(w, fmt.Sprintf("# service=%s\n", rpc)); err != nil {
			fmt.Errorf("pktLine: %v", err)
			return
		}
		if err := pktFlush(w); err != nil {
			fmt.Errorf("pktFlush: %v", err)
			return
		}

		cmd := exec.Command("git", strings.TrimPrefix(rpc, "git-"), "--stateless-rpc", "--advertise-refs", path)
		log.Print(cmd.Args)
		cmd.Stdin = nil
		cmd.Stdout = w
		// stdout, err := cmd.StdoutPipe()
		// if err != nil {
		// 	fail_500(w, err)
		// 	return
		// }
		if err := cmd.Start(); err != nil {
			fail_500(w, err)
			return
		}
		// w.Header().Add("Content-Type", fmt.Sprintf("application/x-%s-advertisement", rpc))
		// no_cache(w)
		// fmt.Fprintf(w, "%s0000", pkt_line(fmt.Sprintf("# service=%s\n", rpc)))
		// if _, err := io.Copy(w, stdout); err != nil {
		// 	fail_500(w, err)
		// 	return
		// }
		
		if err := cmd.Wait(); err != nil {
			fail_500(w, err)
			return
		}
	case "":
		log.Print("dumb info refs")
	}
}


func handle_post_rpc(rpc string, path string, w http.ResponseWriter, r *http.Request) {
	var body io.Reader
	var err error
	if r.Header.Get("Content-Encoding") == "gzip" {
		body, err = gzip.NewReader(r.Body)
		if err != nil {
			fail_500(w, err)
			return
		}
	} else {
		body = r.Body
	}
	cmd := exec.Command("git", strings.TrimPrefix(rpc, "git-"), "--stateless-rpc", path)
	log.Print(cmd.Args)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fail_500(w, err)
		return
	}
	stdin, err := cmd.StdinPipe()
	if err != nil {
		fail_500(w, err)
		return
	}
	if err := cmd.Start(); err != nil {
		fail_500(w, err)
		return
	}
	w.Header().Add("Content-Type", fmt.Sprintf("application/x-%s-result", rpc))
	no_cache(w)
	if _, err := io.Copy(stdin, body); err != nil {
		fail_500(w, err)
		return
	}
	stdin.Close()
	if _, err := io.Copy(w, stdout); err != nil {
		fail_500(w, err)
		return
	}
	if err := cmd.Wait(); err != nil {
		fail_500(w, err)
		return
	}
}

func pkt_line(s string) string {
	return fmt.Sprintf("%04x%s", len(s)+4, s)
}

func fail_500(w http.ResponseWriter, err error) {
	w.WriteHeader(500)
	log.Print(err)
}

func no_cache(w http.ResponseWriter) {
	w.Header().Add("Cache-Control", "no-cache")
}

func pktLine(w io.Writer, s string) error {
	_, err := fmt.Fprintf(w, "%04x%s", len(s)+4, s)
	return err
}

func pktFlush(w io.Writer) error {
	_, err := fmt.Fprint(w, "0000")
	return err
}

// func CleanUpProcessGroup(cmd *exec.Cmd) {
// 	if cmd == nil {
// 		return
// 	}

// 	process := cmd.Process
// 	if process != nil && process.Pid > 0 {
// 		// Send SIGTERM to the process group of cmd
// 		syscall.Kill(-process.Pid, syscall.SIGTERM)
// 	}

// 	// reap our child process
// 	cmd.Wait()
// }

func ReadAllTempfile(r io.Reader) (tempfile *os.File, err error) {
	tempfile, err = ioutil.TempFile("", "gitlab-workhorse-read-all-tempfile")
	if err != nil {
		return nil, err
	}

	defer func() {
		// Avoid leaking an open file if the function returns with an error
		if err != nil {
			tempfile.Close()
		}
	}()

	if err := os.Remove(tempfile.Name()); err != nil {
		return nil, err
	}

	if _, err := io.Copy(tempfile, r); err != nil {
		return nil, err
	}

	if _, err := tempfile.Seek(0, 0); err != nil {
		return nil, err
	}

	return tempfile, nil
}

context

package main

import (
	"fmt"
	"time"
	"golang.org/x/net/context"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	c2 := make(chan string, 1)

	go func(ctx context.Context) {
		for {
			select {
			case <-ctx.Done():
				fmt.Println("监控退出,停止了...")
				return
			default:
				fmt.Println("goroutine监控中...")
				time.Sleep(2 * time.Second)
				if 2==2{
					c2 <- "Wait repo sync end, repo sync successful ..."
				}
			}
		}
	}(ctx)
	// time.Sleep(10 * time.Second)

	select {
			case res := <-c2:
				cancel()
				fmt.Println(res)
			case <-time.After(10 * time.Second):
				fmt.Println("Wait repo sync timeout ...")
				fmt.Println("可以了,通知监控停止")
				cancel()
				return
			}
	//为了检测监控过是否停止,如果没有监控输出,就表示停止了
	fmt.Println("下载中...")
	time.Sleep(5 * time.Second)
}

logout 时session 不失效

sessionConfig := &session.ManagerConfig{
		CookieName:     "beegosessionID",
		Gclifetime:     3600,
		ProviderConfig: "127.0.0.1:6379,100",
	}

看了下源码,CookieName: "beegosessionID",要与客户端session_id的key值保持一致

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.