mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2024-11-25 07:38:57 +00:00
46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
|
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||
|
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||
|
|
||
|
// See page 311.
|
||
|
|
||
|
// Package storage is part of a hypothetical cloud storage server.
|
||
|
//!+main
|
||
|
package storage
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"net/smtp"
|
||
|
)
|
||
|
|
||
|
var usage = make(map[string]int64)
|
||
|
|
||
|
func bytesInUse(username string) int64 { return usage[username] }
|
||
|
|
||
|
// Email sender configuration.
|
||
|
// NOTE: never put passwords in source code!
|
||
|
const sender = "notifications@example.com"
|
||
|
const password = "correcthorsebatterystaple"
|
||
|
const hostname = "smtp.example.com"
|
||
|
|
||
|
const template = `Warning: you are using %d bytes of storage,
|
||
|
%d%% of your quota.`
|
||
|
|
||
|
func CheckQuota(username string) {
|
||
|
used := bytesInUse(username)
|
||
|
const quota = 1000000000 // 1GB
|
||
|
percent := 100 * used / quota
|
||
|
if percent < 90 {
|
||
|
return // OK
|
||
|
}
|
||
|
msg := fmt.Sprintf(template, used, percent)
|
||
|
auth := smtp.PlainAuth("", sender, password, hostname)
|
||
|
err := smtp.SendMail(hostname+":587", auth, sender,
|
||
|
[]string{username}, []byte(msg))
|
||
|
if err != nil {
|
||
|
log.Printf("smtp.SendMail(%s) failed: %s", username, err)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
//!-main
|