repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
HiLittleCat/core
handler.go
ServeHTTP
func (hs *HandlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Get a context for the request from ctxPool. c := getContext(w, r) // Set some "good practice" default headers. c.ResponseWriter.Header().Set("Cache-Control", "no-cache") c.ResponseWriter.Header().Set("Content-Type", "application/json") c.ResponseWriter.Header().Set("Connection", "keep-alive") c.ResponseWriter.Header().Set("Vary", "Accept-Encoding") //c.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*") c.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "X-Requested-With") c.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") // Always recover form panics. defer c.Recover() // Enter the handlers stack. c.Next() // Respnose data // if c.written == false { // c.Fail(errors.New("not written")) // } // Put the context to ctxPool putContext(c) }
go
func (hs *HandlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Get a context for the request from ctxPool. c := getContext(w, r) // Set some "good practice" default headers. c.ResponseWriter.Header().Set("Cache-Control", "no-cache") c.ResponseWriter.Header().Set("Content-Type", "application/json") c.ResponseWriter.Header().Set("Connection", "keep-alive") c.ResponseWriter.Header().Set("Vary", "Accept-Encoding") //c.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*") c.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "X-Requested-With") c.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") // Always recover form panics. defer c.Recover() // Enter the handlers stack. c.Next() // Respnose data // if c.written == false { // c.Fail(errors.New("not written")) // } // Put the context to ctxPool putContext(c) }
[ "func", "(", "hs", "*", "HandlersStack", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "c", ":=", "getContext", "(", "w", ",", "r", ")", "\n", "c", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Set", "(", "\"Cache-Control\"", ",", "\"no-cache\"", ")", "\n", "c", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "c", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Set", "(", "\"Connection\"", ",", "\"keep-alive\"", ")", "\n", "c", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Set", "(", "\"Vary\"", ",", "\"Accept-Encoding\"", ")", "\n", "c", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Set", "(", "\"Access-Control-Allow-Headers\"", ",", "\"X-Requested-With\"", ")", "\n", "c", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Set", "(", "\"Access-Control-Allow-Methods\"", ",", "\"PUT,POST,GET,DELETE,OPTIONS\"", ")", "\n", "defer", "c", ".", "Recover", "(", ")", "\n", "c", ".", "Next", "(", ")", "\n", "putContext", "(", "c", ")", "\n", "}" ]
// ServeHTTP makes a context for the request, sets some good practice default headers and enters the handlers stack.
[ "ServeHTTP", "makes", "a", "context", "for", "the", "request", "sets", "some", "good", "practice", "default", "headers", "and", "enters", "the", "handlers", "stack", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/handler.go#L46-L71
test
HiLittleCat/core
routergroup.go
Use
func (group *RouterGroup) Use(middleware ...RouterHandler) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() }
go
func (group *RouterGroup) Use(middleware ...RouterHandler) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() }
[ "func", "(", "group", "*", "RouterGroup", ")", "Use", "(", "middleware", "...", "RouterHandler", ")", "IRoutes", "{", "group", ".", "Handlers", "=", "append", "(", "group", ".", "Handlers", ",", "middleware", "...", ")", "\n", "return", "group", ".", "returnObj", "(", ")", "\n", "}" ]
// Use adds middleware to the group, see example code in github.
[ "Use", "adds", "middleware", "to", "the", "group", "see", "example", "code", "in", "github", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/routergroup.go#L50-L53
test
HiLittleCat/core
routergroup.go
Group
func (group *RouterGroup) Group(relativePath string, handlers ...RouterHandler) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } }
go
func (group *RouterGroup) Group(relativePath string, handlers ...RouterHandler) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } }
[ "func", "(", "group", "*", "RouterGroup", ")", "Group", "(", "relativePath", "string", ",", "handlers", "...", "RouterHandler", ")", "*", "RouterGroup", "{", "return", "&", "RouterGroup", "{", "Handlers", ":", "group", ".", "combineHandlers", "(", "handlers", ")", ",", "basePath", ":", "group", ".", "calculateAbsolutePath", "(", "relativePath", ")", ",", "engine", ":", "group", ".", "engine", ",", "}", "\n", "}" ]
// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. // For example, all the routes that use a common middlware for authorization could be grouped.
[ "Group", "creates", "a", "new", "router", "group", ".", "You", "should", "add", "all", "the", "routes", "that", "have", "common", "middlwares", "or", "the", "same", "path", "prefix", ".", "For", "example", "all", "the", "routes", "that", "use", "a", "common", "middlware", "for", "authorization", "could", "be", "grouped", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/routergroup.go#L57-L63
test
HiLittleCat/core
server.go
Run
func Run() { for _, f := range beforeRun { f() } // parse command line params. if OpenCommandLine { flag.StringVar(&Address, "address", ":8080", "-address=:8080") flag.BoolVar(&Production, "production", false, "-production=false") flag.Parse() } log.Warnln(fmt.Sprintf("Serving %s with pid %d. Production is %t.", Address, os.Getpid(), Production)) // set default router. Use(Routers.handlers) // set graceful server. srv := &graceful.Server{ ListenLimit: ListenLimit, ConnState: func(conn net.Conn, state http.ConnState) { // conn has a new state }, Server: &http.Server{ Addr: Address, Handler: defaultHandlersStack, ReadTimeout: ReadTimeout, WriteTimeout: WriteTimeout, IdleTimeout: IdleTimeout, MaxHeaderBytes: MaxHeaderBytes, }, } err := srv.ListenAndServe() if err != nil { log.Fatalln(err) } log.Warnln("Server stoped.") }
go
func Run() { for _, f := range beforeRun { f() } // parse command line params. if OpenCommandLine { flag.StringVar(&Address, "address", ":8080", "-address=:8080") flag.BoolVar(&Production, "production", false, "-production=false") flag.Parse() } log.Warnln(fmt.Sprintf("Serving %s with pid %d. Production is %t.", Address, os.Getpid(), Production)) // set default router. Use(Routers.handlers) // set graceful server. srv := &graceful.Server{ ListenLimit: ListenLimit, ConnState: func(conn net.Conn, state http.ConnState) { // conn has a new state }, Server: &http.Server{ Addr: Address, Handler: defaultHandlersStack, ReadTimeout: ReadTimeout, WriteTimeout: WriteTimeout, IdleTimeout: IdleTimeout, MaxHeaderBytes: MaxHeaderBytes, }, } err := srv.ListenAndServe() if err != nil { log.Fatalln(err) } log.Warnln("Server stoped.") }
[ "func", "Run", "(", ")", "{", "for", "_", ",", "f", ":=", "range", "beforeRun", "{", "f", "(", ")", "\n", "}", "\n", "if", "OpenCommandLine", "{", "flag", ".", "StringVar", "(", "&", "Address", ",", "\"address\"", ",", "\":8080\"", ",", "\"-address=:8080\"", ")", "\n", "flag", ".", "BoolVar", "(", "&", "Production", ",", "\"production\"", ",", "false", ",", "\"-production=false\"", ")", "\n", "flag", ".", "Parse", "(", ")", "\n", "}", "\n", "log", ".", "Warnln", "(", "fmt", ".", "Sprintf", "(", "\"Serving %s with pid %d. Production is %t.\"", ",", "Address", ",", "os", ".", "Getpid", "(", ")", ",", "Production", ")", ")", "\n", "Use", "(", "Routers", ".", "handlers", ")", "\n", "srv", ":=", "&", "graceful", ".", "Server", "{", "ListenLimit", ":", "ListenLimit", ",", "ConnState", ":", "func", "(", "conn", "net", ".", "Conn", ",", "state", "http", ".", "ConnState", ")", "{", "}", ",", "Server", ":", "&", "http", ".", "Server", "{", "Addr", ":", "Address", ",", "Handler", ":", "defaultHandlersStack", ",", "ReadTimeout", ":", "ReadTimeout", ",", "WriteTimeout", ":", "WriteTimeout", ",", "IdleTimeout", ":", "IdleTimeout", ",", "MaxHeaderBytes", ":", "MaxHeaderBytes", ",", "}", ",", "}", "\n", "err", ":=", "srv", ".", "ListenAndServe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalln", "(", "err", ")", "\n", "}", "\n", "log", ".", "Warnln", "(", "\"Server stoped.\"", ")", "\n", "}" ]
// Run starts the server for listening and serving.
[ "Run", "starts", "the", "server", "for", "listening", "and", "serving", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/server.go#L65-L104
test
HiLittleCat/core
routerengine.go
create
func create() *Engine { engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, trees: make(methodTrees, 0, 9), } engine.RouterGroup.engine = engine return engine }
go
func create() *Engine { engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, trees: make(methodTrees, 0, 9), } engine.RouterGroup.engine = engine return engine }
[ "func", "create", "(", ")", "*", "Engine", "{", "engine", ":=", "&", "Engine", "{", "RouterGroup", ":", "RouterGroup", "{", "Handlers", ":", "nil", ",", "basePath", ":", "\"/\"", ",", "root", ":", "true", ",", "}", ",", "trees", ":", "make", "(", "methodTrees", ",", "0", ",", "9", ")", ",", "}", "\n", "engine", ".", "RouterGroup", ".", "engine", "=", "engine", "\n", "return", "engine", "\n", "}" ]
// create returns a new blank Engine instance without any middleware attached.
[ "create", "returns", "a", "new", "blank", "Engine", "instance", "without", "any", "middleware", "attached", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/routerengine.go#L30-L41
test
HiLittleCat/core
context.go
Redirect
func (ctx *Context) Redirect(url string, code int) { http.Redirect(ctx.ResponseWriter, ctx.Request, url, code) }
go
func (ctx *Context) Redirect(url string, code int) { http.Redirect(ctx.ResponseWriter, ctx.Request, url, code) }
[ "func", "(", "ctx", "*", "Context", ")", "Redirect", "(", "url", "string", ",", "code", "int", ")", "{", "http", ".", "Redirect", "(", "ctx", ".", "ResponseWriter", ",", "ctx", ".", "Request", ",", "url", ",", "code", ")", "\n", "}" ]
// Redirect Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
[ "Redirect", "Redirect", "replies", "to", "the", "request", "with", "a", "redirect", "to", "url", "which", "may", "be", "a", "path", "relative", "to", "the", "request", "path", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L47-L49
test
HiLittleCat/core
context.go
Ok
func (ctx *Context) Ok(data interface{}) { if ctx.written == true { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln("Context.Success: request has been writed") return } ctx.written = true var json = jsoniter.ConfigCompatibleWithStandardLibrary b, _ := json.Marshal(&ResFormat{Ok: true, Data: data}) ctx.ResponseWriter.WriteHeader(http.StatusOK) ctx.ResponseWriter.Write(b) }
go
func (ctx *Context) Ok(data interface{}) { if ctx.written == true { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln("Context.Success: request has been writed") return } ctx.written = true var json = jsoniter.ConfigCompatibleWithStandardLibrary b, _ := json.Marshal(&ResFormat{Ok: true, Data: data}) ctx.ResponseWriter.WriteHeader(http.StatusOK) ctx.ResponseWriter.Write(b) }
[ "func", "(", "ctx", "*", "Context", ")", "Ok", "(", "data", "interface", "{", "}", ")", "{", "if", "ctx", ".", "written", "==", "true", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"path\"", ":", "ctx", ".", "Request", ".", "URL", ".", "Path", "}", ")", ".", "Warnln", "(", "\"Context.Success: request has been writed\"", ")", "\n", "return", "\n", "}", "\n", "ctx", ".", "written", "=", "true", "\n", "var", "json", "=", "jsoniter", ".", "ConfigCompatibleWithStandardLibrary", "\n", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "&", "ResFormat", "{", "Ok", ":", "true", ",", "Data", ":", "data", "}", ")", "\n", "ctx", ".", "ResponseWriter", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "ctx", ".", "ResponseWriter", ".", "Write", "(", "b", ")", "\n", "}" ]
// Ok Response json
[ "Ok", "Response", "json" ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L52-L62
test
HiLittleCat/core
context.go
Fail
func (ctx *Context) Fail(err error) { if err == nil { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln("Context.Fail: err is nil") ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError) ctx.ResponseWriter.Write(nil) return } if ctx.written == true { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln("Context.Fail: request has been writed") return } errno := 0 errCore, ok := err.(ICoreError) if ok == true { errno = errCore.GetErrno() } ctx.written = true if Production == false { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln(err.Error()) } else if _, ok := err.(*ServerError); ok == true { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln(err.Error()) } var json = jsoniter.ConfigCompatibleWithStandardLibrary b, _ := json.Marshal(&ResFormat{Ok: false, Message: err.Error(), Errno: errno}) coreErr, ok := err.(ICoreError) if ok == true { ctx.ResponseWriter.WriteHeader(coreErr.GetHTTPCode()) } else { ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError) } ctx.ResponseWriter.Write(b) }
go
func (ctx *Context) Fail(err error) { if err == nil { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln("Context.Fail: err is nil") ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError) ctx.ResponseWriter.Write(nil) return } if ctx.written == true { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln("Context.Fail: request has been writed") return } errno := 0 errCore, ok := err.(ICoreError) if ok == true { errno = errCore.GetErrno() } ctx.written = true if Production == false { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln(err.Error()) } else if _, ok := err.(*ServerError); ok == true { log.WithFields(log.Fields{"path": ctx.Request.URL.Path}).Warnln(err.Error()) } var json = jsoniter.ConfigCompatibleWithStandardLibrary b, _ := json.Marshal(&ResFormat{Ok: false, Message: err.Error(), Errno: errno}) coreErr, ok := err.(ICoreError) if ok == true { ctx.ResponseWriter.WriteHeader(coreErr.GetHTTPCode()) } else { ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError) } ctx.ResponseWriter.Write(b) }
[ "func", "(", "ctx", "*", "Context", ")", "Fail", "(", "err", "error", ")", "{", "if", "err", "==", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"path\"", ":", "ctx", ".", "Request", ".", "URL", ".", "Path", "}", ")", ".", "Warnln", "(", "\"Context.Fail: err is nil\"", ")", "\n", "ctx", ".", "ResponseWriter", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "ctx", ".", "ResponseWriter", ".", "Write", "(", "nil", ")", "\n", "return", "\n", "}", "\n", "if", "ctx", ".", "written", "==", "true", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"path\"", ":", "ctx", ".", "Request", ".", "URL", ".", "Path", "}", ")", ".", "Warnln", "(", "\"Context.Fail: request has been writed\"", ")", "\n", "return", "\n", "}", "\n", "errno", ":=", "0", "\n", "errCore", ",", "ok", ":=", "err", ".", "(", "ICoreError", ")", "\n", "if", "ok", "==", "true", "{", "errno", "=", "errCore", ".", "GetErrno", "(", ")", "\n", "}", "\n", "ctx", ".", "written", "=", "true", "\n", "if", "Production", "==", "false", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"path\"", ":", "ctx", ".", "Request", ".", "URL", ".", "Path", "}", ")", ".", "Warnln", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "ServerError", ")", ";", "ok", "==", "true", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"path\"", ":", "ctx", ".", "Request", ".", "URL", ".", "Path", "}", ")", ".", "Warnln", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "var", "json", "=", "jsoniter", ".", "ConfigCompatibleWithStandardLibrary", "\n", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "&", "ResFormat", "{", "Ok", ":", "false", ",", "Message", ":", "err", ".", "Error", "(", ")", ",", "Errno", ":", "errno", "}", ")", "\n", "coreErr", ",", "ok", ":=", "err", ".", "(", "ICoreError", ")", "\n", "if", "ok", "==", "true", "{", "ctx", ".", "ResponseWriter", ".", "WriteHeader", "(", "coreErr", ".", "GetHTTPCode", "(", ")", ")", "\n", "}", "else", "{", "ctx", ".", "ResponseWriter", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "ctx", ".", "ResponseWriter", ".", "Write", "(", "b", ")", "\n", "}" ]
// Fail Response fail
[ "Fail", "Response", "fail" ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L65-L100
test
HiLittleCat/core
context.go
ResStatus
func (ctx *Context) ResStatus(code int) (int, error) { if ctx.written == true { return 0, errors.New("Context.ResStatus: request has been writed") } ctx.written = true ctx.ResponseWriter.WriteHeader(code) return fmt.Fprint(ctx.ResponseWriter, http.StatusText(code)) }
go
func (ctx *Context) ResStatus(code int) (int, error) { if ctx.written == true { return 0, errors.New("Context.ResStatus: request has been writed") } ctx.written = true ctx.ResponseWriter.WriteHeader(code) return fmt.Fprint(ctx.ResponseWriter, http.StatusText(code)) }
[ "func", "(", "ctx", "*", "Context", ")", "ResStatus", "(", "code", "int", ")", "(", "int", ",", "error", ")", "{", "if", "ctx", ".", "written", "==", "true", "{", "return", "0", ",", "errors", ".", "New", "(", "\"Context.ResStatus: request has been writed\"", ")", "\n", "}", "\n", "ctx", ".", "written", "=", "true", "\n", "ctx", ".", "ResponseWriter", ".", "WriteHeader", "(", "code", ")", "\n", "return", "fmt", ".", "Fprint", "(", "ctx", ".", "ResponseWriter", ",", "http", ".", "StatusText", "(", "code", ")", ")", "\n", "}" ]
// ResStatus Response status code, use http.StatusText to write the response.
[ "ResStatus", "Response", "status", "code", "use", "http", ".", "StatusText", "to", "write", "the", "response", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L139-L146
test
HiLittleCat/core
context.go
Next
func (ctx *Context) Next() { // Call the next handler only if there is one and the response hasn't been written. if !ctx.Written() && ctx.index < len(ctx.handlersStack.Handlers)-1 { ctx.index++ ctx.handlersStack.Handlers[ctx.index](ctx) } }
go
func (ctx *Context) Next() { // Call the next handler only if there is one and the response hasn't been written. if !ctx.Written() && ctx.index < len(ctx.handlersStack.Handlers)-1 { ctx.index++ ctx.handlersStack.Handlers[ctx.index](ctx) } }
[ "func", "(", "ctx", "*", "Context", ")", "Next", "(", ")", "{", "if", "!", "ctx", ".", "Written", "(", ")", "&&", "ctx", ".", "index", "<", "len", "(", "ctx", ".", "handlersStack", ".", "Handlers", ")", "-", "1", "{", "ctx", ".", "index", "++", "\n", "ctx", ".", "handlersStack", ".", "Handlers", "[", "ctx", ".", "index", "]", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// Next calls the next handler in the stack, but only if the response isn't already written.
[ "Next", "calls", "the", "next", "handler", "in", "the", "stack", "but", "only", "if", "the", "response", "isn", "t", "already", "written", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L154-L160
test
HiLittleCat/core
context.go
GetSession
func (ctx *Context) GetSession() IStore { store := ctx.Data["session"] if store == nil { return nil } st, ok := store.(IStore) if ok == false { return nil } return st }
go
func (ctx *Context) GetSession() IStore { store := ctx.Data["session"] if store == nil { return nil } st, ok := store.(IStore) if ok == false { return nil } return st }
[ "func", "(", "ctx", "*", "Context", ")", "GetSession", "(", ")", "IStore", "{", "store", ":=", "ctx", ".", "Data", "[", "\"session\"", "]", "\n", "if", "store", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "st", ",", "ok", ":=", "store", ".", "(", "IStore", ")", "\n", "if", "ok", "==", "false", "{", "return", "nil", "\n", "}", "\n", "return", "st", "\n", "}" ]
// GetSession get session
[ "GetSession", "get", "session" ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L173-L183
test
HiLittleCat/core
context.go
GetBodyJSON
func (ctx *Context) GetBodyJSON() { var reqJSON map[string]interface{} body, _ := ioutil.ReadAll(ctx.Request.Body) defer ctx.Request.Body.Close() cType := ctx.Request.Header.Get("Content-Type") a := strings.Split(cType, ";") if a[0] == "application/x-www-form-urlencoded" { reqJSON = make(map[string]interface{}) reqStr := string(body) reqArr := strings.Split(reqStr, "&") for _, v := range reqArr { param := strings.Split(v, "=") reqJSON[param[0]], _ = url.QueryUnescape(param[1]) } } else { json.Unmarshal(body, &reqJSON) } ctx.BodyJSON = reqJSON }
go
func (ctx *Context) GetBodyJSON() { var reqJSON map[string]interface{} body, _ := ioutil.ReadAll(ctx.Request.Body) defer ctx.Request.Body.Close() cType := ctx.Request.Header.Get("Content-Type") a := strings.Split(cType, ";") if a[0] == "application/x-www-form-urlencoded" { reqJSON = make(map[string]interface{}) reqStr := string(body) reqArr := strings.Split(reqStr, "&") for _, v := range reqArr { param := strings.Split(v, "=") reqJSON[param[0]], _ = url.QueryUnescape(param[1]) } } else { json.Unmarshal(body, &reqJSON) } ctx.BodyJSON = reqJSON }
[ "func", "(", "ctx", "*", "Context", ")", "GetBodyJSON", "(", ")", "{", "var", "reqJSON", "map", "[", "string", "]", "interface", "{", "}", "\n", "body", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "ctx", ".", "Request", ".", "Body", ")", "\n", "defer", "ctx", ".", "Request", ".", "Body", ".", "Close", "(", ")", "\n", "cType", ":=", "ctx", ".", "Request", ".", "Header", ".", "Get", "(", "\"Content-Type\"", ")", "\n", "a", ":=", "strings", ".", "Split", "(", "cType", ",", "\";\"", ")", "\n", "if", "a", "[", "0", "]", "==", "\"application/x-www-form-urlencoded\"", "{", "reqJSON", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "reqStr", ":=", "string", "(", "body", ")", "\n", "reqArr", ":=", "strings", ".", "Split", "(", "reqStr", ",", "\"&\"", ")", "\n", "for", "_", ",", "v", ":=", "range", "reqArr", "{", "param", ":=", "strings", ".", "Split", "(", "v", ",", "\"=\"", ")", "\n", "reqJSON", "[", "param", "[", "0", "]", "]", ",", "_", "=", "url", ".", "QueryUnescape", "(", "param", "[", "1", "]", ")", "\n", "}", "\n", "}", "else", "{", "json", ".", "Unmarshal", "(", "body", ",", "&", "reqJSON", ")", "\n", "}", "\n", "ctx", ".", "BodyJSON", "=", "reqJSON", "\n", "}" ]
// GetBodyJSON return a json from body
[ "GetBodyJSON", "return", "a", "json", "from", "body" ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L186-L204
test
HiLittleCat/core
context.go
SetSession
func (ctx *Context) SetSession(key string, values map[string]string) error { sid := ctx.genSid(key) values["Sid"] = sid timestamp := strconv.FormatInt(time.Now().Unix(), 10) token := ctx.genSid(key + timestamp) values["Token"] = token store, err := provider.Set(sid, values) if err != nil { return err } cookie := httpCookie cookie.Value = sid ctx.Data["session"] = store respCookie := ctx.ResponseWriter.Header().Get("Set-Cookie") if strings.HasPrefix(respCookie, cookie.Name) { ctx.ResponseWriter.Header().Del("Set-Cookie") } http.SetCookie(ctx.ResponseWriter, &cookie) return nil }
go
func (ctx *Context) SetSession(key string, values map[string]string) error { sid := ctx.genSid(key) values["Sid"] = sid timestamp := strconv.FormatInt(time.Now().Unix(), 10) token := ctx.genSid(key + timestamp) values["Token"] = token store, err := provider.Set(sid, values) if err != nil { return err } cookie := httpCookie cookie.Value = sid ctx.Data["session"] = store respCookie := ctx.ResponseWriter.Header().Get("Set-Cookie") if strings.HasPrefix(respCookie, cookie.Name) { ctx.ResponseWriter.Header().Del("Set-Cookie") } http.SetCookie(ctx.ResponseWriter, &cookie) return nil }
[ "func", "(", "ctx", "*", "Context", ")", "SetSession", "(", "key", "string", ",", "values", "map", "[", "string", "]", "string", ")", "error", "{", "sid", ":=", "ctx", ".", "genSid", "(", "key", ")", "\n", "values", "[", "\"Sid\"", "]", "=", "sid", "\n", "timestamp", ":=", "strconv", ".", "FormatInt", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "10", ")", "\n", "token", ":=", "ctx", ".", "genSid", "(", "key", "+", "timestamp", ")", "\n", "values", "[", "\"Token\"", "]", "=", "token", "\n", "store", ",", "err", ":=", "provider", ".", "Set", "(", "sid", ",", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cookie", ":=", "httpCookie", "\n", "cookie", ".", "Value", "=", "sid", "\n", "ctx", ".", "Data", "[", "\"session\"", "]", "=", "store", "\n", "respCookie", ":=", "ctx", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Get", "(", "\"Set-Cookie\"", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "respCookie", ",", "cookie", ".", "Name", ")", "{", "ctx", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Del", "(", "\"Set-Cookie\"", ")", "\n", "}", "\n", "http", ".", "SetCookie", "(", "ctx", ".", "ResponseWriter", ",", "&", "cookie", ")", "\n", "return", "nil", "\n", "}" ]
// SetSession set session
[ "SetSession", "set", "session" ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L207-L227
test
HiLittleCat/core
context.go
FreshSession
func (ctx *Context) FreshSession(key string) error { err := provider.UpExpire(key) if err != nil { return err } return nil }
go
func (ctx *Context) FreshSession(key string) error { err := provider.UpExpire(key) if err != nil { return err } return nil }
[ "func", "(", "ctx", "*", "Context", ")", "FreshSession", "(", "key", "string", ")", "error", "{", "err", ":=", "provider", ".", "UpExpire", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FreshSession set session
[ "FreshSession", "set", "session" ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L230-L236
test
HiLittleCat/core
context.go
DeleteSession
func (ctx *Context) DeleteSession() error { sid := ctx.Data["Sid"].(string) ctx.Data["session"] = nil provider.Destroy(sid) cookie := httpCookie cookie.MaxAge = -1 http.SetCookie(ctx.ResponseWriter, &cookie) return nil }
go
func (ctx *Context) DeleteSession() error { sid := ctx.Data["Sid"].(string) ctx.Data["session"] = nil provider.Destroy(sid) cookie := httpCookie cookie.MaxAge = -1 http.SetCookie(ctx.ResponseWriter, &cookie) return nil }
[ "func", "(", "ctx", "*", "Context", ")", "DeleteSession", "(", ")", "error", "{", "sid", ":=", "ctx", ".", "Data", "[", "\"Sid\"", "]", ".", "(", "string", ")", "\n", "ctx", ".", "Data", "[", "\"session\"", "]", "=", "nil", "\n", "provider", ".", "Destroy", "(", "sid", ")", "\n", "cookie", ":=", "httpCookie", "\n", "cookie", ".", "MaxAge", "=", "-", "1", "\n", "http", ".", "SetCookie", "(", "ctx", ".", "ResponseWriter", ",", "&", "cookie", ")", "\n", "return", "nil", "\n", "}" ]
// DeleteSession delete session
[ "DeleteSession", "delete", "session" ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L239-L247
test
HiLittleCat/core
context.go
Write
func (w contextWriter) Write(p []byte) (int, error) { w.context.written = true return w.ResponseWriter.Write(p) }
go
func (w contextWriter) Write(p []byte) (int, error) { w.context.written = true return w.ResponseWriter.Write(p) }
[ "func", "(", "w", "contextWriter", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "w", ".", "context", ".", "written", "=", "true", "\n", "return", "w", ".", "ResponseWriter", ".", "Write", "(", "p", ")", "\n", "}" ]
// Write sets the context's written flag before writing the response.
[ "Write", "sets", "the", "context", "s", "written", "flag", "before", "writing", "the", "response", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L336-L339
test
HiLittleCat/core
context.go
WriteHeader
func (w contextWriter) WriteHeader(code int) { w.context.written = true w.ResponseWriter.WriteHeader(code) }
go
func (w contextWriter) WriteHeader(code int) { w.context.written = true w.ResponseWriter.WriteHeader(code) }
[ "func", "(", "w", "contextWriter", ")", "WriteHeader", "(", "code", "int", ")", "{", "w", ".", "context", ".", "written", "=", "true", "\n", "w", ".", "ResponseWriter", ".", "WriteHeader", "(", "code", ")", "\n", "}" ]
// WriteHeader sets the context's written flag before writing the response header.
[ "WriteHeader", "sets", "the", "context", "s", "written", "flag", "before", "writing", "the", "response", "header", "." ]
ae2101184ecd36354d3fcff0ea69d67d3fdbe156
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L342-L345
test
dailyburn/bigquery
client/client.go
New
func New(pemPath string, options ...func(*Client) error) *Client { c := Client{ pemPath: pemPath, RequestTimeout: defaultRequestTimeout, } c.PrintDebug = false for _, option := range options { err := option(&c) if err != nil { return nil } } return &c }
go
func New(pemPath string, options ...func(*Client) error) *Client { c := Client{ pemPath: pemPath, RequestTimeout: defaultRequestTimeout, } c.PrintDebug = false for _, option := range options { err := option(&c) if err != nil { return nil } } return &c }
[ "func", "New", "(", "pemPath", "string", ",", "options", "...", "func", "(", "*", "Client", ")", "error", ")", "*", "Client", "{", "c", ":=", "Client", "{", "pemPath", ":", "pemPath", ",", "RequestTimeout", ":", "defaultRequestTimeout", ",", "}", "\n", "c", ".", "PrintDebug", "=", "false", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "err", ":=", "option", "(", "&", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "&", "c", "\n", "}" ]
// New instantiates a new client with the given params and return a reference to it
[ "New", "instantiates", "a", "new", "client", "with", "the", "given", "params", "and", "return", "a", "reference", "to", "it" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L43-L59
test
dailyburn/bigquery
client/client.go
setAllowLargeResults
func (c *Client) setAllowLargeResults(shouldAllow bool, tempTableName string, flattenResults bool) error { c.allowLargeResults = shouldAllow c.tempTableName = tempTableName c.flattenResults = flattenResults return nil }
go
func (c *Client) setAllowLargeResults(shouldAllow bool, tempTableName string, flattenResults bool) error { c.allowLargeResults = shouldAllow c.tempTableName = tempTableName c.flattenResults = flattenResults return nil }
[ "func", "(", "c", "*", "Client", ")", "setAllowLargeResults", "(", "shouldAllow", "bool", ",", "tempTableName", "string", ",", "flattenResults", "bool", ")", "error", "{", "c", ".", "allowLargeResults", "=", "shouldAllow", "\n", "c", ".", "tempTableName", "=", "tempTableName", "\n", "c", ".", "flattenResults", "=", "flattenResults", "\n", "return", "nil", "\n", "}" ]
// setAllowLargeResults - private function to set the AllowLargeResults and tempTableName values
[ "setAllowLargeResults", "-", "private", "function", "to", "set", "the", "AllowLargeResults", "and", "tempTableName", "values" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L75-L80
test
dailyburn/bigquery
client/client.go
connect
func (c *Client) connect() (*bigquery.Service, error) { if c.token != nil { if !c.token.Valid() && c.service != nil { return c.service, nil } } // generate auth token and create service object //authScope := bigquery.BigqueryScope pemKeyBytes, err := ioutil.ReadFile(c.pemPath) if err != nil { panic(err) } t, err := google.JWTConfigFromJSON( pemKeyBytes, "https://www.googleapis.com/auth/bigquery") //t := jwt.NewToken(c.accountEmailAddress, bigquery.BigqueryScope, pemKeyBytes) client := t.Client(oauth2.NoContext) service, err := bigquery.New(client) if err != nil { return nil, err } c.service = service return service, nil }
go
func (c *Client) connect() (*bigquery.Service, error) { if c.token != nil { if !c.token.Valid() && c.service != nil { return c.service, nil } } // generate auth token and create service object //authScope := bigquery.BigqueryScope pemKeyBytes, err := ioutil.ReadFile(c.pemPath) if err != nil { panic(err) } t, err := google.JWTConfigFromJSON( pemKeyBytes, "https://www.googleapis.com/auth/bigquery") //t := jwt.NewToken(c.accountEmailAddress, bigquery.BigqueryScope, pemKeyBytes) client := t.Client(oauth2.NoContext) service, err := bigquery.New(client) if err != nil { return nil, err } c.service = service return service, nil }
[ "func", "(", "c", "*", "Client", ")", "connect", "(", ")", "(", "*", "bigquery", ".", "Service", ",", "error", ")", "{", "if", "c", ".", "token", "!=", "nil", "{", "if", "!", "c", ".", "token", ".", "Valid", "(", ")", "&&", "c", ".", "service", "!=", "nil", "{", "return", "c", ".", "service", ",", "nil", "\n", "}", "\n", "}", "\n", "pemKeyBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "c", ".", "pemPath", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "t", ",", "err", ":=", "google", ".", "JWTConfigFromJSON", "(", "pemKeyBytes", ",", "\"https://www.googleapis.com/auth/bigquery\"", ")", "\n", "client", ":=", "t", ".", "Client", "(", "oauth2", ".", "NoContext", ")", "\n", "service", ",", "err", ":=", "bigquery", ".", "New", "(", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "service", "=", "service", "\n", "return", "service", ",", "nil", "\n", "}" ]
// connect - opens a new connection to bigquery, reusing the token if possible or regenerating a new auth token if required
[ "connect", "-", "opens", "a", "new", "connection", "to", "bigquery", "reusing", "the", "token", "if", "possible", "or", "regenerating", "a", "new", "auth", "token", "if", "required" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L83-L110
test
dailyburn/bigquery
client/client.go
InsertRow
func (c *Client) InsertRow(projectID, datasetID, tableID string, rowData map[string]interface{}) error { service, err := c.connect() if err != nil { return err } insertRequest := buildBigQueryInsertRequest([]map[string]interface{}{rowData}) result, err := service.Tabledata.InsertAll(projectID, datasetID, tableID, insertRequest).Do() if err != nil { c.printDebug("Error inserting row: ", err) return err } if len(result.InsertErrors) > 0 { return errors.New("Error inserting row") } return nil }
go
func (c *Client) InsertRow(projectID, datasetID, tableID string, rowData map[string]interface{}) error { service, err := c.connect() if err != nil { return err } insertRequest := buildBigQueryInsertRequest([]map[string]interface{}{rowData}) result, err := service.Tabledata.InsertAll(projectID, datasetID, tableID, insertRequest).Do() if err != nil { c.printDebug("Error inserting row: ", err) return err } if len(result.InsertErrors) > 0 { return errors.New("Error inserting row") } return nil }
[ "func", "(", "c", "*", "Client", ")", "InsertRow", "(", "projectID", ",", "datasetID", ",", "tableID", "string", ",", "rowData", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "service", ",", "err", ":=", "c", ".", "connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "insertRequest", ":=", "buildBigQueryInsertRequest", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "rowData", "}", ")", "\n", "result", ",", "err", ":=", "service", ".", "Tabledata", ".", "InsertAll", "(", "projectID", ",", "datasetID", ",", "tableID", ",", "insertRequest", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "printDebug", "(", "\"Error inserting row: \"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "if", "len", "(", "result", ".", "InsertErrors", ")", ">", "0", "{", "return", "errors", ".", "New", "(", "\"Error inserting row\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// InsertRow inserts a new row into the desired project, dataset and table or returns an error
[ "InsertRow", "inserts", "a", "new", "row", "into", "the", "desired", "project", "dataset", "and", "table", "or", "returns", "an", "error" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L113-L132
test
dailyburn/bigquery
client/client.go
AsyncQuery
func (c *Client) AsyncQuery(pageSize int, dataset, project, queryStr string, dataChan chan Data) { c.pagedQuery(pageSize, dataset, project, queryStr, dataChan) }
go
func (c *Client) AsyncQuery(pageSize int, dataset, project, queryStr string, dataChan chan Data) { c.pagedQuery(pageSize, dataset, project, queryStr, dataChan) }
[ "func", "(", "c", "*", "Client", ")", "AsyncQuery", "(", "pageSize", "int", ",", "dataset", ",", "project", ",", "queryStr", "string", ",", "dataChan", "chan", "Data", ")", "{", "c", ".", "pagedQuery", "(", "pageSize", ",", "dataset", ",", "project", ",", "queryStr", ",", "dataChan", ")", "\n", "}" ]
// AsyncQuery loads the data by paging through the query results and sends back payloads over the dataChan - dataChan sends a payload containing Data objects made up of the headers, rows and an error attribute
[ "AsyncQuery", "loads", "the", "data", "by", "paging", "through", "the", "query", "results", "and", "sends", "back", "payloads", "over", "the", "dataChan", "-", "dataChan", "sends", "a", "payload", "containing", "Data", "objects", "made", "up", "of", "the", "headers", "rows", "and", "an", "error", "attribute" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L172-L174
test
dailyburn/bigquery
client/client.go
Query
func (c *Client) Query(dataset, project, queryStr string) ([][]interface{}, []string, error) { return c.pagedQuery(defaultPageSize, dataset, project, queryStr, nil) }
go
func (c *Client) Query(dataset, project, queryStr string) ([][]interface{}, []string, error) { return c.pagedQuery(defaultPageSize, dataset, project, queryStr, nil) }
[ "func", "(", "c", "*", "Client", ")", "Query", "(", "dataset", ",", "project", ",", "queryStr", "string", ")", "(", "[", "]", "[", "]", "interface", "{", "}", ",", "[", "]", "string", ",", "error", ")", "{", "return", "c", ".", "pagedQuery", "(", "defaultPageSize", ",", "dataset", ",", "project", ",", "queryStr", ",", "nil", ")", "\n", "}" ]
// Query loads the data for the query paging if necessary and return the data rows, headers and error
[ "Query", "loads", "the", "data", "for", "the", "query", "paging", "if", "necessary", "and", "return", "the", "data", "rows", "headers", "and", "error" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L177-L179
test
dailyburn/bigquery
client/client.go
stdPagedQuery
func (c *Client) stdPagedQuery(service *bigquery.Service, pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) { c.printDebug("std paged query") datasetRef := &bigquery.DatasetReference{ DatasetId: dataset, ProjectId: project, } query := &bigquery.QueryRequest{ DefaultDataset: datasetRef, MaxResults: int64(pageSize), Kind: "json", Query: queryStr, } qr, err := service.Jobs.Query(project, query).Do() // extract the initial rows that have already been returned with the Query headers, rows := c.headersAndRows(qr.Schema, qr.Rows) if err != nil { c.printDebug("Error loading query: ", err) if dataChan != nil { dataChan <- Data{Err: err} } return nil, nil, err } return c.processPagedQuery(qr.JobReference, qr.PageToken, dataChan, headers, rows) }
go
func (c *Client) stdPagedQuery(service *bigquery.Service, pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) { c.printDebug("std paged query") datasetRef := &bigquery.DatasetReference{ DatasetId: dataset, ProjectId: project, } query := &bigquery.QueryRequest{ DefaultDataset: datasetRef, MaxResults: int64(pageSize), Kind: "json", Query: queryStr, } qr, err := service.Jobs.Query(project, query).Do() // extract the initial rows that have already been returned with the Query headers, rows := c.headersAndRows(qr.Schema, qr.Rows) if err != nil { c.printDebug("Error loading query: ", err) if dataChan != nil { dataChan <- Data{Err: err} } return nil, nil, err } return c.processPagedQuery(qr.JobReference, qr.PageToken, dataChan, headers, rows) }
[ "func", "(", "c", "*", "Client", ")", "stdPagedQuery", "(", "service", "*", "bigquery", ".", "Service", ",", "pageSize", "int", ",", "dataset", ",", "project", ",", "queryStr", "string", ",", "dataChan", "chan", "Data", ")", "(", "[", "]", "[", "]", "interface", "{", "}", ",", "[", "]", "string", ",", "error", ")", "{", "c", ".", "printDebug", "(", "\"std paged query\"", ")", "\n", "datasetRef", ":=", "&", "bigquery", ".", "DatasetReference", "{", "DatasetId", ":", "dataset", ",", "ProjectId", ":", "project", ",", "}", "\n", "query", ":=", "&", "bigquery", ".", "QueryRequest", "{", "DefaultDataset", ":", "datasetRef", ",", "MaxResults", ":", "int64", "(", "pageSize", ")", ",", "Kind", ":", "\"json\"", ",", "Query", ":", "queryStr", ",", "}", "\n", "qr", ",", "err", ":=", "service", ".", "Jobs", ".", "Query", "(", "project", ",", "query", ")", ".", "Do", "(", ")", "\n", "headers", ",", "rows", ":=", "c", ".", "headersAndRows", "(", "qr", ".", "Schema", ",", "qr", ".", "Rows", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "printDebug", "(", "\"Error loading query: \"", ",", "err", ")", "\n", "if", "dataChan", "!=", "nil", "{", "dataChan", "<-", "Data", "{", "Err", ":", "err", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "c", ".", "processPagedQuery", "(", "qr", ".", "JobReference", ",", "qr", ".", "PageToken", ",", "dataChan", ",", "headers", ",", "rows", ")", "\n", "}" ]
// stdPagedQuery executes a query using default job parameters and paging over the results, returning them over the data chan provided
[ "stdPagedQuery", "executes", "a", "query", "using", "default", "job", "parameters", "and", "paging", "over", "the", "results", "returning", "them", "over", "the", "data", "chan", "provided" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L182-L211
test
dailyburn/bigquery
client/client.go
largeDataPagedQuery
func (c *Client) largeDataPagedQuery(service *bigquery.Service, pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) { c.printDebug("largeDataPagedQuery starting") ts := time.Now() // start query tableRef := bigquery.TableReference{DatasetId: dataset, ProjectId: project, TableId: c.tempTableName} jobConfigQuery := bigquery.JobConfigurationQuery{} datasetRef := &bigquery.DatasetReference{ DatasetId: dataset, ProjectId: project, } jobConfigQuery.AllowLargeResults = true jobConfigQuery.Query = queryStr jobConfigQuery.DestinationTable = &tableRef jobConfigQuery.DefaultDataset = datasetRef if !c.flattenResults { c.printDebug("setting FlattenResults to false") // need a pointer to bool f := false jobConfigQuery.FlattenResults = &f } jobConfigQuery.WriteDisposition = "WRITE_TRUNCATE" jobConfigQuery.CreateDisposition = "CREATE_IF_NEEDED" jobConfig := bigquery.JobConfiguration{} jobConfig.Query = &jobConfigQuery job := bigquery.Job{} job.Configuration = &jobConfig jobInsert := service.Jobs.Insert(project, &job) runningJob, jerr := jobInsert.Do() if jerr != nil { c.printDebug("Error inserting job!", jerr) if dataChan != nil { dataChan <- Data{Err: jerr} } return nil, nil, jerr } var qr *bigquery.GetQueryResultsResponse var rows [][]interface{} var headers []string var err error // Periodically, job references are not created, but errors are also not thrown. // In this scenario, retry up to 5 times to get a job reference before giving up. for i := 1; ; i++ { r := service.Jobs.GetQueryResults(project, runningJob.JobReference.JobId) r.TimeoutMs(c.RequestTimeout) qr, err = r.Do() headers, rows = c.headersAndRows(qr.Schema, qr.Rows) if i >= maxRequestRetry || qr.JobReference != nil || err != nil { if i > 1 { c.printDebug("Took %v tries to get a job reference", i) } break } } if err == nil && qr.JobReference == nil { err = fmt.Errorf("missing job reference") } if err != nil { c.printDebug("Error loading query: ", err) if dataChan != nil { dataChan <- Data{Err: err} } return nil, nil, err } rows, headers, err = c.processPagedQuery(qr.JobReference, qr.PageToken, dataChan, headers, rows) c.printDebug("largeDataPagedQuery completed in ", time.Now().Sub(ts).Seconds(), "s") return rows, headers, err }
go
func (c *Client) largeDataPagedQuery(service *bigquery.Service, pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) { c.printDebug("largeDataPagedQuery starting") ts := time.Now() // start query tableRef := bigquery.TableReference{DatasetId: dataset, ProjectId: project, TableId: c.tempTableName} jobConfigQuery := bigquery.JobConfigurationQuery{} datasetRef := &bigquery.DatasetReference{ DatasetId: dataset, ProjectId: project, } jobConfigQuery.AllowLargeResults = true jobConfigQuery.Query = queryStr jobConfigQuery.DestinationTable = &tableRef jobConfigQuery.DefaultDataset = datasetRef if !c.flattenResults { c.printDebug("setting FlattenResults to false") // need a pointer to bool f := false jobConfigQuery.FlattenResults = &f } jobConfigQuery.WriteDisposition = "WRITE_TRUNCATE" jobConfigQuery.CreateDisposition = "CREATE_IF_NEEDED" jobConfig := bigquery.JobConfiguration{} jobConfig.Query = &jobConfigQuery job := bigquery.Job{} job.Configuration = &jobConfig jobInsert := service.Jobs.Insert(project, &job) runningJob, jerr := jobInsert.Do() if jerr != nil { c.printDebug("Error inserting job!", jerr) if dataChan != nil { dataChan <- Data{Err: jerr} } return nil, nil, jerr } var qr *bigquery.GetQueryResultsResponse var rows [][]interface{} var headers []string var err error // Periodically, job references are not created, but errors are also not thrown. // In this scenario, retry up to 5 times to get a job reference before giving up. for i := 1; ; i++ { r := service.Jobs.GetQueryResults(project, runningJob.JobReference.JobId) r.TimeoutMs(c.RequestTimeout) qr, err = r.Do() headers, rows = c.headersAndRows(qr.Schema, qr.Rows) if i >= maxRequestRetry || qr.JobReference != nil || err != nil { if i > 1 { c.printDebug("Took %v tries to get a job reference", i) } break } } if err == nil && qr.JobReference == nil { err = fmt.Errorf("missing job reference") } if err != nil { c.printDebug("Error loading query: ", err) if dataChan != nil { dataChan <- Data{Err: err} } return nil, nil, err } rows, headers, err = c.processPagedQuery(qr.JobReference, qr.PageToken, dataChan, headers, rows) c.printDebug("largeDataPagedQuery completed in ", time.Now().Sub(ts).Seconds(), "s") return rows, headers, err }
[ "func", "(", "c", "*", "Client", ")", "largeDataPagedQuery", "(", "service", "*", "bigquery", ".", "Service", ",", "pageSize", "int", ",", "dataset", ",", "project", ",", "queryStr", "string", ",", "dataChan", "chan", "Data", ")", "(", "[", "]", "[", "]", "interface", "{", "}", ",", "[", "]", "string", ",", "error", ")", "{", "c", ".", "printDebug", "(", "\"largeDataPagedQuery starting\"", ")", "\n", "ts", ":=", "time", ".", "Now", "(", ")", "\n", "tableRef", ":=", "bigquery", ".", "TableReference", "{", "DatasetId", ":", "dataset", ",", "ProjectId", ":", "project", ",", "TableId", ":", "c", ".", "tempTableName", "}", "\n", "jobConfigQuery", ":=", "bigquery", ".", "JobConfigurationQuery", "{", "}", "\n", "datasetRef", ":=", "&", "bigquery", ".", "DatasetReference", "{", "DatasetId", ":", "dataset", ",", "ProjectId", ":", "project", ",", "}", "\n", "jobConfigQuery", ".", "AllowLargeResults", "=", "true", "\n", "jobConfigQuery", ".", "Query", "=", "queryStr", "\n", "jobConfigQuery", ".", "DestinationTable", "=", "&", "tableRef", "\n", "jobConfigQuery", ".", "DefaultDataset", "=", "datasetRef", "\n", "if", "!", "c", ".", "flattenResults", "{", "c", ".", "printDebug", "(", "\"setting FlattenResults to false\"", ")", "\n", "f", ":=", "false", "\n", "jobConfigQuery", ".", "FlattenResults", "=", "&", "f", "\n", "}", "\n", "jobConfigQuery", ".", "WriteDisposition", "=", "\"WRITE_TRUNCATE\"", "\n", "jobConfigQuery", ".", "CreateDisposition", "=", "\"CREATE_IF_NEEDED\"", "\n", "jobConfig", ":=", "bigquery", ".", "JobConfiguration", "{", "}", "\n", "jobConfig", ".", "Query", "=", "&", "jobConfigQuery", "\n", "job", ":=", "bigquery", ".", "Job", "{", "}", "\n", "job", ".", "Configuration", "=", "&", "jobConfig", "\n", "jobInsert", ":=", "service", ".", "Jobs", ".", "Insert", "(", "project", ",", "&", "job", ")", "\n", "runningJob", ",", "jerr", ":=", "jobInsert", ".", "Do", "(", ")", "\n", "if", "jerr", "!=", "nil", "{", "c", ".", "printDebug", "(", "\"Error inserting job!\"", ",", "jerr", ")", "\n", "if", "dataChan", "!=", "nil", "{", "dataChan", "<-", "Data", "{", "Err", ":", "jerr", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "jerr", "\n", "}", "\n", "var", "qr", "*", "bigquery", ".", "GetQueryResultsResponse", "\n", "var", "rows", "[", "]", "[", "]", "interface", "{", "}", "\n", "var", "headers", "[", "]", "string", "\n", "var", "err", "error", "\n", "for", "i", ":=", "1", ";", ";", "i", "++", "{", "r", ":=", "service", ".", "Jobs", ".", "GetQueryResults", "(", "project", ",", "runningJob", ".", "JobReference", ".", "JobId", ")", "\n", "r", ".", "TimeoutMs", "(", "c", ".", "RequestTimeout", ")", "\n", "qr", ",", "err", "=", "r", ".", "Do", "(", ")", "\n", "headers", ",", "rows", "=", "c", ".", "headersAndRows", "(", "qr", ".", "Schema", ",", "qr", ".", "Rows", ")", "\n", "if", "i", ">=", "maxRequestRetry", "||", "qr", ".", "JobReference", "!=", "nil", "||", "err", "!=", "nil", "{", "if", "i", ">", "1", "{", "c", ".", "printDebug", "(", "\"Took %v tries to get a job reference\"", ",", "i", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "err", "==", "nil", "&&", "qr", ".", "JobReference", "==", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"missing job reference\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "c", ".", "printDebug", "(", "\"Error loading query: \"", ",", "err", ")", "\n", "if", "dataChan", "!=", "nil", "{", "dataChan", "<-", "Data", "{", "Err", ":", "err", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "rows", ",", "headers", ",", "err", "=", "c", ".", "processPagedQuery", "(", "qr", ".", "JobReference", ",", "qr", ".", "PageToken", ",", "dataChan", ",", "headers", ",", "rows", ")", "\n", "c", ".", "printDebug", "(", "\"largeDataPagedQuery completed in \"", ",", "time", ".", "Now", "(", ")", ".", "Sub", "(", "ts", ")", ".", "Seconds", "(", ")", ",", "\"s\"", ")", "\n", "return", "rows", ",", "headers", ",", "err", "\n", "}" ]
// largeDataPagedQuery builds a job and inserts it into the job queue allowing the flexibility to set the custom AllowLargeResults flag for the job
[ "largeDataPagedQuery", "builds", "a", "job", "and", "inserts", "it", "into", "the", "job", "queue", "allowing", "the", "flexibility", "to", "set", "the", "custom", "AllowLargeResults", "flag", "for", "the", "job" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L214-L295
test
dailyburn/bigquery
client/client.go
pagedQuery
func (c *Client) pagedQuery(pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) { // connect to service service, err := c.connect() if err != nil { if dataChan != nil { dataChan <- Data{Err: err} } return nil, nil, err } if c.allowLargeResults && len(c.tempTableName) > 0 { return c.largeDataPagedQuery(service, pageSize, dataset, project, queryStr, dataChan) } return c.stdPagedQuery(service, pageSize, dataset, project, queryStr, dataChan) }
go
func (c *Client) pagedQuery(pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) { // connect to service service, err := c.connect() if err != nil { if dataChan != nil { dataChan <- Data{Err: err} } return nil, nil, err } if c.allowLargeResults && len(c.tempTableName) > 0 { return c.largeDataPagedQuery(service, pageSize, dataset, project, queryStr, dataChan) } return c.stdPagedQuery(service, pageSize, dataset, project, queryStr, dataChan) }
[ "func", "(", "c", "*", "Client", ")", "pagedQuery", "(", "pageSize", "int", ",", "dataset", ",", "project", ",", "queryStr", "string", ",", "dataChan", "chan", "Data", ")", "(", "[", "]", "[", "]", "interface", "{", "}", ",", "[", "]", "string", ",", "error", ")", "{", "service", ",", "err", ":=", "c", ".", "connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "dataChan", "!=", "nil", "{", "dataChan", "<-", "Data", "{", "Err", ":", "err", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "c", ".", "allowLargeResults", "&&", "len", "(", "c", ".", "tempTableName", ")", ">", "0", "{", "return", "c", ".", "largeDataPagedQuery", "(", "service", ",", "pageSize", ",", "dataset", ",", "project", ",", "queryStr", ",", "dataChan", ")", "\n", "}", "\n", "return", "c", ".", "stdPagedQuery", "(", "service", ",", "pageSize", ",", "dataset", ",", "project", ",", "queryStr", ",", "dataChan", ")", "\n", "}" ]
// pagedQuery executes the query using bq's paging mechanism to load all results and sends them back via dataChan if available, otherwise it returns the full result set, headers and error as return values
[ "pagedQuery", "executes", "the", "query", "using", "bq", "s", "paging", "mechanism", "to", "load", "all", "results", "and", "sends", "them", "back", "via", "dataChan", "if", "available", "otherwise", "it", "returns", "the", "full", "result", "set", "headers", "and", "error", "as", "return", "values" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L298-L313
test
dailyburn/bigquery
client/client.go
pageOverJob
func (c *Client) pageOverJob(rowCount int, jobRef *bigquery.JobReference, pageToken string, resultChan chan [][]interface{}, headersChan chan []string) error { service, err := c.connect() if err != nil { return err } qrc := service.Jobs.GetQueryResults(jobRef.ProjectId, jobRef.JobId) if len(pageToken) > 0 { qrc.PageToken(pageToken) } qr, err := qrc.Do() if err != nil { c.printDebug("Error loading additional data: ", err) close(resultChan) return err } if qr.JobComplete { c.printDebug("qr.JobComplete") headers, rows := c.headersAndRows(qr.Schema, qr.Rows) if headersChan != nil { headersChan <- headers close(headersChan) } // send back the rows we got c.printDebug("sending rows") resultChan <- rows rowCount = rowCount + len(rows) c.printDebug("Total rows: ", rowCount) } if qr.TotalRows > uint64(rowCount) || !qr.JobComplete { c.printDebug("!qr.JobComplete") if qr.JobReference == nil { c.pageOverJob(rowCount, jobRef, pageToken, resultChan, headersChan) } else { c.pageOverJob(rowCount, qr.JobReference, qr.PageToken, resultChan, nil) } } else { close(resultChan) return nil } return nil }
go
func (c *Client) pageOverJob(rowCount int, jobRef *bigquery.JobReference, pageToken string, resultChan chan [][]interface{}, headersChan chan []string) error { service, err := c.connect() if err != nil { return err } qrc := service.Jobs.GetQueryResults(jobRef.ProjectId, jobRef.JobId) if len(pageToken) > 0 { qrc.PageToken(pageToken) } qr, err := qrc.Do() if err != nil { c.printDebug("Error loading additional data: ", err) close(resultChan) return err } if qr.JobComplete { c.printDebug("qr.JobComplete") headers, rows := c.headersAndRows(qr.Schema, qr.Rows) if headersChan != nil { headersChan <- headers close(headersChan) } // send back the rows we got c.printDebug("sending rows") resultChan <- rows rowCount = rowCount + len(rows) c.printDebug("Total rows: ", rowCount) } if qr.TotalRows > uint64(rowCount) || !qr.JobComplete { c.printDebug("!qr.JobComplete") if qr.JobReference == nil { c.pageOverJob(rowCount, jobRef, pageToken, resultChan, headersChan) } else { c.pageOverJob(rowCount, qr.JobReference, qr.PageToken, resultChan, nil) } } else { close(resultChan) return nil } return nil }
[ "func", "(", "c", "*", "Client", ")", "pageOverJob", "(", "rowCount", "int", ",", "jobRef", "*", "bigquery", ".", "JobReference", ",", "pageToken", "string", ",", "resultChan", "chan", "[", "]", "[", "]", "interface", "{", "}", ",", "headersChan", "chan", "[", "]", "string", ")", "error", "{", "service", ",", "err", ":=", "c", ".", "connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "qrc", ":=", "service", ".", "Jobs", ".", "GetQueryResults", "(", "jobRef", ".", "ProjectId", ",", "jobRef", ".", "JobId", ")", "\n", "if", "len", "(", "pageToken", ")", ">", "0", "{", "qrc", ".", "PageToken", "(", "pageToken", ")", "\n", "}", "\n", "qr", ",", "err", ":=", "qrc", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "printDebug", "(", "\"Error loading additional data: \"", ",", "err", ")", "\n", "close", "(", "resultChan", ")", "\n", "return", "err", "\n", "}", "\n", "if", "qr", ".", "JobComplete", "{", "c", ".", "printDebug", "(", "\"qr.JobComplete\"", ")", "\n", "headers", ",", "rows", ":=", "c", ".", "headersAndRows", "(", "qr", ".", "Schema", ",", "qr", ".", "Rows", ")", "\n", "if", "headersChan", "!=", "nil", "{", "headersChan", "<-", "headers", "\n", "close", "(", "headersChan", ")", "\n", "}", "\n", "c", ".", "printDebug", "(", "\"sending rows\"", ")", "\n", "resultChan", "<-", "rows", "\n", "rowCount", "=", "rowCount", "+", "len", "(", "rows", ")", "\n", "c", ".", "printDebug", "(", "\"Total rows: \"", ",", "rowCount", ")", "\n", "}", "\n", "if", "qr", ".", "TotalRows", ">", "uint64", "(", "rowCount", ")", "||", "!", "qr", ".", "JobComplete", "{", "c", ".", "printDebug", "(", "\"!qr.JobComplete\"", ")", "\n", "if", "qr", ".", "JobReference", "==", "nil", "{", "c", ".", "pageOverJob", "(", "rowCount", ",", "jobRef", ",", "pageToken", ",", "resultChan", ",", "headersChan", ")", "\n", "}", "else", "{", "c", ".", "pageOverJob", "(", "rowCount", ",", "qr", ".", "JobReference", ",", "qr", ".", "PageToken", ",", "resultChan", ",", "nil", ")", "\n", "}", "\n", "}", "else", "{", "close", "(", "resultChan", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// pageOverJob loads results for the given job reference and if the total results has not been hit continues to load recursively
[ "pageOverJob", "loads", "results", "for", "the", "given", "job", "reference", "and", "if", "the", "total", "results", "has", "not", "been", "hit", "continues", "to", "load", "recursively" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L350-L396
test
dailyburn/bigquery
client/client.go
Count
func (c *Client) Count(dataset, project, datasetTable string) int64 { qstr := fmt.Sprintf("select count(*) from [%s]", datasetTable) res, err := c.SyncQuery(dataset, project, qstr, 1) if err == nil { if len(res) > 0 { val, _ := strconv.ParseInt(res[0][0].(string), 10, 64) return val } } return 0 }
go
func (c *Client) Count(dataset, project, datasetTable string) int64 { qstr := fmt.Sprintf("select count(*) from [%s]", datasetTable) res, err := c.SyncQuery(dataset, project, qstr, 1) if err == nil { if len(res) > 0 { val, _ := strconv.ParseInt(res[0][0].(string), 10, 64) return val } } return 0 }
[ "func", "(", "c", "*", "Client", ")", "Count", "(", "dataset", ",", "project", ",", "datasetTable", "string", ")", "int64", "{", "qstr", ":=", "fmt", ".", "Sprintf", "(", "\"select count(*) from [%s]\"", ",", "datasetTable", ")", "\n", "res", ",", "err", ":=", "c", ".", "SyncQuery", "(", "dataset", ",", "project", ",", "qstr", ",", "1", ")", "\n", "if", "err", "==", "nil", "{", "if", "len", "(", "res", ")", ">", "0", "{", "val", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "res", "[", "0", "]", "[", "0", "]", ".", "(", "string", ")", ",", "10", ",", "64", ")", "\n", "return", "val", "\n", "}", "\n", "}", "\n", "return", "0", "\n", "}" ]
// Count loads the row count for the provided dataset.tablename
[ "Count", "loads", "the", "row", "count", "for", "the", "provided", "dataset", ".", "tablename" ]
b6f18972580ed8882d195da0e9b7c9b94902a1ea
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L519-L529
test
stefantalpalaru/pool
examples/web_crawler.go
work
func work(args ...interface{}) interface{} { url := args[0].(string) depth := args[1].(int) fetcher := args[2].(Fetcher) if depth <= 0 { return crawlResult{} } body, urls, err := fetcher.Fetch(url) return crawlResult{body, urls, err} }
go
func work(args ...interface{}) interface{} { url := args[0].(string) depth := args[1].(int) fetcher := args[2].(Fetcher) if depth <= 0 { return crawlResult{} } body, urls, err := fetcher.Fetch(url) return crawlResult{body, urls, err} }
[ "func", "work", "(", "args", "...", "interface", "{", "}", ")", "interface", "{", "}", "{", "url", ":=", "args", "[", "0", "]", ".", "(", "string", ")", "\n", "depth", ":=", "args", "[", "1", "]", ".", "(", "int", ")", "\n", "fetcher", ":=", "args", "[", "2", "]", ".", "(", "Fetcher", ")", "\n", "if", "depth", "<=", "0", "{", "return", "crawlResult", "{", "}", "\n", "}", "\n", "body", ",", "urls", ",", "err", ":=", "fetcher", ".", "Fetch", "(", "url", ")", "\n", "return", "crawlResult", "{", "body", ",", "urls", ",", "err", "}", "\n", "}" ]
// work uses fetcher to recursively crawl // pages starting with url, to a maximum of depth.
[ "work", "uses", "fetcher", "to", "recursively", "crawl", "pages", "starting", "with", "url", "to", "a", "maximum", "of", "depth", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/examples/web_crawler.go#L28-L37
test
stefantalpalaru/pool
pool.go
subworker
func (pool *Pool) subworker(job *Job) { defer func() { if err := recover(); err != nil { log.Println("panic while running job:", err) job.Result = nil job.Err = fmt.Errorf(err.(string)) } }() job.Result = job.F(job.Args...) }
go
func (pool *Pool) subworker(job *Job) { defer func() { if err := recover(); err != nil { log.Println("panic while running job:", err) job.Result = nil job.Err = fmt.Errorf(err.(string)) } }() job.Result = job.F(job.Args...) }
[ "func", "(", "pool", "*", "Pool", ")", "subworker", "(", "job", "*", "Job", ")", "{", "defer", "func", "(", ")", "{", "if", "err", ":=", "recover", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Println", "(", "\"panic while running job:\"", ",", "err", ")", "\n", "job", ".", "Result", "=", "nil", "\n", "job", ".", "Err", "=", "fmt", ".", "Errorf", "(", "err", ".", "(", "string", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "job", ".", "Result", "=", "job", ".", "F", "(", "job", ".", "Args", "...", ")", "\n", "}" ]
// subworker catches any panic while running the job.
[ "subworker", "catches", "any", "panic", "while", "running", "the", "job", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L63-L72
test
stefantalpalaru/pool
pool.go
worker
func (pool *Pool) worker(worker_id uint) { job_pipe := make(chan *Job) WORKER_LOOP: for { pool.job_wanted_pipe <- job_pipe job := <-job_pipe if job == nil { time.Sleep(pool.interval * time.Millisecond) } else { job.Worker_id = worker_id pool.subworker(job) pool.done_pipe <- job } select { case <-pool.worker_kill_pipe: break WORKER_LOOP default: } } pool.worker_wg.Done() }
go
func (pool *Pool) worker(worker_id uint) { job_pipe := make(chan *Job) WORKER_LOOP: for { pool.job_wanted_pipe <- job_pipe job := <-job_pipe if job == nil { time.Sleep(pool.interval * time.Millisecond) } else { job.Worker_id = worker_id pool.subworker(job) pool.done_pipe <- job } select { case <-pool.worker_kill_pipe: break WORKER_LOOP default: } } pool.worker_wg.Done() }
[ "func", "(", "pool", "*", "Pool", ")", "worker", "(", "worker_id", "uint", ")", "{", "job_pipe", ":=", "make", "(", "chan", "*", "Job", ")", "\n", "WORKER_LOOP", ":", "for", "{", "pool", ".", "job_wanted_pipe", "<-", "job_pipe", "\n", "job", ":=", "<-", "job_pipe", "\n", "if", "job", "==", "nil", "{", "time", ".", "Sleep", "(", "pool", ".", "interval", "*", "time", ".", "Millisecond", ")", "\n", "}", "else", "{", "job", ".", "Worker_id", "=", "worker_id", "\n", "pool", ".", "subworker", "(", "job", ")", "\n", "pool", ".", "done_pipe", "<-", "job", "\n", "}", "\n", "select", "{", "case", "<-", "pool", ".", "worker_kill_pipe", ":", "break", "WORKER_LOOP", "\n", "default", ":", "}", "\n", "}", "\n", "pool", ".", "worker_wg", ".", "Done", "(", ")", "\n", "}" ]
// worker gets a job from the job_pipe, passes it to a // subworker and puts the job in the done_pipe when finished.
[ "worker", "gets", "a", "job", "from", "the", "job_pipe", "passes", "it", "to", "a", "subworker", "and", "puts", "the", "job", "in", "the", "done_pipe", "when", "finished", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L76-L96
test
stefantalpalaru/pool
pool.go
supervisor
func (pool *Pool) supervisor() { SUPERVISOR_LOOP: for { select { // new job case job := <-pool.add_pipe: pool.jobs_ready_to_run.PushBack(job) pool.num_jobs_submitted++ job.added <- true // send jobs to the workers case job_pipe := <-pool.job_wanted_pipe: element := pool.jobs_ready_to_run.Front() var job *Job = nil if element != nil { job = element.Value.(*Job) pool.num_jobs_running++ pool.jobs_ready_to_run.Remove(element) } job_pipe <- job // job completed case job := <-pool.done_pipe: pool.num_jobs_running-- pool.jobs_completed.PushBack(job) pool.num_jobs_completed++ // wait for job case result_pipe := <-pool.result_wanted_pipe: close_pipe := false job := (*Job)(nil) element := pool.jobs_completed.Front() if element != nil { job = element.Value.(*Job) pool.jobs_completed.Remove(element) } else { if pool.num_jobs_running == 0 && pool.num_jobs_completed == pool.num_jobs_submitted { close_pipe = true } } if close_pipe { close(result_pipe) } else { result_pipe <- job } // is the pool working or just lazing on a Sunday afternoon? case working_pipe := <-pool.working_wanted_pipe: working := true if pool.jobs_ready_to_run.Len() == 0 && pool.num_jobs_running == 0 { working = false } working_pipe <- working // stats case stats_pipe := <-pool.stats_wanted_pipe: pool_stats := stats{pool.num_jobs_submitted, pool.num_jobs_running, pool.num_jobs_completed} stats_pipe <- pool_stats // stopping case <-pool.supervisor_kill_pipe: break SUPERVISOR_LOOP } } pool.supervisor_wg.Done() }
go
func (pool *Pool) supervisor() { SUPERVISOR_LOOP: for { select { // new job case job := <-pool.add_pipe: pool.jobs_ready_to_run.PushBack(job) pool.num_jobs_submitted++ job.added <- true // send jobs to the workers case job_pipe := <-pool.job_wanted_pipe: element := pool.jobs_ready_to_run.Front() var job *Job = nil if element != nil { job = element.Value.(*Job) pool.num_jobs_running++ pool.jobs_ready_to_run.Remove(element) } job_pipe <- job // job completed case job := <-pool.done_pipe: pool.num_jobs_running-- pool.jobs_completed.PushBack(job) pool.num_jobs_completed++ // wait for job case result_pipe := <-pool.result_wanted_pipe: close_pipe := false job := (*Job)(nil) element := pool.jobs_completed.Front() if element != nil { job = element.Value.(*Job) pool.jobs_completed.Remove(element) } else { if pool.num_jobs_running == 0 && pool.num_jobs_completed == pool.num_jobs_submitted { close_pipe = true } } if close_pipe { close(result_pipe) } else { result_pipe <- job } // is the pool working or just lazing on a Sunday afternoon? case working_pipe := <-pool.working_wanted_pipe: working := true if pool.jobs_ready_to_run.Len() == 0 && pool.num_jobs_running == 0 { working = false } working_pipe <- working // stats case stats_pipe := <-pool.stats_wanted_pipe: pool_stats := stats{pool.num_jobs_submitted, pool.num_jobs_running, pool.num_jobs_completed} stats_pipe <- pool_stats // stopping case <-pool.supervisor_kill_pipe: break SUPERVISOR_LOOP } } pool.supervisor_wg.Done() }
[ "func", "(", "pool", "*", "Pool", ")", "supervisor", "(", ")", "{", "SUPERVISOR_LOOP", ":", "for", "{", "select", "{", "case", "job", ":=", "<-", "pool", ".", "add_pipe", ":", "pool", ".", "jobs_ready_to_run", ".", "PushBack", "(", "job", ")", "\n", "pool", ".", "num_jobs_submitted", "++", "\n", "job", ".", "added", "<-", "true", "\n", "case", "job_pipe", ":=", "<-", "pool", ".", "job_wanted_pipe", ":", "element", ":=", "pool", ".", "jobs_ready_to_run", ".", "Front", "(", ")", "\n", "var", "job", "*", "Job", "=", "nil", "\n", "if", "element", "!=", "nil", "{", "job", "=", "element", ".", "Value", ".", "(", "*", "Job", ")", "\n", "pool", ".", "num_jobs_running", "++", "\n", "pool", ".", "jobs_ready_to_run", ".", "Remove", "(", "element", ")", "\n", "}", "\n", "job_pipe", "<-", "job", "\n", "case", "job", ":=", "<-", "pool", ".", "done_pipe", ":", "pool", ".", "num_jobs_running", "--", "\n", "pool", ".", "jobs_completed", ".", "PushBack", "(", "job", ")", "\n", "pool", ".", "num_jobs_completed", "++", "\n", "case", "result_pipe", ":=", "<-", "pool", ".", "result_wanted_pipe", ":", "close_pipe", ":=", "false", "\n", "job", ":=", "(", "*", "Job", ")", "(", "nil", ")", "\n", "element", ":=", "pool", ".", "jobs_completed", ".", "Front", "(", ")", "\n", "if", "element", "!=", "nil", "{", "job", "=", "element", ".", "Value", ".", "(", "*", "Job", ")", "\n", "pool", ".", "jobs_completed", ".", "Remove", "(", "element", ")", "\n", "}", "else", "{", "if", "pool", ".", "num_jobs_running", "==", "0", "&&", "pool", ".", "num_jobs_completed", "==", "pool", ".", "num_jobs_submitted", "{", "close_pipe", "=", "true", "\n", "}", "\n", "}", "\n", "if", "close_pipe", "{", "close", "(", "result_pipe", ")", "\n", "}", "else", "{", "result_pipe", "<-", "job", "\n", "}", "\n", "case", "working_pipe", ":=", "<-", "pool", ".", "working_wanted_pipe", ":", "working", ":=", "true", "\n", "if", "pool", ".", "jobs_ready_to_run", ".", "Len", "(", ")", "==", "0", "&&", "pool", ".", "num_jobs_running", "==", "0", "{", "working", "=", "false", "\n", "}", "\n", "working_pipe", "<-", "working", "\n", "case", "stats_pipe", ":=", "<-", "pool", ".", "stats_wanted_pipe", ":", "pool_stats", ":=", "stats", "{", "pool", ".", "num_jobs_submitted", ",", "pool", ".", "num_jobs_running", ",", "pool", ".", "num_jobs_completed", "}", "\n", "stats_pipe", "<-", "pool_stats", "\n", "case", "<-", "pool", ".", "supervisor_kill_pipe", ":", "break", "SUPERVISOR_LOOP", "\n", "}", "\n", "}", "\n", "pool", ".", "supervisor_wg", ".", "Done", "(", ")", "\n", "}" ]
// the supervisor feeds jobs to workers and keeps track of them.
[ "the", "supervisor", "feeds", "jobs", "to", "workers", "and", "keeps", "track", "of", "them", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L120-L179
test
stefantalpalaru/pool
pool.go
Run
func (pool *Pool) Run() { if pool.workers_started { panic("trying to start a pool that's already running") } for i := uint(0); i < uint(pool.num_workers); i++ { pool.worker_wg.Add(1) go pool.worker(i) } pool.workers_started = true // handle the supervisor if !pool.supervisor_started { pool.startSupervisor() } }
go
func (pool *Pool) Run() { if pool.workers_started { panic("trying to start a pool that's already running") } for i := uint(0); i < uint(pool.num_workers); i++ { pool.worker_wg.Add(1) go pool.worker(i) } pool.workers_started = true // handle the supervisor if !pool.supervisor_started { pool.startSupervisor() } }
[ "func", "(", "pool", "*", "Pool", ")", "Run", "(", ")", "{", "if", "pool", ".", "workers_started", "{", "panic", "(", "\"trying to start a pool that's already running\"", ")", "\n", "}", "\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "uint", "(", "pool", ".", "num_workers", ")", ";", "i", "++", "{", "pool", ".", "worker_wg", ".", "Add", "(", "1", ")", "\n", "go", "pool", ".", "worker", "(", "i", ")", "\n", "}", "\n", "pool", ".", "workers_started", "=", "true", "\n", "if", "!", "pool", ".", "supervisor_started", "{", "pool", ".", "startSupervisor", "(", ")", "\n", "}", "\n", "}" ]
// Run starts the Pool by launching the workers. // It's OK to start an empty Pool. The jobs will be fed to the workers as soon // as they become available.
[ "Run", "starts", "the", "Pool", "by", "launching", "the", "workers", ".", "It", "s", "OK", "to", "start", "an", "empty", "Pool", ".", "The", "jobs", "will", "be", "fed", "to", "the", "workers", "as", "soon", "as", "they", "become", "available", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L184-L197
test
stefantalpalaru/pool
pool.go
Add
func (pool *Pool) Add(f func(...interface{}) interface{}, args ...interface{}) { job := &Job{f, args, nil, nil, make(chan bool), 0, pool.getNextJobId()} pool.add_pipe <- job <-job.added }
go
func (pool *Pool) Add(f func(...interface{}) interface{}, args ...interface{}) { job := &Job{f, args, nil, nil, make(chan bool), 0, pool.getNextJobId()} pool.add_pipe <- job <-job.added }
[ "func", "(", "pool", "*", "Pool", ")", "Add", "(", "f", "func", "(", "...", "interface", "{", "}", ")", "interface", "{", "}", ",", "args", "...", "interface", "{", "}", ")", "{", "job", ":=", "&", "Job", "{", "f", ",", "args", ",", "nil", ",", "nil", ",", "make", "(", "chan", "bool", ")", ",", "0", ",", "pool", ".", "getNextJobId", "(", ")", "}", "\n", "pool", ".", "add_pipe", "<-", "job", "\n", "<-", "job", ".", "added", "\n", "}" ]
// Add creates a Job from the given function and args and // adds it to the Pool.
[ "Add", "creates", "a", "Job", "from", "the", "given", "function", "and", "args", "and", "adds", "it", "to", "the", "Pool", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L234-L238
test
stefantalpalaru/pool
pool.go
Wait
func (pool *Pool) Wait() { working_pipe := make(chan bool) for { pool.working_wanted_pipe <- working_pipe if !<-working_pipe { break } time.Sleep(pool.interval * time.Millisecond) } }
go
func (pool *Pool) Wait() { working_pipe := make(chan bool) for { pool.working_wanted_pipe <- working_pipe if !<-working_pipe { break } time.Sleep(pool.interval * time.Millisecond) } }
[ "func", "(", "pool", "*", "Pool", ")", "Wait", "(", ")", "{", "working_pipe", ":=", "make", "(", "chan", "bool", ")", "\n", "for", "{", "pool", ".", "working_wanted_pipe", "<-", "working_pipe", "\n", "if", "!", "<-", "working_pipe", "{", "break", "\n", "}", "\n", "time", ".", "Sleep", "(", "pool", ".", "interval", "*", "time", ".", "Millisecond", ")", "\n", "}", "\n", "}" ]
// Wait blocks until all the jobs in the Pool are done.
[ "Wait", "blocks", "until", "all", "the", "jobs", "in", "the", "Pool", "are", "done", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L246-L255
test
stefantalpalaru/pool
pool.go
Results
func (pool *Pool) Results() (res []*Job) { res = make([]*Job, pool.jobs_completed.Len()) i := 0 for e := pool.jobs_completed.Front(); e != nil; e = e.Next() { res[i] = e.Value.(*Job) i++ } pool.jobs_completed = list.New() return }
go
func (pool *Pool) Results() (res []*Job) { res = make([]*Job, pool.jobs_completed.Len()) i := 0 for e := pool.jobs_completed.Front(); e != nil; e = e.Next() { res[i] = e.Value.(*Job) i++ } pool.jobs_completed = list.New() return }
[ "func", "(", "pool", "*", "Pool", ")", "Results", "(", ")", "(", "res", "[", "]", "*", "Job", ")", "{", "res", "=", "make", "(", "[", "]", "*", "Job", ",", "pool", ".", "jobs_completed", ".", "Len", "(", ")", ")", "\n", "i", ":=", "0", "\n", "for", "e", ":=", "pool", ".", "jobs_completed", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "res", "[", "i", "]", "=", "e", ".", "Value", ".", "(", "*", "Job", ")", "\n", "i", "++", "\n", "}", "\n", "pool", ".", "jobs_completed", "=", "list", ".", "New", "(", ")", "\n", "return", "\n", "}" ]
// Results retrieves the completed jobs.
[ "Results", "retrieves", "the", "completed", "jobs", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L258-L267
test
stefantalpalaru/pool
pool.go
WaitForJob
func (pool *Pool) WaitForJob() *Job { result_pipe := make(chan *Job) var job *Job var ok bool for { pool.result_wanted_pipe <- result_pipe job, ok = <-result_pipe if !ok { // no more results available return nil } if job == (*Job)(nil) { // no result available right now but there are jobs running time.Sleep(pool.interval * time.Millisecond) } else { break } } return job }
go
func (pool *Pool) WaitForJob() *Job { result_pipe := make(chan *Job) var job *Job var ok bool for { pool.result_wanted_pipe <- result_pipe job, ok = <-result_pipe if !ok { // no more results available return nil } if job == (*Job)(nil) { // no result available right now but there are jobs running time.Sleep(pool.interval * time.Millisecond) } else { break } } return job }
[ "func", "(", "pool", "*", "Pool", ")", "WaitForJob", "(", ")", "*", "Job", "{", "result_pipe", ":=", "make", "(", "chan", "*", "Job", ")", "\n", "var", "job", "*", "Job", "\n", "var", "ok", "bool", "\n", "for", "{", "pool", ".", "result_wanted_pipe", "<-", "result_pipe", "\n", "job", ",", "ok", "=", "<-", "result_pipe", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "if", "job", "==", "(", "*", "Job", ")", "(", "nil", ")", "{", "time", ".", "Sleep", "(", "pool", ".", "interval", "*", "time", ".", "Millisecond", ")", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "return", "job", "\n", "}" ]
// WaitForJob blocks until a completed job is available and returns it. // If there are no jobs running, it returns nil.
[ "WaitForJob", "blocks", "until", "a", "completed", "job", "is", "available", "and", "returns", "it", ".", "If", "there", "are", "no", "jobs", "running", "it", "returns", "nil", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L271-L290
test
stefantalpalaru/pool
pool.go
Status
func (pool *Pool) Status() stats { stats_pipe := make(chan stats) if pool.supervisor_started { pool.stats_wanted_pipe <- stats_pipe return <-stats_pipe } // the supervisor wasn't started so we return a zeroed structure return stats{} }
go
func (pool *Pool) Status() stats { stats_pipe := make(chan stats) if pool.supervisor_started { pool.stats_wanted_pipe <- stats_pipe return <-stats_pipe } // the supervisor wasn't started so we return a zeroed structure return stats{} }
[ "func", "(", "pool", "*", "Pool", ")", "Status", "(", ")", "stats", "{", "stats_pipe", ":=", "make", "(", "chan", "stats", ")", "\n", "if", "pool", ".", "supervisor_started", "{", "pool", ".", "stats_wanted_pipe", "<-", "stats_pipe", "\n", "return", "<-", "stats_pipe", "\n", "}", "\n", "return", "stats", "{", "}", "\n", "}" ]
// Status returns a "stats" instance.
[ "Status", "returns", "a", "stats", "instance", "." ]
df8b849d27751462526089005979b28064c1e08e
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L293-L301
test
mikespook/possum
helper.go
WrapHTTPHandlerFunc
func WrapHTTPHandlerFunc(f http.HandlerFunc) HandlerFunc { newF := func(ctx *Context) error { f(ctx.Response, ctx.Request) return nil } return newF }
go
func WrapHTTPHandlerFunc(f http.HandlerFunc) HandlerFunc { newF := func(ctx *Context) error { f(ctx.Response, ctx.Request) return nil } return newF }
[ "func", "WrapHTTPHandlerFunc", "(", "f", "http", ".", "HandlerFunc", ")", "HandlerFunc", "{", "newF", ":=", "func", "(", "ctx", "*", "Context", ")", "error", "{", "f", "(", "ctx", ".", "Response", ",", "ctx", ".", "Request", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "newF", "\n", "}" ]
// WrapHTTPHandlerFunc wraps http.HandlerFunc in possum.HandlerFunc. // See pprof.go.
[ "WrapHTTPHandlerFunc", "wraps", "http", ".", "HandlerFunc", "in", "possum", ".", "HandlerFunc", ".", "See", "pprof", ".", "go", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/helper.go#L50-L56
test
mikespook/possum
helper.go
WebSocketHandlerFunc
func WebSocketHandlerFunc(f func(ws *websocket.Conn)) HandlerFunc { h := websocket.Handler(f) return WrapHTTPHandlerFunc(h.ServeHTTP) }
go
func WebSocketHandlerFunc(f func(ws *websocket.Conn)) HandlerFunc { h := websocket.Handler(f) return WrapHTTPHandlerFunc(h.ServeHTTP) }
[ "func", "WebSocketHandlerFunc", "(", "f", "func", "(", "ws", "*", "websocket", ".", "Conn", ")", ")", "HandlerFunc", "{", "h", ":=", "websocket", ".", "Handler", "(", "f", ")", "\n", "return", "WrapHTTPHandlerFunc", "(", "h", ".", "ServeHTTP", ")", "\n", "}" ]
// WebSocketHandlerFunc convert websocket function to possum.HandlerFunc.
[ "WebSocketHandlerFunc", "convert", "websocket", "function", "to", "possum", ".", "HandlerFunc", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/helper.go#L59-L62
test
mikespook/possum
view/static.go
StaticFile
func StaticFile(filename string, contentType string) staticFile { if contentType == "" { contentType = mime.TypeByExtension(path.Ext(filename)) } header := make(http.Header) header.Set("Content-Type", contentType) return staticFile{filename, header} }
go
func StaticFile(filename string, contentType string) staticFile { if contentType == "" { contentType = mime.TypeByExtension(path.Ext(filename)) } header := make(http.Header) header.Set("Content-Type", contentType) return staticFile{filename, header} }
[ "func", "StaticFile", "(", "filename", "string", ",", "contentType", "string", ")", "staticFile", "{", "if", "contentType", "==", "\"\"", "{", "contentType", "=", "mime", ".", "TypeByExtension", "(", "path", ".", "Ext", "(", "filename", ")", ")", "\n", "}", "\n", "header", ":=", "make", "(", "http", ".", "Header", ")", "\n", "header", ".", "Set", "(", "\"Content-Type\"", ",", "contentType", ")", "\n", "return", "staticFile", "{", "filename", ",", "header", "}", "\n", "}" ]
// StaticFile returns the view which can serve static files.
[ "StaticFile", "returns", "the", "view", "which", "can", "serve", "static", "files", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/static.go#L11-L18
test
mikespook/possum
view/preload.go
PreloadFile
func PreloadFile(filename string, contentType string) (preloadFile, error) { body, err := ioutil.ReadFile(filename) if err != nil { return preloadFile{}, err } if contentType == "" { contentType = mime.TypeByExtension(path.Ext(filename)) } header := make(http.Header) header.Set("Content-Type", contentType) return preloadFile{body, header}, nil }
go
func PreloadFile(filename string, contentType string) (preloadFile, error) { body, err := ioutil.ReadFile(filename) if err != nil { return preloadFile{}, err } if contentType == "" { contentType = mime.TypeByExtension(path.Ext(filename)) } header := make(http.Header) header.Set("Content-Type", contentType) return preloadFile{body, header}, nil }
[ "func", "PreloadFile", "(", "filename", "string", ",", "contentType", "string", ")", "(", "preloadFile", ",", "error", ")", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "preloadFile", "{", "}", ",", "err", "\n", "}", "\n", "if", "contentType", "==", "\"\"", "{", "contentType", "=", "mime", ".", "TypeByExtension", "(", "path", ".", "Ext", "(", "filename", ")", ")", "\n", "}", "\n", "header", ":=", "make", "(", "http", ".", "Header", ")", "\n", "header", ".", "Set", "(", "\"Content-Type\"", ",", "contentType", ")", "\n", "return", "preloadFile", "{", "body", ",", "header", "}", ",", "nil", "\n", "}" ]
// PreloadFile returns the view which can preload static files and serve them. // The different between `StaticFile` and `PreloadFile` is that `StaticFile` // load the content of file at every request, while `PreloadFile` load // the content into memory at the initial stage. Despite that `PreloadFile` // will be using more memories and could not update the content in time until // restart the application, it should be fast than `StaticFile` in runtime.
[ "PreloadFile", "returns", "the", "view", "which", "can", "preload", "static", "files", "and", "serve", "them", ".", "The", "different", "between", "StaticFile", "and", "PreloadFile", "is", "that", "StaticFile", "load", "the", "content", "of", "file", "at", "every", "request", "while", "PreloadFile", "load", "the", "content", "into", "memory", "at", "the", "initial", "stage", ".", "Despite", "that", "PreloadFile", "will", "be", "using", "more", "memories", "and", "could", "not", "update", "the", "content", "in", "time", "until", "restart", "the", "application", "it", "should", "be", "fast", "than", "StaticFile", "in", "runtime", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/preload.go#L16-L27
test
mikespook/possum
view/template.go
InitHtmlTemplates
func InitHtmlTemplates(pattern string) (err error) { htmlTemp.Template, err = html.ParseGlob(pattern) return }
go
func InitHtmlTemplates(pattern string) (err error) { htmlTemp.Template, err = html.ParseGlob(pattern) return }
[ "func", "InitHtmlTemplates", "(", "pattern", "string", ")", "(", "err", "error", ")", "{", "htmlTemp", ".", "Template", ",", "err", "=", "html", ".", "ParseGlob", "(", "pattern", ")", "\n", "return", "\n", "}" ]
// InitHtmlTemplates initialzes a series of HTML templates // in the directory `pattern`.
[ "InitHtmlTemplates", "initialzes", "a", "series", "of", "HTML", "templates", "in", "the", "directory", "pattern", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L40-L43
test
mikespook/possum
view/template.go
InitTextTemplates
func InitTextTemplates(pattern string) (err error) { textTemp.Template, err = text.ParseGlob(pattern) return nil }
go
func InitTextTemplates(pattern string) (err error) { textTemp.Template, err = text.ParseGlob(pattern) return nil }
[ "func", "InitTextTemplates", "(", "pattern", "string", ")", "(", "err", "error", ")", "{", "textTemp", ".", "Template", ",", "err", "=", "text", ".", "ParseGlob", "(", "pattern", ")", "\n", "return", "nil", "\n", "}" ]
// InitTextTemplates initialzes a series of plain text templates // in the directory `pattern`.
[ "InitTextTemplates", "initialzes", "a", "series", "of", "plain", "text", "templates", "in", "the", "directory", "pattern", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L47-L50
test
mikespook/possum
view/template.go
Html
func Html(name, contentType, charSet string) template { if htmlTemp.Template == nil { panic("Function `InitHtmlTemplates` should be called first.") } if contentType == "" { contentType = ContentTypeHTML } if charSet == "" { charSet = CharSetUTF8 } header := make(http.Header) header.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charSet)) return template{&htmlTemp, name, header} }
go
func Html(name, contentType, charSet string) template { if htmlTemp.Template == nil { panic("Function `InitHtmlTemplates` should be called first.") } if contentType == "" { contentType = ContentTypeHTML } if charSet == "" { charSet = CharSetUTF8 } header := make(http.Header) header.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charSet)) return template{&htmlTemp, name, header} }
[ "func", "Html", "(", "name", ",", "contentType", ",", "charSet", "string", ")", "template", "{", "if", "htmlTemp", ".", "Template", "==", "nil", "{", "panic", "(", "\"Function `InitHtmlTemplates` should be called first.\"", ")", "\n", "}", "\n", "if", "contentType", "==", "\"\"", "{", "contentType", "=", "ContentTypeHTML", "\n", "}", "\n", "if", "charSet", "==", "\"\"", "{", "charSet", "=", "CharSetUTF8", "\n", "}", "\n", "header", ":=", "make", "(", "http", ".", "Header", ")", "\n", "header", ".", "Set", "(", "\"Content-Type\"", ",", "fmt", ".", "Sprintf", "(", "\"%s; charset=%s\"", ",", "contentType", ",", "charSet", ")", ")", "\n", "return", "template", "{", "&", "htmlTemp", ",", "name", ",", "header", "}", "\n", "}" ]
// Html retruns a TemplateView witch uses HTML templates internally.
[ "Html", "retruns", "a", "TemplateView", "witch", "uses", "HTML", "templates", "internally", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L53-L67
test
mikespook/possum
view/template.go
Text
func Text(name, contentType, charSet string) template { if textTemp.Template == nil { panic("Function `InitTextTemplates` should be called first.") } if contentType == "" { contentType = ContentTypePlain } if charSet == "" { charSet = CharSetUTF8 } header := make(http.Header) header.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charSet)) return template{&textTemp, name, header} }
go
func Text(name, contentType, charSet string) template { if textTemp.Template == nil { panic("Function `InitTextTemplates` should be called first.") } if contentType == "" { contentType = ContentTypePlain } if charSet == "" { charSet = CharSetUTF8 } header := make(http.Header) header.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charSet)) return template{&textTemp, name, header} }
[ "func", "Text", "(", "name", ",", "contentType", ",", "charSet", "string", ")", "template", "{", "if", "textTemp", ".", "Template", "==", "nil", "{", "panic", "(", "\"Function `InitTextTemplates` should be called first.\"", ")", "\n", "}", "\n", "if", "contentType", "==", "\"\"", "{", "contentType", "=", "ContentTypePlain", "\n", "}", "\n", "if", "charSet", "==", "\"\"", "{", "charSet", "=", "CharSetUTF8", "\n", "}", "\n", "header", ":=", "make", "(", "http", ".", "Header", ")", "\n", "header", ".", "Set", "(", "\"Content-Type\"", ",", "fmt", ".", "Sprintf", "(", "\"%s; charset=%s\"", ",", "contentType", ",", "charSet", ")", ")", "\n", "return", "template", "{", "&", "textTemp", ",", "name", ",", "header", "}", "\n", "}" ]
// Text retruns a TemplateView witch uses text templates internally.
[ "Text", "retruns", "a", "TemplateView", "witch", "uses", "text", "templates", "internally", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L70-L84
test
mikespook/possum
view/template.go
InitWatcher
func InitWatcher(pattern string, f func(string) error, ef func(error)) (err error) { if err = f(pattern); err != nil { return } if watcher.Watcher == nil { watcher.Watcher, err = fsnotify.NewWatcher() if err != nil { return } watcher.closer = make(chan bool) } go func() { atomic.AddUint32(&watcher.count, 1) for { select { case <-watcher.Events: if err := f(pattern); err != nil { ef(err) } case err := <-watcher.Errors: if ef != nil { ef(err) } case <-watcher.closer: break } } }() var matches []string matches, err = filepath.Glob(pattern) if err != nil { return } for _, v := range matches { if err = watcher.Add(v); err != nil { return } } return }
go
func InitWatcher(pattern string, f func(string) error, ef func(error)) (err error) { if err = f(pattern); err != nil { return } if watcher.Watcher == nil { watcher.Watcher, err = fsnotify.NewWatcher() if err != nil { return } watcher.closer = make(chan bool) } go func() { atomic.AddUint32(&watcher.count, 1) for { select { case <-watcher.Events: if err := f(pattern); err != nil { ef(err) } case err := <-watcher.Errors: if ef != nil { ef(err) } case <-watcher.closer: break } } }() var matches []string matches, err = filepath.Glob(pattern) if err != nil { return } for _, v := range matches { if err = watcher.Add(v); err != nil { return } } return }
[ "func", "InitWatcher", "(", "pattern", "string", ",", "f", "func", "(", "string", ")", "error", ",", "ef", "func", "(", "error", ")", ")", "(", "err", "error", ")", "{", "if", "err", "=", "f", "(", "pattern", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "watcher", ".", "Watcher", "==", "nil", "{", "watcher", ".", "Watcher", ",", "err", "=", "fsnotify", ".", "NewWatcher", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "watcher", ".", "closer", "=", "make", "(", "chan", "bool", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "atomic", ".", "AddUint32", "(", "&", "watcher", ".", "count", ",", "1", ")", "\n", "for", "{", "select", "{", "case", "<-", "watcher", ".", "Events", ":", "if", "err", ":=", "f", "(", "pattern", ")", ";", "err", "!=", "nil", "{", "ef", "(", "err", ")", "\n", "}", "\n", "case", "err", ":=", "<-", "watcher", ".", "Errors", ":", "if", "ef", "!=", "nil", "{", "ef", "(", "err", ")", "\n", "}", "\n", "case", "<-", "watcher", ".", "closer", ":", "break", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "var", "matches", "[", "]", "string", "\n", "matches", ",", "err", "=", "filepath", ".", "Glob", "(", "pattern", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "matches", "{", "if", "err", "=", "watcher", ".", "Add", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// InitWatcher initialzes a watcher to watch templates changes in the `pattern`. // f would be InitHtmlTemplates or InitTextTemplates. // If the watcher raises an error internally, the callback function ef will be executed. // ef can be nil witch represents ignoring all internal errors.
[ "InitWatcher", "initialzes", "a", "watcher", "to", "watch", "templates", "changes", "in", "the", "pattern", ".", "f", "would", "be", "InitHtmlTemplates", "or", "InitTextTemplates", ".", "If", "the", "watcher", "raises", "an", "error", "internally", "the", "callback", "function", "ef", "will", "be", "executed", ".", "ef", "can", "be", "nil", "witch", "represents", "ignoring", "all", "internal", "errors", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L90-L130
test
mikespook/possum
view/template.go
CloseWatcher
func CloseWatcher() error { for i := uint32(0); i < watcher.count; i++ { watcher.closer <- true } return watcher.Close() }
go
func CloseWatcher() error { for i := uint32(0); i < watcher.count; i++ { watcher.closer <- true } return watcher.Close() }
[ "func", "CloseWatcher", "(", ")", "error", "{", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "watcher", ".", "count", ";", "i", "++", "{", "watcher", ".", "closer", "<-", "true", "\n", "}", "\n", "return", "watcher", ".", "Close", "(", ")", "\n", "}" ]
// CloseWatcher closes the wathcer.
[ "CloseWatcher", "closes", "the", "wathcer", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L133-L138
test
mikespook/possum
router.go
Find
func (rs *Routers) Find(path string) (url.Values, HandlerFunc, view.View) { defer rs.RUnlock() rs.RLock() if s, ok := rs.s[path]; ok { return nil, s.h, s.v } for e := rs.l.Front(); e != nil; e = e.Next() { s := e.Value.(struct { r router.Router v view.View h HandlerFunc }) if params, ok := s.r.Match(path); ok { return params, s.h, s.v } } return nil, nil, nil }
go
func (rs *Routers) Find(path string) (url.Values, HandlerFunc, view.View) { defer rs.RUnlock() rs.RLock() if s, ok := rs.s[path]; ok { return nil, s.h, s.v } for e := rs.l.Front(); e != nil; e = e.Next() { s := e.Value.(struct { r router.Router v view.View h HandlerFunc }) if params, ok := s.r.Match(path); ok { return params, s.h, s.v } } return nil, nil, nil }
[ "func", "(", "rs", "*", "Routers", ")", "Find", "(", "path", "string", ")", "(", "url", ".", "Values", ",", "HandlerFunc", ",", "view", ".", "View", ")", "{", "defer", "rs", ".", "RUnlock", "(", ")", "\n", "rs", ".", "RLock", "(", ")", "\n", "if", "s", ",", "ok", ":=", "rs", ".", "s", "[", "path", "]", ";", "ok", "{", "return", "nil", ",", "s", ".", "h", ",", "s", ".", "v", "\n", "}", "\n", "for", "e", ":=", "rs", ".", "l", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "s", ":=", "e", ".", "Value", ".", "(", "struct", "{", "r", "router", ".", "Router", "\n", "v", "view", ".", "View", "\n", "h", "HandlerFunc", "\n", "}", ")", "\n", "if", "params", ",", "ok", ":=", "s", ".", "r", ".", "Match", "(", "path", ")", ";", "ok", "{", "return", "params", ",", "s", ".", "h", ",", "s", ".", "v", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "nil", "\n", "}" ]
// Find a router with the specific path and return it.
[ "Find", "a", "router", "with", "the", "specific", "path", "and", "return", "it", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/router.go#L24-L41
test
mikespook/possum
router.go
Add
func (rs *Routers) Add(r router.Router, h HandlerFunc, v view.View) { defer rs.Unlock() rs.Lock() s := struct { r router.Router v view.View h HandlerFunc }{r, v, h} // simple will full-match the path if sr, ok := r.(*router.Base); ok { rs.s[sr.Path] = s return } rs.l.PushFront(s) }
go
func (rs *Routers) Add(r router.Router, h HandlerFunc, v view.View) { defer rs.Unlock() rs.Lock() s := struct { r router.Router v view.View h HandlerFunc }{r, v, h} // simple will full-match the path if sr, ok := r.(*router.Base); ok { rs.s[sr.Path] = s return } rs.l.PushFront(s) }
[ "func", "(", "rs", "*", "Routers", ")", "Add", "(", "r", "router", ".", "Router", ",", "h", "HandlerFunc", ",", "v", "view", ".", "View", ")", "{", "defer", "rs", ".", "Unlock", "(", ")", "\n", "rs", ".", "Lock", "(", ")", "\n", "s", ":=", "struct", "{", "r", "router", ".", "Router", "\n", "v", "view", ".", "View", "\n", "h", "HandlerFunc", "\n", "}", "{", "r", ",", "v", ",", "h", "}", "\n", "if", "sr", ",", "ok", ":=", "r", ".", "(", "*", "router", ".", "Base", ")", ";", "ok", "{", "rs", ".", "s", "[", "sr", ".", "Path", "]", "=", "s", "\n", "return", "\n", "}", "\n", "rs", ".", "l", ".", "PushFront", "(", "s", ")", "\n", "}" ]
// Add a router to list
[ "Add", "a", "router", "to", "list" ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/router.go#L44-L58
test
mikespook/possum
router.go
NewRouters
func NewRouters() *Routers { return &Routers{ s: make(map[string]struct { r router.Router v view.View h HandlerFunc }), l: list.New(), } }
go
func NewRouters() *Routers { return &Routers{ s: make(map[string]struct { r router.Router v view.View h HandlerFunc }), l: list.New(), } }
[ "func", "NewRouters", "(", ")", "*", "Routers", "{", "return", "&", "Routers", "{", "s", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "r", "router", ".", "Router", "\n", "v", "view", ".", "View", "\n", "h", "HandlerFunc", "\n", "}", ")", ",", "l", ":", "list", ".", "New", "(", ")", ",", "}", "\n", "}" ]
// NewRouters initailizes Routers instance.
[ "NewRouters", "initailizes", "Routers", "instance", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/router.go#L61-L70
test
mikespook/possum
server.go
NewServerMux
func NewServerMux() (mux *ServerMux) { nf := struct { View view.View Handler HandlerFunc }{view.Simple(view.ContentTypePlain, view.CharSetUTF8), defaultNotFound} return &ServerMux{NewRouters(), nil, nil, nil, nf} }
go
func NewServerMux() (mux *ServerMux) { nf := struct { View view.View Handler HandlerFunc }{view.Simple(view.ContentTypePlain, view.CharSetUTF8), defaultNotFound} return &ServerMux{NewRouters(), nil, nil, nil, nf} }
[ "func", "NewServerMux", "(", ")", "(", "mux", "*", "ServerMux", ")", "{", "nf", ":=", "struct", "{", "View", "view", ".", "View", "\n", "Handler", "HandlerFunc", "\n", "}", "{", "view", ".", "Simple", "(", "view", ".", "ContentTypePlain", ",", "view", ".", "CharSetUTF8", ")", ",", "defaultNotFound", "}", "\n", "return", "&", "ServerMux", "{", "NewRouters", "(", ")", ",", "nil", ",", "nil", ",", "nil", ",", "nf", "}", "\n", "}" ]
// NewServerMux returns a new Handler.
[ "NewServerMux", "returns", "a", "new", "Handler", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/server.go#L36-L42
test
mikespook/possum
server.go
err
func (mux *ServerMux) err(err error) { if mux.ErrorHandle != nil { mux.ErrorHandle(err) } }
go
func (mux *ServerMux) err(err error) { if mux.ErrorHandle != nil { mux.ErrorHandle(err) } }
[ "func", "(", "mux", "*", "ServerMux", ")", "err", "(", "err", "error", ")", "{", "if", "mux", ".", "ErrorHandle", "!=", "nil", "{", "mux", ".", "ErrorHandle", "(", "err", ")", "\n", "}", "\n", "}" ]
// Internal error handler
[ "Internal", "error", "handler" ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/server.go#L45-L49
test
mikespook/possum
server.go
HandleFunc
func (mux *ServerMux) HandleFunc(r router.Router, h HandlerFunc, v view.View) { mux.routers.Add(r, h, v) }
go
func (mux *ServerMux) HandleFunc(r router.Router, h HandlerFunc, v view.View) { mux.routers.Add(r, h, v) }
[ "func", "(", "mux", "*", "ServerMux", ")", "HandleFunc", "(", "r", "router", ".", "Router", ",", "h", "HandlerFunc", ",", "v", "view", ".", "View", ")", "{", "mux", ".", "routers", ".", "Add", "(", "r", ",", "h", ",", "v", ")", "\n", "}" ]
// HandleFunc specifies a pair of handler and view to handle // the request witch matching router.
[ "HandleFunc", "specifies", "a", "pair", "of", "handler", "and", "view", "to", "handle", "the", "request", "witch", "matching", "router", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/server.go#L53-L55
test
mikespook/possum
server.go
handleError
func (mux *ServerMux) handleError(ctx *Context, err error) bool { if err == nil { return false } if e, ok := err.(Error); ok { ctx.Response.Status = e.Status ctx.Response.Data = e return true } if ctx.Response.Status == http.StatusOK { ctx.Response.Status = http.StatusInternalServerError } ctx.Response.Data = err.Error() mux.err(err) return true }
go
func (mux *ServerMux) handleError(ctx *Context, err error) bool { if err == nil { return false } if e, ok := err.(Error); ok { ctx.Response.Status = e.Status ctx.Response.Data = e return true } if ctx.Response.Status == http.StatusOK { ctx.Response.Status = http.StatusInternalServerError } ctx.Response.Data = err.Error() mux.err(err) return true }
[ "func", "(", "mux", "*", "ServerMux", ")", "handleError", "(", "ctx", "*", "Context", ",", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "Error", ")", ";", "ok", "{", "ctx", ".", "Response", ".", "Status", "=", "e", ".", "Status", "\n", "ctx", ".", "Response", ".", "Data", "=", "e", "\n", "return", "true", "\n", "}", "\n", "if", "ctx", ".", "Response", ".", "Status", "==", "http", ".", "StatusOK", "{", "ctx", ".", "Response", ".", "Status", "=", "http", ".", "StatusInternalServerError", "\n", "}", "\n", "ctx", ".", "Response", ".", "Data", "=", "err", ".", "Error", "(", ")", "\n", "mux", ".", "err", "(", "err", ")", "\n", "return", "true", "\n", "}" ]
// handleError tests the context `Error` and assign it to response.
[ "handleError", "tests", "the", "context", "Error", "and", "assign", "it", "to", "response", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/server.go#L58-L73
test
mikespook/possum
context.go
Redirect
func (ctx *Context) Redirect(code int, url string) { ctx.Response.Status = code ctx.Response.Data = url }
go
func (ctx *Context) Redirect(code int, url string) { ctx.Response.Status = code ctx.Response.Data = url }
[ "func", "(", "ctx", "*", "Context", ")", "Redirect", "(", "code", "int", ",", "url", "string", ")", "{", "ctx", ".", "Response", ".", "Status", "=", "code", "\n", "ctx", ".", "Response", ".", "Data", "=", "url", "\n", "}" ]
// Redirect performs a redirecting to the url, if the code belongs to // one of StatusMovedPermanently, StatusFound, StatusSeeOther, and // StatusTemporaryRedirect.
[ "Redirect", "performs", "a", "redirecting", "to", "the", "url", "if", "the", "code", "belongs", "to", "one", "of", "StatusMovedPermanently", "StatusFound", "StatusSeeOther", "and", "StatusTemporaryRedirect", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/context.go#L32-L35
test
mikespook/possum
pprof.go
InitPProf
func (mux *ServerMux) InitPProf(prefix string) { if prefix == "" { prefix = "/debug/pprof" } mux.HandleFunc(router.Wildcard(fmt.Sprintf("%s/*", prefix)), WrapHTTPHandlerFunc(pprofIndex(prefix)), nil) mux.HandleFunc(router.Simple(fmt.Sprintf("%s/cmdline", prefix)), WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Cmdline)), nil) mux.HandleFunc(router.Simple(fmt.Sprintf("%s/profile", prefix)), WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Profile)), nil) mux.HandleFunc(router.Simple(fmt.Sprintf("%s/symbol", prefix)), WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Symbol)), nil) }
go
func (mux *ServerMux) InitPProf(prefix string) { if prefix == "" { prefix = "/debug/pprof" } mux.HandleFunc(router.Wildcard(fmt.Sprintf("%s/*", prefix)), WrapHTTPHandlerFunc(pprofIndex(prefix)), nil) mux.HandleFunc(router.Simple(fmt.Sprintf("%s/cmdline", prefix)), WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Cmdline)), nil) mux.HandleFunc(router.Simple(fmt.Sprintf("%s/profile", prefix)), WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Profile)), nil) mux.HandleFunc(router.Simple(fmt.Sprintf("%s/symbol", prefix)), WrapHTTPHandlerFunc(http.HandlerFunc(pprof.Symbol)), nil) }
[ "func", "(", "mux", "*", "ServerMux", ")", "InitPProf", "(", "prefix", "string", ")", "{", "if", "prefix", "==", "\"\"", "{", "prefix", "=", "\"/debug/pprof\"", "\n", "}", "\n", "mux", ".", "HandleFunc", "(", "router", ".", "Wildcard", "(", "fmt", ".", "Sprintf", "(", "\"%s/*\"", ",", "prefix", ")", ")", ",", "WrapHTTPHandlerFunc", "(", "pprofIndex", "(", "prefix", ")", ")", ",", "nil", ")", "\n", "mux", ".", "HandleFunc", "(", "router", ".", "Simple", "(", "fmt", ".", "Sprintf", "(", "\"%s/cmdline\"", ",", "prefix", ")", ")", ",", "WrapHTTPHandlerFunc", "(", "http", ".", "HandlerFunc", "(", "pprof", ".", "Cmdline", ")", ")", ",", "nil", ")", "\n", "mux", ".", "HandleFunc", "(", "router", ".", "Simple", "(", "fmt", ".", "Sprintf", "(", "\"%s/profile\"", ",", "prefix", ")", ")", ",", "WrapHTTPHandlerFunc", "(", "http", ".", "HandlerFunc", "(", "pprof", ".", "Profile", ")", ")", ",", "nil", ")", "\n", "mux", ".", "HandleFunc", "(", "router", ".", "Simple", "(", "fmt", ".", "Sprintf", "(", "\"%s/symbol\"", ",", "prefix", ")", ")", ",", "WrapHTTPHandlerFunc", "(", "http", ".", "HandlerFunc", "(", "pprof", ".", "Symbol", ")", ")", ",", "nil", ")", "\n", "}" ]
// InitPProf registers pprof handlers to the ServeMux. // The pprof handlers can be specified a customized prefix.
[ "InitPProf", "registers", "pprof", "handlers", "to", "the", "ServeMux", ".", "The", "pprof", "handlers", "can", "be", "specified", "a", "customized", "prefix", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/pprof.go#L18-L30
test
mikespook/possum
session.go
StartSession
func (ctx *Context) StartSession(f session.FactoryFunc) (err error) { ctx.Session, err = f(ctx.Response, ctx.Request) return }
go
func (ctx *Context) StartSession(f session.FactoryFunc) (err error) { ctx.Session, err = f(ctx.Response, ctx.Request) return }
[ "func", "(", "ctx", "*", "Context", ")", "StartSession", "(", "f", "session", ".", "FactoryFunc", ")", "(", "err", "error", ")", "{", "ctx", ".", "Session", ",", "err", "=", "f", "(", "ctx", ".", "Response", ",", "ctx", ".", "Request", ")", "\n", "return", "\n", "}" ]
// StartSession initaillizes a session context. // This function should be called in a implementation // of possum.HandleFunc.
[ "StartSession", "initaillizes", "a", "session", "context", ".", "This", "function", "should", "be", "called", "in", "a", "implementation", "of", "possum", ".", "HandleFunc", "." ]
56d7ebb6470b670001632b11be7fc089038f4dd7
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/session.go#L8-L11
test
kokardy/listing
comb.go
combinations
func combinations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch { case select_num == 0: c <- []int{} case select_num == len(list): c <- list case len(list) < select_num: return default: for i := 0; i < len(list); i++ { for sub_comb := range combinations(list[i+1:], select_num-1, buf) { c <- append([]int{list[i]}, sub_comb...) } } } }() return }
go
func combinations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch { case select_num == 0: c <- []int{} case select_num == len(list): c <- list case len(list) < select_num: return default: for i := 0; i < len(list); i++ { for sub_comb := range combinations(list[i+1:], select_num-1, buf) { c <- append([]int{list[i]}, sub_comb...) } } } }() return }
[ "func", "combinations", "(", "list", "[", "]", "int", ",", "select_num", ",", "buf", "int", ")", "(", "c", "chan", "[", "]", "int", ")", "{", "c", "=", "make", "(", "chan", "[", "]", "int", ",", "buf", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "switch", "{", "case", "select_num", "==", "0", ":", "c", "<-", "[", "]", "int", "{", "}", "\n", "case", "select_num", "==", "len", "(", "list", ")", ":", "c", "<-", "list", "\n", "case", "len", "(", "list", ")", "<", "select_num", ":", "return", "\n", "default", ":", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", ";", "i", "++", "{", "for", "sub_comb", ":=", "range", "combinations", "(", "list", "[", "i", "+", "1", ":", "]", ",", "select_num", "-", "1", ",", "buf", ")", "{", "c", "<-", "append", "(", "[", "]", "int", "{", "list", "[", "i", "]", "}", ",", "sub_comb", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "\n", "}" ]
//Combination generator for int slice
[ "Combination", "generator", "for", "int", "slice" ]
795534c33c5ab6be8b85a15951664ab11fb70ea7
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/comb.go#L29-L49
test
kokardy/listing
comb.go
repeated_combinations
func repeated_combinations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) if select_num == 1 { for v := range list { c <- []int{v} } return } for i := 0; i < len(list); i++ { for sub_comb := range repeated_combinations(list[i:], select_num-1, buf) { c <- append([]int{list[i]}, sub_comb...) } } }() return }
go
func repeated_combinations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) if select_num == 1 { for v := range list { c <- []int{v} } return } for i := 0; i < len(list); i++ { for sub_comb := range repeated_combinations(list[i:], select_num-1, buf) { c <- append([]int{list[i]}, sub_comb...) } } }() return }
[ "func", "repeated_combinations", "(", "list", "[", "]", "int", ",", "select_num", ",", "buf", "int", ")", "(", "c", "chan", "[", "]", "int", ")", "{", "c", "=", "make", "(", "chan", "[", "]", "int", ",", "buf", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "if", "select_num", "==", "1", "{", "for", "v", ":=", "range", "list", "{", "c", "<-", "[", "]", "int", "{", "v", "}", "\n", "}", "\n", "return", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", ";", "i", "++", "{", "for", "sub_comb", ":=", "range", "repeated_combinations", "(", "list", "[", "i", ":", "]", ",", "select_num", "-", "1", ",", "buf", ")", "{", "c", "<-", "append", "(", "[", "]", "int", "{", "list", "[", "i", "]", "}", ",", "sub_comb", "...", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "\n", "}" ]
//Repeated combination generator for int slice
[ "Repeated", "combination", "generator", "for", "int", "slice" ]
795534c33c5ab6be8b85a15951664ab11fb70ea7
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/comb.go#L52-L69
test
kokardy/listing
perm.go
permutations
func permutations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch select_num { case 1: for _, v := range list { c <- []int{v} } return case 0: return case len(list): for i := 0; i < len(list); i++ { top, sub_list := pop(list, i) for perm := range permutations(sub_list, select_num-1, buf) { c <- append([]int{top}, perm...) } } default: for comb := range combinations(list, select_num, buf) { for perm := range permutations(comb, select_num, buf) { c <- perm } } } }() return }
go
func permutations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch select_num { case 1: for _, v := range list { c <- []int{v} } return case 0: return case len(list): for i := 0; i < len(list); i++ { top, sub_list := pop(list, i) for perm := range permutations(sub_list, select_num-1, buf) { c <- append([]int{top}, perm...) } } default: for comb := range combinations(list, select_num, buf) { for perm := range permutations(comb, select_num, buf) { c <- perm } } } }() return }
[ "func", "permutations", "(", "list", "[", "]", "int", ",", "select_num", ",", "buf", "int", ")", "(", "c", "chan", "[", "]", "int", ")", "{", "c", "=", "make", "(", "chan", "[", "]", "int", ",", "buf", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "switch", "select_num", "{", "case", "1", ":", "for", "_", ",", "v", ":=", "range", "list", "{", "c", "<-", "[", "]", "int", "{", "v", "}", "\n", "}", "\n", "return", "\n", "case", "0", ":", "return", "\n", "case", "len", "(", "list", ")", ":", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", ";", "i", "++", "{", "top", ",", "sub_list", ":=", "pop", "(", "list", ",", "i", ")", "\n", "for", "perm", ":=", "range", "permutations", "(", "sub_list", ",", "select_num", "-", "1", ",", "buf", ")", "{", "c", "<-", "append", "(", "[", "]", "int", "{", "top", "}", ",", "perm", "...", ")", "\n", "}", "\n", "}", "\n", "default", ":", "for", "comb", ":=", "range", "combinations", "(", "list", ",", "select_num", ",", "buf", ")", "{", "for", "perm", ":=", "range", "permutations", "(", "comb", ",", "select_num", ",", "buf", ")", "{", "c", "<-", "perm", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "\n", "}" ]
//Permtation generator for int slice
[ "Permtation", "generator", "for", "int", "slice" ]
795534c33c5ab6be8b85a15951664ab11fb70ea7
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/perm.go#L35-L63
test
kokardy/listing
perm.go
repeated_permutations
func repeated_permutations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch select_num { case 1: for _, v := range list { c <- []int{v} } default: for i := 0; i < len(list); i++ { for perm := range repeated_permutations(list, select_num-1, buf) { c <- append([]int{list[i]}, perm...) } } } }() return }
go
func repeated_permutations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch select_num { case 1: for _, v := range list { c <- []int{v} } default: for i := 0; i < len(list); i++ { for perm := range repeated_permutations(list, select_num-1, buf) { c <- append([]int{list[i]}, perm...) } } } }() return }
[ "func", "repeated_permutations", "(", "list", "[", "]", "int", ",", "select_num", ",", "buf", "int", ")", "(", "c", "chan", "[", "]", "int", ")", "{", "c", "=", "make", "(", "chan", "[", "]", "int", ",", "buf", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "switch", "select_num", "{", "case", "1", ":", "for", "_", ",", "v", ":=", "range", "list", "{", "c", "<-", "[", "]", "int", "{", "v", "}", "\n", "}", "\n", "default", ":", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", ";", "i", "++", "{", "for", "perm", ":=", "range", "repeated_permutations", "(", "list", ",", "select_num", "-", "1", ",", "buf", ")", "{", "c", "<-", "append", "(", "[", "]", "int", "{", "list", "[", "i", "]", "}", ",", "perm", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "\n", "}" ]
//Repeated permtation generator for int slice
[ "Repeated", "permtation", "generator", "for", "int", "slice" ]
795534c33c5ab6be8b85a15951664ab11fb70ea7
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/perm.go#L66-L84
test
delicb/gstring
gstring.go
gformat
func gformat(format string, args map[string]interface{}) (string, []interface{}) { // holder for new format string - capacity as length of provided string // should be enough not to resize during appending, since expected length // of new format is smaller then provided one (names are removed) var new_format = make([]rune, 0, len(format)) // flag that indicates if current place in format string in inside { } var in_format = false // flag that indicates if current place is format string in inside { } and after : var in_args = false var previousChar rune // temp slice for holding name in current format var current_name_runes = make([]rune, 0, 10) // temp slice for holding args in current format var current_args_runes = make([]rune, 0, 10) var new_format_params []interface{} for i, ch := range format { if i > 0 { previousChar = rune(format[i-1]) } switch ch { case '{': if in_format && previousChar == '{' { in_format = false new_format = append(new_format, ch) break } in_format = true case '}': if !in_format { if previousChar == '}' { new_format = append(new_format, ch) break } // what to do if not in_format and only single } appears? break } if in_format { if len(current_args_runes) > 0 { // append formatting arguments to new_format directly new_format = append(new_format, current_args_runes...) } else { // if no arguments are supplied, use default ones new_format = append(new_format, defaultFormat...) } // reset format args for new iteration current_args_runes = current_args_runes[0:0] } var name string if len(current_name_runes) == 0 { name = "EMPTY_PLACEHOLDER" } else { name = string(current_name_runes) } // reset name runes for next iteration current_name_runes = current_name_runes[0:0] // get value from provided args and append it to new_format_args val, ok := args[name] if !ok { val = fmt.Sprintf("%%MISSING=%s", name) } new_format_params = append(new_format_params, val) // reset flags in_format = false in_args = false case ':': if in_format { in_args = true } default: if in_format { if in_args { current_args_runes = append(current_args_runes, ch) } else { current_name_runes = append(current_name_runes, ch) } } else { new_format = append(new_format, ch) } } } return string(new_format), new_format_params }
go
func gformat(format string, args map[string]interface{}) (string, []interface{}) { // holder for new format string - capacity as length of provided string // should be enough not to resize during appending, since expected length // of new format is smaller then provided one (names are removed) var new_format = make([]rune, 0, len(format)) // flag that indicates if current place in format string in inside { } var in_format = false // flag that indicates if current place is format string in inside { } and after : var in_args = false var previousChar rune // temp slice for holding name in current format var current_name_runes = make([]rune, 0, 10) // temp slice for holding args in current format var current_args_runes = make([]rune, 0, 10) var new_format_params []interface{} for i, ch := range format { if i > 0 { previousChar = rune(format[i-1]) } switch ch { case '{': if in_format && previousChar == '{' { in_format = false new_format = append(new_format, ch) break } in_format = true case '}': if !in_format { if previousChar == '}' { new_format = append(new_format, ch) break } // what to do if not in_format and only single } appears? break } if in_format { if len(current_args_runes) > 0 { // append formatting arguments to new_format directly new_format = append(new_format, current_args_runes...) } else { // if no arguments are supplied, use default ones new_format = append(new_format, defaultFormat...) } // reset format args for new iteration current_args_runes = current_args_runes[0:0] } var name string if len(current_name_runes) == 0 { name = "EMPTY_PLACEHOLDER" } else { name = string(current_name_runes) } // reset name runes for next iteration current_name_runes = current_name_runes[0:0] // get value from provided args and append it to new_format_args val, ok := args[name] if !ok { val = fmt.Sprintf("%%MISSING=%s", name) } new_format_params = append(new_format_params, val) // reset flags in_format = false in_args = false case ':': if in_format { in_args = true } default: if in_format { if in_args { current_args_runes = append(current_args_runes, ch) } else { current_name_runes = append(current_name_runes, ch) } } else { new_format = append(new_format, ch) } } } return string(new_format), new_format_params }
[ "func", "gformat", "(", "format", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "string", ",", "[", "]", "interface", "{", "}", ")", "{", "var", "new_format", "=", "make", "(", "[", "]", "rune", ",", "0", ",", "len", "(", "format", ")", ")", "\n", "var", "in_format", "=", "false", "\n", "var", "in_args", "=", "false", "\n", "var", "previousChar", "rune", "\n", "var", "current_name_runes", "=", "make", "(", "[", "]", "rune", ",", "0", ",", "10", ")", "\n", "var", "current_args_runes", "=", "make", "(", "[", "]", "rune", ",", "0", ",", "10", ")", "\n", "var", "new_format_params", "[", "]", "interface", "{", "}", "\n", "for", "i", ",", "ch", ":=", "range", "format", "{", "if", "i", ">", "0", "{", "previousChar", "=", "rune", "(", "format", "[", "i", "-", "1", "]", ")", "\n", "}", "\n", "switch", "ch", "{", "case", "'{'", ":", "if", "in_format", "&&", "previousChar", "==", "'{'", "{", "in_format", "=", "false", "\n", "new_format", "=", "append", "(", "new_format", ",", "ch", ")", "\n", "break", "\n", "}", "\n", "in_format", "=", "true", "\n", "case", "'}'", ":", "if", "!", "in_format", "{", "if", "previousChar", "==", "'}'", "{", "new_format", "=", "append", "(", "new_format", ",", "ch", ")", "\n", "break", "\n", "}", "\n", "break", "\n", "}", "\n", "if", "in_format", "{", "if", "len", "(", "current_args_runes", ")", ">", "0", "{", "new_format", "=", "append", "(", "new_format", ",", "current_args_runes", "...", ")", "\n", "}", "else", "{", "new_format", "=", "append", "(", "new_format", ",", "defaultFormat", "...", ")", "\n", "}", "\n", "current_args_runes", "=", "current_args_runes", "[", "0", ":", "0", "]", "\n", "}", "\n", "var", "name", "string", "\n", "if", "len", "(", "current_name_runes", ")", "==", "0", "{", "name", "=", "\"EMPTY_PLACEHOLDER\"", "\n", "}", "else", "{", "name", "=", "string", "(", "current_name_runes", ")", "\n", "}", "\n", "current_name_runes", "=", "current_name_runes", "[", "0", ":", "0", "]", "\n", "val", ",", "ok", ":=", "args", "[", "name", "]", "\n", "if", "!", "ok", "{", "val", "=", "fmt", ".", "Sprintf", "(", "\"%%MISSING=%s\"", ",", "name", ")", "\n", "}", "\n", "new_format_params", "=", "append", "(", "new_format_params", ",", "val", ")", "\n", "in_format", "=", "false", "\n", "in_args", "=", "false", "\n", "case", "':'", ":", "if", "in_format", "{", "in_args", "=", "true", "\n", "}", "\n", "default", ":", "if", "in_format", "{", "if", "in_args", "{", "current_args_runes", "=", "append", "(", "current_args_runes", ",", "ch", ")", "\n", "}", "else", "{", "current_name_runes", "=", "append", "(", "current_name_runes", ",", "ch", ")", "\n", "}", "\n", "}", "else", "{", "new_format", "=", "append", "(", "new_format", ",", "ch", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "string", "(", "new_format", ")", ",", "new_format_params", "\n", "}" ]
// Receives format string in gstring format and map of arguments and translates // them to format and arguments compatible with standard golang formatting.
[ "Receives", "format", "string", "in", "gstring", "format", "and", "map", "of", "arguments", "and", "translates", "them", "to", "format", "and", "arguments", "compatible", "with", "standard", "golang", "formatting", "." ]
77637d5e476b8e22d81f6a7bc5311a836dceb1c2
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L12-L103
test
delicb/gstring
gstring.go
Errorm
func Errorm(format string, args map[string]interface{}) error { f, a := gformat(format, args) return fmt.Errorf(f, a...) }
go
func Errorm(format string, args map[string]interface{}) error { f, a := gformat(format, args) return fmt.Errorf(f, a...) }
[ "func", "Errorm", "(", "format", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "f", ",", "a", ":=", "gformat", "(", "format", ",", "args", ")", "\n", "return", "fmt", ".", "Errorf", "(", "f", ",", "a", "...", ")", "\n", "}" ]
// interface similar to "fmt" package // Errorm returns error instance with formatted error message. // This is same as fmt.Errorf, but uses gstring formatting.
[ "interface", "similar", "to", "fmt", "package", "Errorm", "returns", "error", "instance", "with", "formatted", "error", "message", ".", "This", "is", "same", "as", "fmt", ".", "Errorf", "but", "uses", "gstring", "formatting", "." ]
77637d5e476b8e22d81f6a7bc5311a836dceb1c2
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L109-L112
test
delicb/gstring
gstring.go
Fprintm
func Fprintm(w io.Writer, format string, args map[string]interface{}) (n int, err error) { f, a := gformat(format, args) return fmt.Fprintf(w, f, a...) }
go
func Fprintm(w io.Writer, format string, args map[string]interface{}) (n int, err error) { f, a := gformat(format, args) return fmt.Fprintf(w, f, a...) }
[ "func", "Fprintm", "(", "w", "io", ".", "Writer", ",", "format", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "n", "int", ",", "err", "error", ")", "{", "f", ",", "a", ":=", "gformat", "(", "format", ",", "args", ")", "\n", "return", "fmt", ".", "Fprintf", "(", "w", ",", "f", ",", "a", "...", ")", "\n", "}" ]
// Fprintm writes formatted string to provided writer. // This is same as fmt.Fprintf, but uses gstring formatting.
[ "Fprintm", "writes", "formatted", "string", "to", "provided", "writer", ".", "This", "is", "same", "as", "fmt", ".", "Fprintf", "but", "uses", "gstring", "formatting", "." ]
77637d5e476b8e22d81f6a7bc5311a836dceb1c2
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L116-L119
test
delicb/gstring
gstring.go
Printm
func Printm(format string, args map[string]interface{}) (n int, err error) { f, a := gformat(format, args) return fmt.Printf(f, a...) }
go
func Printm(format string, args map[string]interface{}) (n int, err error) { f, a := gformat(format, args) return fmt.Printf(f, a...) }
[ "func", "Printm", "(", "format", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "n", "int", ",", "err", "error", ")", "{", "f", ",", "a", ":=", "gformat", "(", "format", ",", "args", ")", "\n", "return", "fmt", ".", "Printf", "(", "f", ",", "a", "...", ")", "\n", "}" ]
// Printf prints formatted string to stdout. // This is same as fmt.Printf, but uses gstring formatting.
[ "Printf", "prints", "formatted", "string", "to", "stdout", ".", "This", "is", "same", "as", "fmt", ".", "Printf", "but", "uses", "gstring", "formatting", "." ]
77637d5e476b8e22d81f6a7bc5311a836dceb1c2
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L123-L126
test
delicb/gstring
gstring.go
Sprintm
func Sprintm(format string, args map[string]interface{}) string { f, a := gformat(format, args) return fmt.Sprintf(f, a...) }
go
func Sprintm(format string, args map[string]interface{}) string { f, a := gformat(format, args) return fmt.Sprintf(f, a...) }
[ "func", "Sprintm", "(", "format", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ")", "string", "{", "f", ",", "a", ":=", "gformat", "(", "format", ",", "args", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "f", ",", "a", "...", ")", "\n", "}" ]
// Sprintf returns formatted string. // This is same as fmt.Sprintf, but uses gstring formatting.
[ "Sprintf", "returns", "formatted", "string", ".", "This", "is", "same", "as", "fmt", ".", "Sprintf", "but", "uses", "gstring", "formatting", "." ]
77637d5e476b8e22d81f6a7bc5311a836dceb1c2
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L130-L133
test
michaelbironneau/garbler
lib/password_strength.go
Validate
func (p *PasswordStrengthRequirements) Validate(password string) (bool, string) { reqs := MakeRequirements(password) if p.MaximumTotalLength > 0 && reqs.MaximumTotalLength > p.MaximumTotalLength { return false, "password is too long" } if reqs.MinimumTotalLength < p.MinimumTotalLength { return false, "password is too short" } if reqs.Digits < p.Digits { return false, "password has too few digits" } if reqs.Punctuation < p.Punctuation { return false, "password has too few punctuation characters" } if reqs.Uppercase < p.Uppercase { return false, "password has too few uppercase characters" } return true, "" }
go
func (p *PasswordStrengthRequirements) Validate(password string) (bool, string) { reqs := MakeRequirements(password) if p.MaximumTotalLength > 0 && reqs.MaximumTotalLength > p.MaximumTotalLength { return false, "password is too long" } if reqs.MinimumTotalLength < p.MinimumTotalLength { return false, "password is too short" } if reqs.Digits < p.Digits { return false, "password has too few digits" } if reqs.Punctuation < p.Punctuation { return false, "password has too few punctuation characters" } if reqs.Uppercase < p.Uppercase { return false, "password has too few uppercase characters" } return true, "" }
[ "func", "(", "p", "*", "PasswordStrengthRequirements", ")", "Validate", "(", "password", "string", ")", "(", "bool", ",", "string", ")", "{", "reqs", ":=", "MakeRequirements", "(", "password", ")", "\n", "if", "p", ".", "MaximumTotalLength", ">", "0", "&&", "reqs", ".", "MaximumTotalLength", ">", "p", ".", "MaximumTotalLength", "{", "return", "false", ",", "\"password is too long\"", "\n", "}", "\n", "if", "reqs", ".", "MinimumTotalLength", "<", "p", ".", "MinimumTotalLength", "{", "return", "false", ",", "\"password is too short\"", "\n", "}", "\n", "if", "reqs", ".", "Digits", "<", "p", ".", "Digits", "{", "return", "false", ",", "\"password has too few digits\"", "\n", "}", "\n", "if", "reqs", ".", "Punctuation", "<", "p", ".", "Punctuation", "{", "return", "false", ",", "\"password has too few punctuation characters\"", "\n", "}", "\n", "if", "reqs", ".", "Uppercase", "<", "p", ".", "Uppercase", "{", "return", "false", ",", "\"password has too few uppercase characters\"", "\n", "}", "\n", "return", "true", ",", "\"\"", "\n", "}" ]
//Validate a password against the given requirements //Returns a boolean indicating whether the password meets the requirements. //The second argument is a string explaining why it doesn't meet the requirements, //if it doesn't. It is empty if the requirements are met.
[ "Validate", "a", "password", "against", "the", "given", "requirements", "Returns", "a", "boolean", "indicating", "whether", "the", "password", "meets", "the", "requirements", ".", "The", "second", "argument", "is", "a", "string", "explaining", "why", "it", "doesn", "t", "meet", "the", "requirements", "if", "it", "doesn", "t", ".", "It", "is", "empty", "if", "the", "requirements", "are", "met", "." ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/password_strength.go#L41-L59
test
michaelbironneau/garbler
lib/password_strength.go
MakeRequirements
func MakeRequirements(password string) PasswordStrengthRequirements { pwd := []byte(password) reqs := PasswordStrengthRequirements{} reqs.MaximumTotalLength = len(password) reqs.MinimumTotalLength = len(password) for i := range pwd { switch { case unicode.IsDigit(rune(pwd[i])): reqs.Digits++ case unicode.IsUpper(rune(pwd[i])): reqs.Uppercase++ case unicode.IsPunct(rune(pwd[i])): reqs.Punctuation++ } } return reqs }
go
func MakeRequirements(password string) PasswordStrengthRequirements { pwd := []byte(password) reqs := PasswordStrengthRequirements{} reqs.MaximumTotalLength = len(password) reqs.MinimumTotalLength = len(password) for i := range pwd { switch { case unicode.IsDigit(rune(pwd[i])): reqs.Digits++ case unicode.IsUpper(rune(pwd[i])): reqs.Uppercase++ case unicode.IsPunct(rune(pwd[i])): reqs.Punctuation++ } } return reqs }
[ "func", "MakeRequirements", "(", "password", "string", ")", "PasswordStrengthRequirements", "{", "pwd", ":=", "[", "]", "byte", "(", "password", ")", "\n", "reqs", ":=", "PasswordStrengthRequirements", "{", "}", "\n", "reqs", ".", "MaximumTotalLength", "=", "len", "(", "password", ")", "\n", "reqs", ".", "MinimumTotalLength", "=", "len", "(", "password", ")", "\n", "for", "i", ":=", "range", "pwd", "{", "switch", "{", "case", "unicode", ".", "IsDigit", "(", "rune", "(", "pwd", "[", "i", "]", ")", ")", ":", "reqs", ".", "Digits", "++", "\n", "case", "unicode", ".", "IsUpper", "(", "rune", "(", "pwd", "[", "i", "]", ")", ")", ":", "reqs", ".", "Uppercase", "++", "\n", "case", "unicode", ".", "IsPunct", "(", "rune", "(", "pwd", "[", "i", "]", ")", ")", ":", "reqs", ".", "Punctuation", "++", "\n", "}", "\n", "}", "\n", "return", "reqs", "\n", "}" ]
//Generate password requirements from an existing password.
[ "Generate", "password", "requirements", "from", "an", "existing", "password", "." ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/password_strength.go#L62-L78
test
michaelbironneau/garbler
lib/password_strength.go
sanityCheck
func (p *PasswordStrengthRequirements) sanityCheck() (bool, string) { if p.MaximumTotalLength == 0 { return true, "" } if p.MaximumTotalLength < p.MinimumTotalLength { return false, "maximum total length is less than minimum total length" } if p.MaximumTotalLength < p.Digits { return false, "maximum required digits is more than maximum total length" } if p.MaximumTotalLength < p.Punctuation { return false, "maximum required punctuation is more than maximum total length" } if p.MaximumTotalLength < p.Uppercase { return false, "maximum required uppercase characters is more than maximum total length" } if p.MaximumTotalLength < p.Digits+p.Uppercase+p.Punctuation { return false, "maximum required digits + uppercase + punctuation is more than maximum total length" } return true, "" }
go
func (p *PasswordStrengthRequirements) sanityCheck() (bool, string) { if p.MaximumTotalLength == 0 { return true, "" } if p.MaximumTotalLength < p.MinimumTotalLength { return false, "maximum total length is less than minimum total length" } if p.MaximumTotalLength < p.Digits { return false, "maximum required digits is more than maximum total length" } if p.MaximumTotalLength < p.Punctuation { return false, "maximum required punctuation is more than maximum total length" } if p.MaximumTotalLength < p.Uppercase { return false, "maximum required uppercase characters is more than maximum total length" } if p.MaximumTotalLength < p.Digits+p.Uppercase+p.Punctuation { return false, "maximum required digits + uppercase + punctuation is more than maximum total length" } return true, "" }
[ "func", "(", "p", "*", "PasswordStrengthRequirements", ")", "sanityCheck", "(", ")", "(", "bool", ",", "string", ")", "{", "if", "p", ".", "MaximumTotalLength", "==", "0", "{", "return", "true", ",", "\"\"", "\n", "}", "\n", "if", "p", ".", "MaximumTotalLength", "<", "p", ".", "MinimumTotalLength", "{", "return", "false", ",", "\"maximum total length is less than minimum total length\"", "\n", "}", "\n", "if", "p", ".", "MaximumTotalLength", "<", "p", ".", "Digits", "{", "return", "false", ",", "\"maximum required digits is more than maximum total length\"", "\n", "}", "\n", "if", "p", ".", "MaximumTotalLength", "<", "p", ".", "Punctuation", "{", "return", "false", ",", "\"maximum required punctuation is more than maximum total length\"", "\n", "}", "\n", "if", "p", ".", "MaximumTotalLength", "<", "p", ".", "Uppercase", "{", "return", "false", ",", "\"maximum required uppercase characters is more than maximum total length\"", "\n", "}", "\n", "if", "p", ".", "MaximumTotalLength", "<", "p", ".", "Digits", "+", "p", ".", "Uppercase", "+", "p", ".", "Punctuation", "{", "return", "false", ",", "\"maximum required digits + uppercase + punctuation is more than maximum total length\"", "\n", "}", "\n", "return", "true", ",", "\"\"", "\n", "}" ]
//Make sure password strength requirements make sense
[ "Make", "sure", "password", "strength", "requirements", "make", "sense" ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/password_strength.go#L81-L101
test
michaelbironneau/garbler
lib/garbler.go
password
func (g Garbler) password(req PasswordStrengthRequirements) (string, error) { //Step 1: Figure out settings letters := 0 mustGarble := 0 switch { case req.MaximumTotalLength > 0 && req.MaximumTotalLength > 6: letters = req.MaximumTotalLength - req.Digits - req.Punctuation case req.MaximumTotalLength > 0 && req.MaximumTotalLength <= 6: letters = req.MaximumTotalLength - req.Punctuation mustGarble = req.Digits case req.MinimumTotalLength > req.Digits+req.Punctuation+6: letters = req.MinimumTotalLength - req.Digits - req.Punctuation default: letters = req.MinimumTotalLength } if req.Uppercase > letters { letters = req.Uppercase } password := g.garbledSequence(letters, mustGarble) password = g.uppercase(password, req.Uppercase) password = g.addNums(password, req.Digits-mustGarble) password = g.punctuate(password, req.Punctuation) return password, nil }
go
func (g Garbler) password(req PasswordStrengthRequirements) (string, error) { //Step 1: Figure out settings letters := 0 mustGarble := 0 switch { case req.MaximumTotalLength > 0 && req.MaximumTotalLength > 6: letters = req.MaximumTotalLength - req.Digits - req.Punctuation case req.MaximumTotalLength > 0 && req.MaximumTotalLength <= 6: letters = req.MaximumTotalLength - req.Punctuation mustGarble = req.Digits case req.MinimumTotalLength > req.Digits+req.Punctuation+6: letters = req.MinimumTotalLength - req.Digits - req.Punctuation default: letters = req.MinimumTotalLength } if req.Uppercase > letters { letters = req.Uppercase } password := g.garbledSequence(letters, mustGarble) password = g.uppercase(password, req.Uppercase) password = g.addNums(password, req.Digits-mustGarble) password = g.punctuate(password, req.Punctuation) return password, nil }
[ "func", "(", "g", "Garbler", ")", "password", "(", "req", "PasswordStrengthRequirements", ")", "(", "string", ",", "error", ")", "{", "letters", ":=", "0", "\n", "mustGarble", ":=", "0", "\n", "switch", "{", "case", "req", ".", "MaximumTotalLength", ">", "0", "&&", "req", ".", "MaximumTotalLength", ">", "6", ":", "letters", "=", "req", ".", "MaximumTotalLength", "-", "req", ".", "Digits", "-", "req", ".", "Punctuation", "\n", "case", "req", ".", "MaximumTotalLength", ">", "0", "&&", "req", ".", "MaximumTotalLength", "<=", "6", ":", "letters", "=", "req", ".", "MaximumTotalLength", "-", "req", ".", "Punctuation", "\n", "mustGarble", "=", "req", ".", "Digits", "\n", "case", "req", ".", "MinimumTotalLength", ">", "req", ".", "Digits", "+", "req", ".", "Punctuation", "+", "6", ":", "letters", "=", "req", ".", "MinimumTotalLength", "-", "req", ".", "Digits", "-", "req", ".", "Punctuation", "\n", "default", ":", "letters", "=", "req", ".", "MinimumTotalLength", "\n", "}", "\n", "if", "req", ".", "Uppercase", ">", "letters", "{", "letters", "=", "req", ".", "Uppercase", "\n", "}", "\n", "password", ":=", "g", ".", "garbledSequence", "(", "letters", ",", "mustGarble", ")", "\n", "password", "=", "g", ".", "uppercase", "(", "password", ",", "req", ".", "Uppercase", ")", "\n", "password", "=", "g", ".", "addNums", "(", "password", ",", "req", ".", "Digits", "-", "mustGarble", ")", "\n", "password", "=", "g", ".", "punctuate", "(", "password", ",", "req", ".", "Punctuation", ")", "\n", "return", "password", ",", "nil", "\n", "}" ]
//Generate a password given requirements
[ "Generate", "a", "password", "given", "requirements" ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L55-L78
test
michaelbironneau/garbler
lib/garbler.go
NewPassword
func NewPassword(reqs *PasswordStrengthRequirements) (string, error) { if reqs == nil { reqs = &Medium } if ok, problems := reqs.sanityCheck(); !ok { return "", errors.New("requirements failed validation: " + problems) } e := Garbler{} return e.password(*reqs) }
go
func NewPassword(reqs *PasswordStrengthRequirements) (string, error) { if reqs == nil { reqs = &Medium } if ok, problems := reqs.sanityCheck(); !ok { return "", errors.New("requirements failed validation: " + problems) } e := Garbler{} return e.password(*reqs) }
[ "func", "NewPassword", "(", "reqs", "*", "PasswordStrengthRequirements", ")", "(", "string", ",", "error", ")", "{", "if", "reqs", "==", "nil", "{", "reqs", "=", "&", "Medium", "\n", "}", "\n", "if", "ok", ",", "problems", ":=", "reqs", ".", "sanityCheck", "(", ")", ";", "!", "ok", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"requirements failed validation: \"", "+", "problems", ")", "\n", "}", "\n", "e", ":=", "Garbler", "{", "}", "\n", "return", "e", ".", "password", "(", "*", "reqs", ")", "\n", "}" ]
//Generate one password that meets the given requirements
[ "Generate", "one", "password", "that", "meets", "the", "given", "requirements" ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L81-L90
test
michaelbironneau/garbler
lib/garbler.go
NewPasswords
func NewPasswords(reqs *PasswordStrengthRequirements, n int) ([]string, error) { var err error if reqs == nil { reqs = &Medium } if ok, problems := reqs.sanityCheck(); !ok { return nil, errors.New("requirements failed validation: " + problems) } e := Garbler{} passes := make([]string, n, n) for i := 0; i < n; i++ { passes[i], err = e.password(*reqs) if err != nil { return nil, err } } return passes, nil }
go
func NewPasswords(reqs *PasswordStrengthRequirements, n int) ([]string, error) { var err error if reqs == nil { reqs = &Medium } if ok, problems := reqs.sanityCheck(); !ok { return nil, errors.New("requirements failed validation: " + problems) } e := Garbler{} passes := make([]string, n, n) for i := 0; i < n; i++ { passes[i], err = e.password(*reqs) if err != nil { return nil, err } } return passes, nil }
[ "func", "NewPasswords", "(", "reqs", "*", "PasswordStrengthRequirements", ",", "n", "int", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "if", "reqs", "==", "nil", "{", "reqs", "=", "&", "Medium", "\n", "}", "\n", "if", "ok", ",", "problems", ":=", "reqs", ".", "sanityCheck", "(", ")", ";", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"requirements failed validation: \"", "+", "problems", ")", "\n", "}", "\n", "e", ":=", "Garbler", "{", "}", "\n", "passes", ":=", "make", "(", "[", "]", "string", ",", "n", ",", "n", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "passes", "[", "i", "]", ",", "err", "=", "e", ".", "password", "(", "*", "reqs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "passes", ",", "nil", "\n", "}" ]
//Generate n passwords that meet the given requirements
[ "Generate", "n", "passwords", "that", "meet", "the", "given", "requirements" ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L93-L110
test
michaelbironneau/garbler
lib/garbler.go
addNums
func (g Garbler) addNums(p string, numDigits int) string { if numDigits <= 0 { return p } ret := p remaining := numDigits for remaining > 10 { ret += fmt.Sprintf("%d", pow(10, 9)+randInt(pow(10, 10)-pow(10, 9))) remaining -= 10 } ret += fmt.Sprintf("%d", pow(10, remaining-1)+randInt(pow(10, remaining)-pow(10, remaining-1))) return ret }
go
func (g Garbler) addNums(p string, numDigits int) string { if numDigits <= 0 { return p } ret := p remaining := numDigits for remaining > 10 { ret += fmt.Sprintf("%d", pow(10, 9)+randInt(pow(10, 10)-pow(10, 9))) remaining -= 10 } ret += fmt.Sprintf("%d", pow(10, remaining-1)+randInt(pow(10, remaining)-pow(10, remaining-1))) return ret }
[ "func", "(", "g", "Garbler", ")", "addNums", "(", "p", "string", ",", "numDigits", "int", ")", "string", "{", "if", "numDigits", "<=", "0", "{", "return", "p", "\n", "}", "\n", "ret", ":=", "p", "\n", "remaining", ":=", "numDigits", "\n", "for", "remaining", ">", "10", "{", "ret", "+=", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "pow", "(", "10", ",", "9", ")", "+", "randInt", "(", "pow", "(", "10", ",", "10", ")", "-", "pow", "(", "10", ",", "9", ")", ")", ")", "\n", "remaining", "-=", "10", "\n", "}", "\n", "ret", "+=", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "pow", "(", "10", ",", "remaining", "-", "1", ")", "+", "randInt", "(", "pow", "(", "10", ",", "remaining", ")", "-", "pow", "(", "10", ",", "remaining", "-", "1", ")", ")", ")", "\n", "return", "ret", "\n", "}" ]
//append digits to string
[ "append", "digits", "to", "string" ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L113-L126
test
michaelbironneau/garbler
lib/garbler.go
punctuate
func (g Garbler) punctuate(p string, numPunc int) string { if numPunc <= 0 { return p } ret := p for i := 0; i < numPunc; i++ { if i%2 == 0 { ret += string(Punctuation[randInt(len(Punctuation))]) } else { ret = string(Punctuation[randInt(len(Punctuation))]) + ret } } return ret }
go
func (g Garbler) punctuate(p string, numPunc int) string { if numPunc <= 0 { return p } ret := p for i := 0; i < numPunc; i++ { if i%2 == 0 { ret += string(Punctuation[randInt(len(Punctuation))]) } else { ret = string(Punctuation[randInt(len(Punctuation))]) + ret } } return ret }
[ "func", "(", "g", "Garbler", ")", "punctuate", "(", "p", "string", ",", "numPunc", "int", ")", "string", "{", "if", "numPunc", "<=", "0", "{", "return", "p", "\n", "}", "\n", "ret", ":=", "p", "\n", "for", "i", ":=", "0", ";", "i", "<", "numPunc", ";", "i", "++", "{", "if", "i", "%", "2", "==", "0", "{", "ret", "+=", "string", "(", "Punctuation", "[", "randInt", "(", "len", "(", "Punctuation", ")", ")", "]", ")", "\n", "}", "else", "{", "ret", "=", "string", "(", "Punctuation", "[", "randInt", "(", "len", "(", "Punctuation", ")", ")", "]", ")", "+", "ret", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
//add punctuation characters to start and end of string
[ "add", "punctuation", "characters", "to", "start", "and", "end", "of", "string" ]
2018e2dc9c1173564cc1352ccb90bdc0ac29c12f
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L129-L142
test
drone/drone-plugin-go
plugin/param.go
deprecated_init
func deprecated_init() { // if piping from stdin we can just exit // and use the default Stdin value stat, _ := os.Stdin.Stat() if (stat.Mode() & os.ModeCharDevice) == 0 { return } // check for params after the double dash // in the command string for i, argv := range os.Args { if argv == "--" { arg := os.Args[i+1] buf := bytes.NewBufferString(arg) Stdin = NewParamSet(buf) return } } // else use the first variable in the list if len(os.Args) > 1 { buf := bytes.NewBufferString(os.Args[1]) Stdin = NewParamSet(buf) } }
go
func deprecated_init() { // if piping from stdin we can just exit // and use the default Stdin value stat, _ := os.Stdin.Stat() if (stat.Mode() & os.ModeCharDevice) == 0 { return } // check for params after the double dash // in the command string for i, argv := range os.Args { if argv == "--" { arg := os.Args[i+1] buf := bytes.NewBufferString(arg) Stdin = NewParamSet(buf) return } } // else use the first variable in the list if len(os.Args) > 1 { buf := bytes.NewBufferString(os.Args[1]) Stdin = NewParamSet(buf) } }
[ "func", "deprecated_init", "(", ")", "{", "stat", ",", "_", ":=", "os", ".", "Stdin", ".", "Stat", "(", ")", "\n", "if", "(", "stat", ".", "Mode", "(", ")", "&", "os", ".", "ModeCharDevice", ")", "==", "0", "{", "return", "\n", "}", "\n", "for", "i", ",", "argv", ":=", "range", "os", ".", "Args", "{", "if", "argv", "==", "\"--\"", "{", "arg", ":=", "os", ".", "Args", "[", "i", "+", "1", "]", "\n", "buf", ":=", "bytes", ".", "NewBufferString", "(", "arg", ")", "\n", "Stdin", "=", "NewParamSet", "(", "buf", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "len", "(", "os", ".", "Args", ")", ">", "1", "{", "buf", ":=", "bytes", ".", "NewBufferString", "(", "os", ".", "Args", "[", "1", "]", ")", "\n", "Stdin", "=", "NewParamSet", "(", "buf", ")", "\n", "}", "\n", "}" ]
// this init function is deprecated, but I'm keeping it // around just in case it proves useful in the future.
[ "this", "init", "function", "is", "deprecated", "but", "I", "m", "keeping", "it", "around", "just", "in", "case", "it", "proves", "useful", "in", "the", "future", "." ]
d6109f644c5935c22620081b4c234bb2263743c7
https://github.com/drone/drone-plugin-go/blob/d6109f644c5935c22620081b4c234bb2263743c7/plugin/param.go#L31-L55
test
drone/drone-plugin-go
plugin/param.go
Param
func (p ParamSet) Param(name string, value interface{}) { p.params[name] = value }
go
func (p ParamSet) Param(name string, value interface{}) { p.params[name] = value }
[ "func", "(", "p", "ParamSet", ")", "Param", "(", "name", "string", ",", "value", "interface", "{", "}", ")", "{", "p", ".", "params", "[", "name", "]", "=", "value", "\n", "}" ]
// Param defines a parameter with the specified name.
[ "Param", "defines", "a", "parameter", "with", "the", "specified", "name", "." ]
d6109f644c5935c22620081b4c234bb2263743c7
https://github.com/drone/drone-plugin-go/blob/d6109f644c5935c22620081b4c234bb2263743c7/plugin/param.go#L70-L72
test
drone/drone-plugin-go
plugin/param.go
Parse
func (p ParamSet) Parse() error { raw := map[string]json.RawMessage{} err := json.NewDecoder(p.reader).Decode(&raw) if err != nil { return err } for key, val := range p.params { data, ok := raw[key] if !ok { continue } err := json.Unmarshal(data, val) if err != nil { return fmt.Errorf("Unable to unarmshal %s. %s", key, err) } } return nil }
go
func (p ParamSet) Parse() error { raw := map[string]json.RawMessage{} err := json.NewDecoder(p.reader).Decode(&raw) if err != nil { return err } for key, val := range p.params { data, ok := raw[key] if !ok { continue } err := json.Unmarshal(data, val) if err != nil { return fmt.Errorf("Unable to unarmshal %s. %s", key, err) } } return nil }
[ "func", "(", "p", "ParamSet", ")", "Parse", "(", ")", "error", "{", "raw", ":=", "map", "[", "string", "]", "json", ".", "RawMessage", "{", "}", "\n", "err", ":=", "json", ".", "NewDecoder", "(", "p", ".", "reader", ")", ".", "Decode", "(", "&", "raw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "key", ",", "val", ":=", "range", "p", ".", "params", "{", "data", ",", "ok", ":=", "raw", "[", "key", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Unable to unarmshal %s. %s\"", ",", "key", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Parse parses parameter definitions from the map.
[ "Parse", "parses", "parameter", "definitions", "from", "the", "map", "." ]
d6109f644c5935c22620081b4c234bb2263743c7
https://github.com/drone/drone-plugin-go/blob/d6109f644c5935c22620081b4c234bb2263743c7/plugin/param.go#L75-L94
test
drone/drone-plugin-go
plugin/param.go
Unmarshal
func (p ParamSet) Unmarshal(v interface{}) error { return json.NewDecoder(p.reader).Decode(v) }
go
func (p ParamSet) Unmarshal(v interface{}) error { return json.NewDecoder(p.reader).Decode(v) }
[ "func", "(", "p", "ParamSet", ")", "Unmarshal", "(", "v", "interface", "{", "}", ")", "error", "{", "return", "json", ".", "NewDecoder", "(", "p", ".", "reader", ")", ".", "Decode", "(", "v", ")", "\n", "}" ]
// Unmarshal parses the JSON payload from the command // arguments and unmarshal into a value pointed to by v.
[ "Unmarshal", "parses", "the", "JSON", "payload", "from", "the", "command", "arguments", "and", "unmarshal", "into", "a", "value", "pointed", "to", "by", "v", "." ]
d6109f644c5935c22620081b4c234bb2263743c7
https://github.com/drone/drone-plugin-go/blob/d6109f644c5935c22620081b4c234bb2263743c7/plugin/param.go#L98-L100
test
fossapps/pushy
pushy.go
GetDefaultHTTPClient
func GetDefaultHTTPClient(timeout time.Duration) IHTTPClient { client := http.Client{ Timeout: timeout, } return IHTTPClient(&client) }
go
func GetDefaultHTTPClient(timeout time.Duration) IHTTPClient { client := http.Client{ Timeout: timeout, } return IHTTPClient(&client) }
[ "func", "GetDefaultHTTPClient", "(", "timeout", "time", ".", "Duration", ")", "IHTTPClient", "{", "client", ":=", "http", ".", "Client", "{", "Timeout", ":", "timeout", ",", "}", "\n", "return", "IHTTPClient", "(", "&", "client", ")", "\n", "}" ]
// GetDefaultHTTPClient returns a httpClient with configured timeout
[ "GetDefaultHTTPClient", "returns", "a", "httpClient", "with", "configured", "timeout" ]
4c6045d7a1d3c310d61168ff1ccd5421d5c162f6
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L29-L34
test
fossapps/pushy
pushy.go
DeviceInfo
func (p Pushy) DeviceInfo(deviceID string) (*DeviceInfo, *Error, error) { url := fmt.Sprintf("%s/devices/%s?api_key=%s", p.APIEndpoint, deviceID, p.APIToken) var errResponse *Error var info *DeviceInfo err := get(p.httpClient, url, &info, &errResponse) return info, errResponse, err }
go
func (p Pushy) DeviceInfo(deviceID string) (*DeviceInfo, *Error, error) { url := fmt.Sprintf("%s/devices/%s?api_key=%s", p.APIEndpoint, deviceID, p.APIToken) var errResponse *Error var info *DeviceInfo err := get(p.httpClient, url, &info, &errResponse) return info, errResponse, err }
[ "func", "(", "p", "Pushy", ")", "DeviceInfo", "(", "deviceID", "string", ")", "(", "*", "DeviceInfo", ",", "*", "Error", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"%s/devices/%s?api_key=%s\"", ",", "p", ".", "APIEndpoint", ",", "deviceID", ",", "p", ".", "APIToken", ")", "\n", "var", "errResponse", "*", "Error", "\n", "var", "info", "*", "DeviceInfo", "\n", "err", ":=", "get", "(", "p", ".", "httpClient", ",", "url", ",", "&", "info", ",", "&", "errResponse", ")", "\n", "return", "info", ",", "errResponse", ",", "err", "\n", "}" ]
// DeviceInfo returns information about a particular device
[ "DeviceInfo", "returns", "information", "about", "a", "particular", "device" ]
4c6045d7a1d3c310d61168ff1ccd5421d5c162f6
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L48-L54
test
fossapps/pushy
pushy.go
DevicePresence
func (p *Pushy) DevicePresence(deviceID ...string) (*DevicePresenceResponse, *Error, error) { url := fmt.Sprintf("%s/devices/presence?api_key=%s", p.APIEndpoint, p.APIToken) var devicePresenceResponse *DevicePresenceResponse var pushyErr *Error err := post(p.httpClient, url, DevicePresenceRequest{Tokens: deviceID}, &devicePresenceResponse, &pushyErr) return devicePresenceResponse, pushyErr, err }
go
func (p *Pushy) DevicePresence(deviceID ...string) (*DevicePresenceResponse, *Error, error) { url := fmt.Sprintf("%s/devices/presence?api_key=%s", p.APIEndpoint, p.APIToken) var devicePresenceResponse *DevicePresenceResponse var pushyErr *Error err := post(p.httpClient, url, DevicePresenceRequest{Tokens: deviceID}, &devicePresenceResponse, &pushyErr) return devicePresenceResponse, pushyErr, err }
[ "func", "(", "p", "*", "Pushy", ")", "DevicePresence", "(", "deviceID", "...", "string", ")", "(", "*", "DevicePresenceResponse", ",", "*", "Error", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"%s/devices/presence?api_key=%s\"", ",", "p", ".", "APIEndpoint", ",", "p", ".", "APIToken", ")", "\n", "var", "devicePresenceResponse", "*", "DevicePresenceResponse", "\n", "var", "pushyErr", "*", "Error", "\n", "err", ":=", "post", "(", "p", ".", "httpClient", ",", "url", ",", "DevicePresenceRequest", "{", "Tokens", ":", "deviceID", "}", ",", "&", "devicePresenceResponse", ",", "&", "pushyErr", ")", "\n", "return", "devicePresenceResponse", ",", "pushyErr", ",", "err", "\n", "}" ]
// DevicePresence returns data about presence of a data
[ "DevicePresence", "returns", "data", "about", "presence", "of", "a", "data" ]
4c6045d7a1d3c310d61168ff1ccd5421d5c162f6
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L57-L63
test
fossapps/pushy
pushy.go
NotificationStatus
func (p *Pushy) NotificationStatus(pushID string) (*NotificationStatus, *Error, error) { url := fmt.Sprintf("%s/pushes/%s?api_key=%s", p.APIEndpoint, pushID, p.APIToken) var errResponse *Error var status *NotificationStatus err := get(p.httpClient, url, &status, &errResponse) return status, errResponse, err }
go
func (p *Pushy) NotificationStatus(pushID string) (*NotificationStatus, *Error, error) { url := fmt.Sprintf("%s/pushes/%s?api_key=%s", p.APIEndpoint, pushID, p.APIToken) var errResponse *Error var status *NotificationStatus err := get(p.httpClient, url, &status, &errResponse) return status, errResponse, err }
[ "func", "(", "p", "*", "Pushy", ")", "NotificationStatus", "(", "pushID", "string", ")", "(", "*", "NotificationStatus", ",", "*", "Error", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"%s/pushes/%s?api_key=%s\"", ",", "p", ".", "APIEndpoint", ",", "pushID", ",", "p", ".", "APIToken", ")", "\n", "var", "errResponse", "*", "Error", "\n", "var", "status", "*", "NotificationStatus", "\n", "err", ":=", "get", "(", "p", ".", "httpClient", ",", "url", ",", "&", "status", ",", "&", "errResponse", ")", "\n", "return", "status", ",", "errResponse", ",", "err", "\n", "}" ]
// NotificationStatus returns status of a particular notification
[ "NotificationStatus", "returns", "status", "of", "a", "particular", "notification" ]
4c6045d7a1d3c310d61168ff1ccd5421d5c162f6
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L66-L72
test
fossapps/pushy
pushy.go
DeleteNotification
func (p *Pushy) DeleteNotification(pushID string) (*SimpleSuccess, *Error, error) { url := fmt.Sprintf("%s/pushes/%s?api_key=%s", p.APIEndpoint, pushID, p.APIToken) var success *SimpleSuccess var pushyErr *Error err := del(p.httpClient, url, &success, &pushyErr) return success, pushyErr, err }
go
func (p *Pushy) DeleteNotification(pushID string) (*SimpleSuccess, *Error, error) { url := fmt.Sprintf("%s/pushes/%s?api_key=%s", p.APIEndpoint, pushID, p.APIToken) var success *SimpleSuccess var pushyErr *Error err := del(p.httpClient, url, &success, &pushyErr) return success, pushyErr, err }
[ "func", "(", "p", "*", "Pushy", ")", "DeleteNotification", "(", "pushID", "string", ")", "(", "*", "SimpleSuccess", ",", "*", "Error", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"%s/pushes/%s?api_key=%s\"", ",", "p", ".", "APIEndpoint", ",", "pushID", ",", "p", ".", "APIToken", ")", "\n", "var", "success", "*", "SimpleSuccess", "\n", "var", "pushyErr", "*", "Error", "\n", "err", ":=", "del", "(", "p", ".", "httpClient", ",", "url", ",", "&", "success", ",", "&", "pushyErr", ")", "\n", "return", "success", ",", "pushyErr", ",", "err", "\n", "}" ]
// DeleteNotification deletes a created notification
[ "DeleteNotification", "deletes", "a", "created", "notification" ]
4c6045d7a1d3c310d61168ff1ccd5421d5c162f6
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L75-L81
test
fossapps/pushy
pushy.go
NotifyDevice
func (p *Pushy) NotifyDevice(request SendNotificationRequest) (*NotificationResponse, *Error, error) { url := fmt.Sprintf("%s/push?api_key=%s", p.APIEndpoint, p.APIToken) var success *NotificationResponse var pushyErr *Error err := post(p.httpClient, url, request, &success, &pushyErr) return success, pushyErr, err }
go
func (p *Pushy) NotifyDevice(request SendNotificationRequest) (*NotificationResponse, *Error, error) { url := fmt.Sprintf("%s/push?api_key=%s", p.APIEndpoint, p.APIToken) var success *NotificationResponse var pushyErr *Error err := post(p.httpClient, url, request, &success, &pushyErr) return success, pushyErr, err }
[ "func", "(", "p", "*", "Pushy", ")", "NotifyDevice", "(", "request", "SendNotificationRequest", ")", "(", "*", "NotificationResponse", ",", "*", "Error", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"%s/push?api_key=%s\"", ",", "p", ".", "APIEndpoint", ",", "p", ".", "APIToken", ")", "\n", "var", "success", "*", "NotificationResponse", "\n", "var", "pushyErr", "*", "Error", "\n", "err", ":=", "post", "(", "p", ".", "httpClient", ",", "url", ",", "request", ",", "&", "success", ",", "&", "pushyErr", ")", "\n", "return", "success", ",", "pushyErr", ",", "err", "\n", "}" ]
// NotifyDevice sends notification data to devices
[ "NotifyDevice", "sends", "notification", "data", "to", "devices" ]
4c6045d7a1d3c310d61168ff1ccd5421d5c162f6
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L110-L116
test
heketi/tests
assert.go
Assert
func Assert(t Tester, b bool, message ...interface{}) { if !b { pc, file, line, _ := runtime.Caller(1) caller_func_info := runtime.FuncForPC(pc) error_string := fmt.Sprintf("\n\rASSERT:\tfunc (%s) 0x%x\n\r\tFile %s:%d", caller_func_info.Name(), pc, file, line) if len(message) > 0 { error_string += fmt.Sprintf("\n\r\tInfo: %+v", message) } t.Errorf(error_string) t.FailNow() } }
go
func Assert(t Tester, b bool, message ...interface{}) { if !b { pc, file, line, _ := runtime.Caller(1) caller_func_info := runtime.FuncForPC(pc) error_string := fmt.Sprintf("\n\rASSERT:\tfunc (%s) 0x%x\n\r\tFile %s:%d", caller_func_info.Name(), pc, file, line) if len(message) > 0 { error_string += fmt.Sprintf("\n\r\tInfo: %+v", message) } t.Errorf(error_string) t.FailNow() } }
[ "func", "Assert", "(", "t", "Tester", ",", "b", "bool", ",", "message", "...", "interface", "{", "}", ")", "{", "if", "!", "b", "{", "pc", ",", "file", ",", "line", ",", "_", ":=", "runtime", ".", "Caller", "(", "1", ")", "\n", "caller_func_info", ":=", "runtime", ".", "FuncForPC", "(", "pc", ")", "\n", "error_string", ":=", "fmt", ".", "Sprintf", "(", "\"\\n\\rASSERT:\\tfunc (%s) 0x%x\\n\\r\\tFile %s:%d\"", ",", "\\n", ",", "\\r", ",", "\\t", ",", "\\n", ")", "\n", "\\r", "\n", "\\t", "\n", "caller_func_info", ".", "Name", "(", ")", "\n", "}", "\n", "}" ]
// Simple assert call for unit and functional tests
[ "Simple", "assert", "call", "for", "unit", "and", "functional", "tests" ]
f3775cbcefd6822086c729e3ce4b70ca85a5bd21
https://github.com/heketi/tests/blob/f3775cbcefd6822086c729e3ce4b70ca85a5bd21/assert.go#L29-L47
test
heketi/tests
tempfile.go
CreateFile
func CreateFile(filename string, size int64) error { buf := make([]byte, size) // Create the file store some data fp, err := os.Create(filename) if err != nil { return err } // Write the buffer _, err = fp.Write(buf) // Cleanup fp.Close() return err }
go
func CreateFile(filename string, size int64) error { buf := make([]byte, size) // Create the file store some data fp, err := os.Create(filename) if err != nil { return err } // Write the buffer _, err = fp.Write(buf) // Cleanup fp.Close() return err }
[ "func", "CreateFile", "(", "filename", "string", ",", "size", "int64", ")", "error", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "fp", ",", "err", ":=", "os", ".", "Create", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "fp", ".", "Write", "(", "buf", ")", "\n", "fp", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}" ]
// We could use Fallocate, but some test CI systems // do not support it, like Travis-ci.org.
[ "We", "could", "use", "Fallocate", "but", "some", "test", "CI", "systems", "do", "not", "support", "it", "like", "Travis", "-", "ci", ".", "org", "." ]
f3775cbcefd6822086c729e3ce4b70ca85a5bd21
https://github.com/heketi/tests/blob/f3775cbcefd6822086c729e3ce4b70ca85a5bd21/tempfile.go#L42-L59
test
janos/web
form.go
AddError
func (f *FormErrors) AddError(e string) { f.Errors = append(f.Errors, e) }
go
func (f *FormErrors) AddError(e string) { f.Errors = append(f.Errors, e) }
[ "func", "(", "f", "*", "FormErrors", ")", "AddError", "(", "e", "string", ")", "{", "f", ".", "Errors", "=", "append", "(", "f", ".", "Errors", ",", "e", ")", "\n", "}" ]
// AddError appends an error to a list of general errors.
[ "AddError", "appends", "an", "error", "to", "a", "list", "of", "general", "errors", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/form.go#L16-L18
test
janos/web
form.go
AddFieldError
func (f *FormErrors) AddFieldError(field, e string) { if f.FieldErrors == nil { f.FieldErrors = map[string][]string{} } if _, ok := f.FieldErrors[field]; !ok { f.FieldErrors[field] = []string{} } f.FieldErrors[field] = append(f.FieldErrors[field], e) }
go
func (f *FormErrors) AddFieldError(field, e string) { if f.FieldErrors == nil { f.FieldErrors = map[string][]string{} } if _, ok := f.FieldErrors[field]; !ok { f.FieldErrors[field] = []string{} } f.FieldErrors[field] = append(f.FieldErrors[field], e) }
[ "func", "(", "f", "*", "FormErrors", ")", "AddFieldError", "(", "field", ",", "e", "string", ")", "{", "if", "f", ".", "FieldErrors", "==", "nil", "{", "f", ".", "FieldErrors", "=", "map", "[", "string", "]", "[", "]", "string", "{", "}", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "f", ".", "FieldErrors", "[", "field", "]", ";", "!", "ok", "{", "f", ".", "FieldErrors", "[", "field", "]", "=", "[", "]", "string", "{", "}", "\n", "}", "\n", "f", ".", "FieldErrors", "[", "field", "]", "=", "append", "(", "f", ".", "FieldErrors", "[", "field", "]", ",", "e", ")", "\n", "}" ]
// AddFieldError appends an error to a list of field specific errors.
[ "AddFieldError", "appends", "an", "error", "to", "a", "list", "of", "field", "specific", "errors", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/form.go#L21-L29
test
janos/web
form.go
HasErrors
func (f FormErrors) HasErrors() bool { if len(f.Errors) > 0 { return true } for _, v := range f.FieldErrors { if len(v) > 0 { return true } } return false }
go
func (f FormErrors) HasErrors() bool { if len(f.Errors) > 0 { return true } for _, v := range f.FieldErrors { if len(v) > 0 { return true } } return false }
[ "func", "(", "f", "FormErrors", ")", "HasErrors", "(", ")", "bool", "{", "if", "len", "(", "f", ".", "Errors", ")", ">", "0", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "f", ".", "FieldErrors", "{", "if", "len", "(", "v", ")", ">", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasErrors returns weather FormErrors instance contains at leas one error.
[ "HasErrors", "returns", "weather", "FormErrors", "instance", "contains", "at", "leas", "one", "error", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/form.go#L32-L42
test
janos/web
form.go
NewError
func NewError(e string) FormErrors { errors := FormErrors{} errors.AddError(e) return errors }
go
func NewError(e string) FormErrors { errors := FormErrors{} errors.AddError(e) return errors }
[ "func", "NewError", "(", "e", "string", ")", "FormErrors", "{", "errors", ":=", "FormErrors", "{", "}", "\n", "errors", ".", "AddError", "(", "e", ")", "\n", "return", "errors", "\n", "}" ]
// NewError initializes FormErrors with one general error.
[ "NewError", "initializes", "FormErrors", "with", "one", "general", "error", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/form.go#L45-L49
test
janos/web
form.go
NewFieldError
func NewFieldError(field, e string) FormErrors { errors := FormErrors{} errors.AddFieldError(field, e) return errors }
go
func NewFieldError(field, e string) FormErrors { errors := FormErrors{} errors.AddFieldError(field, e) return errors }
[ "func", "NewFieldError", "(", "field", ",", "e", "string", ")", "FormErrors", "{", "errors", ":=", "FormErrors", "{", "}", "\n", "errors", ".", "AddFieldError", "(", "field", ",", "e", ")", "\n", "return", "errors", "\n", "}" ]
// NewFieldError initializes FormErrors with one field error.
[ "NewFieldError", "initializes", "FormErrors", "with", "one", "field", "error", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/form.go#L52-L56
test
janos/web
chain.go
ChainHandlers
func ChainHandlers(handlers ...func(http.Handler) http.Handler) (h http.Handler) { for i := len(handlers) - 1; i >= 0; i-- { h = handlers[i](h) } return }
go
func ChainHandlers(handlers ...func(http.Handler) http.Handler) (h http.Handler) { for i := len(handlers) - 1; i >= 0; i-- { h = handlers[i](h) } return }
[ "func", "ChainHandlers", "(", "handlers", "...", "func", "(", "http", ".", "Handler", ")", "http", ".", "Handler", ")", "(", "h", "http", ".", "Handler", ")", "{", "for", "i", ":=", "len", "(", "handlers", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "h", "=", "handlers", "[", "i", "]", "(", "h", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ChainHandlers executes each function from the arguments with handler // from the next function to construct a chan fo callers.
[ "ChainHandlers", "executes", "each", "function", "from", "the", "arguments", "with", "handler", "from", "the", "next", "function", "to", "construct", "a", "chan", "fo", "callers", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/chain.go#L12-L17
test
janos/web
chain.go
FinalHandler
func FinalHandler(h http.Handler) func(http.Handler) http.Handler { return func(_ http.Handler) http.Handler { return h } }
go
func FinalHandler(h http.Handler) func(http.Handler) http.Handler { return func(_ http.Handler) http.Handler { return h } }
[ "func", "FinalHandler", "(", "h", "http", ".", "Handler", ")", "func", "(", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "func", "(", "_", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "h", "\n", "}", "\n", "}" ]
// FinalHandler is a helper function to wrap the last http.Handler element // in the ChainHandlers function.
[ "FinalHandler", "is", "a", "helper", "function", "to", "wrap", "the", "last", "http", ".", "Handler", "element", "in", "the", "ChainHandlers", "function", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/chain.go#L21-L25
test
janos/web
file-server/hasher.go
Hash
func (s MD5Hasher) Hash(reader io.Reader) (string, error) { hash := md5.New() if _, err := io.Copy(hash, reader); err != nil { return "", err } h := hash.Sum(nil) if len(h) < s.HashLength { return "", nil } return strings.TrimRight(hex.EncodeToString(h)[:s.HashLength], "="), nil }
go
func (s MD5Hasher) Hash(reader io.Reader) (string, error) { hash := md5.New() if _, err := io.Copy(hash, reader); err != nil { return "", err } h := hash.Sum(nil) if len(h) < s.HashLength { return "", nil } return strings.TrimRight(hex.EncodeToString(h)[:s.HashLength], "="), nil }
[ "func", "(", "s", "MD5Hasher", ")", "Hash", "(", "reader", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "hash", ":=", "md5", ".", "New", "(", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "hash", ",", "reader", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "h", ":=", "hash", ".", "Sum", "(", "nil", ")", "\n", "if", "len", "(", "h", ")", "<", "s", ".", "HashLength", "{", "return", "\"\"", ",", "nil", "\n", "}", "\n", "return", "strings", ".", "TrimRight", "(", "hex", ".", "EncodeToString", "(", "h", ")", "[", ":", "s", ".", "HashLength", "]", ",", "\"=\"", ")", ",", "nil", "\n", "}" ]
// Hash returns a part of a MD5 sum of a file.
[ "Hash", "returns", "a", "part", "of", "a", "MD5", "sum", "of", "a", "file", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/file-server/hasher.go#L29-L39
test
janos/web
file-server/hasher.go
IsHash
func (s MD5Hasher) IsHash(h string) bool { if len(h) != s.HashLength { return false } var found bool for _, c := range h { found = false for _, m := range hexChars { if c == m { found = true break } } if !found { return false } } return true }
go
func (s MD5Hasher) IsHash(h string) bool { if len(h) != s.HashLength { return false } var found bool for _, c := range h { found = false for _, m := range hexChars { if c == m { found = true break } } if !found { return false } } return true }
[ "func", "(", "s", "MD5Hasher", ")", "IsHash", "(", "h", "string", ")", "bool", "{", "if", "len", "(", "h", ")", "!=", "s", ".", "HashLength", "{", "return", "false", "\n", "}", "\n", "var", "found", "bool", "\n", "for", "_", ",", "c", ":=", "range", "h", "{", "found", "=", "false", "\n", "for", "_", ",", "m", ":=", "range", "hexChars", "{", "if", "c", "==", "m", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsHash checks is provided string a valid hash.
[ "IsHash", "checks", "is", "provided", "string", "a", "valid", "hash", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/file-server/hasher.go#L42-L60
test
janos/web
templates/templates.go
WithBaseDir
func WithBaseDir(dir string) Option { return func(o *Options) { o.fileFindFunc = func(f string) string { return filepath.Join(dir, f) } } }
go
func WithBaseDir(dir string) Option { return func(o *Options) { o.fileFindFunc = func(f string) string { return filepath.Join(dir, f) } } }
[ "func", "WithBaseDir", "(", "dir", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "fileFindFunc", "=", "func", "(", "f", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "dir", ",", "f", ")", "\n", "}", "\n", "}", "\n", "}" ]
// WithBaseDir sets the directory in which template files // are stored.
[ "WithBaseDir", "sets", "the", "directory", "in", "which", "template", "files", "are", "stored", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L65-L71
test
janos/web
templates/templates.go
WithFileFindFunc
func WithFileFindFunc(fn func(filename string) string) Option { return func(o *Options) { o.fileFindFunc = fn } }
go
func WithFileFindFunc(fn func(filename string) string) Option { return func(o *Options) { o.fileFindFunc = fn } }
[ "func", "WithFileFindFunc", "(", "fn", "func", "(", "filename", "string", ")", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "fileFindFunc", "=", "fn", "}", "\n", "}" ]
// WithFileFindFunc sets the function that will return the // file path on disk based on filename provided from files // defind using WithTemplateFromFile or WithTemplateFromFiles.
[ "WithFileFindFunc", "sets", "the", "function", "that", "will", "return", "the", "file", "path", "on", "disk", "based", "on", "filename", "provided", "from", "files", "defind", "using", "WithTemplateFromFile", "or", "WithTemplateFromFiles", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L76-L78
test
janos/web
templates/templates.go
WithTemplateFromFiles
func WithTemplateFromFiles(name string, files ...string) Option { return func(o *Options) { o.files[name] = files } }
go
func WithTemplateFromFiles(name string, files ...string) Option { return func(o *Options) { o.files[name] = files } }
[ "func", "WithTemplateFromFiles", "(", "name", "string", ",", "files", "...", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "files", "[", "name", "]", "=", "files", "}", "\n", "}" ]
// WithTemplateFromFiles adds a template parsed from files.
[ "WithTemplateFromFiles", "adds", "a", "template", "parsed", "from", "files", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L87-L89
test
janos/web
templates/templates.go
WithTemplatesFromFiles
func WithTemplatesFromFiles(ts map[string][]string) Option { return func(o *Options) { for name, files := range ts { o.files[name] = files } } }
go
func WithTemplatesFromFiles(ts map[string][]string) Option { return func(o *Options) { for name, files := range ts { o.files[name] = files } } }
[ "func", "WithTemplatesFromFiles", "(", "ts", "map", "[", "string", "]", "[", "]", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "for", "name", ",", "files", ":=", "range", "ts", "{", "o", ".", "files", "[", "name", "]", "=", "files", "\n", "}", "\n", "}", "\n", "}" ]
// WithTemplatesFromFiles adds a map of templates parsed from files.
[ "WithTemplatesFromFiles", "adds", "a", "map", "of", "templates", "parsed", "from", "files", "." ]
0fb0203103deb84424510a8d5166ac00700f2b0e
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/templates/templates.go#L92-L98
test