当前位置: 首页>>代码示例>>Golang>>正文


Golang io.WriteString函数代码示例

本文整理汇总了Golang中io.WriteString函数的典型用法代码示例。如果您正苦于以下问题:Golang WriteString函数的具体用法?Golang WriteString怎么用?Golang WriteString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了WriteString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: sign

// 内容签名。生成规则:
// A)提取请求方法method(GET或POST);
// B)提取请求url信息,包括Host字段的IP或域名和URI的path部分,注意不包括Host的端口和Path的querystring。请在请求中带上Host字段,否则将视为无效请求。比如openapi.xg.qq.com/v2/push/single_device或者10.198.18.239/v2/push/single_device;
// C)将请求参数(不包括sign参数)格式化成K=V方式,注意:计算sign时所有参数不应进行urlencode;
// D)将格式化后的参数以K的字典序升序排列,拼接在一起,注意字典序中大写字母在前;
// E)拼接请求方法、url、排序后格式化的字符串以及应用的secret_key;
// F)将E形成字符串计算MD5值,形成一个32位的十六进制(字母小写)字符串,即为本次请求sign(签名)的值;
// Sign=MD5($http_method$url$k1=$v1$k2=$v2$secret_key); 该签名值基本可以保证请求是合法者发送且参数没有被修改,但无法保证不被偷窥。
// 例如: POST请求到接口http://openapi.xg.qq.com/v2/push/single_device,有四个参数,access_id=123,timestamp=1386691200,Param1=Value1,Param2=Value2,secret_key为abcde。则上述E步骤拼接出的字符串为POSTopenapi.xg.qq.com/v2/push/single_deviceParam1=Value1Param2=Value2access_id=123timestamp=1386691200abcde,注意字典序中大写在前。计算出该字符串的MD5为ccafecaef6be07493cfe75ebc43b7d53,以此作为sign参数的值
func (xgpush *XGPush) sign(method string, device_type int, params map[string]string) (err error) {
	var secret_key string
	switch device_type {
	case XGPushDeviceType_IOS:
		params["environment"] = xgpush.Param_environment
		params["access_id"] = xgpush.Param_ios_access_id
		secret_key = xgpush.Param_ios_secret_key
	case XGPushDeviceType_Android:
		params["access_id"] = xgpush.Param_android_access_id
		secret_key = xgpush.Param_android_secret_key
	default:
		return ErrUnknownDeviceType
	}
	if _, found := params["timestamp"]; !found {
		params["timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
	}

	//params["valid_time"] = XGPUSH_VALID_TIME
	h := md5.New()
	io.WriteString(h, XGPUSH_METHOD)
	io.WriteString(h, XGPUSH_V2_BASE_URL)
	io.WriteString(h, method)
	var kvs []string
	for key, value := range params {
		kvs = append(kvs, key+"="+value)
	}
	sort.Sort(sort.StringSlice(kvs))
	for _, kv := range kvs {
		io.WriteString(h, kv)
	}
	io.WriteString(h, secret_key)
	params["sign"] = fmt.Sprintf("%x", h.Sum(nil))
	return
}
开发者ID:sadlyads,项目名称:xgpush,代码行数:43,代码来源:xgpush.go

示例2: escapeString

// mysql_real_escape_string()  “\”, “'”, “"”, NUL (ASCII 0), “\n”, “\r”, and Control+Z
func escapeString(txt string) string {
	var (
		esc string
		buf bytes.Buffer
	)
	last := 0
	for ii, bb := range txt {
		switch bb {
		case 0:
			esc = `\0`
		case '\n':
			esc = `\n`
		case '\r':
			esc = `\r`
		case '\\':
			esc = `\\`
		case '\'':
			esc = `\'`
		case '"':
			esc = `\"`
		case '\032':
			esc = `\Z`
		default:
			continue
		}
		io.WriteString(&buf, txt[last:ii])
		io.WriteString(&buf, esc)
		last = ii + 1
	}
	io.WriteString(&buf, txt[last:])
	return buf.String()
}
开发者ID:Carbyn,项目名称:sphinx,代码行数:33,代码来源:sphinxql.go

示例3: ListFilesHandlers

//--------------------------------------
//文件管理逻辑
//
//KindEditor提交参数:
//dir{"image", "flash", "media", "file"},默认"image"
//path,默认"",格式:"2014年","2014年1月","201401-<filename>"
//order,默认"name"
//
//返回给KindEditor的参数:
//moveup_dir_path": "",
//"current_dir_path": "",
//"current_url": "/ke4/php/../attached/",
//"total_count": 5,
//"file_list": [
//
//{
//    "is_dir": false,
//    "has_file": false,
//    "filesize": 208736,
//    "is_photo": true,
//    "filetype": "jpg",
//    "filename": "1241601537255682809.jpg",
//    "datetime": "2011-08-02 15:32:43"
//},
//{
//    "is_dir": true,
//    "has_file": (file.listFiles() != null),
//    "filesize": 0L,
//    "is_photo": false,
//    "filetype": "",
//    "filename": file.getName(),
//    "datetime": "2011-08-02 15:32:43"
//},
//--------------------------------------
//martini handler
func ListFilesHandlers() []martini.Handler {
	var bind = binding.Bind(ListReqData{})
	var listHandler = func(data ListReqData, w http.ResponseWriter, r *http.Request) {
		if strings.ToUpper(data.Dir) != "IMAGE" {
			data.Err(w, "dir should be IMAGE")
			return
		}
		//根据path建立KindList
		list := &KindList{CurrentDirPath: strings.TrimSuffix(data.Path, "/")}
		switch length := len([]rune(list.CurrentDirPath)); length {
		case 0: //""
			listYears(r, list)
		case 5: //"2014年, 2014年"
			if err := listMonths(r, list); err != nil {
				data.Err(w, err.Error())
				return
			}
		case 7, 8: //"2014年4月"
			if err := listFiles(&data, list); err != nil {
				data.Err(w, err.Error())
				return
			}
		default:
			data.Err(w, `Path wrong:`+data.Path)
			return
		}
		io.WriteString(w, data.Callback+"(")
		resJson(w, list)
		io.WriteString(w, ")")
	}
	return []martini.Handler{bind, listHandler}
}
开发者ID:empirefox,项目名称:iniu-old,代码行数:67,代码来源:kindeditor.go

示例4: doLogin

/**
* 登录处理
 */
func doLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	manageName := r.Form["manage_name"][0]
	password := r.Form["password"][0]
	code := r.Form["code"][0]

	if manageName == "" || password == "" || code == "" {
		io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
	}

	//判断验证码是否正确
	imagecode := getSession(w, r, imageCodeKey)
	if code == imagecode {
		//判断账号和密码是否正确
		userInfo, err := checkLogin(manageName, getSha1(password))
		if err != nil {
			io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
		} else {
			setSession(w, r, manageIdKey, userInfo["manage_id"])
			io.WriteString(w, "<script type='text/javascript'>location.href='/admin'</script>")
		}
	} else {
		io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
	}
}
开发者ID:ruansheng,项目名称:blog,代码行数:28,代码来源:server.go

