Beispiel #1
0
func (h *HTTPSession) AcceptLanguages() LangQes {
	if len(h.R.Header["Accept-Language"]) < 1 {
		return LangQes{}
	}
	lstr := h.R.Header["Accept-Language"][0]
	var als LangQes = LangQes{} //all access languages.
	regexp.MustCompile("[^;]*;q?[^,]*").ReplaceAllStringFunc(lstr, func(src string) string {
		src = strings.Trim(src, "\t \n,")
		lq := strings.Split(src, ";")
		qua, err := strconv.ParseFloat(strings.Replace(lq[1], "q=", "", -1), 64)
		if err != nil {
			log.D("invalid Accept-Language q:%s", src)
			return src
		}
		for _, lan := range strings.Split(lq[0], ",") {
			als = append(als, LangQ{
				Lang: lan,
				Q:    qua,
			})
		}
		return src
	})
	sort.Sort(als)
	return als
}
Beispiel #2
0
func ExampleSessionMux() {
	sb := NewSrvSessionBuilder("", "/", "example", 60*60*1000, 10000)
	mux := NewSessionMux("/example", sb)
	mux.HFilterFunc("^.*$", func(hs *HTTPSession) HResult {
		log.D("filt 001")
		return HRES_CONTINUE
	})
	//http://localhost:8080/example/ok
	mux.HFunc("^/ok(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.MsgRes("OK")
		return HRES_RETURN
	})
	//http://localhost:8080/example/data
	mux.HFunc("^/data(\\?.*)?$", func(hs *HTTPSession) HResult {
		var tid int64
		var name string
		err := hs.ValidRVal(`
			tid,R|I,R:0
			name,R|S,L:0`, //valid the argument
			&tid, &name)
		if err != nil {
			return hs.MsgResE(1, err.Error())
		}
		return hs.MsgRes(fmt.Sprintf("%v:%v", tid, name))
	})
	mux.HFunc("^/mdata(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.W.Write([]byte("some data\n"))
		return HRES_RETURN
	})
	s := http.Server{Addr: ":8080", Handler: mux}
	err := s.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}
Beispiel #3
0
//run the server.
func RunSrv(name, dir, port string) {
	s_running = true
	lock.Add(1)
	go StartSrv(name, dir, port)
	lock.Wait()
	s_running = false
	log.D("jcr server stopped...")
}
Beispiel #4
0
//add data to data set by key,
//if val is nil,it will delete the key value.
func (b *Builder) Set(key string, val interface{}) *Builder {
	if val == nil {
		delete(b.Kvs, key)
	} else {
		b.Kvs[key] = val
	}
	log.D("adding the cache data:%v", key)
	return b
}
Beispiel #5
0
func (c *CookieSession) UnCrypto(v string) {
	if len(v) < 1 {
		return
	}
	bys, err := hex.DecodeString(v)
	if err != nil {
		log.D("UnCrypto erro:%s", err.Error())
		return
	}
	ubys, err := c.Sb.UnCrypto(bys)
	if err != nil {
		log.D("UnCrypto erro:%s", err.Error())
		return
	}
	d := gob.NewDecoder(bytes.NewBuffer(ubys))
	// Decoding the serialized data
	err = d.Decode(&c.kvs)
	if err != nil {
		log.D("UnCrypto erro:%s", err.Error())
		return
	}
}
Beispiel #6
0
func StartSrv(name, dir, port string) {
	_conf_.Name = name
	_conf_.Dir = dir
	_conf_.Listen = port
	mux := http.NewServeMux()
	mux.Handle("/jcr/", NewJcrMux())
	log.D("running server on %v", _conf_.Listen)
	s = http.Server{Addr: _conf_.Listen, Handler: mux}
	err := s.ListenAndServe()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
}
Beispiel #7
0
func (j *JsonINT) LoadJson(lang string) error {
	fpath := filepath.Join(j.Path, lang+".json")
	bys, err := ioutil.ReadFile(fpath)
	if err != nil {
		// fmt.Println(err.Error())
		return err
	}
	mv := map[string]string{}
	err = json.Unmarshal(bys, &mv)
	if err != nil {
		log.D("load the lang(%s) json file(%s) error:%s", lang, fpath, err.Error())
		return err
	}
	j.Kvs[lang] = mv
	return nil
}
Beispiel #8
0
func main() {
	db, err := sql.Open("mysql", test.TDbCon)
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()
	sb := routing.NewSrvSessionBuilder("", "/", "example", 60*60*1000, 10000)
	mux := routing.NewSessionMux("/example", sb)
	mux.HFilterFunc("^.*$", func(hs *routing.HTTPSession) routing.HResult {
		log.D("filt 001")
		return routing.HRES_CONTINUE
	})
	//http://localhost:8080/example/ok
	mux.HFunc("^/ok(\\?.*)?$", func(hs *routing.HTTPSession) routing.HResult {
		hs.MsgRes("OK")
		return routing.HRES_RETURN
	})
	//http://localhost:8080/example/data
	mux.HFunc("^/data(\\?.*)?$", func(hs *routing.HTTPSession) routing.HResult {
		var tid int64
		var name string
		err := hs.ValidRVal(`//valid the argument
			tid,R|I,R:0,tid is error;
			name,R|S,L:0,name is empty;
			`, &tid, &name)
		if err != nil {
			return hs.MsgResE(1, err.Error())
		}
		name = "%" + name + "%"
		var ts []TSt
		err = dbutil.DbQueryS(db, &ts, "select * from ttable where tid>? and tname like ?", tid, name)
		if err != nil {
			return hs.MsgResE(1, err.Error())
		}
		return hs.MsgRes(ts)
	})
	mux.HFunc("^/mdata(\\?.*)?$", func(hs *routing.HTTPSession) routing.HResult {
		hs.W.Write([]byte("some data\n"))
		return routing.HRES_RETURN
	})
	s := http.Server{Addr: ":8080", Handler: mux}
	err = s.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}
