1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 07:10:55 +00:00

golint toolbox

This commit is contained in:
astaxie 2015-09-12 23:28:24 +08:00
parent be7accc94c
commit 1d200da472
4 changed files with 68 additions and 67 deletions

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// toolbox healthcheck // Package toolbox healthcheck
// //
// type DatabaseCheck struct { // type DatabaseCheck struct {
// } // }
@ -33,12 +33,12 @@ package toolbox
// health checker map // health checker map
var AdminCheckList map[string]HealthChecker var AdminCheckList map[string]HealthChecker
// health checker interface // HealthChecker health checker interface
type HealthChecker interface { type HealthChecker interface {
Check() error Check() error
} }
// add health checker with name string // AddHealthCheck add health checker with name string
func AddHealthCheck(name string, hc HealthChecker) { func AddHealthCheck(name string, hc HealthChecker) {
AdminCheckList[name] = hc AdminCheckList[name] = hc
} }

View File

@ -34,7 +34,7 @@ func init() {
pid = os.Getpid() pid = os.Getpid()
} }
// parse input command string // ProcessInput parse input command string
func ProcessInput(input string, w io.Writer) { func ProcessInput(input string, w io.Writer) {
switch input { switch input {
case "lookup goroutine": case "lookup goroutine":
@ -58,7 +58,7 @@ func ProcessInput(input string, w io.Writer) {
} }
} }
// record memory profile in pprof // MemProf record memory profile in pprof
func MemProf(w io.Writer) { func MemProf(w io.Writer) {
filename := "mem-" + strconv.Itoa(pid) + ".memprof" filename := "mem-" + strconv.Itoa(pid) + ".memprof"
if f, err := os.Create(filename); err != nil { if f, err := os.Create(filename); err != nil {
@ -74,7 +74,7 @@ func MemProf(w io.Writer) {
} }
} }
// start cpu profile monitor // GetCPUProfile start cpu profile monitor
func GetCPUProfile(w io.Writer) { func GetCPUProfile(w io.Writer) {
sec := 30 sec := 30
filename := "cpu-" + strconv.Itoa(pid) + ".pprof" filename := "cpu-" + strconv.Itoa(pid) + ".pprof"
@ -92,7 +92,7 @@ func GetCPUProfile(w io.Writer) {
fmt.Fprintf(w, "Now you can use this to check it: go tool pprof %s %s\n", fl, filename) fmt.Fprintf(w, "Now you can use this to check it: go tool pprof %s %s\n", fl, filename)
} }
// print gc information to io.Writer // PrintGCSummary print gc information to io.Writer
func PrintGCSummary(w io.Writer) { func PrintGCSummary(w io.Writer) {
memStats := &runtime.MemStats{} memStats := &runtime.MemStats{}
runtime.ReadMemStats(memStats) runtime.ReadMemStats(memStats)

View File

@ -22,7 +22,7 @@ import (
// Statistics struct // Statistics struct
type Statistics struct { type Statistics struct {
RequestUrl string RequestURL string
RequestController string RequestController string
RequestNum int64 RequestNum int64
MinTime time.Duration MinTime time.Duration
@ -30,21 +30,21 @@ type Statistics struct {
TotalTime time.Duration TotalTime time.Duration
} }
// UrlMap contains several statistics struct to log different data // URLMap contains several statistics struct to log different data
type UrlMap struct { type URLMap struct {
lock sync.RWMutex lock sync.RWMutex
LengthLimit int //limit the urlmap's length if it's equal to 0 there's no limit LengthLimit int //limit the urlmap's length if it's equal to 0 there's no limit
urlmap map[string]map[string]*Statistics urlmap map[string]map[string]*Statistics
} }
// add statistics task. // AddStatistics add statistics task.
// it needs request method, request url, request controller and statistics time duration // it needs request method, request url, request controller and statistics time duration
func (m *UrlMap) AddStatistics(requestMethod, requestUrl, requestController string, requesttime time.Duration) { func (m *URLMap) AddStatistics(requestMethod, requestURL, requestController string, requesttime time.Duration) {
m.lock.Lock() m.lock.Lock()
defer m.lock.Unlock() defer m.lock.Unlock()
if method, ok := m.urlmap[requestUrl]; ok { if method, ok := m.urlmap[requestURL]; ok {
if s, ok := method[requestMethod]; ok { if s, ok := method[requestMethod]; ok {
s.RequestNum += 1 s.RequestNum++
if s.MaxTime < requesttime { if s.MaxTime < requesttime {
s.MaxTime = requesttime s.MaxTime = requesttime
} }
@ -54,14 +54,14 @@ func (m *UrlMap) AddStatistics(requestMethod, requestUrl, requestController stri
s.TotalTime += requesttime s.TotalTime += requesttime
} else { } else {
nb := &Statistics{ nb := &Statistics{
RequestUrl: requestUrl, RequestURL: requestURL,
RequestController: requestController, RequestController: requestController,
RequestNum: 1, RequestNum: 1,
MinTime: requesttime, MinTime: requesttime,
MaxTime: requesttime, MaxTime: requesttime,
TotalTime: requesttime, TotalTime: requesttime,
} }
m.urlmap[requestUrl][requestMethod] = nb m.urlmap[requestURL][requestMethod] = nb
} }
} else { } else {
@ -70,7 +70,7 @@ func (m *UrlMap) AddStatistics(requestMethod, requestUrl, requestController stri
} }
methodmap := make(map[string]*Statistics) methodmap := make(map[string]*Statistics)
nb := &Statistics{ nb := &Statistics{
RequestUrl: requestUrl, RequestURL: requestURL,
RequestController: requestController, RequestController: requestController,
RequestNum: 1, RequestNum: 1,
MinTime: requesttime, MinTime: requesttime,
@ -78,18 +78,18 @@ func (m *UrlMap) AddStatistics(requestMethod, requestUrl, requestController stri
TotalTime: requesttime, TotalTime: requesttime,
} }
methodmap[requestMethod] = nb methodmap[requestMethod] = nb
m.urlmap[requestUrl] = methodmap m.urlmap[requestURL] = methodmap
} }
} }
// put url statistics result in io.Writer // GetMap put url statistics result in io.Writer
func (m *UrlMap) GetMap() map[string]interface{} { func (m *URLMap) GetMap() map[string]interface{} {
m.lock.RLock() m.lock.RLock()
defer m.lock.RUnlock() defer m.lock.RUnlock()
var fields = []string{"requestUrl", "method", "times", "used", "max used", "min used", "avg used"} var fields = []string{"requestUrl", "method", "times", "used", "max used", "min used", "avg used"}
resultLists := make([][]string, 0) var resultLists [][]string
content := make(map[string]interface{}) content := make(map[string]interface{})
content["Fields"] = fields content["Fields"] = fields
@ -111,9 +111,10 @@ func (m *UrlMap) GetMap() map[string]interface{} {
return content return content
} }
func (m *UrlMap) GetMapData() []map[string]interface{} { // GetMapData return all mapdata
func (m *URLMap) GetMapData() []map[string]interface{} {
resultLists := make([]map[string]interface{}, 0) var resultLists []map[string]interface{}
for k, v := range m.urlmap { for k, v := range m.urlmap {
for kk, vv := range v { for kk, vv := range v {
@ -133,10 +134,10 @@ func (m *UrlMap) GetMapData() []map[string]interface{} {
} }
// global statistics data map // global statistics data map
var StatisticsMap *UrlMap var StatisticsMap *URLMap
func init() { func init() {
StatisticsMap = &UrlMap{ StatisticsMap = &URLMap{
urlmap: make(map[string]map[string]*Statistics), urlmap: make(map[string]map[string]*Statistics),
} }
} }

View File

@ -69,7 +69,7 @@ const (
starBit = 1 << 63 starBit = 1 << 63
) )
// time taks schedule // Schedule time taks schedule
type Schedule struct { type Schedule struct {
Second uint64 Second uint64
Minute uint64 Minute uint64
@ -79,10 +79,10 @@ type Schedule struct {
Week uint64 Week uint64
} }
// task func type // TaskFunc task func type
type TaskFunc func() error type TaskFunc func() error
// task interface // Tasker task interface
type Tasker interface { type Tasker interface {
GetSpec() string GetSpec() string
GetStatus() string GetStatus() string
@ -99,7 +99,7 @@ type taskerr struct {
errinfo string errinfo string
} }
// task struct // Task task struct
type Task struct { type Task struct {
Taskname string Taskname string
Spec *Schedule Spec *Schedule
@ -111,7 +111,7 @@ type Task struct {
ErrLimit int // max length for the errlist, 0 stand for no limit ErrLimit int // max length for the errlist, 0 stand for no limit
} }
// add new task with name, time and func // NewTask add new task with name, time and func
func NewTask(tname string, spec string, f TaskFunc) *Task { func NewTask(tname string, spec string, f TaskFunc) *Task {
task := &Task{ task := &Task{
@ -124,49 +124,49 @@ func NewTask(tname string, spec string, f TaskFunc) *Task {
return task return task
} }
//get spec string // GetSpec get spec string
func (s *Task) GetSpec() string { func (t *Task) GetSpec() string {
return s.SpecStr return t.SpecStr
} }
// get current task status // GetStatus get current task status
func (tk *Task) GetStatus() string { func (t *Task) GetStatus() string {
var str string var str string
for _, v := range tk.Errlist { for _, v := range t.Errlist {
str += v.t.String() + ":" + v.errinfo + "<br>" str += v.t.String() + ":" + v.errinfo + "<br>"
} }
return str return str
} }
// run task // Run run all tasks
func (tk *Task) Run() error { func (t *Task) Run() error {
err := tk.DoFunc() err := t.DoFunc()
if err != nil { if err != nil {
if tk.ErrLimit > 0 && tk.ErrLimit > len(tk.Errlist) { if t.ErrLimit > 0 && t.ErrLimit > len(t.Errlist) {
tk.Errlist = append(tk.Errlist, &taskerr{t: tk.Next, errinfo: err.Error()}) t.Errlist = append(t.Errlist, &taskerr{t: t.Next, errinfo: err.Error()})
} }
} }
return err return err
} }
// set next time for this task // SetNext set next time for this task
func (tk *Task) SetNext(now time.Time) { func (t *Task) SetNext(now time.Time) {
tk.Next = tk.Spec.Next(now) t.Next = t.Spec.Next(now)
} }
// get the next call time of this task // GetNext get the next call time of this task
func (tk *Task) GetNext() time.Time { func (t *Task) GetNext() time.Time {
return tk.Next return t.Next
} }
// set prev time of this task // SetPrev set prev time of this task
func (tk *Task) SetPrev(now time.Time) { func (t *Task) SetPrev(now time.Time) {
tk.Prev = now t.Prev = now
} }
// get prev time of this task // GetPrev get prev time of this task
func (tk *Task) GetPrev() time.Time { func (t *Task) GetPrev() time.Time {
return tk.Prev return t.Prev
} }
// six columns mean // six columns mean
@ -177,7 +177,7 @@ func (tk *Task) GetPrev() time.Time {
// month1-12 // month1-12
// week0-60 means Sunday // week0-60 means Sunday
// some signals // SetCron some signals
// * any time // * any time
// ,  separate signal // ,  separate signal
//   duration //   duration
@ -289,7 +289,7 @@ func (t *Task) parseSpec(spec string) *Schedule {
return nil return nil
} }
// set schedule to next time // Next set schedule to next time
func (s *Schedule) Next(t time.Time) time.Time { func (s *Schedule) Next(t time.Time) time.Time {
// Start at the earliest possible time (the upcoming second). // Start at the earliest possible time (the upcoming second).
@ -377,8 +377,8 @@ WRAP:
func dayMatches(s *Schedule, t time.Time) bool { func dayMatches(s *Schedule, t time.Time) bool {
var ( var (
domMatch bool = 1<<uint(t.Day())&s.Day > 0 domMatch = 1<<uint(t.Day())&s.Day > 0
dowMatch bool = 1<<uint(t.Weekday())&s.Week > 0 dowMatch = 1<<uint(t.Weekday())&s.Week > 0
) )
if s.Day&starBit > 0 || s.Week&starBit > 0 { if s.Day&starBit > 0 || s.Week&starBit > 0 {
@ -387,7 +387,7 @@ func dayMatches(s *Schedule, t time.Time) bool {
return domMatch || dowMatch return domMatch || dowMatch
} }
// start all tasks // StartTask start all tasks
func StartTask() { func StartTask() {
isstart = true isstart = true
go run() go run()
@ -430,13 +430,13 @@ func run() {
} }
} }
// start all tasks // StopTask stop all tasks
func StopTask() { func StopTask() {
isstart = false isstart = false
stop <- true stop <- true
} }
// add task with name // AddTask add task with name
func AddTask(taskname string, t Tasker) { func AddTask(taskname string, t Tasker) {
AdminTaskList[taskname] = t AdminTaskList[taskname] = t
if isstart { if isstart {
@ -444,7 +444,7 @@ func AddTask(taskname string, t Tasker) {
} }
} }
// add task with name // DeleteTask delete task with name
func DeleteTask(taskname string) { func DeleteTask(taskname string) {
delete(AdminTaskList, taskname) delete(AdminTaskList, taskname)
if isstart { if isstart {
@ -452,13 +452,13 @@ func DeleteTask(taskname string) {
} }
} }
// sort map for tasker // MapSorter sort map for tasker
type MapSorter struct { type MapSorter struct {
Keys []string Keys []string
Vals []Tasker Vals []Tasker
} }
// create new tasker map // NewMapSorter create new tasker map
func NewMapSorter(m map[string]Tasker) *MapSorter { func NewMapSorter(m map[string]Tasker) *MapSorter {
ms := &MapSorter{ ms := &MapSorter{
Keys: make([]string, 0, len(m)), Keys: make([]string, 0, len(m)),
@ -471,7 +471,7 @@ func NewMapSorter(m map[string]Tasker) *MapSorter {
return ms return ms
} }
// sort tasker map // Sort sort tasker map
func (ms *MapSorter) Sort() { func (ms *MapSorter) Sort() {
sort.Sort(ms) sort.Sort(ms)
} }
@ -512,11 +512,11 @@ func getRange(expr string, r bounds) uint64 {
singleDigit = len(lowAndHigh) == 1 singleDigit = len(lowAndHigh) == 1
) )
var extra_star uint64 var extrastar uint64
if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" {
start = r.min start = r.min
end = r.max end = r.max
extra_star = starBit extrastar = starBit
} else { } else {
start = parseIntOrName(lowAndHigh[0], r.names) start = parseIntOrName(lowAndHigh[0], r.names)
switch len(lowAndHigh) { switch len(lowAndHigh) {
@ -553,7 +553,7 @@ func getRange(expr string, r bounds) uint64 {
log.Panicf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr) log.Panicf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr)
} }
return getBits(start, end, step) | extra_star return getBits(start, end, step) | extrastar
} }
// parseIntOrName returns the (possibly-named) integer contained in expr. // parseIntOrName returns the (possibly-named) integer contained in expr.