示例5: GenerateId

//生成节点id
func GenerateId() Id {
	random := rand.New(rand.NewSource(time.Now().UnixNano()))
	h := sha1.New()
	io.WriteString(h, time.Now().String())
	io.WriteString(h, string(random.Int()))
	return h.Sum(nil)
}
开发者ID:kissthink,项目名称:DhtBT,代码行数:8,代码来源:main.go

示例6: jsonify

// Generate JSON output
func jsonify(w http.ResponseWriter, r *http.Request, question []dns.Question, answer []dns.RR, authority []dns.RR, additional []dns.RR) {
	var answerArray, authorityArray, additionalArray []*Section

	callback := r.URL.Query().Get("callback")

	for _, answer := range answer {
		answerArray = append(answerArray, &Section{answer.Header().Name, dns.TypeToString[answer.Header().Rrtype], dns.ClassToString[answer.Header().Class], answer.Header().Ttl, answer.Header().Rdlength, rdata(answer)})
	}

	for _, authority := range authority {
		authorityArray = append(authorityArray, &Section{authority.Header().Name, dns.TypeToString[authority.Header().Rrtype], dns.ClassToString[authority.Header().Class], authority.Header().Ttl, authority.Header().Rdlength, rdata(authority)})
	}

	for _, additional := range additional {
		additionalArray = append(additionalArray, &Section{additional.Header().Name, dns.TypeToString[additional.Header().Rrtype], dns.ClassToString[additional.Header().Class], additional.Header().Ttl, additional.Header().Rdlength, rdata(additional)})
	}

	if json, err := json.MarshalIndent(Message{[]*Question{&Question{question[0].Name, dns.TypeToString[question[0].Qtype], dns.ClassToString[question[0].Qclass]}}, answerArray, authorityArray, additionalArray}, "", "    "); err == nil {
		if callback != "" {
			io.WriteString(w, callback+"("+string(json)+");")
		} else {
			io.WriteString(w, string(json))
		}
	}
}
开发者ID:onceking,项目名称:rrda,代码行数:26,代码来源:rrda.go

