GOLANG代码片段集锦

go语言 admin 128℃ 0评论

图片下载存储

import (
	"bytes"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
)
func main() {
    resp, err := http.Get("http://1.png")
	if err != nil {
		log.Println(err)
		return
	}
	body, _ := ioutil.ReadAll(resp.Body)
	out, _ := os.Create("./download/2.png")
	io.Copy(out, bytes.NewReader(body))
}

重写time json格式

import "time"
type Time time.Time
const (
	timeFormart = "2006-01-02 15:04:05"
)
func (t *Time) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
	*t = Time(now)
	return
}
func (t Time) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(timeFormart)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, timeFormart)
	b = append(b, '"')
	return b, nil
}
func (t Time) String() string {
	return time.Time(t).Format(timeFormart)
}

CSV文件解析

    opencast, err := os.Open(filepath)
	if err != nil {
		log.Println("csv文件打开失败!")
	}
	defer opencast.Close()
	//创建csv读取接口实例
	ReadCsv := csv.NewReader(bufio.NewReader(opencast))
	ReadCsv.LazyQuotes = true
	ReadCsv.FieldsPerRecord = -1
	orders := list.New()
	rowIndex := 0
	for {
		read, err := ReadCsv.Read()
 
		if err != nil {
			break
		}
		 log.Println(iconv.ConvertString(read[0], "gb2312", "utf-8"))
	}

转载请注明:我的经验分享 » GOLANG代码片段集锦

喜欢 (0)or分享 (0)

您必须 登录 才能发表评论!