Golang Request.Intn Examples

Golang Request.Intn - 5 examples found. These are the top rated real world Golang examples of net/http.Request.Intn extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
func (ttt *TicTacToeApi) BoardGetMove(r *http.Request,
	req *BoardMsg, resp *BoardMsg) error {

	const boardLen = 9
	if len(req.State) != boardLen {
		return fmt.Errorf("Bad Request: Invalid board: %q", req.State)
	}
	runes := []rune(req.State)
	freeIndices := make([]int, 0)
	for pos, r := range runes {
		if r != 'O' && r != 'X' && r != '-' {
			return fmt.Errorf("Bad Request: Invalid rune: %q", r)
		}
		if r == '-' {
			freeIndices = append(freeIndices, pos)
		}
	}
	freeIdxLen := len(freeIndices)
	if freeIdxLen > 0 {
		r := rand.New(rand.NewSource(time.Now().UnixNano()))
		randomIdx := r.Intn(freeIdxLen)
		runes[randomIdx] = 'O'
		resp.State = string(runes)
	} else {
		return fmt.Errorf("Bad Request: This board is full: %q", req.State)
	}
	return nil
}
Example #2
0
func Rock(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content Type", "text/html")
	tmpl, err := template.New("RPSLS").Parse(doc)
	if err == nil {
		var p1, p2 int
		var winner string
		r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) // makes a rand instance
		p1 = 3
		p2 = r.Intn(5) + 1
		// Judge
		result, death := judge(p1, p2, true)
		// Print
		switch result {
		case -1:
			winner = "Computer wins"
		case 0:
			winner = "Tie"
		case 1, 2, 3, 4:
			winner = "You win!"
		}
		choice := Choice{patterns[p1], patterns[p2], death, winner}
		tmpl.Execute(w, choice)
		//time.Sleep(3000 * time.Millisecond)
		//http.Redirect(w, r, "https://github.com", 301)
	}
}
/*
select c.id,e.really_name,ce.name,c.mother,c.mother_phone,c.father,c.father_phone,c.home_phone,c.child,c.contact_status
from tmk_consumer tc
left join consumer c on tc.consumer_id=c.id
left join employee e on e.user_id=tc.employee_id
left join center ce on ce.cid=c.center_id
where tc.employee_id=?
*/
func TmkStatisticsDetailAction(w http.ResponseWriter, r *http.Request) {
	m := make(map[string]interface{})

	employee := lessgo.GetCurrentEmployee(r)

	if employee.UserId == "" {
		lessgo.Log.Warn("用户未登陆")
		m["success"] = false
		m["code"] = 100
		m["msg"] = "用户未登陆"
		commonlib.OutputJson(w, m, " ")
		return
	}

	err := r.ParseForm()

	if err != nil {
		m["success"] = false
		m["code"] = 100
		m["msg"] = "出现错误,请联系IT部门,错误信息:" + err.Error()
		commonlib.OutputJson(w, m, " ")
		return
	}

	pageNoString := r.FormValue("page")
	pageNo := 1
	if pageNoString != "" {
		pageNo, err = strconv.Atoi(pageNoString)
		if err != nil {
			pageNo = 1
			lessgo.Log.Warn("错误的pageNo:", pageNo)
		}
	}

	pageSizeString := r.FormValue("rows")
	pageSize := 10
	if pageSizeString != "" {
		pageSize, err = strconv.Atoi(pageSizeString)
		if err != nil {
			lessgo.Log.Warn("错误的pageSize:", pageSize)
		}
	}

	id := r.FormValue("id")

	params := []interface{}{}

	sql := " select c.id,e.user_id,e.really_name,ce.name,c.mother,c.mother_phone,c.father,c.father_phone,c.home_phone,c.child,c.contact_status "
	sql += " from tmk_consumer tc "
	sql += " left join consumer c on tc.consumer_id=c.id "
	sql += " left join employee e on e.user_id=tc.employee_id "
	sql += " left join center ce on ce.cid=c.center_id "
	sql += " where tc.employee_id=? "

	countSql := "select count(1) from tmk_consumer where employee_id=?"

	params = append(params, id)

	lessgo.Log.Debug(countSql)

	db := lessgo.GetMySQL()
	defer db.Close()

	rows, err := db.Query(countSql, params...)

	if err != nil {
		lessgo.Log.Warn(err.Error())
		m["success"] = false
		m["code"] = 100
		m["msg"] = "系统发生错误,请联系IT部门"
		commonlib.OutputJson(w, m, " ")
		return
	}

	totalNum := 0

	if rows.Next() {
		err := rows.Scan(&totalNum)

		if err != nil {
			lessgo.Log.Warn(err.Error())
			m["success"] = false
			m["code"] = 100
			m["msg"] = "系统发生错误,请联系IT部门"
			commonlib.OutputJson(w, m, " ")
			return
		}
	}

	totalPage := int(math.Ceil(float64(totalNum) / float64(pageSize)))

	currPageNo := pageNo

	if currPageNo > totalPage {
		currPageNo = totalPage
	}

	sql += " limit ?,?"

	params = append(params, (currPageNo-1)*pageSize)
	params = append(params, pageSize)

	lessgo.Log.Debug(sql)

	rows, err = db.Query(sql, params...)

	if err != nil {
		lessgo.Log.Warn(err.Error())
		m["success"] = false
		m["code"] = 100
		m["msg"] = "系统发生错误,请联系IT部门"
		commonlib.OutputJson(w, m, " ")
		return
	}

	objects := []interface{}{}

	for rows.Next() {

		model := new(lessgo.Model)
		r := rand.New(rand.NewSource(time.Now().UnixNano()))
		model.Id = fmt.Sprint(r.Intn(1000))
		model.Props = []*lessgo.Prop{}

		fillObjects := []interface{}{}

		for i := 0; i < 11; i++ {
			prop := new(lessgo.Prop)
			prop.Name = fmt.Sprint(i)
			prop.Value = ""
			fillObjects = append(fillObjects, &prop.Value)
			model.Props = append(model.Props, prop)
		}

		err = commonlib.PutRecord(rows, fillObjects...)

		if err != nil {
			lessgo.Log.Warn(err.Error())
			m["success"] = false
			m["code"] = 100
			m["msg"] = "系统发生错误,请联系IT部门"
			commonlib.OutputJson(w, m, " ")
			return
		}

		objects = append(objects, model)
	}

	pageData := commonlib.BulidTraditionPage(currPageNo, pageSize, totalNum, objects)

	m["PageData"] = pageData
	m["DataLength"] = len(pageData.Datas) - 1
	if len(pageData.Datas) > 0 {
		m["FieldLength"] = len(pageData.Datas[0].(*lessgo.Model).Props) - 1
	}

	commonlib.RenderTemplate(w, r, "entity_page.json", m, template.FuncMap{"getPropValue": lessgo.GetPropValue, "compareInt": lessgo.CompareInt, "dealJsonString": lessgo.DealJsonString}, "../lessgo/template/entity_page.json")
}
//顾问分页数据服务
func ConsultantPhoneListAction(w http.ResponseWriter, r *http.Request) {

	m := make(map[string]interface{})

	employee := lessgo.GetCurrentEmployee(r)

	if employee.UserId == "" {
		lessgo.Log.Warn("用户未登陆")
		m["success"] = false
		m["code"] = 100
		m["msg"] = "用户未登陆"
		commonlib.OutputJson(w, m, " ")
		return
	}

	err := r.ParseForm()

	if err != nil {
		m["success"] = false
		m["code"] = 100
		m["msg"] = "出现错误,请联系IT部门,错误信息:" + err.Error()
		commonlib.OutputJson(w, m, " ")
		return
	}

	pageNoString := r.FormValue("page")
	pageNo := 1
	if pageNoString != "" {
		pageNo, err = strconv.Atoi(pageNoString)
		if err != nil {
			pageNo = 1
			lessgo.Log.Warn("错误的pageNo:", pageNo)
		}
	}

	pageSizeString := r.FormValue("rows")
	pageSize := 10
	if pageSizeString != "" {
		pageSize, err = strconv.Atoi(pageSizeString)
		if err != nil {
			lessgo.Log.Warn("错误的pageSize:", pageSize)
		}
	}

	dataType := ""

	roleCodes := strings.Split(employee.RoleCode, ",")

	for _, roleCode := range roleCodes {
		if roleCode == "admin" || roleCode == "yyzj" || roleCode == "zjl" || roleCode == "yyzy" {
			dataType = "all"
			break
		} else if roleCode == "cd" {
			dataType = "center"
			break
		} else {
			dataType = "self"
		}
	}

	cid := r.FormValue("cid-eq")
	employeeId := r.FormValue("employee_id-eq")
	year := r.FormValue("year-eq")
	month := r.FormValue("month-eq")
	week := r.FormValue("week-eq")
	startTime := r.FormValue("start_time-eq")

	st := ""
	et := ""
	flag := true

	if startTime != "" {
		st = startTime + " 00:00:00"
		et = startTime + " 23:59:59"
	} else {
		if week != "" && month != "" && year != "" {
			st, et, flag = lessgo.FindRangeTimeDim("", "", year+month+week)
		} else if month != "" && year != "" {
			st, et, flag = lessgo.FindRangeTimeDim("", year+month, "")
		} else if year != "" {
			st, et, flag = lessgo.FindRangeTimeDim(year, "", "")
		}
	}

	params := []interface{}{}

	sql := ""
	countSql := ""

	if dataType == "all" {

		sql += "select c.name,c.cid,e.user_id,e.really_name,phone_count.num a,rank.rowNo b,phone_count.localphone from (select count(*) num,localphone,cid from audio where remotephone!='' and remotephone is not null "

		if cid != "" {
			sql += " and cid=? "
			params = append(params, cid)
		}

		if flag {
			if st != "" && et != "" {
				sql += " and start_time >= ? and start_time<= ?"
				params = append(params, st)
				params = append(params, et)
			}
		} else { //找不到相应的时间区间
			sql += " and start_time >= ? and start_time<= ?"
			params = append(params, "2000-01-01 00:00:00")
			params = append(params, "2000-01-01 00:00:01")
		}

		sql += " group by  localphone,cid) phone_count left join center c on c.cid=phone_count.cid left join employee e on e.phone_in_center=phone_count.localphone and e.center_id=phone_count.cid left join (select a.*,(@rowNum:=@rowNum+1) as rowNo from (select count(*) num,localphone,cid from audio where remotephone!='' and remotephone is not null "

		if flag {
			if st != "" && et != "" {
				sql += " and start_time >= ? and start_time<= ?"
				params = append(params, st)
				params = append(params, et)
			}
		} else { //找不到相应的时间区间
			sql += " and start_time >= ? and start_time<= ?"
			params = append(params, "2000-01-01 00:00:00")
			params = append(params, "2000-01-01 00:00:01")
		}

		sql += " group by  localphone,cid order by num desc) a,(Select (@rowNum :=0) ) b)rank on rank.localphone=phone_count.localphone and rank.cid=phone_count.cid"

		if employeeId != "" {
			sql += " where e.user_id = ? "
			params = append(params, employeeId)
		}

		sql += " order by rank.rowNo "

	} else if dataType == "center" {

		sql += "select c.name,c.cid,e.user_id,e.really_name,phone_count.num a,rank.rowNo b,phone_count.localphone from (select count(*) num,localphone,cid from audio  where cid=? and remotephone!='' and remotephone is not null "

		userId, _ := strconv.Atoi(employee.UserId)
		_employee, err := FindEmployeeById(userId)
		if err != nil {
			m["success"] = false
			m["code"] = 100
			m["msg"] = "出现错误,请联系IT部门,错误信息:" + err.Error()
			commonlib.OutputJson(w, m, " ")
			return
		}
		params = append(params, _employee.CenterId)

		if flag {
			if st != "" && et != "" {
				sql += " and start_time >= ? and start_time<= ?"
				params = append(params, st)
				params = append(params, et)
			}
		} else { //找不到相应的时间区间
			sql += " and start_time >= ? and start_time<= ?"
			params = append(params, "2000-01-01 00:00:00")
			params = append(params, "2000-01-01 00:00:01")
		}

		sql += " group by  localphone,cid) phone_count left join center c on c.cid=phone_count.cid left join employee e on e.phone_in_center=phone_count.localphone and e.center_id=phone_count.cid  left join (select a.*,(@rowNum:=@rowNum+1) as rowNo from (select count(*) num,localphone,cid from audio where remotephone!='' and remotephone is not null "

		if flag {
			if st != "" && et != "" {
				sql += " and start_time >= ? and start_time<= ?"
				params = append(params, st)
				params = append(params, et)
			}
		} else { //找不到相应的时间区间
			sql += " and start_time >= ? and start_time<= ?"
			params = append(params, "2000-01-01 00:00:00")
			params = append(params, "2000-01-01 00:00:01")
		}

		sql += " group by  localphone,cid order by num desc) a,(Select (@rowNum :=0) ) b)rank on rank.localphone=phone_count.localphone and rank.cid=phone_count.cid "

		if employeeId != "" {
			sql += " where e.user_id = ? "
			params = append(params, employeeId)
		}

		sql += " order by rank.rowNo "

	} else if dataType == "self" {

		sql += "select c.name,c.cid,e.user_id,e.really_name,phone_count.num a,rank.rowNo b,phone_count.localphone from (select count(*) num,localphone,cid from audio where remotephone!='' and remotephone is not null "

		if flag {
			if st != "" && et != "" {
				sql += " and start_time >= ? and start_time<= ?"
				params = append(params, st)
				params = append(params, et)
			}
		} else { //找不到相应的时间区间
			sql += " and start_time >= ? and start_time<= ?"
			params = append(params, "2000-01-01 00:00:00")
			params = append(params, "2000-01-01 00:00:01")
		}

		sql += " group by  localphone,cid) phone_count left join center c on c.cid=phone_count.cid left join employee e on e.phone_in_center=phone_count.localphone and e.center_id=phone_count.cid left join (select a.*,(@rowNum:=@rowNum+1) as rowNo from (select count(*) num,localphone,cid from audio where remotephone!='' and remotephone is not null "

		if flag {
			if st != "" && et != "" {
				sql += " and start_time >= ? and start_time<= ?"
				params = append(params, st)
				params = append(params, et)
			}
		} else { //找不到相应的时间区间
			sql += " and start_time >= ? and start_time<= ?"
			params = append(params, "2000-01-01 00:00:00")
			params = append(params, "2000-01-01 00:00:01")
		}

		sql += " group by  localphone,cid order by num desc) a,(Select (@rowNum :=0) ) b)rank on rank.localphone=phone_count.localphone and rank.cid=phone_count.cid "

		sql += " where e.user_id=? "

		params = append(params, employee.UserId)

		sql += " order by rank.rowNo "
	}

	countSql = "select count(1) from (" + sql + ") num"

	lessgo.Log.Debug(countSql)

	db := lessgo.GetMySQL()
	defer db.Close()

	rows, err := db.Query(countSql, params...)

	if err != nil {
		lessgo.Log.Warn(err.Error())
		m["success"] = false
		m["code"] = 100
		m["msg"] = "系统发生错误,请联系IT部门"
		commonlib.OutputJson(w, m, " ")
		return
	}

	totalNum := 0

	if rows.Next() {
		err := rows.Scan(&totalNum)

		if err != nil {
			lessgo.Log.Warn(err.Error())
			m["success"] = false
			m["code"] = 100
			m["msg"] = "系统发生错误,请联系IT部门"
			commonlib.OutputJson(w, m, " ")
			return
		}
	}

	totalPage := int(math.Ceil(float64(totalNum) / float64(pageSize)))

	currPageNo := pageNo

	if currPageNo > totalPage {
		currPageNo = totalPage
	}

	lessgo.Log.Debug(sql + " limit ?,?")

	params = append(params, (currPageNo-1)*pageSize)
	params = append(params, pageSize)

	rows, err = db.Query(sql+" limit ?,?", params...)

	if err != nil {
		lessgo.Log.Warn(err.Error())
		m["success"] = false
		m["code"] = 100
		m["msg"] = "系统发生错误,请联系IT部门"
		commonlib.OutputJson(w, m, " ")
		return
	}

	objects := []interface{}{}

	for rows.Next() {

		model := new(lessgo.Model)
		r := rand.New(rand.NewSource(time.Now().UnixNano()))
		model.Id = fmt.Sprint(r.Intn(1000))
		model.Props = []*lessgo.Prop{}

		fillObjects := []interface{}{}

		for i := 0; i < 7; i++ {
			prop := new(lessgo.Prop)
			prop.Name = fmt.Sprint(i)
			prop.Value = ""
			fillObjects = append(fillObjects, &prop.Value)
			model.Props = append(model.Props, prop)
		}

		err = commonlib.PutRecord(rows, fillObjects...)

		if err != nil {
			lessgo.Log.Warn(err.Error())
			m["success"] = false
			m["code"] = 100
			m["msg"] = "系统发生错误,请联系IT部门"
			commonlib.OutputJson(w, m, " ")
			return
		}

		objects = append(objects, model)
	}

	pageData := commonlib.BulidTraditionPage(currPageNo, pageSize, totalNum, objects)

	m["PageData"] = pageData
	m["DataLength"] = len(pageData.Datas) - 1
	if len(pageData.Datas) > 0 {
		m["FieldLength"] = len(pageData.Datas[0].(*lessgo.Model).Props) - 1
	}

	commonlib.RenderTemplate(w, r, "entity_page.json", m, template.FuncMap{"getPropValue": lessgo.GetPropValue, "compareInt": lessgo.CompareInt, "dealJsonString": lessgo.DealJsonString}, "../lessgo/template/entity_page.json")

}
Example #5
0
func pay(w http.ResponseWriter, r *http.Request) {
	if strings.ToUpper(r.Method) == "GET" {
		http.NotFound(w, r)
	} else if strings.ToUpper(r.Method) == "POST" {
		var chargeParams pingpp.ChargeParams
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Content-Type", "application/json")
		defer r.Body.Close()
		buf := new(bytes.Buffer)
		buf.ReadFrom(r.Body)

		json.Unmarshal(buf.Bytes(), &chargeParams)
		r := rand.New(rand.NewSource(time.Now().UnixNano()))
		orderno := r.Intn(999999999999999)
		extra := make(map[string]interface{})
		switch strings.ToLower(chargeParams.Channel) {
		case "upacp_wap":
			extra["result_url"] = "http://www.yourdomain.com/result"
		case "alipay_wap":
			extra["cancel_url"] = "http://www.yourdomain.com/cancel"
			extra["success_url"] = "http://www.yourdomain.com/success"
		case "bfb_wap":
			extra["result_url"] = "http://www.yourdomain.com/result"
			extra["bfb_login"] = false
		case "yeepay_wap":
			extra["product_category"] = "1"
			extra["identity_id"] = "your_identity_id"
			extra["identity_type"] = 1
			extra["terminal_type"] = 1
			extra["terminal_id"] = "1sdf"
			extra["user_ua"] = "1qwec"
			extra["result_url"] = "http://www.yourdomain.com/result"
		case "wx_pub":
			extra["open_id"] = "your_openid"
		case "jdpay_wap":
			extra["success_url"] = "http://www.yourdomain.com/success"
			extra["fail_url"] = "http://www.yourdomain.com/fail"
			extra["token"] = "your_token_from_jd"
		case "wx_pub_qr":
			extra["product_id"] = "your_productid"

		}

		pingpp.Key = "sk_test_ibbTe5jLGCi5rzfH4OqPW9KC"

		params := &pingpp.ChargeParams{
			Order_no:  strconv.Itoa(orderno),
			App:       pingpp.App{Id: "app_1Gqj58ynP0mHeX1q"},
			Amount:    chargeParams.Amount,
			Channel:   strings.ToLower(chargeParams.Channel),
			Currency:  "cny",
			Client_ip: "127.0.0.1",
			Subject:   "Your Subject",
			Body:      "Your Body",
			Extra:     extra,
		}

		//返回的第一个参数是 charge 对象,你需要将其转换成 json 给客户端,或者客户端接收后转换。
		ch, err := charge.New(params)

		if err != nil {
			errs, _ := json.Marshal(err)
			fmt.Fprint(w, string(errs))
		} else {
			chs, _ := json.Marshal(ch)
			fmt.Fprintln(w, string(chs))
		}

	}
}