方法的回调线程
func MqMethodInit(ipPort string, groupName string, topic string, callback func(topic string, msg string)) {
time.Sleep(2 * time.Second)
Topic := "topic1"
Body := []byte("线程回调处理")
go callback(Topic, string(Body))
fmt.Println("Rocketmq Consumer 初始化成功")
}
func UpOnofflineCallback(topic string, msg string) {
fmt.Printf("%v:%+v \n", topic, msg)
}
func TestPageName(t *testing.T) {
MqMethodInit("1", "groupName", "topic", UpOnofflineCallback)
}
1.对象的创建和使用
type Role struct {
Id string `json:"Id"`
RoleName string `json:"RoleName"`
State uint `json:"State"`
}
var u = new(Role)
var role Role
var data []Role
structObj := Role{}
2.对象和orm的使用
func TestSelectOne(t *testing.T) {
//query := "sn" + " = ?"
var u = new(Role)
Gormdb.Table("role").Where("role_id", int64(1)).Find(&u)
b, err := jsoniter.Marshal(u)
datajsonx, err := json.Marshal(u)
if err != nil {
fmt.Println("json marshal failed")
return
}
fmt.Println("===", string(datajsonx), "==", string(b))
fmt.Printf("%#v\n", u)
var result = new(Role)
Gormdb.Raw("SELECT role_id as Id, role_name as RoleName FROM role WHERE role_id = ?", int64(1)).Scan(&result)
bx, _ := jsoniter.Marshal(result)
fmt.Printf(string(bx))
}
2.集合的查询
GORM 指南 | 入门指南 |《GORM 中文文档 v2》| Go 技术论坛
func TestSelelctList(t *testing.T) {
//创建一个对象
//var role Role
//Gormdb.AutoMigrate(&Role{})
//var roleId rolePermission
var data []Role
Gormdb.Table("role").Select("role_name").Where("role_id", int64(1)).Find(&data) //.Scan(&roleId)
b, _ := jsoniter.Marshal(data)
fmt.Println(data, "==", string(b))
Gormdb.Exec("update role set `state`=0 where role_id=1")
Gormdb.Exec("update role set `state`=1 where role_id=1")
//Gormdb.Table("role").Update("state", 0).Where("role_id", int64(1))
/*Gormdb.First(&role, 1) // 根据整型主键查找
//创建一个对象
structObj := Role{}
strKeys, err := utilsJson.Struct2KeysStr(structObj)
if err != nil {
fmt.Println("Error")
}
query := "id = ?"
find := Gormdb.Select(strKeys).Where(query, "超级管理员").Find(&structObj)
fmt.Println(find)
fmt.Println("=========")*/
}
3.对象的创建
GoFrame gmap遍历hashmap listmap treemap使用技巧_Golang_脚本之家
m := gmap.New()
// 创建并发安全的int类型数组
a := garray.NewIntArray(true)
4.时间的工具类
HTTPClient-基本使用 - GoFrame (ZH)-Latest - GoFrame官网 - 类似PHP-Laravel, Java-SpringBoot的Go企业级开发框架文章来源地址https://www.toymoban.com/news/detail-848234.html
t := gtime.Now()
// 通过时间字符串创建
gtime.New("2020-10-24 12:00:00")
// 通过time.Time对象创建
gtime.New(time.Now())
// 去年今日,系统时间
fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d"))
// 去年今日,UTC时间
fmt.Println(gtime.Now().AddDate(-1, 0, 0).Format("Y-m-d H:i:s T"))
fmt.Println(gtime.Now().AddDate(-1, 0, 0).UTC().Format("Y-m-d H:i:s T"))
// 下个月1号凌晨0点整
fmt.Println(gtime.Now().AddDate(0, 1, 0).Format("Y-m-01 00:00:00"))
// 1个小时前
fmt.Println(gtime.Now().Add(-time.Hour).Format("Y-m-d H:i:s"))
gt1 := gtime.New("2018-08-08 08:08:08")
fmt.Println(gt1.Format("Y-m-d"))
fmt.Println(gt1.Format("l"))
fmt.Println(gt1.Format("F j, Y, g:i a"))
fmt.Println(gt1.Format("j, n, Y"))
fmt.Println(gt1.Format("h-i-s, j-m-y, it is w Day z"))
fmt.Println(gt1.Format("D M j G:i:s T Y"))
5.json转换
package utils
//https://www.jianshu.com/p/f797343eb04f
import (
"fmt"
"os"
"strings"
"github.com/json-iterator/go" // 引入
)
type ColorGroup struct {
ID int
Name string
Colors []string
}
type Animal struct {
Name string
Order string
}
func test01() {
// ================= 序列化 =====================
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := jsoniter.Marshal(group)
bb, err := jsoniter.MarshalIndent(group, "", " ")
if err != nil {
fmt.Println("error: ", err)
}
os.Stdout.Write(b)
fmt.Println()
os.Stdout.Write(bb)
fmt.Println()
// =================== Deconde 解码 =================
jsoniter.NewDecoder(os.Stdin).Decode(&group)
fmt.Println(group)
//encoder := jsoniter.NewEncoder(os.Stdout)
//encoder.SetEscapeHTML(true)
//encoder.Encode(bb)
//fmt.Println(string(bb))
// =================== 反序列化 =======================
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
var animals []Animal
if err := jsoniter.Unmarshal(jsonBlob, &animals); err != nil {
fmt.Println("error: ", err)
}
fmt.Printf("the unmarshal is %+v", animals)
// ======================= 流式 ========================
fmt.Println()
// 序列化
stream := jsoniter.ConfigFastest.BorrowStream(nil)
defer jsoniter.ConfigFastest.ReturnStream(stream)
stream.WriteVal(group)
if stream.Error != nil {
fmt.Println("error: ", stream.Error)
}
os.Stdout.Write(stream.Buffer())
fmt.Println()
// 反序列化
iter := jsoniter.ConfigFastest.BorrowIterator(jsonBlob)
defer jsoniter.ConfigFastest.ReturnIterator(iter)
iter.ReadVal(&animals)
if iter.Error != nil {
fmt.Println("error: ", iter.Error)
}
fmt.Printf("%+v", animals)
fmt.Println()
// ====================其他操作===================
// get
val := []byte(`{"ID":1,"Name":"Reds","Colors":
{"c":"Crimson","r":"Red","rb":"Ruby","m":"Maroon","tests":["tests_1","tests_2","tests_3","tests_4"]}}`)
fmt.Println(jsoniter.Get(val, "Colors").ToString())
fmt.Println("the result is ", jsoniter.Get(val, "Colors", "tests", 0).ToString())
// fmt.Println(jsoniter.Get(val, "colors", 0).ToString())
fmt.Println()
hello := MyKey("hello")
output, _ := jsoniter.Marshal(map[*MyKey]string{&hello: "world"})
fmt.Println(string(output))
obj := map[*MyKey]string{}
jsoniter.Unmarshal(output, &obj)
for k, v := range obj {
fmt.Println(*k, " = ", v)
}
}
// 自定义类型
// 序列化: 需要实现MarshellText
type MyKey string
func (m *MyKey) MarshalText() ([]byte, error) {
// return []byte(string(*m)) , nil // 针对序列化的内容不做任何调整
return []byte(strings.Replace(string(*m), "h", "H", -1)), nil
}
func (m *MyKey) UnmarshalText(text []byte) error {
*m = MyKey(text[:]) // 针对text不做处理
return nil
}
6.get、post
go语言http请求(一)_go http import-CSDN博客
GO 发起HTTP请求调用接口_go-http-client/1.1-CSDN博客文章来源:https://www.toymoban.com/news/detail-848234.html
HTTPClient-基本使用 - GoFrame (ZH)-Latest - GoFrame官网 - 类似PHP-Laravel, Java-SpringBoot的Go企业级开发框架
import (
"fmt"
"net/http"
"io/ioutil"
)
func main(){
response,err := http.Get("http://www.baidu.com")
if(err!=nil){
fmt.Println(err)
}
defer response.Body.Close()
body,err := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}
到了这里,关于go对象的创建和使用 orm map对象和List 时间 json get/post请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!