Beispiel #9
0
func JcrStore(hs *routing.HTTPSession) routing.HResult {
	var cover string
	err := hs.ValidRVal(`
		cover,R|S,L:0
		`, &cover)
	if err != nil {
		return hs.MsgResE(1, err.Error())
	}
	spath := _conf_.SavePath()
	log.D("saving coverage report to %s", spath)
	err = util.FWrite(spath, cover)
	if err != nil {
		log.E("saving coverage report to %s error:%s", spath, err.Error())
		return hs.MsgResE(1, err.Error())
	} else {
		return hs.MsgRes("SUCCESS")
	}
}
Beispiel #10
0
//append file
func AppendF(fname string) {
	log.D("append file:%s", fname)
	f, err := os.Open(fname)
	if err != nil {
		log.W("open file(%v) error:%s", fname, err.Error())
		return
	}
	defer f.Close()
	buf := bufio.NewReader(f)
	for {
		l, err := util.ReadLine(buf, 102400, false)
		if err == io.EOF {
			break
		} else if err != nil {
			log.W("read file(%s) error:%s", fname, err.Error())
		} else {
			AppendR(string(l))
		}
	}
}
Beispiel #11
0
func RunAppend(dir, ex, in, out, js string) error {
	exs := strings.Split(ex, ",")
	ins := strings.Split(in, ",")
	dir, _ = filepath.Abs(dir)
	out, _ = filepath.Abs(out)
	if !util.Fexists(out) {
		err := os.Mkdir(out, os.ModePerm)
		if err != nil {
			fmt.Println(err.Error())
			return err
		}
	}
	cover_c := 0
	err := list(dir, out, func(path string) error {
		if match(exs, path) {
			return nil
		}
		if !match(ins, path) {
			return nil
		}
		defer func() {
			cover_c++
		}()
		opath := out + "/" + strings.TrimPrefix(path, dir)
		odir := filepath.Dir(opath)
		os.MkdirAll(odir, os.ModePerm)
		err := util.FCopy(path, opath)
		if err != nil {
			return err
		}
		return util.FAppend(opath, fmt.Sprintf(`
<script type="text/javascript" src="%s" ></script>
			`, js))
	})
	if err != nil {
		log.E("jcr error:%s", err.Error())
	} else {
		log.D("jcr execute success, %d file is covered...", cover_c)
	}
	return err
}
Beispiel #12
0
func main() {
	//create and open log file
	util.FTouch("/tmp/tt.tmp")
	f, err := os.OpenFile("/tmp/tt.tmp", os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		panic(err.Error())
		return
	}
	//create file buffer writer.
	bo := bufio.NewWriter(f)
	defer f.Close()
	defer bo.Flush()
	//set the log writer to file and stdout.
	//or log.SetWriter(bo) to only file.
	log.SetWriter(io.MultiWriter(bo, os.Stdout))
	//set the log level
	log.SetLevel(log.DEBUG)
	//use
	log.I("tesing")
	log.D("tesing")
}
Beispiel #13
0
func ValidAttrF(f string, cf AttrFunc, limit_r bool, args ...interface{}) error {
	f = regexp.MustCompile("\\/\\/.*").ReplaceAllString(f, "")
	f = strings.Replace(f, "\n", "", -1)
	f = strings.Trim(f, " \t;")
	if len(f) < 1 {
		return errors.New("format not found")
	}
	trimfs := strings.Split(f, ";")
	if len(trimfs) != len(args) {
		return errors.New("args count is not equal format count")
	}
	for idx, fs := range trimfs {
		fs = strings.Trim(fs, " \t")
		fstr := strings.SplitN(fs, ",", 4)
		if len(fstr) < 3 {
			return errors.New(fmt.Sprintf("format error:%s", fs))
		}
		rval, err := ValidAttrT(cf(fstr[0]), fstr[1], fstr[2], limit_r)
		if err != nil {
			rerr := errors.New(fmt.Sprintf("limit(%s),%s", fs, err.Error()))
			if len(fstr) > 3 {
				log.D("%s", rerr.Error())
				return errors.New(fstr[3])
			} else {
				return rerr
			}
		}
		if rval == nil {
			continue
		}
		pval := reflect.Indirect(reflect.ValueOf(args[idx]))
		tval := reflect.ValueOf(rval)
		if pval.Kind() != tval.Kind() {
			return errors.New(fmt.Sprintf("target kind is %v, but %v found", pval.Kind(), tval.Kind()))
		}
		pval.Set(tval)
	}
	return nil
}
Beispiel #14
0
func (c *CORS) exec(w http.ResponseWriter, r *http.Request) routing.HResult {
	origin := r.Header.Get("Origin")
	found := func(origin string) routing.HResult {
		log.D("sending CORS to %s", origin)
		w.Header().Set("Access-Control-Allow-Origin", origin)
		if r.Method == "OPTIONS" {
			return routing.HRES_RETURN
		} else {
			return routing.HRES_CONTINUE
		}
	}
	if len(origin) > 0 {
		if v, ok := c.Sites["*"]; ok && v > 0 {
			return found("*")
		} else if v, ok := c.Sites[origin]; ok && v > 0 {
			return found(origin)
		} else {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return routing.HRES_RETURN
		}
	} else {
		return routing.HRES_CONTINUE
	}
}
Beispiel #15
0
//store data to data set by key.
func (b *Builder) StoreData(key string, val interface{}) *Builder {
	b.Dset[key] = val
	log.D("adding the test data to set:%v", key)
	return b
}
Beispiel #16
0
func (c *Ctx) log(f string, args ...interface{}) {
	if c.ShowLog {
		log.D(f, args...)
	}
}
Beispiel #17
0
func (d *Dir) log(f string, args ...interface{}) {
	if d.ShowLog {
		log.D(f, args...)
	}
}
Beispiel #18
0
//delete the data from data set by key
func (b *Builder) DeleteData(key string) *Builder {
	delete(b.Dset, key)
	log.D("remove the test data from set:%v", key)
	return b
}
Beispiel #19
0
func (s *SrvSessionBuilder) log(f string, args ...interface{}) {
	if s.ShowLog {
		log.D(f, args...)
	}
}
Beispiel #20
0
func JcrExit(hs *routing.HTTPSession) routing.HResult {
	log.D("Jcr receiving exit command...")
	StopSrv()
	return hs.MsgRes("SUCCESS")
}
Beispiel #21
0
func (s *SessionMux) slog(fmt string, args ...interface{}) {
	if s.ShowLog {
		log.D(fmt, args...)
	}
}