示例7: bEncode

// bEncode encodes s using base64 encoding and writes it to buf.
func (e WordEncoder) bEncode(buf *bytes.Buffer, charset, s string) {
	w := base64.NewEncoder(base64.StdEncoding, buf)
	// If the charset is not UTF-8 or if the content is short, do not bother
	// splitting the encoded-word.
	if !isUTF8(charset) || base64.StdEncoding.EncodedLen(len(s)) <= maxContentLen {
		io.WriteString(w, s)
		w.Close()
		return
	}

	var currentLen, last, runeLen int
	for i := 0; i < len(s); i += runeLen {
		// Multi-byte characters must not be split accross encoded-words.
		// See RFC 2047, section 5.3.
		_, runeLen = utf8.DecodeRuneInString(s[i:])

		if currentLen+runeLen <= maxBase64Len {
			currentLen += runeLen
		} else {
			io.WriteString(w, s[last:i])
			w.Close()
			e.splitWord(buf, charset)
			last = i
			currentLen = runeLen
		}
	}
	io.WriteString(w, s[last:])
	w.Close()
}
开发者ID:reillywatson,项目名称:go,代码行数:30,代码来源:encodedword.go

示例8: commandHandler

func commandHandler(res http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	command := new(SlackCommand)
	decoder := schema.NewDecoder()

	err := decoder.Decode(command, req.PostForm)
	if err != nil {
		res.WriteHeader(400)
		io.WriteString(res, "Invalid form data\n")
		return
	}

	if command.Token != config.IncomingToken {
		res.WriteHeader(403)
		io.WriteString(res, "Invalid token\n")
		return
	}

	user, created := userStore.GetOrAdd(command.UserID)
	if created {
		user.UserName = command.UserName
	}

	commandFunc, exists := commands[command.getSubCommand()]
	if !exists {
		commandFunc = commands["help"]
	}
	err = commandFunc(command, user)
	if err != nil {
		res.WriteHeader(400)
		io.WriteString(res, err.Error())
	}
}
开发者ID:arjandepooter,项目名称:slack-exact,代码行数:33,代码来源:handlers.go

示例9: Quote

func (l List) Quote(w io.Writer, t Type) error {
	_, err := io.WriteString(w, "[ ")
	if err != nil {
		return err
	}

	lt, isList := t.(ListType)
	if !isList {
		return fmt.Errorf("internal error: %v is not a list", t.Name())
	}

	for i, v := range l {
		if i != 0 {
			_, err = io.WriteString(w, ", ")
			if err != nil {
				return err
			}
		}

		if err := v.Quote(w, lt.Elem); err != nil {
			return err
		}
	}

	_, err = io.WriteString(w, " ]")
	return err
}
开发者ID:julochrobak,项目名称:comp,代码行数:27,代码来源:value.go

示例10: RegisterHandler

func RegisterHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		tmpl, _ := template.ParseFiles("./static/adduser.html")

		tmpl.Execute(w, "")
		return
	}
	username := r.FormValue("user")
	pwd := r.FormValue("pwd")
	pwdConfirm := r.FormValue("pwd_confirm")

	user := dao.QueryUserByUserName(username)
	if user != nil {
		io.WriteString(w, "user "+username+"alread exists")
		return
	}
	if pwd == "" || pwd != pwdConfirm {
		io.WriteString(w, "password confirm error, not the same one!")
		return
	}

	user = new(dao.User)
	user.UserName = username
	user.Name = username
	user.Pwd = wb_util.CreateMD5String(pwd)
	dao.CreateUser(user)
	dao.RegistUser(user)
	msg := "register success!!!"
	tmpl, _ := template.ParseFiles("./static/success.html")
	tmpl.Execute(w, msg)
}
开发者ID:sgp2004,项目名称:WeiboLibrary,代码行数:31,代码来源:user_handler.go

示例11: handlePing

