I am randomly generating a bunch of log messages, and after they have been generated, I need to sort them by timestamp before writing them to the logs. I'm utilising the sort.Interface
aspect of the sort
library so I can sort based on my timestamp. I'm using a fan-in concurrency design, so my sorting function aggregates all the log messages from the goroutines, then sorts them.
Here is my code:
type CommonLogFormat struct {
HostIP string
UserIdent string
User string
Timestamp string
Request string
HttpStatusCode int
Size int
}
type Logs struct {
Messages []*CommonLogFormat
}
func sortByTimestamp(ch chan <- *CommonLogFormat) *Logs {
logs := &Logs{Messages: make([]*CommonLogFormat, 1)}
for i := range ch {
logs.Messages = append(logs.Messages, <- i)
}
sort.Sort(logs)
return logs
}
func (l Logs) Len() int {
return len(l.Messages)
}
func (l Logs) Less(i,j int) bool {
return l.Messages[i].Timestamp < l.Messages[j].Timestamp
}
func (l *Logs) Swap(i,j int) {
l.Messages[i], l.Messages[j] = l.Messages[j], l.Messages[i]
}
However, when I go to receive a log message from the channel, I get this error:
invalid operation: <-i (receive from non-chan type *CommonLogFormat)
Why can't I receive a value from the channel?