golang Golang Code Snippets
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang Golang Code Snippets相关的知识,希望对你有一定的参考价值。
func captureOutput(f func()) string {
rescueStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
//var buf bytes.Buffer
//log.SetOutput(&buf)
f()
//log.SetOutput(os.Stdout)
//return buf.String()
w.Close()
out, _ := ioutil.ReadAll(r)
os.Stdout = rescueStdout
return string(out)
}
package main
import "fmt"
type Creature struct {
Name string
Real bool
}
func (c Creature) DumpName() {
fmt.Printf("Name: %s\n", c.Name)
}
func (c Creature) DumpIsReal() {
if c.Real == true {
fmt.Printf("%s is real creature\n", c.Name)
} else {
fmt.Printf("%s is from fiction\n", c.Name)
}
}
type Person struct {
Name string
Real bool
}
func (c Person) DumpName() {
fmt.Printf("Name of person is %s\n", c.Name)
}
func (c Person) DumpIsReal() {
if c.Real == true {
fmt.Printf("%s is real person\n", c.Name)
} else {
fmt.Printf("%s is fictional character\n", c.Name)
}
}
type Creaturing interface {
DumpIsReal()
DumpName()
}
func TestInterface(t Creaturing) {
t.DumpName()
t.DumpIsReal()
}
func main() {
c := Creature{
Name: "Dragon",
Real: false,
}
p := Person{
Name: "Obama",
Real: true,
}
TestInterface(c)
TestInterface(p)
}
package main
import "fmt"
type Creature struct {
Name string
Real bool
}
func (c *Creature) Dump() {
fmt.Printf("Name: '%s', Real: %t\n", c.Name, c.Real)
}
func main() {
myCreature := Creature{
Name: "blah",
Real: true,
}
myCreature.Dump()
}
package main
import "fmt"
type Places struct {
country string
}
type Nation struct {
Places
president string
currency string
lang string
}
type Culture struct {
Places
food string
drink string
festival string
}
func (p *Places) MyCountry() {
fmt.Printf("Country is %s\n", p.country)
}
func (n *Nation) Politics() {
fmt.Printf("%s is president of %s which has %s as currency\n", n.president, n.country, n.currency)
}
func (c *Culture) Celebrate() {
fmt.Printf("People in %s during %s eat %s and drink %s\n", c.country, c.festival, c.food, c.drink)
}
func main() {
t := Nation{Places{"USA"}, "Trump", "dollar", "english"}
b := Culture{Places{"USA"}, "turkey", "wine", "ThanksGiving"}
t.Politics()
b.Celebrate()
t.MyCountry()
b.MyCountry()
}
package geometry
import "fmt"
type Interface interface {
Area() int
Circumference() int
}
func Display(data Interface) {
a := data.Area()
c := data.Circumference()
fmt.Printf("Area of given shape is %d\n", a)
fmt.Printf("Circumference of given shape is %d\n", c)
}
/////////////////////
package main
import (
"fmt"
"github.com/abhsawan/geometry"
)
type Circle struct {
AArea int
CCircumference int
}
func (d *Circle) Area() int {
fmt.Printf("THis is area function for circle\n")
d.AArea = 232
return 232
}
func (d *Circle) Circumference() int {
fmt.Printf("THis is circumference function for circle\n")
d.CCircumference = 2342
return 2342
}
func main() {
data := Circle{}
geometry.Display(&data)
fmt.Println(data)
}
///////////
//THis is area function for circle
//THis is circumference function for circle
//Area of given shape is 232
//Circumference of given shape is 2342
//{232 2342}
/////
package log
import "github.com/abhsawan/log/logger"
import "github.com/abhsawan/log/initialize"
var Logger initialize.MyInterface
func init() {
Logger = logger.Ini()
}
func Debug(v ...interface{}) {
Logger.Debug(v...)
}
func Warn(v ...interface{}) {
Logger.Warn(v...)
}
/////
package initialize
type MyInterface interface {
Debug(v ...interface{})
Warn(v ...interface{})
}
////
package logger
import "fmt"
import "github.com/abhsawan/log/initialize"
type Mylog struct {
initialize.MyInterface
}
func Ini() initialize.MyInterface {
return Mylog{}
}
func (l Mylog) Debug(v ...interface{}) {
fmt.Print("It went through Debug call \n")
fmt.Print(v...)
}
func (l Mylog) Warn(v ...interface{}) {
fmt.Print("It went through Warn call \n")
fmt.Print(v...)
}
////
package main
import "github.com/abhsawan/log"
func main() {
log.Debug("blah\n")
log.Warn("blah blah\n")
}
package main
import (
"fmt"
"os"
"github.com/BurntSushi/toml"
)
type tomlConfig struct {
OAuth struct {
Token string
}
}
func main() {
var config tomlConfig
if _, err := toml.DecodeFile("oauth.toml", &config); err != nil {
fmt.Println(err)
return
}
fmt.Printf("Auth: %s\n", config.OAuth.Token)
var blah tomlConfig
.OAuth.Token = "xxxxxxxxxxxxx"
toml.NewEncoder(os.Stdout).Encode(&tomlConfig.OAuth.Token)
}
package main
import "encoding/json"
import "fmt"
type Response1 struct {
Page int
Fruits []string
}
type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
func main() {
/*
bolB, _ := json.Marshal(true)
fmt.Println(string(bolB))
intB, _ := json.Marshal(1)
fmt.Println(string(intB))
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD)
fmt.Println(string(slcB))
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))
*/
/*
res1D := &Response1{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res1B, _ := json.Marshal(res1D)
fmt.Println(string(res1B))
res2D := &Response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
*/
byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
var dat map[string]interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
}
package main
import "fmt"
func main() {
var map1 = map[string]interface{}{
"A": "a",
"B": "b",
"C": "c",
"D": "d",
"E": "",
"F": nil,
}
var map2 = map[string]interface{}{
"A": "a",
"B": "b",
"C": "c",
"D": "d",
"E": "e",
"F": "f",
}
for k, v := range map2 {
if val, _ := map1[k]; val == "" {
map1[k] = v
}
}
fmt.Println(map1)
}
package main
import "errors"
import "fmt"
type MyError interface {
error
Status() int
}
type StatusError struct {
Code int
Err error
}
func (se StatusError) Error() string {
return se.Err.Error()
}
func (se StatusError) Status() int {
return se.Code
}
func NewE() MyError {
return &StatusError{
Code: 100,
Err: errors.New("Error obj"),
}
}
type Handler struct {
H func() MyError
}
func (h Handler) Call() {
x := h.H()
fmt.Println(x.Error())
fmt.Println(x.Status())
}
func main() {
h := &Handler{NewE}
h.Call()
}
golang Golang code_coverage
// Run your test against your package - this generates your html output cov file
go test -covermode=count -cover -coverprofile=coverage.out ./lib/app/
// This will render the html file with diffs
go tool cover -html=coverage.out
以上是关于golang Golang Code Snippets的主要内容,如果未能解决你的问题,请参考以下文章