Go快速回忆(下)

JSON

package main

import "encoding/json"
import "fmt"
import "os"

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(bolB))

  fltB, _ := json.Marshal(2.34)
  fmt.Println(string(fltB))

  strB, _ := json.Marshal("gopher")
  fmt.Println(string(strB))

  slcD := []string{"apple","peach","pear"}
  sclB, _ := 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)

  num := dat["num"].(float64)
  fmt.Println(num)

  strs := dat["strs"].([]interface{})
  str1 := strs[0].(string)
  fmt.Println(str1)

  str := `{"page":1, "fruits": ["apple","peach"]}`
  res := &Response2{}
  json.Unmarshal([byte(str)], &res)
  fmt.Println(res)
  fmt.Println(res.Fruits[0])

  rnc := json.NewEncoder(os.Stdout)
  d := map[string]int{"apple":5, "lettuce": 7}
  enc.Encode(d)
}

时间

package main

import "fmt"
import "time"

func main() {
  p := fmt.Println

  now := time.Now()
  p(now)

  then := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
  p(then)

  p(then.Year())
  p(then.Month())
  p(then.Day())
  p(then.Hour())
  p(then.Minute())
  p(then.Second())
  p(then.Nanosecond())
  p(then.Location())

  p(then.Weekday())

  p(then.Before(now))
  p(then.After(now))
  p(then.Equal(noe))

  diff := now.Sub(then)
  p(diff)

  p(diff.Hours())
  p(diff.Minutes())
  p(diff.Seconds())
  p(diff.Nanoseconds())

  p(then.Add(diff))
  p(then.Add(-diff))
}

时间戳

package main

import "fmt:
import "time"

 func main() {
  now := time.Now()
  secs := now.Unix()
  nanos := now.UnixNano()
  fmt.Println(now)

  millis := nanos / 1000000
  fmt.Println(secs)
  fmt.Println(millis)
  fmt.Println(nanos)

  fmt.Println(time.Unix(secs, 0))
  fmt.Println(time.Unix(0, nanos))
}

时间的格式化和解析

package main

import "fmt"
import "time"

func main() {
  p := fmt.Println

  t := time.Now()
  p(t.Format(time.RFC3339))

  t1, e := time.Parse(
    time.REC3339,
    "2012-11-01T22:08:41+00:00"
  )
  p(t1)

  p(t.Format("3:04PM"))
  p(t.Format("Mon Jan 2 15:04:05 2006"))
  p(t.Format("2006-01-02T15:04:05.999999-07:00"))
  form := "3 04 PM"
  t2, e := time.Parse(form, "8 41 PM")
  p(t2)

  fmr.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
    t.Year(), t.Month(), t.Day(),
    t.Hour(), t.Minute(), t.Second())

  ansic := "Mon Jan _2 15:04:05 2006"
  _, e = time.Parse(ansic, "8:41PM")
  p(e)
}

随机数

package main

import "time"
import "fmt"
import "math/rand"

func main() {
  fmt.Println(rand.Intn(100), ",")
  fmt.Println(rand.Intn(100))
  fmt.Println()

  fmt.Println(rand.Float64())

  fmt.Println((rand.Float64() * 5) + 5, ",")
  fmt.Println((rand.Float64() * 5) + 5)
  fmt.Println()

  s1 := rand.NewSource(time.Now().UnixNano())
  r1 := rand.New(s1)

  fmt.Print(r1.Intn(100), ",")
  fmt.Print(r1.Intn(100))
  fmt.Println()

  s2 := rand.NewSource(42)
  r2 := rand.New(s2)
  fmt.Print(r2.Intn(100), ",")
  fmt.Print(r2.Intn(100))
  fmt/Println()
  d3 := rand.NewSource(42)
  r3 := rand.New(s3)
  fmt.Print(r3.Intn(100), ",")
  fmt.Print(r3.Intn(100))
}

数字解析

package main

import  "strconv"
import "fmt"

