doc
stringlengths
10
26.3k
code
stringlengths
52
3.87M
// check if version is a valid pkgver format
func validPkgver(version string) bool { if len(version) < 1 { return false } if !isAlphaNumeric(rune(version[0])) { return false } for _, r := range version[1:] { if !isValidPkgverChar(r) { return false } } return true }
// ParseDeps parses a string slice of dependencies into a slice of Dependency // objects.
func ParseDeps(deps []string) ([]*Dependency, error) { var err error dependencies := make([]*Dependency, 0) for _, dep := range deps { dependencies, err = parseDependency(dep, dependencies) if err != nil { return nil, err } } return dependencies, nil }
// parse dependency with possible version restriction
func parseDependency(dep string, deps []*Dependency) ([]*Dependency, error) { var name string var dependency *Dependency index := -1 if dep == "" { return deps, nil } if dep[0] == '-' { return nil, fmt.Errorf("invalid dependency name") } i := 0 for _, c := range dep { if !isValidPkgnameChar(c) { break } i++ } // check if the dependency has been set before name = dep[0:i] for n, d := range deps { if d.Name == name { index = n break } } dependency = &Dependency{ Name: name, sgt: false, slt: false, } if len(dep) != len(name) { var eq bytes.Buffer for _, c := range dep[i:] { if c == '<' || c == '>' || c == '=' { i++ eq.WriteRune(c) continue } break } version, err := NewCompleteVersion(dep[i:]) if err != nil { return nil, err } switch eq.String() { case "=": dependency.MinVer = version dependency.MaxVer = version case "<=": dependency.MaxVer = version case ">=": dependency.MinVer = version case "<": dependency.MaxVer = version dependency.slt = true case ">": dependency.MinVer = version dependency.sgt = true } } if index == -1 { deps = append(deps, dependency) } else { deps[index] = deps[index].Restrict(dependency) } return deps, nil }
// check if c is a valid pkgname char
func isValidPkgnameChar(c rune) bool { return isAlphaNumeric(c) || c == '@' || c == '.' || c == '_' || c == '+' || c == '-' }
// check if c is a valid pkgver char
func isValidPkgverChar(c rune) bool { return isAlphaNumeric(c) || c == '_' || c == '+' || c == '.' || c == '~' }
// MakeHTTPHandler returns a handler that makes a set of endpoints available // on predefined paths.
func MakeHTTPHandler(ctx context.Context, endpoints Endpoints, tracer stdopentracing.Tracer, logger log.Logger, opts ...HTTPHandlerOption) http.Handler { transportOpts := []httptransport.ServerOption{ httptransport.ServerErrorEncoder(kitty.TransportErrorEncoder), httptransport.ServerErrorLogger(logger), } handlerOpts := &httpHandlerOptions{ accessTokenCookie: "access_token", accessTokenHeader: "Styx-Access-Token", payloadHeader: "Styx-Payload", sessionHeader: "Styx-Session", redirectURLHeader: "Redirect-Url", redirectURLQueryParam: "redirectUrl", requestURLHeader: "Request-Url", } for _, opt := range opts { opt(handlerOpts) } authorizeTokenHandler := httptransport.NewServer( ctx, endpoints.AuthorizeTokenEndpoint, DecodeHTTPAuthorizeTokenRequest(handlerOpts.accessTokenCookie, handlerOpts.accessTokenHeader, handlerOpts.requestURLHeader), EncodeHTTPAuthorizeTokenResponse(handlerOpts.accessTokenHeader, handlerOpts.payloadHeader, handlerOpts.sessionHeader), append( transportOpts, httptransport.ServerBefore(kitty.FromHTTPRequest(tracer, "Authorize token", logger)), httptransport.ServerAfter(kitty.ToHTTPResponse(tracer, logger)), )..., ) redirectHandler := httptransport.NewServer( ctx, endpoints.RedirectEndpoint, DecodeHTTPRedirectRequest(handlerOpts.requestURLHeader), EncodeHTTPRedirectResponse(handlerOpts.redirectURLHeader, handlerOpts.redirectURLQueryParam), append(transportOpts, httptransport.ServerBefore(kitty.FromHTTPRequest(tracer, "Redirect URL", logger)))..., ) r := chi.NewRouter() r.Get("/authorizeToken", authorizeTokenHandler.ServeHTTP) r.Get("/redirect", redirectHandler.ServeHTTP) return r }
// DecodeHTTPAuthorizeTokenRequest is a transport/http.DecodeRequestFunc that decodes the // JSON-encoded request from the HTTP request body.
func DecodeHTTPAuthorizeTokenRequest(accessTokenCookie, accessTokenHeader, requestURLHeader string) httptransport.DecodeRequestFunc { return func(_ context.Context, r *http.Request) (interface{}, error) { token := "" if cookie, err := r.Cookie(accessTokenCookie); err == nil { token = cookie.Value } if header := r.Header.Get(accessTokenHeader); header != "" { token = header } hostname, path := "", "" requestURL := r.Header.Get(requestURLHeader) if u, err := url.ParseRequestURI(requestURL); err == nil { hostname = u.Host path = u.Path } return authorizeTokenRequest{ Hostname: hostname, Path: path, Token: token, }, nil } }
// EncodeHTTPAuthorizeTokenResponse is a transport/http.EncodeResponseFunc that encodes // the response as JSON to the response writer.
func EncodeHTTPAuthorizeTokenResponse(accessTokenHeader, payloadHeader, sessionHeader string) httptransport.EncodeResponseFunc { return func(ctx context.Context, w http.ResponseWriter, response interface{}) error { res := response.(authorizeTokenResponse) if res.Err != nil { return businessErrorEncoder(ctx, res.Err, w) } w.Header().Add(accessTokenHeader, res.Token) if res.Session != nil { if res.Session.Payload != nil { w.Header().Add(payloadHeader, base64.StdEncoding.EncodeToString(res.Session.Payload)) } res.Session.Policies = nil res.Session.Payload = nil s, _ := json.Marshal(res.Session) w.Header().Add(sessionHeader, base64.StdEncoding.EncodeToString(s)) } defer kitty.TraceStatusAndFinish(ctx, w.Header(), 204) w.WriteHeader(204) return nil } }
// DecodeHTTPRedirectRequest is a transport/http.DecodeRequestFunc that decodes the // JSON-encoded request from the HTTP request body.
func DecodeHTTPRedirectRequest(requestURLHeader string) httptransport.DecodeRequestFunc { return func(_ context.Context, r *http.Request) (interface{}, error) { hostname := "" requestURL := r.Header.Get(requestURLHeader) if u, err := url.ParseRequestURI(requestURL); err == nil { hostname = u.Host } return redirectRequest{ RequestURL: requestURL, Hostname: hostname, }, nil } }
// EncodeHTTPRedirectResponse is a transport/http.EncodeResponseFunc that encodes // the response as JSON to the response writer.
func EncodeHTTPRedirectResponse(redirectURLHeader, redirectURLQueryParam string) httptransport.EncodeResponseFunc { return func(ctx context.Context, w http.ResponseWriter, response interface{}) error { res := response.(redirectResponse) if res.Err != nil { return businessErrorEncoder(ctx, res.Err, w) } w.Header().Add("Location", fmt.Sprintf("%s?%s=%s", res.RedirectURL, redirectURLQueryParam, res.RequestURL)) w.Header().Add(redirectURLHeader, res.RequestURL) defer kitty.TraceStatusAndFinish(ctx, w.Header(), 307) w.WriteHeader(307) return nil } }
// StartTasks starts all tasks in the task group and returns the created // StopChan instances in the same order as the tasks.
func (group TaskGroup) StartTasks(wg *sync.WaitGroup) []StopChan { channels := make([]StopChan, len(group)) for i, task := range group { channels[i] = task.Start(wg) } return channels }
// Stop stops all tasks in the task group in parallel. // Stop blocks until all Stop() invocations of all tasks have returned. // // If the global PrintTaskStopWait variable is set, a log message // is printed before stopping every task.
func (group TaskGroup) Stop() { var wg sync.WaitGroup for _, task := range group { wg.Add(1) go func(task Task) { defer wg.Done() if PrintTaskStopWait { Log.Println("Stopping", task) } task.Stop() }(task) } wg.Wait() }
// WaitAndStop executes the entire lifecycle sequence for all tasks in the task group: // - Start all tasks using StartTasks() with a new instance of sync.WaitGroup // - Wait for the first task to finish // - Stop all tasks using Stop() // - Wait until all goroutines end using sync.WaitGroup.Wait() // - Wait until all tasks finish using CollectErrors() // // All errors produced by any task are logged. // Afterwards, the task that caused the shutdown is returned, as well as the number // of errors encountered. // // If the timeout parameter is >0, a timer will be started before stopping all tasks. // After the timer expires, all goroutines will be dumped to the standard output // and the program will terminate. This can be used to debug the task shutdown sequence, // in case one task does not shut down properly, e.g. due to a deadlock.
func (group TaskGroup) WaitAndStop(timeout time.Duration) (Task, int) { var wg sync.WaitGroup channels := group.StartTasks(&wg) reason := WaitForAny(channels) if reason == -1 { return nil, -1 } exited := false if timeout > 0 { time.AfterFunc(timeout, func() { if !exited { DumpGoroutineStacks() if PanicOnTaskTimeout { panic("Waiting for stopping goroutines timed out") } } }) } group.Stop() wg.Wait() numErrors := group.CollectErrors(channels, func(err error) { Log.Errorln(err) }) exited = true return group[reason], numErrors }
// PrintWaitAndStop calls WaitAndStop() using the global variable TaskStopTimeout // as the timeout parameter. Afterwards, the task that caused the shutdown is printed // as a debug log-message and the number of errors encountered is returned. // This is a convenience function that can be used in main() functions.
func (group TaskGroup) PrintWaitAndStop() int { reason, numErrors := group.WaitAndStop(TaskStopTimeout) Log.Debugln("Stopped because of", reason) return numErrors }
// CollectErrors waits for the given StopChan instances to stop and calls the given // callback function for every collected non-nil error instance. // // The channels slice must be the one created by StartTasks(). // // If the global PrintTaskStopWait variable is true, and additional log message // is printed when starting waiting for a task. This can be used to identify the task // that prevents the shutdown from progressing.
func (group TaskGroup) CollectErrors(channels []StopChan, do func(err error)) (numErrors int) { for i, input := range channels { if input.stopChan != nil { if PrintTaskStopWait { task := group[i] Log.Println("Waiting for", task) } input.Wait() if err := input.Err(); err != nil { numErrors++ do(err) } } } return }
// CollectMultiError uses CollectErrors to collect all errors returned from all StopChan instances // into one MultiError object. // // The channels slice must be the one created by StartTasks().
func (group TaskGroup) CollectMultiError(channels []StopChan) MultiError { var err MultiError group.CollectErrors(channels, func(newErr error) { err.Add(newErr) }) return err }
// Wrapper for (*Logger).LoadConfiguration
func LoadConfiguration(filename string) { Global.LoadConfiguration(filename) //check defualt logger _, ok := Global["stdout"] if !ok { Global["stdout"] = &Filter{INFO, "./logs/", NewConsoleLogWriter()} } }
// Wrapper for (*Logger).AddFilter
func AddFilter(name string, lvl level, writer LogWriter) { Global.AddFilter(name, lvl, writer) }
// Utility for error log messages (returns an error for easy function returns) (see Debug() for parameter explanation) // These functions will execute a closure exactly once, to build the error message for the return // Wrapper for (*Logger).Error
func DebugLog(logname string, arg0 interface{}, args ...interface{}) error { const ( lvl = DEBUG ) switch first := arg0.(type) { case string: // Use the string as a format string Global.intLogNamef(logname, lvl, first, args...) case func() string: // Log the closure (no other arguments used) Global.intLogNamec(logname, lvl, first) default: // Build a format string so that it will be similar to Sprint Global.intLogNamef(logname, lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) } return nil }
/* Examples: IsTerminal(os.Stdin) IsTerminal(os.Stdout) IsTerminal(os.Stderr) */
func IsTerminal(file *os.File) bool { var st uint32 return getConsoleMode(syscall.Handle(file.Fd()), &st) == nil }
// leftOf returns the string to the left of the given delimiter
func leftOf(s, delim string) string { if left, _, ok := twoFields(s, delim); ok { return strings.TrimSpace(left) } return "" }
// rightOf returns the string to the right of the given delimiter
func rightOf(s, delim string) string { if _, right, ok := twoFields(s, delim); ok { return strings.TrimSpace(right) } return "" }
// Parse a DSN
func splitConnectionString(connectionString string) (username, password string, hasPassword bool, host, port, dbname, args string) { var hostPortDatabase, hostPort string // Gather the fields // Optional left side of @ with username and password userPass := leftOf(connectionString, "@") if userPass != "" { hostPortDatabase = rightOf(connectionString, "@") } else { hostPortDatabase = strings.TrimRight(connectionString, "@") } // Optional right side of / with database name dbname = rightOf(hostPortDatabase, "/") if dbname != "" { hostPort = leftOf(hostPortDatabase, "/") } else { hostPort = strings.TrimRight(connectionString, "/") dbname = defaultDatabaseName } if strings.Contains(hostPort, "@") { hostPort = rightOf(hostPort, "@") } // Optional right side of : with password password = strings.TrimSpace(rightOf(userPass, ":")) if password != "" { username = leftOf(userPass, ":") } else { username = strings.TrimRight(userPass, ":") } hasPassword = password != "" // Optional right side of : with port port = rightOf(hostPort, ":") if port != "" { host = leftOf(hostPort, ":") } else { host = strings.TrimRight(hostPort, ":") if host != "" { port = strconv.Itoa(defaultPort) } } if strings.Contains(dbname, "?") && strings.Contains(dbname, "=") { args = rightOf(dbname, "?") if args != "" { dbname = leftOf(dbname, "?") } } if Verbose { log.Println("Connection:") log.Println("\tusername:\t", username) log.Println("\tpassword:\t", password) log.Println("\thas password:\t", hasPassword) log.Println("\thost:\t\t", host) log.Println("\tport:\t\t", port) log.Println("\tdbname:\t\t", dbname) log.Println("\targs:\t\t", args) log.Println() } return }
// Build a DSN.
func buildConnectionString(username, password string, hasPassword bool, host, port, dbname, args string) string { // Build a new connection string var buf bytes.Buffer if !strings.HasPrefix(username, "postgres://") { buf.WriteString("postgres://") } if (username != "") && hasPassword { buf.WriteString(username + ":" + password + "@") } else if username != "" { buf.WriteString(username + "@") } else if hasPassword { buf.WriteString(":" + password + "@") } if host != "" { buf.WriteString(host) } if port != "" { buf.WriteString(":" + port) } buf.WriteString("/" + dbname) if args != "" { buf.WriteString("?" + args) } else { buf.WriteString("?sslmode=disable") } if Verbose { log.Println("Connection string:", buf.String()) } return buf.String() }
// Take apart and rebuild the connection string. Also extract and return the dbname. // withoutDB is for pinging database hosts without opening a specific database.
func rebuildConnectionString(connectionString string, withDB bool) (string, string) { username, password, hasPassword, hostname, port, dbname, args := splitConnectionString(connectionString) if withDB { return buildConnectionString(username, password, hasPassword, hostname, port, dbname, args), dbname } return buildConnectionString(username, password, hasPassword, hostname, port, "", args), "" }
// NewStopChan allocates a new, un-stopped StopChan.
func NewStopChan() StopChan { return StopChan{ stopChan: &stopChan{ cond: sync.Cond{ L: new(sync.Mutex), }, }, } }
// NewStoppedChan returns a StopChan that is already stopped, and contains the // given error value.
func NewStoppedChan(err error) StopChan { res := NewStopChan() res.StopErr(err) return res }
// StopErrFunc stops the receiving StopChan, iff it is not already stopped. // In that case, the given function is executed and the resulting error value // is stored within the StopChan.
func (s *stopChan) StopErrFunc(perform func() error) { if s == nil { return } s.cond.L.Lock() defer s.cond.L.Unlock() if s.stopped { return } if perform != nil { s.err = perform() } s.stopped = true s.cond.Broadcast() }
// StopFunc stops the receiving StopChan and executes the given function, iff // it was not already stopped.
func (s *stopChan) StopFunc(perform func()) { s.StopErrFunc(func() error { if perform != nil { perform() } return nil }) }
// Stopped returns whether the StopChan is stopped or not. It blocks, if the // StopChan is currently being stopped by another goroutine.
func (s *stopChan) Stopped() bool { if s == nil { return true } s.cond.L.Lock() defer s.cond.L.Unlock() return s.stopped }
// Wait blocks until the receiving StopChan is stopped.
func (s *stopChan) Wait() { if s == nil { return } s.cond.L.Lock() defer s.cond.L.Unlock() for !s.stopped { s.cond.Wait() } }
// WaitChan returns a channel that is closed as soon as the receiving StopChan // is stopped. The returned channel never receives any values. // The Err() method can be used to retrieve the error instance stored in the // StopChan afterwards. // // To avoid memory leaks, only one channel is lazily created per StopChan instance, // accompanied by one goroutine that closes that channel after waiting for the StopChan // to be stopped. The same channel will be returned by all calls to WaitChan().
func (s *stopChan) WaitChan() <-chan error { if s == nil { c := make(chan error) close(c) return c } // Double checked locking // To avoid memory leak, lazily create one channel and one goroutine. if s.waitChan == nil { s.cond.L.Lock() defer s.cond.L.Unlock() if s.waitChan == nil { s.waitChan = make(chan error) c := s.waitChan go func() { s.Wait() close(c) }() } } return s.waitChan }
// WaitTimeout waits for the StopChan to be stopped, but returns if the given // time duration has passed without that happening. // The return value indicates which one of the two happened: // 1. Return true means the wait timed out and the StopChan is still active. // 2. Return false means the StopChan was stopped before the timeout expired.
func (s *stopChan) WaitTimeout(t time.Duration) bool { return s.WaitTimeoutPrecise(t, 1, nil) }
// WaitTimeoutLoop behaves like WaitTimeout, but tries to achieve a more precise timeout timing // by waking up frequently and checking the passed sleep time. // The wakeupFactor parameter must be in ]0..1] or it is adjusted to 1. It is multiplied with the totalDuration // to determine the sleep duration of intermediate sleeps for increasing the sleep duration accuracy in high-load situations. // For example, a wakeupFactor of 0.1 will lead to 10 intermediate wake-ups that check if the desired sleep time has passed already. // If the lastTime parameter is not nil and not zero, the sleep time will be counted not from time.Now(), but from the stored time. // If the lastTime parameter is not zero, the current time is stored into it before returning.
func (s *stopChan) WaitTimeoutPrecise(totalTimeout time.Duration, wakeupFactor float64, lastTimePointer *time.Time) bool { if s == nil { return false } now := time.Now() var lastTime time.Time if lastTimePointer != nil { defer func() { // The now time might be changed in the loop below *lastTimePointer = now }() lastTime = *lastTimePointer } var end time.Time if lastTime.IsZero() || now.Before(lastTime) { end = now.Add(totalTimeout) } else { end = lastTime.Add(totalTimeout) totalTimeout = end.Sub(now) if totalTimeout <= 0 { return !s.Stopped() } } waitChan := s.WaitChan() if wakeupFactor <= 0 || wakeupFactor > 1 { wakeupFactor = 1 } subTimeout := time.Duration(float64(totalTimeout) * wakeupFactor) for { select { case <-time.After(subTimeout): now = time.Now() leftTime := end.Sub(now) if leftTime <= 0 { return true } else if leftTime < subTimeout { subTimeout = leftTime } case <-waitChan: return false } } }
// Execute executes the given function while grabbing the internal lock of the StopChan. // This means that no other goroutine can stop the StopChan while the function is running, // and that it is mutually exclusive with any of the IfStopped etc. methods. // This is sometimes useful, if the StopChan is used for its locking capabilities.
func (s *stopChan) Execute(execute func()) { if s != nil { s.cond.L.Lock() defer s.cond.L.Unlock() } execute() }
// IfStopped executes the given function, iff the receiving StopChan is not yet // stopped. This call guarantees that the StopChan is not stopped while the // function is being executed.
func (s *stopChan) IfStopped(execute func()) { if s == nil { execute() return } s.cond.L.Lock() defer s.cond.L.Unlock() if !s.stopped { return } execute() }
// IfElseStopped executes one of the two given functions, depending on the stopped state // of the StopChan. This call guarantees that the StopChan is not stopped while any of the // functions is being executed.
func (s *stopChan) IfElseStopped(stopped func(), notStopped func()) { if s == nil { stopped() return } s.cond.L.Lock() defer s.cond.L.Unlock() if s.stopped { stopped() } else { notStopped() } }
// WaitErrFunc executes the given function and returns a StopChan, that // will automatically be stopped after the function finishes. // The error instance return by the function will be stored in the StopChan.
func WaitErrFunc(wg *sync.WaitGroup, wait func() error) StopChan { if wg != nil { wg.Add(1) } finished := NewStopChan() go func() { if wg != nil { defer wg.Done() } var err error if wait != nil { err = wait() } finished.StopErr(err) }() return finished }
// WaitErrFunc executes the given function and returns a StopChan, that // will automatically be stopped after the function finishes.
func WaitFunc(wg *sync.WaitGroup, wait func()) StopChan { return WaitErrFunc(wg, func() error { wait() return nil }) }
// WaitForSetup executes the given function and returns a StopChan, // that will be stopped after the function finishes, but ONLY if the // function returns a non-nil error value. In that case the returned error // is stored in the stopped StopChan. // // This behaviour is similar to WaitErrFunc, but it leaves the StopChan // active if the setup function finished successfully.
func WaitForSetup(wg *sync.WaitGroup, setup func() error) StopChan { if wg != nil { wg.Add(1) } failed := NewStopChan() go func() { if wg != nil { defer wg.Done() } if setup != nil { if err := setup(); err != nil { failed.StopErr(err) } } }() return failed }
// WaitForAny returns if any of the give StopChan values are stopped. The implementation/ // uses the reflect package to create a select-statement of variable size. // // Exception: Uninitialized StopChans (created through the nil-value StopChan{}) are ignored, // although they behave like stopped StopChans otherwise. // // The return value is the index of the StopChan that caused this function to return. // If the given channel slice is empty, or if it contains only uninitialized StopChan instances, // the return value will be -1.
func WaitForAny(channels []StopChan) int { if len(channels) == 0 { return -1 } // Use reflect package to wait for any of the given channels var cases []reflect.SelectCase validCases := 0 for _, ch := range channels { var waitChan <-chan error if ch.stopChan == nil { // Channel that never returns. This dummy channel is used to make the // return value consistent (index of the channel closed in the select statement) waitChan = make(chan error, 1) } else { validCases++ waitChan = ch.WaitChan() } refCase := reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(waitChan)} cases = append(cases, refCase) } if validCases == 0 { return -1 } choice, _, _ := reflect.Select(cases) return choice }
// ExternalInterrupt creates a StopChan that is automatically stopped as soon // as an interrupt signal (like pressing Ctrl-C) is received. // This can be used in conjunction with the NoopTask to create a task // that automatically stops when the process receives an interrupt signal.
func ExternalInterrupt() StopChan { interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) stop := NewStopChan() go func() { defer signal.Stop(interrupt) select { case <-interrupt: stop.Stop() case <-stop.WaitChan(): } }() return stop }
// UserInput creates a StopChan that is automatically stopped when the // a newline character is received on os.Stdin. // This can be used in conjunction with the NoopTask to create a task // that automatically stops when the user presses the enter key. // This should not be used if the standard input is used for different purposes.
func UserInput() StopChan { userInput := NewStopChan() go func() { reader := bufio.NewReader(os.Stdin) _, err := reader.ReadString('\n') if err != nil { err = fmt.Errorf("Error reading user input: %v", err) } userInput.StopErr(err) }() return userInput }
// StdinClosed creates a StopChan that is automatically stopped when the // standard input stream is closed. // This can be used in conjunction with the NoopTask to create a task // that automatically stops when the user presses Ctrl-D or stdin is closed for any other reason. // This should not be user if the standard input is used for different purposes.
func StdinClosed() StopChan { closed := NewStopChan() go func() { _, err := ioutil.ReadAll(os.Stdin) if err != nil { err = fmt.Errorf("Error reading stdin: %v", err) } closed.StopErr(err) }() return closed }
// prepareOptions prepares the configuration options and sets some default options.
func prepareOptions(options []StaticOptions) StaticOptions { var opt StaticOptions if len(options) > 0 { opt = options[0] } if len(opt.IndexFile) == 0 { opt.IndexFile = "index.html" } if len(opt.Prefix) != 0 { // ensure we have a leading "/" if opt.Prefix[0] != '/' { opt.Prefix = "/" + opt.Prefix } // remove all trailing "/" opt.Prefix = strings.TrimRight(opt.Prefix, "/") } return opt }
///////////////// //Public function ///////////////// //Connect connects the bot to the server and joins the channels
func (b *IrcBot) Connect() error { //launch a go routine that handle errors // b.handleError() log.WithField("address", b.url()).Debugln("Connection") var conn net.Conn var err error if b.encrypted { cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem") if err != nil { log.Errorln("error during certificate loading") return err } config := tls.Config{Certificates: []tls.Certificate{cert}} config.Rand = rand.Reader conn, err = tls.Dial("tcp", b.url(), &config) } else { conn, err = net.Dial("tcp", b.url()) } if err != nil { log.WithField("address", b.url()).Errorln("Dial server") return err } b.conn = conn r := bufio.NewReader(b.conn) w := bufio.NewWriter(b.conn) b.reader = textproto.NewReader(r) b.writer = textproto.NewWriter(w) //connect to server b.writer.PrintfLine("USER %s 8 * :%s", b.Nick, b.Nick) b.writer.PrintfLine("NICK %s", b.Nick) //launch go routines that handle requests b.listen() b.handleActionIn() b.handleActionOut() b.handlerError() b.identify() return nil }
//Disconnect sends QUIT command to server and closes connections
func (b *IrcBot) Disconnect() { log.Debugln("disconnection...") for _, ch := range b.channels { log.WithField("channel", ch).Debugln("leaving") b.Say(ch, "See you soon...") } b.writer.PrintfLine("QUIT") b.conn.Close() log.Debugln("connection close") // b.Exit <- true }
//Say makes the bot say text to channel
func (b *IrcBot) Say(channel string, text string) { msg := NewIrcMsg() msg.Command = "PRIVMSG" msg.CmdParams = []string{channel} msg.Trailing = []string{":", text} b.ChOut <- msg }
//AddUserAction add an action fired by the user to handle //command is the commands send by user, action is an ActionFunc callback
func (b *IrcBot) AddUserAction(a Actioner) { for _, cmd := range a.Command() { b.handlersUser[cmd] = a } }
//GetActionnersCmds returns all registred user actioners commands
func (b *IrcBot) GetActionnersCmds() []string { var cmds []string for cmd, _ := range b.handlersUser { fmt.Println(cmd) cmds = append(cmds, cmd) } return cmds }
//GetActionUsage returns the Actioner from the user actions map or return an error if //no action if found with this name //Usefull if you want to access actioner information within other actioner //see Help actionner for example
func (b *IrcBot) GetActioner(actionName string) (Actioner, error) { actioner, ok := b.handlersUser[actionName] if !ok { log.WithField("action name", actionName).Warningln("action not found") return nil, errors.New("no action found with that name") } return actioner, nil }
//DBConnection return a new connection do the database. Use it if your custom action need to access the database
func (b *IrcBot) DBConnection() (*db.DB, error) { return db.Open(b.db.Path()) }
//String implements the Stringer interface
func (b *IrcBot) String() string { s := fmt.Sprintf("server: %s\n", b.server) s += fmt.Sprintf("port: %s\n", b.port) s += fmt.Sprintf("ssl: %t\n", b.encrypted) if len(b.channels) > 0 { s += "channels: " for _, v := range b.channels { s += fmt.Sprintf("%s ", v) } } return s }
// popUntil pops the stack of open elements at the highest element whose tag // is in matchTags, provided there is no higher element in the scope's stop // tags (as defined in section 12.2.3.2). It returns whether or not there was // such an element. If there was not, popUntil leaves the stack unchanged. // // For example, the set of stop tags for table scope is: "html", "table". If // the stack was: // ["html", "body", "font", "table", "b", "i", "u"] // then popUntil(tableScope, "font") would return false, but // popUntil(tableScope, "i") would return true and the stack would become: // ["html", "body", "font", "table", "b"] // // If an element's tag is in both the stop tags and matchTags, then the stack // will be popped and the function returns true (provided, of course, there was // no higher element in the stack that was also in the stop tags). For example, // popUntil(tableScope, "table") returns true and leaves: // ["html", "body", "font"]
func (p *parser) popUntil(s scope, matchTags ...a.Atom) bool { if i := p.indexOfElementInScope(s, matchTags...); i != -1 { p.oe = p.oe[:i] return true } return false }
// indexOfElementInScope returns the index in p.oe of the highest element whose // tag is in matchTags that is in scope. If no matching element is in scope, it // returns -1.
func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { for i := len(p.oe) - 1; i >= 0; i-- { tagAtom := p.oe[i].DataAtom if p.oe[i].Namespace == "" { for _, t := range matchTags { if t == tagAtom { return i } } switch s { case defaultScope: // No-op. case listItemScope: if tagAtom == a.Ol || tagAtom == a.Ul { return -1 } case buttonScope: if tagAtom == a.Button { return -1 } case tableScope: if tagAtom == a.Html || tagAtom == a.Table { return -1 } case selectScope: if tagAtom != a.Optgroup && tagAtom != a.Option { return -1 } default: panic("unreachable") } } switch s { case defaultScope, listItemScope, buttonScope: for _, t := range defaultScopeStopTags[p.oe[i].Namespace] { if t == tagAtom { return -1 } } } } return -1 }
// elementInScope is like popUntil, except that it doesn't modify the stack of // open elements.
func (p *parser) elementInScope(s scope, matchTags ...a.Atom) bool { return p.indexOfElementInScope(s, matchTags...) != -1 }
// clearStackToContext pops elements off the stack of open elements until a // scope-defined element is found.
func (p *parser) clearStackToContext(s scope) { for i := len(p.oe) - 1; i >= 0; i-- { tagAtom := p.oe[i].DataAtom switch s { case tableScope: if tagAtom == a.Html || tagAtom == a.Table { p.oe = p.oe[:i+1] return } case tableRowScope: if tagAtom == a.Html || tagAtom == a.Tr { p.oe = p.oe[:i+1] return } case tableBodyScope: if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead { p.oe = p.oe[:i+1] return } default: panic("unreachable") } } }
// generateImpliedEndTags pops nodes off the stack of open elements as long as // the top node has a tag name of dd, dt, li, option, optgroup, p, rp, or rt. // If exceptions are specified, nodes with that name will not be popped off.
func (p *parser) generateImpliedEndTags(exceptions ...string) { var i int loop: for i = len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] if n.Type == ElementNode { switch n.DataAtom { case a.Dd, a.Dt, a.Li, a.Option, a.Optgroup, a.P, a.Rp, a.Rt: for _, except := range exceptions { if n.Data == except { break loop } } continue } } break } p.oe = p.oe[:i+1] }
// addChild adds a child node n to the top element, and pushes n onto the stack // of open elements if it is an element node.
func (p *parser) addChild(n *Node) { if p.shouldFosterParent() { p.fosterParent(n) } else { p.top().AppendChild(n) } if n.Type == ElementNode { p.oe = append(p.oe, n) } }
// shouldFosterParent returns whether the next node to be added should be // foster parented.
func (p *parser) shouldFosterParent() bool { if p.fosterParenting { switch p.top().DataAtom { case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: return true } } return false }
// fosterParent adds a child node according to the foster parenting rules. // Section 12.2.5.3, "foster parenting".
func (p *parser) fosterParent(n *Node) { var table, parent, prev *Node var i int for i = len(p.oe) - 1; i >= 0; i-- { if p.oe[i].DataAtom == a.Table { table = p.oe[i] break } } if table == nil { // The foster parent is the html element. parent = p.oe[0] } else { parent = table.Parent } if parent == nil { parent = p.oe[i-1] } if table != nil { prev = table.PrevSibling } else { prev = parent.LastChild } if prev != nil && prev.Type == TextNode && n.Type == TextNode { prev.Data += n.Data return } parent.InsertBefore(n, table) }
// addText adds text to the preceding node if it is a text node, or else it // calls addChild with a new text node.
func (p *parser) addText(text string) { if text == "" { return } if p.shouldFosterParent() { p.fosterParent(&Node{ Type: TextNode, Data: text, }) return } t := p.top() if n := t.LastChild; n != nil && n.Type == TextNode { n.Data += text return } p.addChild(&Node{ Type: TextNode, Data: text, }) }
// addElement adds a child element based on the current token.
func (p *parser) addElement() { p.addChild(&Node{ Type: ElementNode, DataAtom: p.tok.DataAtom, Data: p.tok.Data, Attr: p.tok.Attr, }) }
// setOriginalIM sets the insertion mode to return to after completing a text or // inTableText insertion mode. // Section 12.2.3.1, "using the rules for".
func (p *parser) setOriginalIM() { if p.originalIM != nil { panic("html: bad parser state: originalIM was set twice") } p.originalIM = p.im }
// Section 12.2.3.1, "reset the insertion mode".
func (p *parser) resetInsertionMode() { for i := len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] if i == 0 && p.context != nil { n = p.context } switch n.DataAtom { case a.Select: p.im = inSelectIM case a.Td, a.Th: p.im = inCellIM case a.Tr: p.im = inRowIM case a.Tbody, a.Thead, a.Tfoot: p.im = inTableBodyIM case a.Caption: p.im = inCaptionIM case a.Colgroup: p.im = inColumnGroupIM case a.Table: p.im = inTableIM case a.Head: p.im = inBodyIM case a.Body: p.im = inBodyIM case a.Frameset: p.im = inFramesetIM case a.Html: p.im = beforeHeadIM default: continue } return } p.im = inBodyIM }
// copyAttributes copies attributes of src not found on dst to dst.
func copyAttributes(dst *Node, src Token) { if len(src.Attr) == 0 { return } attr := map[string]string{} for _, t := range dst.Attr { attr[t.Key] = t.Val } for _, t := range src.Attr { if _, ok := attr[t.Key]; !ok { dst.Attr = append(dst.Attr, t) attr[t.Key] = t.Val } } }
// inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM. // "Any other end tag" handling from 12.2.5.5 The rules for parsing tokens in foreign content // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
func (p *parser) inBodyEndTagOther(tagAtom a.Atom) { for i := len(p.oe) - 1; i >= 0; i-- { if p.oe[i].DataAtom == tagAtom { p.oe = p.oe[:i] break } if isSpecialElement(p.oe[i]) { break } } }
// parseImpliedToken parses a token as though it had appeared in the parser's // input.
func (p *parser) parseImpliedToken(t TokenType, dataAtom a.Atom, data string) { realToken, selfClosing := p.tok, p.hasSelfClosingToken p.tok = Token{ Type: t, DataAtom: dataAtom, Data: data, } p.hasSelfClosingToken = false p.parseCurrentToken() p.tok, p.hasSelfClosingToken = realToken, selfClosing }
// parseCurrentToken runs the current token through the parsing routines // until it is consumed.
func (p *parser) parseCurrentToken() { if p.tok.Type == SelfClosingTagToken { p.hasSelfClosingToken = true p.tok.Type = StartTagToken } consumed := false for !consumed { if p.inForeignContent() { consumed = parseForeignContent(p) } else { consumed = p.im(p) } } if p.hasSelfClosingToken { // This is a parse error, but ignore it. p.hasSelfClosingToken = false } }
// Parse returns the parse tree for the HTML from the given Reader. // The input is assumed to be UTF-8 encoded.
func Parse(r io.Reader) (*Node, error) { p := &parser{ tokenizer: NewTokenizer(r), doc: &Node{ Type: DocumentNode, }, scripting: true, framesetOK: true, im: initialIM, } err := p.parse() if err != nil { return nil, err } return p.doc, nil }
// ParseFragment parses a fragment of HTML and returns the nodes that were // found. If the fragment is the InnerHTML for an existing element, pass that // element in context.
func ParseFragment(r io.Reader, context *Node) ([]*Node, error) { contextTag := "" if context != nil { if context.Type != ElementNode { return nil, errors.New("html: ParseFragment of non-element Node") } // The next check isn't just context.DataAtom.String() == context.Data because // it is valid to pass an element whose tag isn't a known atom. For example, // DataAtom == 0 and Data = "tagfromthefuture" is perfectly consistent. if context.DataAtom != a.Lookup([]byte(context.Data)) { return nil, fmt.Errorf("html: inconsistent Node: DataAtom=%q, Data=%q", context.DataAtom, context.Data) } contextTag = context.DataAtom.String() } p := &parser{ tokenizer: NewTokenizerFragment(r, contextTag), doc: &Node{ Type: DocumentNode, }, scripting: true, fragment: true, context: context, } root := &Node{ Type: ElementNode, DataAtom: a.Html, Data: a.Html.String(), } p.doc.AppendChild(root) p.oe = nodeStack{root} p.resetInsertionMode() for n := context; n != nil; n = n.Parent { if n.Type == ElementNode && n.DataAtom == a.Form { p.form = n break } } err := p.parse() if err != nil { return nil, err } parent := p.doc if context != nil { parent = root } var result []*Node for c := parent.FirstChild; c != nil; { next := c.NextSibling parent.RemoveChild(c) result = append(result, c) c = next } return result, nil }
// FromFile parses and validates a configuration file.
func FromFile(file []byte) (*Config, error) { config := &Config{} if errYAML := yaml.Unmarshal(file, config); errYAML != nil { if errJSON := json.Unmarshal(file, config); errJSON != nil { return nil, errors.New("could not parse the config file: YAML: " + errYAML.Error() + ", JSON: " + errJSON.Error()) } } // We use name and hostname maps to test uniqueness resourceNames := make(map[string]struct{}) resourceHostnames := make(map[string]struct{}) resourceValidator := validateResource(resourceNames, resourceHostnames) if config.Resources != nil { for _, resource := range config.Resources { if err := resourceValidator(&resource); err != nil { return nil, err } resourceNames[resource.Name] = struct{}{} resourceHostnames[resource.Hostname] = struct{}{} } } // We use a name map to test uniqueness policyNames := make(map[string]struct{}) policyValidator := validatePolicy(policyNames, resourceNames) if config.Policies != nil { for _, policy := range config.Policies { if err := policyValidator(&policy); err != nil { return nil, err } policyNames[policy.Name] = struct{}{} } } return config, nil }
// Put sets the value for a key.
func (kv *KV) Put(key, value []byte) error { return kv.db.Update(func(tx *buntdb.Tx) error { _, _, err := tx.Set(gkv.Btos(key), gkv.Btos(value), nil) return err }) }
// Get retrieves the value for a key.
func (kv *KV) Get(key []byte) (value []byte) { kv.db.View(func(tx *buntdb.Tx) error { val, err := tx.Get(gkv.Btos(key)) if err != nil { return err } value = gkv.Stob(val) return nil }) return }
// Delete deletes the given key from the database resources.
func (kv *KV) Delete(key []byte) error { return kv.db.Update(func(tx *buntdb.Tx) error { _, err := tx.Delete(gkv.Btos(key)) return err }) }
// Count returns the total number of all the keys.
func (kv *KV) Count() (i int) { kv.db.View(func(tx *buntdb.Tx) error { err := tx.Ascend("", func(key, value string) bool { i++ return true }) return err }) return }
// Iterator creates an iterator for iterating over all the keys.
func (kv *KV) Iterator(f func([]byte, []byte) bool) error { return kv.db.View(func(tx *buntdb.Tx) error { err := tx.Ascend("", func(key, value string) bool { return f(gkv.Stob(key), gkv.Stob(value)) }) return err }) }
// Register initializes a new database if it doesn't already exist.
func (kv *KV) Register(table []byte) error { if len(table) == 0 { return gkv.ErrTableName } kv.table = table _, err := kv.db.Exec(fmt.Sprintf(` PRAGMA foreign_keys = FALSE; CREATE TABLE IF NOT EXISTS %s ( id VARCHAR(34) NOT NULL, k TEXT NOT NULL, v TEXT NOT NULL, PRIMARY KEY (id) ); PRAGMA foreign_keys = TRUE; `, string(table))) return err }
// Put sets the value for a key.
func (kv *KV) Put(key, value []byte) error { _, err := kv.db.Exec( fmt.Sprintf("REPLACE INTO %s(id, k, v) VALUES (?,?,?)", string(kv.table)), kv.id(key), gkv.Btos(key), gkv.Btos(value), ) return err }
// Get retrieves the value for a key.
func (kv *KV) Get(key []byte) (value []byte) { rows, err := kv.db.Query( fmt.Sprintf("SELECT v FROM %s WHERE id=? LIMIT 1", string(kv.table)), kv.id(key), ) if err != nil { return } defer rows.Close() if rows.Next() { var s string err = rows.Scan(&s) value = gkv.Stob(s) } return }
// Delete deletes the given key from the database resources.
func (kv *KV) Delete(key []byte) error { _, err := kv.db.Exec( fmt.Sprintf("DELETE FROM %s WHERE id=?", string(kv.table)), kv.id(key), ) return err }
// Count returns the total number of all the keys.
func (kv *KV) Count() (i int) { rows, err := kv.db.Query( fmt.Sprintf("SELECT COUNT(*) FROM %s LIMIT 1", string(kv.table)), ) if err != nil { return } defer rows.Close() if rows.Next() { err = rows.Scan(&i) } return }
// Iterator creates an iterator for iterating over all the keys.
func (kv *KV) Iterator(f func([]byte, []byte) bool) error { rows, err := kv.db.Query( fmt.Sprintf("SELECT k, v FROM %s", string(kv.table)), ) if err != nil { return err } defer rows.Close() var k, v []byte for rows.Next() { if err = rows.Scan(&k, &v); err == nil { if !f(k, v) { break } } } return err }
// float32 version of math.Fmodf
func Mod(x, y float32) float32 { return float32(math.Mod(float64(x), float64(y))) }
// NewPackage wraps the given Job and assigned ID in a *Package and returns it.
func NewPackage(id int64, j Job) *Package { p := &Package{ ID: id, status: Queued, job: j, statusLock: new(sync.RWMutex), } return p }
// SetStatus sets the completion status of the Package.
func (p *Package) SetStatus(inc JobStatus) { p.statusLock.Lock() defer p.statusLock.Unlock() p.status = inc }
// Status returns the completion status of the package.
func (p *Package) Status() JobStatus { p.statusLock.RLock() defer p.statusLock.RUnlock() return p.status }
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder { return &Encoder{ enc: codec.NewEncoder(w, new(codec.CborHandle)), } }
// Error satisfies the error interface.
func (e Error) Error() string { return fmt.Sprintf("[%d] %s: %s", e, e.Title(), e.Description()) }
// Temporary returns true if the operation that generated the error may succeed // if retried at a later time.
func (e Error) Temporary() bool { return e == LeaderNotAvailable || e == BrokerNotAvailable || e == ReplicaNotAvailable || e == GroupLoadInProgress || e == GroupCoordinatorNotAvailable || e == RebalanceInProgress || e.Timeout() }
// Title returns a human readable title for the error.
func (e Error) Title() string { switch e { case Unknown: return "Unknown" case OffsetOutOfRange: return "Offset Out Of Range" case InvalidMessage: return "Invalid Message" case UnknownTopicOrPartition: return "Unknown Topic Or Partition" case InvalidMessageSize: return "Invalid Message Size" case LeaderNotAvailable: return "Leader Not Available" case NotLeaderForPartition: return "Not Leader For Partition" case RequestTimedOut: return "Request Timed Out" case BrokerNotAvailable: return "Broker Not Available" case ReplicaNotAvailable: return "Replica Not Available" case MessageSizeTooLarge: return "Message Size Too Large" case StaleControllerEpoch: return "Stale Controller Epoch" case OffsetMetadataTooLarge: return "Offset Metadata Too Large" case GroupLoadInProgress: return "Group Load In Progress" case GroupCoordinatorNotAvailable: return "Group Coordinator Not Available" case NotCoordinatorForGroup: return "Not Coordinator For Group" case InvalidTopic: return "Invalid Topic" case RecordListTooLarge: return "Record List Too Large" case NotEnoughReplicas: return "Not Enough Replicas" case NotEnoughReplicasAfterAppend: return "Not Enough Replicas After Append" case InvalidRequiredAcks: return "Invalid Required Acks" case IllegalGeneration: return "Illegal Generation" case InconsistentGroupProtocol: return "Inconsistent Group Protocol" case InvalidGroupId: return "Invalid Group ID" case UnknownMemberId: return "Unknown Member ID" case InvalidSessionTimeout: return "Invalid Session Timeout" case RebalanceInProgress: return "Rebalance In Progress" case InvalidCommitOffsetSize: return "Invalid Commit Offset Size" case TopicAuthorizationFailed: return "Topic Authorization Failed" case GroupAuthorizationFailed: return "Group Authorization Failed" case ClusterAuthorizationFailed: return "Cluster Authorization Failed" case InvalidTimestamp: return "Invalid Timestamp" case UnsupportedSASLMechanism: return "Unsupported SASL Mechanism" case IllegalSASLState: return "Illegal SASL State" case UnsupportedVersion: return "Unsupported Version" case TopicAlreadyExists: return "Topic Already Exists" case InvalidPartitionNumber: return "Invalid Partition Number" case InvalidReplicationFactor: return "Invalid Replication Factor" case InvalidReplicaAssignment: return "Invalid Replica Assignment" case InvalidConfiguration: return "Invalid Configuration" case NotController: return "Not Controller" case InvalidRequest: return "Invalid Request" case UnsupportedForMessageFormat: return "Unsupported For Message Format" case PolicyViolation: return "Policy Violation" case OutOfOrderSequenceNumber: return "Out Of Order Sequence Number" case DuplicateSequenceNumber: return "Duplicate Sequence Number" case InvalidProducerEpoch: return "Invalid Producer Epoch" case InvalidTransactionState: return "Invalid Transaction State" case InvalidProducerIDMapping: return "Invalid Producer ID Mapping" case InvalidTransactionTimeout: return "Invalid Transaction Timeout" case ConcurrentTransactions: return "Concurrent Transactions" case TransactionCoordinatorFenced: return "Transaction Coordinator Fenced" case TransactionalIDAuthorizationFailed: return "Transactional ID Authorization Failed" case SecurityDisabled: return "Security Disabled" case BrokerAuthorizationFailed: return "Broker Authorization Failed" } return "" }
// Spin all jobs
func (s *Spinner) Spin() error { for _, j := range s.jobs { go func(j *Job) { ticker := time.NewTicker(j.RunsEvery.Duration) for range ticker.C { cmd := exec.Command(j.Cmd, j.Args...) SigChan := make(chan os.Signal) p := &Process{id: uuid.NewV4().String(), cmd: cmd, SigChan: SigChan} err := j.AddProcess(p) if err == nil { go p.run() } } }(j) } return nil }
// Md5 md5 hash string
func Md5(str string) string { m := md5.New() io.WriteString(m, str) return hex.EncodeToString(m.Sum(nil)) }
// StrRepeat repeat string times
func StrRepeat(str string, times int) string { return strings.Repeat(str, times) }
// StrReplace replace find all occurs to string
func StrReplace(str string, find string, to string) string { return strings.Replace(str, find, to, -1) }
// Substr returns the substr from start to length.
func Substr(s string, dot string, lengthAndStart ...int) string { var start, length, argsLen, ln int argsLen = len(lengthAndStart) if argsLen > 0 { length = lengthAndStart[0] } if argsLen > 1 { start = lengthAndStart[1] } bt := []rune(s) if start < 0 { start = 0 } ln = len(bt) if start > ln { start = start % ln } end := start + length if end > (ln - 1) { end = ln } if dot == "" || end == ln { return string(bt[start:end]) } return string(bt[start:end]) + dot }
// GonicCase : webxTop => webx_top
func GonicCase(name string) string { s := make([]rune, 0, len(name)+3) for idx, chr := range name { if IsASCIIUpper(chr) && idx > 0 { if !IsASCIIUpper(s[len(s)-1]) { s = append(s, '_') } } if !IsASCIIUpper(chr) && idx > 1 { l := len(s) if IsASCIIUpper(s[l-1]) && IsASCIIUpper(s[l-2]) { s = append(s, s[l-1]) s[l-1] = '_' } } s = append(s, chr) } return strings.ToLower(string(s)) }
// TitleCase : webx_top => Webx_Top
func TitleCase(name string) string { var s []rune upNextChar := true name = strings.ToLower(name) for _, chr := range name { switch { case upNextChar: upNextChar = false chr = ToASCIIUpper(chr) case chr == '_': upNextChar = true continue } s = append(s, chr) } return string(s) }
// SnakeCase : WebxTop => webx_top
func SnakeCase(name string) string { var s []rune for idx, chr := range name { if isUpper := IsASCIIUpper(chr); isUpper { if idx > 0 { s = append(s, '_') } chr -= ('A' - 'a') } s = append(s, chr) } return string(s) }
// CamelCase : webx_top => webxTop
func CamelCase(s string) string { n := "" var capNext bool for _, v := range s { if v >= 'a' && v <= 'z' { if capNext { n += strings.ToUpper(string(v)) capNext = false } else { n += string(v) } continue } if v == '_' || v == ' ' { capNext = true } else { capNext = false n += string(v) } } return n }