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 rolePermissionvar data []RoleGormdb.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企业级开发框架
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/f797343eb04fimport ("fmt""os""strings""github.com/json-iterator/go" // 引入
)type ColorGroup struct {ID intName stringColors []string
}type Animal struct {Name stringOrder 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 []Animalif 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()// ====================其他操作===================// getval := []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 stringfunc (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博客
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))
}