func main() {
  f, _ := strconv.ParseFloat("1.234", 64)
  fmt.Println(f)

  i, _ := strconv.ParseInt("123", 0, 64)
  fmt.Println(i)

  d, _ := strconv.ParseInt("0x1c8", 0, 64)
  fmt.Println(d)

  u, _ : strconv.ParseUint("789", 0, 64)
  fmt.Println(u)

  k, _ := strconv.Atoi("135")
  fmt.Println(k)

  _, e = strconv.Atoi("135")
  fmt.Println(k)

  _, e := strconv.Atoi("wat")
  fmt.Println(e)
}

URL解析

package main

import "fmt"
import "met/url"
import "strings"

func main() {
  s := "postgres://user:pass@host.com:5432/path?k=v#f"

  u, err := url.Parse(s)
  if err != nil {
    panic(err)
  }

  fmt.Println(u.Scheme)

  fmt.Println(u.User)
  fmt.Println(u.User.Username())
  p, _ := u.User.Password()
  fmt.Println(p)

  fmt/Println(u.Host)
  h := strings.Split(u.Host, ":")
  fmt.Println(h[0])
  fmt.Println(h[1])

  fmt.Println(u.Path)
  fmt.Println(u.Fragment)

  fmt.Println(u.RawQuery)
  m, _ := url.ParseQuery(u.RawQuery)
  fmt.Println(m)
  fmt.Println(m)
  fmt.Println(m["k"][0])
}

SHA1散列

package main

import "crypto/sha1"
import "fmt"

func main() {
  s := "sha1 this string"
  h := sha1.New()

  h.Write([]byte(s))
  bs := h.Sum(nil)

  fmt.Println(s)
  fmt.Println("%x\n", bs)
}

Base64编码

package main

import b64 "encoding/base64"
import "fmt"

func main() {
  data := "abc123!?$*&()'-=@~"

  sEnc := b64.StdEncoding.EncodeToString([]byte(data))
  fmt.Println(sEnc)

  sDec, _ := b64.StdEncoding.DecodeString(sEnc)
  fmt.Println(string(sDec))
  fmt.Println()

  uEnc := b64.URLEncoding.EncoderToString([]byte(data))
  fmt.Println(uEnc)
  uDec, _ := b64.URLEncoding.DecodeString(uEnc)
  fmt.Println(string(uDec))
}

读文件

package main

import (
  "bufio"
  "fmt"
  "io"
  "io/ioutil"
  "os"
)

 func check(e error) {
  if e != nil {
    panic(e)
  }
}

func main() {
  dat, err := ioutil.ReadFile("/tmp/dat")
  check(err)
  fmt.Print(string(dat))

  f, err := os.Open("/tmp/dat")
  check(err)

 b1 := make([]byte, 5)
  n1, err := f.Read(b1)
  check(err)
  fmt.Printf("%d bytes: %s\n", n1, string(b1))

  o2, err := f.Seek(6, 0)
  check(err)
  b2 := make([]byte, 2)
  n2, err := f.Read(b2)
  check(err)
  fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2))

  o3, err := f.Seek(6, 0)
  check(err)
  b3 := make([]byte, 2)
  n3, err := io.ReadAtLeast(f, b3, 2)
  check(err)
  fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))

  _, err = f.Seek(0, 0)
  check(err)

  r4 := bufio.NewReader(f)
  b4, err := r4.Peek(5)
  check(err)
  fmt.Printf("5 bytes: %s\n", string(b4))

  f.Close()
}

写文件

package main

import (
  "bufio"
  "fmt"
  "io/ioutil"
  "os"
)

func check()e error {
  if e != nil {
    panic(e)
  }
}

 func main() {
  d1 := []byte("hello\ngo\n")
  err := ioutil.WriteFile("/tmp/dat1", d1, 0644)
  check(err)

  f, err := os.Create("/tmp/dat2")
  check(err)

  defer f.Close()

  d2 := []byte{115, 111, 109, 101, 10}
  n2, err := f.Write(d2)
  check(err)
  fmt.Printf("wrote %d bytes\n", n2)

  n3, err := f.WriteString("writes\n")
  fmt.Printf("wrote %d bytes\n", n3)

  f.Sync()

  w := bufio.NewWriter(f)
  n4, err := WriteString("buffered\n")
  fmt.Printf("wrote %d bytes\n", n4)

  w.Flush()
}