func (svc *GoPushService) handlePing(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		serve404(w)
		return
	}

	v, _ := url.ParseQuery(r.URL.RawQuery)
	center := v.Get("center")
	callback := v.Get("callback") // For JSONP

	if _, ok := svc.lastState[center]; center == "" || !ok {
		serve404(w)
		return
	}

	if callback == "" { // Normal response
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusOK)
		io.WriteString(w, svc.lastState[center])
	} else { // JSONP response
		w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
		w.WriteHeader(http.StatusOK)
		marshaled, _ := json.Marshal(svc.lastState[center])
		io.WriteString(w, callback+"("+string(marshaled)+");")
	}
}
开发者ID:Pronovix,项目名称:gopush,代码行数:26,代码来源:ping.go

示例12: pushHandler

func pushHandler(w http.ResponseWriter, r *http.Request, backend *dbBackend) {
	decoder := json.NewDecoder(r.Body)
	decoder.UseNumber()
	var ent map[string]interface{}
	e := decoder.Decode(&ent)
	if nil != e {
		w.WriteHeader(http.StatusBadRequest)
		io.WriteString(w, e.Error())
		return
	}

	job, e := createJobFromMap(backend, ent)
	if nil != e {
		w.WriteHeader(http.StatusInternalServerError)
		io.WriteString(w, e.Error())
		return
	}

	e = backend.create(job)
	if nil != e {
		w.WriteHeader(http.StatusInternalServerError)
		io.WriteString(w, e.Error())
		return
	}
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, "OK")
	return
}
开发者ID:runner-mei,项目名称:delayed_job,代码行数:28,代码来源:server.go

示例13: testJobHandler

func testJobHandler(w http.ResponseWriter, r *http.Request, backend *dbBackend) {
	decoder := json.NewDecoder(r.Body)
	decoder.UseNumber()
	var ent map[string]interface{}
	e := decoder.Decode(&ent)
	if nil != e {
		w.WriteHeader(http.StatusBadRequest)
		io.WriteString(w, e.Error())
		return
	}

	job, e := createJobFromMap(backend, ent)
	if nil != e {
		w.WriteHeader(http.StatusInternalServerError)
		io.WriteString(w, e.Error())
		return
	}

	if args, _ := job.attributes(); args != nil {
		if _, ok := args["content"]; !ok {
			args["content"] = "this is test job message."
		}
	}

	e = job.invokeJob()
	if nil != e {
		w.WriteHeader(http.StatusInternalServerError)
		io.WriteString(w, e.Error())
		return
	}
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, "OK")
	return
}
开发者ID:runner-mei,项目名称:delayed_job,代码行数:34,代码来源:server.go

示例14: countsHandler

func countsHandler(w http.ResponseWriter, r *http.Request, backend *dbBackend) {
	var all_size, failed_size, queued_size, active_size int64
	var e error

	all_size, e = backend.count(nil)
	if nil != e {
		goto failed
	}
	failed_size, e = backend.count(map[string]interface{}{"@failed_at": "[notnull]"})
	if nil != e {
		goto failed
	}
	queued_size, e = backend.count(map[string]interface{}{"@failed_at": nil, "locked_by": nil})
	if nil != e {
		goto failed
	}
	active_size, e = backend.count(map[string]interface{}{"@failed_at": nil, "locked_by": "[notnull]"})
	if nil != e {
		goto failed
	}

	w.Header()["Content-Type"] = []string{"application/json; charset=utf-8"}
	io.WriteString(w, fmt.Sprintf(`{"all":%v,"failed":%v,"active":%v,"queued":%v}`, all_size, failed_size, active_size, queued_size))
	return

failed:
	w.Header()["Content-Type"] = []string{"text/plain; charset=utf-8"}
	w.WriteHeader(http.StatusInternalServerError)
	io.WriteString(w, e.Error())
	return
}
开发者ID:runner-mei,项目名称:delayed_job,代码行数:31,代码来源:server.go

示例15: genToken

// create a csrf token
func (cf *Csrf) genToken(salt, secret string) string {
	h := sha1.New()
	io.WriteString(h, salt)
	io.WriteString(h, "-")
	io.WriteString(h, secret)
	return salt + "-" + base64.StdEncoding.EncodeToString(h.Sum(nil))
}
开发者ID:ot24net,项目名称:uweb,代码行数:8,代码来源:csrf.go


注:本文中的io.WriteString函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。