### 日志
**logrus**
```go
package main
import (
"github.com/sirupsen/logrus"
"os"
)
func init() {
logrus.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:04:05",
})
logrus.SetOutput(os.Stdout)
logrus.SetLevel(logrus.InfoLevel)
}
func main() {
logrus.WithFields(logrus.Fields{
"animal": "walrus",
}).Info("A walrus appears")
logrus.Info("hello")
}
```
- 打印效果
```bash
{"animal":"walrus","level":"info","msg":"A walrus appears","time":"2020-11-22 11:34:52"}
{"level":"info","msg":"hello","time":"2020-11-22 11:34:52"}
```
### 定时任务
**robfig**
```go
package main
import (
"fmt"
"github.com/robfig/cron/v3"
"log"
"time"
)
func main() {
TimeTask()
}
// TimeTask 定时任务
// cron.New() 分钟级别定时任务
// cron.New(cron.WithSeconds()) 秒级定时任务
func TimeTask() {
c := cron.New(cron.WithSeconds())
// 定时表
cronTab := "*/3 * * * * ?"
id, err := c.AddFunc(cronTab, task1)
if err != nil {
log.Println(err)
}
//开启任务
c.Start()
//任务id
fmt.Println(id)
time.Sleep(time.Minute * 2) //测试使用
}
// task1 需要执行的任务
func task1() {
now := time.Now().Format("2006-01-02 15:04:05")
fmt.Println("定时任务执行时间", "-->", now)
}
```
### 文件上传
```go
package main
import (
"io"
"io/ioutil"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
const (
MAX_UPLOAD_SIZE = 1024 * 1024 * 20 //50MB
)
func main() {
r := RegisterHandlers()
http.ListenAndServe(":8080", r)
}
//RegisterHandlers ...
func RegisterHandlers() *httprouter.Router {
router := httprouter.New()
router.POST("/upload", uploadHandler)
return router
}
func uploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)
if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
log.Printf("File is too big")
return
}
file, headers, err := r.FormFile("file")
if err != nil {
log.Printf("Error when try to get file: %v", err)
return
}
//获取上传文件的类型
if headers.Header.Get("Content-Type") != "image/png" {
log.Printf("只允许上传png图片")
return
}
data, err := ioutil.ReadAll(file)
if err != nil {
log.Printf("Read file error: %v", err)
return
}
fn := headers.Filename
err = ioutil.WriteFile("./video/"+fn, data, 0666)
if err != nil {
log.Printf("Write file error: %v", err)
return
}
w.WriteHeader(http.StatusCreated)
io.WriteString(w, "Uploaded successfully")
}
```