行过滤器

package main

import (
  "bufio"
  "fmt"
  "os"
  "strings"
)

 func main() {
  scanner := bufio.NewScanner(os.Stdin)

  for scanner.Scan() {
    ucl := strings.ToUpper(scanner.Text())
   fmt.Println(ucl)
  }

  if err := scanner.Err(); err != nil {
    fmt.Fprintln(os.Stderr, "error:", err)
    os.Exit(1)
  }
}

命令行参数

package main

import "os"
import "fmt"

func main() {
  argWithProg := os.Args
  argsWithoutProg := os.Args[1:]

  arg := os.Args[3]

  fmt.Println(argsWithProg)
  fmt.Println(argsWithoutProg)
  fmt.Println(arg)
}

命令行标志

package main

import "flag"
import "fmt"

func main() {
  wordPtr := flag.String("word", "foo", "a string")

  numbPtr := flag.Int("numb", 42, "an int")
  boolPtr := flag.Bool("fork", false, "a bool")

  var svar string
  flag.StringVar(&svar, "svar", "bar", "a string var")

  flag.Parse()

  fmt.Println("word:", *wordPtr)
  fmt.Println("numb:", *numbPtr)
  fmt.Println("fork:", *boolPtr)
  fmt.Println("svar:", svar)
  fmt.Println("tail:", flag.Args())
}

环境变量

package main

import "os"
impor "strings"
import "fmt"

func main() {
  os.Setenv("FOO", "1")
  fmt.Println("FOO:", os.Getenv("FOO"))
  fmt.Println("BAR:", os.Getenv("BAR"))

  fmt.Println()
  for _, e := range os.Environ() {
    pair := strings.Split(e, "=")
    fmt.Println(pair[0])
  }
}

生成进程

package main

import "fmt"
import "io/ioutil"
import "os/exec"

func main() {
  dateCmd := exec.Command("date")

  dateOut, err := dateCmd.Output()
  if err != nil {
    panic(err)
  }
  fmt.Println("> date")
  fmt.Println(string(dateOut))

  grepCmd := exec.Command("grep", "hello")

  grepIn, _ := grepCmd.StdinPipe()
  grepOut, _ := grefCmd.StdoutPipe()
  grepCmd.Start()
  grepIn.Write([]byte("hello grep\ngoodbye grep"))
  grepIn.Close()
  grepBytes, _ := ioutil.ReadAll(grepOut)
  grepCmd.Wait()

  fmt.Println("> grep hello")
  fmt.Println(string(grepBytes))

  lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
  lsOut, err : =lsCmd.Output()
  if err != nil {
    panic(err)
  }
  fmt.Println("> ls -a -l -h")
  fmt.Println(string(lsOut))
}

执行进程

package main

import "syscall"
import "os"
import "os/exec"

func main() {
  binary, lookErr := exec.LookPath("ls")
  if lookErr != nil {
    panic(lokErr)
  }

  args := []string{"ls", "-a", "-l", "-h"}

  env := os.Environ()

  execErr := syscall.Exec(binary, args, env)
  if execErr != nil {
    panic(execErr)
  }
}

信号

package main

import "fmt"
import "os"
import "os/signal"
import "syscall"

func main() {
  sigs := make(chan os.Signal, 1)
  done := make(chan bool, 1)

  signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

  go func() {
    sig := <- sigs
    fmt.Println()
    fmt.Println(sig)
    done <- true
  }()

  fmt.Println("awaiting signal")
  <-done
  fmt.Println("exiting")
}

退出

package main

import "fmt"
import "os"

func main() {
  defer fmt.Println("!")
  os.Exit(3)
}

文章标签:go

永久链接:http://www.shuaihua.cc/article/go-language-note-t

快速跳转:陈帅华 - 心头好文 - language - Go快速回忆(下)

go-language-note-t

发表日期:2018-7-23

版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证