本文整理汇总了Golang中github.com/antonholmquist/jason.NewObjectFromBytes函数的典型用法代码示例。如果您正苦于以下问题:Golang NewObjectFromBytes函数的具体用法?Golang NewObjectFromBytes怎么用?Golang NewObjectFromBytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewObjectFromBytes函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: GetWeather
func GetWeather(city string, state string) {
json_link := fmt.Sprintf("%s/hourly/q/%s/%s.json", API_LINK, state, city)
resp, err := http.Get(json_link)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
v, err := jason.NewObjectFromBytes(body)
if err != nil {
log.Fatal(err)
}
hourlyForecast, err := v.GetObjectArray("hourly_forecast")
if err != nil {
log.Fatal(err)
}
for _, hourCast := range hourlyForecast {
stringhour, _ := hourCast.GetString("FCTTIME", "hour")
temp, _ := hourCast.GetString("temp", "english")
hour, _ := strconv.Atoi(stringhour)
if hour == time.Now().Hour() {
SendWeather(temp)
break
}
}
}
开发者ID:Shadey,项目名称:Leo,代码行数:29,代码来源:main.go
示例2: PollCmds
// Fetch commands
func (s *Client) PollCmds() {
bytes, err := s._get(fmt.Sprintf("client/%s/cmds", url.QueryEscape(s.Id)))
if err == nil {
obj, jerr := jason.NewObjectFromBytes(bytes)
if jerr == nil {
status, statusE := obj.GetString("status")
// Re-auth
if statusE != nil || status != "OK" {
log.Println(string(bytes))
log.Println("Re-authenticate with server")
s.AuthServer()
return
}
// List commands
cmds, _ := obj.GetObjectArray("cmds")
for _, cmd := range cmds {
id, _ := cmd.GetString("Id")
command, _ := cmd.GetString("Command")
signature, _ := cmd.GetString("Signature")
templateId, _ := cmd.GetString("TemplateId")
timeout, _ := cmd.GetInt64("Timeout")
cmd := newCmd(command, int(timeout))
cmd.ClientId = client.Id
cmd.TemplateId = templateId
cmd.Id = id
cmd.Signature = signature
cmd.Execute(s)
}
}
} else {
// In case of fast error back off a bit
time.Sleep(1 * time.Second)
}
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:36,代码来源:client.go
示例3: extractBlogPosts
func extractBlogPosts() map[string]*BlogPost {
outcome := make(map[string]*BlogPost)
rawContent, readErr := ioutil.ReadFile(appConfiguration["saved_data_filename"].StringValue)
if readErr == nil {
json, _ := jason.NewObjectFromBytes(rawContent)
for k1, _ := range json.Map() {
hash := make(map[string]int)
author, _ := json.GetString(k1, "author")
headline, _ := json.GetString(k1, "headline")
date, _ := json.GetInt64(k1, "date")
contentHash, _ := json.GetObject(k1, "contentHash")
brief, _ := json.GetString(k1, "brief")
post := BlogPost{
k1,
author,
headline,
time.Unix(date, 0),
hash,
brief,
}
for k2, v2 := range contentHash.Map() {
n, _ := v2.Int64()
hash[k2] = int(n)
}
outcome[k1] = &post
}
}
return outcome
}
开发者ID:coshx,项目名称:james,代码行数:35,代码来源:blog_post.go
示例4: listContainers
func listContainers() {
response := instainerGet("/containers")
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
check(err)
v, err := jason.NewObjectFromBytes(contents)
data, err := v.GetObject("data")
permanents, err := data.GetObjectArray("permanents")
nonpermanents, err := data.GetObjectArray("nonPermanents")
banner.Print("instainer")
fmt.Println("")
fmt.Println("")
fmt.Println("Permanent Containers")
fmt.Println("")
fmt.Printf("%-32s %-52s %-32s %-24s\n", "CONTAINER ID", "NAME", "IMAGE NAME", "CREATED")
for _, container := range permanents {
containerId, err := container.GetString("id")
name, err := container.GetString("name")
imageName, err := container.GetString("imageName")
createdTime, err := container.GetString("createdTime")
check(err)
fmt.Printf("%-32s %-52s %-32s %-24s\n", containerId, name, imageName, createdTime)
}
fmt.Println("")
fmt.Println("")
fmt.Println("Non-Permanent Containers")
fmt.Println("")
fmt.Printf("%-32s %-52s %-32s %-24s\n", "CONTAINER ID", "NAME", "IMAGE NAME", "CREATED")
for _, container := range nonpermanents {
containerId, err := container.GetString("id")
name, err := container.GetString("name")
imageName, err := container.GetString("imageName")
createdTime, err := container.GetString("createdTime")
check(err)
fmt.Printf("%-32s %-52s %-32s %-24s\n", containerId, name, imageName, createdTime)
}
}
开发者ID:SudeepParajuli,项目名称:instainer,代码行数:55,代码来源:instainer.go
示例5: BenchmarkJasonSmall
func BenchmarkJasonSmall(b *testing.B) {
for i := 0; i < b.N; i++ {
json, _ := jason.NewObjectFromBytes(smallFixture)
json.GetString("uuid")
json.GetFloat64("tz")
json.GetString("ua")
json.GetFloat64("st")
nothing()
}
}
开发者ID:qband,项目名称:down,代码行数:12,代码来源:benchmark_small_payload_test.go
示例6: twitchDecode
func twitchDecode(stream []byte) string {
datajson, _ := jason.NewObjectFromBytes(stream)
game, err := datajson.GetString("stream", "game")
status, err := datajson.GetString("stream", "channel", "status")
url, err := datajson.GetString("stream", "channel", "url")
viewers, err := datajson.GetInt64("stream", "viewers")
streamname, err := datajson.GetString("stream", "channel", "name")
if err != nil {
return "Not Online or API server is down(probably not online)!"
}
return url + " " + streamname + " is online with " + strconv.Itoa(int(viewers)) + " viewers, Playing: " + game + "! " + status + "\n"
}
开发者ID:Vaultpls,项目名称:Telegram-Twitch-Bot,代码行数:14,代码来源:json.go
示例7: GetLanguageConfig
func GetLanguageConfig(lang string) LanguageConfig {
raw, _ := ioutil.ReadFile("./config.json")
decoded, _ := jason.NewObjectFromBytes([]byte(raw))
time, _ := decoded.GetInt64("Languages", lang, "Time")
memory, _ := decoded.GetInt64("Languages", lang, "Memory")
compile, _ := decoded.GetString("Languages", lang, "Compile")
run, _ := decoded.GetString("Languages", lang, "Run")
file, _ := decoded.GetString("FileName")
return LanguageConfig{
Time: time,
Memory: memory,
Compile: compile,
Run: run,
FilePlaceholder: file,
}
}
开发者ID:swapagarwal,项目名称:gojudge,代码行数:16,代码来源:helper.go
示例8: BenchmarkJasonMedium
func BenchmarkJasonMedium(b *testing.B) {
for i := 0; i < b.N; i++ {
json, _ := jason.NewObjectFromBytes(mediumFixture)
json.GetString("person.name.fullName")
json.GetFloat64("person.github.followers")
json.GetObject("company")
arr, _ := json.GetObjectArray("person.gravatar.avatars")
for _, el := range arr {
el.GetString("url")
}
nothing()
}
}
开发者ID:qband,项目名称:down,代码行数:16,代码来源:benchmark_medium_payload_test.go
示例9: main
func main() {
// Use the same library and method we defined before
body := controller.GetHosts("https://sandboxapic.cisco.com")
// Use the JSON library, jason, to do the heavy lifting of creating go objects
v, _ := jason.NewObjectFromBytes(body)
// Since the result is an array of objects, we need to use GetObjectArray()
r, _ := v.GetObjectArray("response")
// Loop over the objects
for _, obj := range r {
// Use the jason library's GetString() method to get the right elements of the
// returned JSON.
//
// Example JSON
// {
// "connectedInterfaceId": "30bb14c1-8fb6-45c4-8f6d-5b845a7f448c",
// "connectedInterfaceName": "GigabitEthernet2/0/2",
// "connectedNetworkDeviceId": "7895a45f-47aa-42ee-9d06-c66d3b784594",
// "connectedNetworkDeviceIpAddress": "40.0.2.18",
// "hostIp": "40.0.5.12",
// "hostMac": "00:50:56:8A:27:A3",
// "hostType": "WIRED",
// "id": "8f41bef8-698c-4701-af14-471e910ed9ff",
// "lastUpdated": "September 29, 2014 1:54:13 PM PDT",
// "numUpdates": 1,
// "source": 200,
// "userStatus": "Active",
// "vlanId": "1"
// }
iFace, err := obj.GetString("connectedInterfaceId")
deviceType, err := obj.GetString("hostType")
log.Println("id: " + iFace + " type: " + deviceType)
if err != nil {
log.Println(err)
}
}
}
开发者ID:CiscoDevNet,项目名称:coding-skills-go,代码行数:45,代码来源:learning-labs-basics-step2.go
示例10: jsonDecode
func jsonDecode(data []byte) int {
updateidreturn := 1
datajson, _ := jason.NewObjectFromBytes(data)
result, _ := datajson.GetObjectArray("result")
for _, results := range result {
userid, _ := results.GetInt64("message", "from", "id")
chatid, _ := results.GetInt64("message", "chat", "id")
updateid, _ := results.GetInt64("update_id")
text, _ := results.GetString("message", "text")
username, _ := results.GetString("message", "from", "username")
firstname, _ := results.GetString("message", "from", "first_name")
lastname, _ := results.GetString("message", "from", "last_name")
fmt.Printf("[%d/%d]%s %s(%s): %s\n", userid, chatid, firstname, lastname, username, text)
go interpret(int(chatid), text)
updateidreturn = int(updateid)
}
return updateidreturn
}
开发者ID:Vaultpls,项目名称:Telegram-Twitch-Bot,代码行数:19,代码来源:json.go
示例11: FBLogin
func FBLogin(w http.ResponseWriter, r *http.Request) {
// grab the code fragment
w.Header().Set("Content-Type", "text/html; charset=utf-8")
code := r.FormValue("code")
ClientId := "137453133278122" // change this to yours
ClientSecret := "ee16109c966f12014bbcfccb4547813c"
RedirectURL := "http://localhost:8080/FBLogin"
accessToken := GetAccessToken(ClientId, code, ClientSecret, RedirectURL)
response, err := http.Get("https://graph.facebook.com/me?fields=id,email,first_name,last_name&access_token=" + accessToken.Token)
// handle err. You need to change this into something more robust
// such as redirect back to home page with error message
if err != nil {
w.Write([]byte(err.Error()))
}
str := readHttpBody(response)
//fmt.Println(str)
// dump out all the data
// w.Write([]byte(str))
// see https://www.socketloop.com/tutorials/golang-process-json-data-with-jason-package
user, _ := jason.NewObjectFromBytes([]byte(str))
id, _ := user.GetString("id")
email, _ := user.GetString("email")
fbFirstName, _ := user.GetString("first_name")
fbLastName, _ := user.GetString("last_name")
w.Write([]byte(fmt.Sprintf("Username %s %s ID is %s and email is %s<br>", fbFirstName, fbLastName, id, email)))
img := "https://graph.facebook.com/" + id + "/picture?width=180&height=180"
//w.Write([]byte("Photo is located at " + img + "<br>"))
// see https://www.socketloop.com/tutorials/golang-download-file-example on how to save FB file to disk
w.Write([]byte("<img src='" + img + "'>"))
}
开发者ID:pavanchokshi,项目名称:GO,代码行数:42,代码来源:FBoAuth.go
示例12: PingServer
// Ping server
func (s *Client) PingServer() {
bytes, e := s._get(fmt.Sprintf("client/%s/ping?tags=%s&hostname=%s", url.QueryEscape(s.Id), url.QueryEscape(strings.Join(conf.GetTags(), ",")), url.QueryEscape(s.Hostname)))
if e == nil {
obj, jerr := jason.NewObjectFromBytes(bytes)
if jerr == nil {
status, statusE := obj.GetString("status")
serverInstanceId, _ := obj.GetString("server_instance_id")
// Ping failed, re-authenticate
if statusE != nil || status != "OK" {
log.Println(string(bytes))
log.Println("Re-authenticate with server")
s.AuthServer()
} else {
// Only log a connect if the instance ID changed
if len(s.ConnectedServerInstanceId) == 0 || s.ConnectedServerInstanceId != serverInstanceId {
s.ConnectedServerInstanceId = serverInstanceId
log.Println(fmt.Sprintf("Client registered with server %s", s.ConnectedServerInstanceId))
}
}
}
}
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:24,代码来源:client.go
示例13: AuthServer
// Auth server, token is used for verifying commands
// @todo This function needs more logging in failure scenarios
func (s *Client) AuthServer() {
b, e := s._req("POST", fmt.Sprintf("client/%s/auth", url.QueryEscape(s.Id)), nil)
if e == nil {
obj, jerr := jason.NewObjectFromBytes(b)
if jerr == nil {
// Get signature
token, et := obj.GetString("token")
if et != nil || len(token) < 1 {
return
}
// Get token signatur
tokenSignature, ets := obj.GetString("token_signature")
if ets != nil || len(tokenSignature) < 1 {
return
}
// Verify token signature with our secure token
hasher := sha256.New()
hasher.Write([]byte(token))
hasher.Write([]byte(conf.Token))
expectedTokenSignature := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
// The same?
if tokenSignature != expectedTokenSignature {
log.Println("ERROR! Token signature from server is invalid, communication between server and client might be tampered with")
return
}
// Store token if it is valid
s.mux.Lock()
s.AuthToken = token
s.mux.Unlock()
log.Printf("Client authenticated with server")
}
}
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:39,代码来源:client.go
示例14: parseWhere
func (f *Filter) parseWhere(str string) (err error) {
where := &Where{}
f.where = where
if str == "" {
return
}
root, err := jason.NewObjectFromBytes([]byte(str))
if err != nil {
fmt.Println("parse json failed")
return err
}
oa, _ := root.GetObjectArray("$or")
if oa == nil {
c, err := parseCondition(root)
if err != nil {
fmt.Println("parseCondition failed")
return err
}
*where = append(*where, c)
} else {
for _, o := range oa {
c, err := parseCondition(o)
if err != nil {
fmt.Println("parseCondition failed")
return err
}
*where = append(*where, c)
}
}
return nil
}
开发者ID:aiyi,项目名称:go,代码行数:37,代码来源:where.go
示例15:
BeforeEach(func() {
ImportHoverflyRecords(jsonRequestResponsePair1)
ImportHoverflyRecords(jsonRequestResponsePair2)
ImportHoverflyRecords(jsonRequestResponsePairTemplate)
SetHoverflyResponseDelays("testdata/delays.json")
})
It("Should get all the Hoverfly simulation data in one JSON file", func() {
req := sling.New().Get(hoverflyAdminUrl + "/api/v2/simulation")
res := DoRequest(req)
Expect(res.StatusCode).To(Equal(200))
responseJson, err := ioutil.ReadAll(res.Body)
Expect(err).To(BeNil())
jsonObject, err := jason.NewObjectFromBytes(responseJson)
Expect(err).To(BeNil())
metaObject, err := jsonObject.GetObject("meta")
Expect(err).To(BeNil())
schemaVersion, err := metaObject.GetString("schemaVersion")
Expect(err).To(BeNil())
Expect(schemaVersion).To(Equal("v1"))
hoverflyVersion, err := metaObject.GetString("hoverflyVersion")
Expect(err).To(BeNil())
Expect(hoverflyVersion).ToNot(BeNil())
timeExported, err := metaObject.GetString("timeExported")
Expect(err).To(BeNil())
Expect(timeExported).ToNot(BeNil())
dataObject, err := jsonObject.GetObject("data")
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:30,代码来源:ft_api_test.go
示例16: main
func main() {
// Get mongo url from config.json, otherwise default to 127.0.0.1
mongo := "127.0.0.1"
bitcannonPort := "1337"
bitcannonBindIp := "0.0.0.0"
f, err := ioutil.ReadFile("config.json")
if err != nil {
log.Println("[!!!] Config not loaded")
} else {
json, err := jason.NewObjectFromBytes(f)
if err == nil {
// Get mongo connection details
val, err := json.GetString("mongo")
if err == nil {
mongo = val
}
// Get desired port
val, err = json.GetString("bitcannonPort")
if err == nil {
bitcannonPort = val
}
// Get archive sources
arc, err := json.GetObjectArray("archives")
if err == nil {
archives = arc
}
// Get trackers
trac, err := json.GetStringArray("trackers")
if err == nil {
trackers = trac
}
// Get scraping enabled
scrape, err := json.GetBoolean("scrapeEnabled")
if err == nil {
config.ScrapeEnabled = scrape
}
// Get scrape delay
scrapeDelay, err := json.GetInt64("scrapeDelay")
if err == nil {
config.ScrapeDelay = int(scrapeDelay)
}
// Get desired listening host
val, err = json.GetString("bitcannonBindIp")
if err == nil {
bitcannonBindIp = val
}
}
}
// Try to connect to the database
log.Println("[OK!] Connecting to Mongo at " + mongo)
torrentDB, err = NewTorrentDB(mongo)
if err != nil {
log.Println("[ERR] I'm sorry! I Couldn't connect to Mongo.")
log.Println(" Please make sure it is installed and running.")
return
}
defer torrentDB.Close()
if len(os.Args) > 1 {
importFile(os.Args[1])
enterExit()
} else {
runServer(bitcannonPort, bitcannonBindIp)
}
}
开发者ID:unrealord,项目名称:bitcannon,代码行数:65,代码来源:bitcannon.go
示例17: createContainer
func createContainer(dockerName string, volumeRequest []string, envVariables []string) {
m := &RunParams{VolumeRequests: volumeRequest, EnvVariables: envVariables}
b, err := json.Marshal(m)
response := instainerPost("/container/run?image="+dockerName, string(b))
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
check(err)
v, err := jason.NewObjectFromBytes(contents)
data, err := v.GetObject("data")
username, err := data.GetString("gitUser")
password, err := data.GetString("gitPassword")
banner.Print("instainer")
fmt.Println("")
fmt.Println("")
color.Green("------------Git Information------------")
color.Yellow("Git User = %s", username)
color.Yellow("Git Password = %s", password)
fmt.Println("")
fmt.Println("")
color.Green("----------Volumes Information----------")
volumes, err := data.GetObjectArray("volumes")
for _, volume := range volumes {
mntDir, err := volume.GetString("mntDir")
gitUrl, err := volume.GetString("gitUrl")
check(err)
color.Blue(" %s", mntDir)
color.Yellow(" Git URL = %s", gitUrl)
fmt.Println("")
}
fmt.Println("")
color.Green("------------Port Information------------")
ports, err := data.GetObjectArray("ports")
for _, port := range ports {
dockerPort, err := port.GetString("dockerPort")
instainerPort, err := port.GetString("instainerPort")
check(err)
color.Blue(" Container Port %s", dockerPort)
color.Yellow(" Instainer Port instainer.io:%s", instainerPort)
fmt.Println("")
}
fmt.Println("")
envVariablesData, err := data.GetStringArray("envVariables")
if len(envVariablesData) > 0 {
color.Green("---------Environment Variables----------")
for _, variable := range envVariablesData {
color.Yellow(" Variable=Value = %s", variable)
}
}
fmt.Println("")
fmt.Println("")
fmt.Println("Successfully deployed!")
fmt.Println("")
fmt.Println("")
check(err)
}
开发者ID:SudeepParajuli,项目名称:instainer,代码行数:69,代码来源:instainer.go
示例18: ServeHTTP
func (srv *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
if req.Method != "POST" {
msg := "Github hook request is POST only"
http.Error(w, msg, http.StatusMethodNotAllowed)
fmt.Println(msg)
return
}
if req.URL.Path != srv.Path {
msg := "Invalid Path"
http.Error(w, msg, http.StatusNotFound)
fmt.Println(msg)
return
}
eventType := req.Header.Get("X-GitHub-Event")
if eventType != "push" && eventType != "pull_request" {
w.Write([]byte(fmt.Sprintf("Evernt Type %s is not supported", eventType)))
return
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(w, "Fail to read req.Body", http.StatusBadRequest)
}
if srv.Secret != "" {
sig := req.Header.Get("X-Hub-Signature")
if sig == "" {
http.Error(w, "Missing X-Hub-Signature", http.StatusForbidden)
return
}
mac := hmac.New(sha1.New, []byte(srv.Secret))
mac.Write(body)
expected := "sha1=" + hex.EncodeToString(mac.Sum(nil))
// hmac Equal won't leak through timing side-channel
if !hmac.Equal([]byte(expected), []byte(sig)) {
http.Error(w, "Secret not match", http.StatusForbidden)
return
}
}
request, err := jason.NewObjectFromBytes(body)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// https://developer.github.com/v3/activity/events/types/#pushevent
// (*jason.Object)(0xc20803b590)({"added":["test.go"],"author":{"email":"[email protected]","name":"naituida","username":"dyzz"},"committer":{"email":"[email protected]","name":"naituida","username":"dyzz"},"distinct":true,"id":"76fa79bab843450020bd73fbba0b30741f99055f","message":"init push","modified":[],"removed":[],"timestamp":"2015-09-11T02:22:02-04:00","url":"https://github.com/dyzz/gothubhook/commit/76fa79bab843450020bd73fbba0b30741f99055f"}) }
var log string
if eventType == "push" {
repo, _ := request.GetString("repository", "name")
ref, _ := request.GetString("ref")
chunks := strings.Split(ref, "/")
branch := chunks[len(chunks)-1]
commits, _ := request.GetObjectArray("commits")
for _, commit := range commits {
author, _ := commit.GetString("author", "name")
msg, _ := commit.GetString("message")
date, _ := commit.GetString("timestamp")
event := NewEvent(author, repo, branch, "commit", msg, date, "push")
log = event.String()
w.Write([]byte(log))
}
}
// https://developer.github.com/v3/activity/events/types/#pullrequestevent
if eventType == "pull_request" {
action, _ := request.GetString("action")
number, _ := request.GetInt64("number")
pq, _ := request.GetObject("pull_request")
msg, _ := pq.GetString("title")
date, _ := pq.GetString("updated_at")
author, _ := pq.GetString("user", "login")
repo, _ := request.GetString("repository", "name")
event := NewEvent(author, repo, "#"+strconv.Itoa(int(number)), action, msg, date, "pullrequest")
log = event.String()
w.Write([]byte(log))
}
fmt.Println(log)
AppendLog(log)
}
开发者ID:dyzz,项目名称:gothubhook,代码行数:91,代码来源:main.go
示例19: reqWithBufferio
func reqWithBufferio(conn *net.TCPConn, data string, times int) {
req_ready_byte, _ := protocol.Packet(data)
conn.Write(req_ready_byte)
var i int
i = 0
sid := ""
str := `{ "cmd":"socket.getSession"}`
reader := bufio.NewReader(conn)
for {
msg, err := reader.ReadString('\n')
if err != nil {
fmt.Println(conn.RemoteAddr().String(), " connection error: ", err)
conn.Close()
return
}
if msg == "" {
continue
}
msg_json, errjson := jason.NewObjectFromBytes([]byte(msg))
if errjson != nil {
//fmt.Println( " errjson :", errjson.Error() )
continue
}
cmd, _ := msg_json.GetString("cmd")
//fmt.Printf( " msg: %s\n", msg )
if cmd == "socket.user_login" {
sid, _ = msg_json.GetString("data")
//fmt.Printf( " sid: %s\n", sid )
str = fmt.Sprintf(`{ "cmd":"socket.getSession","params":{"sid":"%s"} }`, sid)
session_req_byte, _ := protocol.Packet(str)
conn.Write(session_req_byte)
//time.Sleep(10 * time.Millisecond )
checkError(err)
}
if cmd == "socket.getSession" && sid != "" {
// session_str, _ := msg_json.GetString("data" )
//session_json, _ := jason.NewObjectFromBytes( []byte(session_str) )
//sid ,_= session_json.GetString("msg","Sid")
//fmt.Printf( " sid: %s\n", sid )
str = fmt.Sprintf(`{ "cmd":"socket.getSession","params":{"sid":"%s"} }`, sid)
session_req_byte, _ := protocol.Packet(str)
conn.Write(session_req_byte)
checkError(err)
i++
time.Sleep(10 * time.Millisecond)
if i > times {
conn.Close()
fmt.Println(" i : ", i)
fmt.Println(" conn close! ", i, "\n")
break
}
}
}
conn.Close()
}
开发者ID:weichaoduo,项目名称:zeromore,代码行数:65,代码来源:cc.go
示例20: reqWithJson
func reqWithJson(conn *net.TCPConn, data string, times int) {
_, err := conn.Write([]byte(data + "\n"))
checkError(err)
var i int
i = 0
sid := ""
str := `{ "cmd":"socket.getSession"}`
d := json.NewDecoder(conn)
for {
var msg interface{}
err := d.Decode(&msg)
if err != nil {
conn.Close()
fmt.Println("d.Decode(&msg) ", err.Error())
break
}
json_encode, err_encode := json.Marshal(msg)
if err_encode != nil {
fmt.Println("json.Marshal error:", err_encode.Error())
conn.Close()
break
}
response_str := string(json_encode)
//fmt.Printf( " response: %s\n", response_str )
msg_json, errjson := jason.NewObjectFromBytes([]byte(response_str))
checkError(errjson)
cmd, _ := msg_json.GetString("cmd")
//fmt.Printf( " cmd: %s\n", cmd )
if cmd == "socket.user_login" {
sid, _ = msg_json.GetString("data", "sid")
//fmt.Printf( " sid: %s\n", sid )
str = fmt.Sprintf(`{ "cmd":"socket.getSession","params":{"sid":"%s"} }`, sid)
str = str + "\n"
//fmt.Println( " post : ", str )
_, err = conn.Write([]byte(str))
//time.Sleep(10 * time.Millisecond )
checkError(err)
}
if cmd == "socket.getSession" {
_, err = conn.Write([]byte(str + "\n"))
checkError(err)
i++
time.Sleep(10 * time.Millisecond)
if i >= times {
//conn.Close()
fmt.Println(" i : ", i)
fmt.Println(" conn close! ", i, "\n")
break
}
}
//ch <- &SocketResponse{ data, string(response_str), err}
}
//conn.Close()
}
开发者ID:weichaoduo,项目名称:zeromore,代码行数:62,代码来源:cc.go
注:本文中的github.com/antonholmquist/jason.NewObjectFromBytes函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论