_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q167800
DelClientCookie
validation
func (h *ResponseHeader) DelClientCookie(key string) { h.DelCookie(key) c := AcquireCookie() c.SetKey(key) c.SetExpire(CookieExpireDelete) h.SetCookie(c) ReleaseCookie(c) }
go
{ "resource": "" }
q167801
DelCookie
validation
func (h *ResponseHeader) DelCookie(key string) { h.cookies = delAllArgs(h.cookies, key) }
go
{ "resource": "" }
q167802
DelCookie
validation
func (h *RequestHeader) DelCookie(key string) { h.parseRawHeaders() h.collectCookies() h.cookies = delAllArgs(h.cookies, key) }
go
{ "resource": "" }
q167803
DelAllCookies
validation
func (h *RequestHeader) DelAllCookies() { h.parseRawHeaders() h.collectCookies() h.cookies = h.cookies[:0] }
go
{ "resource": "" }
q167804
Peek
validation
func (h *ResponseHeader) Peek(key string) []byte { k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing) return h.peek(k) }
go
{ "resource": "" }
q167805
PeekBytes
validation
func (h *ResponseHeader) PeekBytes(key []byte) []byte { h.bufKV.key = append(h.bufKV.key[:0], key...) normalizeHeaderKey(h.bufKV.key, h.disableNormalizing) return h.peek(h.bufKV.key) }
go
{ "resource": "" }
q167806
Cookie
validation
func (h *RequestHeader) Cookie(key string) []byte { h.parseRawHeaders() h.collectCookies() return peekArgStr(h.cookies, key) }
go
{ "resource": "" }
q167807
CookieBytes
validation
func (h *RequestHeader) CookieBytes(key []byte) []byte { h.parseRawHeaders() h.collectCookies() return peekArgBytes(h.cookies, key) }
go
{ "resource": "" }
q167808
Cookie
validation
func (h *ResponseHeader) Cookie(cookie *Cookie) bool { v := peekArgBytes(h.cookies, cookie.Key()) if v == nil { return false } cookie.ParseBytes(v) return true }
go
{ "resource": "" }
q167809
Read
validation
func (h *RequestHeader) Read(r *bufio.Reader) error { n := 1 for { err := h.tryRead(r, n) if err == nil { return nil } if err != errNeedMore { h.resetSkipNormalize() return err } n = r.Buffered() + 1 } }
go
{ "resource": "" }
q167810
Header
validation
func (h *ResponseHeader) Header() []byte { h.bufKV.value = h.AppendBytes(h.bufKV.value[:0]) return h.bufKV.value }
go
{ "resource": "" }
q167811
AppendBytes
validation
func (h *ResponseHeader) AppendBytes(dst []byte) []byte { statusCode := h.StatusCode() if statusCode < 0 { statusCode = StatusOK } dst = append(dst, statusLine(statusCode)...) server := h.Server() if len(server) != 0 { dst = appendHeaderLine(dst, strServer, server) } dst = appendHeaderLine(dst, strDate, se...
go
{ "resource": "" }
q167812
Write
validation
func (h *RequestHeader) Write(w *bufio.Writer) error { _, err := w.Write(h.Header()) return err }
go
{ "resource": "" }
q167813
WriteTo
validation
func (h *RequestHeader) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(h.Header()) return int64(n), err }
go
{ "resource": "" }
q167814
Header
validation
func (h *RequestHeader) Header() []byte { h.bufKV.value = h.AppendBytes(h.bufKV.value[:0]) return h.bufKV.value }
go
{ "resource": "" }
q167815
AppendBytes
validation
func (h *RequestHeader) AppendBytes(dst []byte) []byte { // there is no need in h.parseRawHeaders() here - raw headers are specially handled below. dst = append(dst, h.Method()...) dst = append(dst, ' ') dst = append(dst, h.RequestURI()...) dst = append(dst, ' ') dst = append(dst, strHTTP11...) dst = append(dst,...
go
{ "resource": "" }
q167816
ServeFileUncompressed
validation
func ServeFileUncompressed(ctx *RequestCtx, path string) { ctx.Request.Header.DelBytes(strAcceptEncoding) ServeFile(ctx, path) }
go
{ "resource": "" }
q167817
NewRequestHandler
validation
func (fs *FS) NewRequestHandler() RequestHandler { fs.once.Do(fs.initRequestHandler) return fs.h }
go
{ "resource": "" }
q167818
FileLastModified
validation
func FileLastModified(path string) (time.Time, error) { f, err := os.Open(path) if err != nil { return zeroTime, err } fileInfo, err := f.Stat() f.Close() if err != nil { return zeroTime, err } return fsModTime(fileInfo.ModTime()), nil }
go
{ "resource": "" }
q167819
CopyTo
validation
func (c *Cookie) CopyTo(src *Cookie) { c.Reset() c.key = append(c.key[:0], src.key...) c.value = append(c.value[:0], src.value...) c.expire = src.expire c.maxAge = src.maxAge c.domain = append(c.domain[:0], src.domain...) c.path = append(c.path[:0], src.path...) c.httpOnly = src.httpOnly c.secure = src.secure ...
go
{ "resource": "" }
q167820
SetPath
validation
func (c *Cookie) SetPath(path string) { c.buf = append(c.buf[:0], path...) c.path = normalizePath(c.path, c.buf) }
go
{ "resource": "" }
q167821
SetPathBytes
validation
func (c *Cookie) SetPathBytes(path []byte) { c.buf = append(c.buf[:0], path...) c.path = normalizePath(c.path, c.buf) }
go
{ "resource": "" }
q167822
SetDomain
validation
func (c *Cookie) SetDomain(domain string) { c.domain = append(c.domain[:0], domain...) }
go
{ "resource": "" }
q167823
SetDomainBytes
validation
func (c *Cookie) SetDomainBytes(domain []byte) { c.domain = append(c.domain[:0], domain...) }
go
{ "resource": "" }
q167824
Expire
validation
func (c *Cookie) Expire() time.Time { expire := c.expire if expire.IsZero() { expire = CookieExpireUnlimited } return expire }
go
{ "resource": "" }
q167825
SetValue
validation
func (c *Cookie) SetValue(value string) { c.value = append(c.value[:0], value...) }
go
{ "resource": "" }
q167826
SetValueBytes
validation
func (c *Cookie) SetValueBytes(value []byte) { c.value = append(c.value[:0], value...) }
go
{ "resource": "" }
q167827
SetKey
validation
func (c *Cookie) SetKey(key string) { c.key = append(c.key[:0], key...) }
go
{ "resource": "" }
q167828
SetKeyBytes
validation
func (c *Cookie) SetKeyBytes(key []byte) { c.key = append(c.key[:0], key...) }
go
{ "resource": "" }
q167829
Reset
validation
func (c *Cookie) Reset() { c.key = c.key[:0] c.value = c.value[:0] c.expire = zeroTime c.maxAge = 0 c.domain = c.domain[:0] c.path = c.path[:0] c.httpOnly = false c.secure = false c.sameSite = CookieSameSiteDisabled }
go
{ "resource": "" }
q167830
AppendBytes
validation
func (c *Cookie) AppendBytes(dst []byte) []byte { if len(c.key) > 0 { dst = append(dst, c.key...) dst = append(dst, '=') } dst = append(dst, c.value...) if c.maxAge > 0 { dst = append(dst, ';', ' ') dst = append(dst, strCookieMaxAge...) dst = append(dst, '=') dst = AppendUint(dst, c.maxAge) } else if ...
go
{ "resource": "" }
q167831
Cookie
validation
func (c *Cookie) Cookie() []byte { c.buf = c.AppendBytes(c.buf[:0]) return c.buf }
go
{ "resource": "" }
q167832
WriteTo
validation
func (c *Cookie) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(c.Cookie()) return int64(n), err }
go
{ "resource": "" }
q167833
Parse
validation
func (c *Cookie) Parse(src string) error { c.buf = append(c.buf[:0], src...) return c.ParseBytes(c.buf) }
go
{ "resource": "" }
q167834
ParseBytes
validation
func (c *Cookie) ParseBytes(src []byte) error { c.Reset() var s cookieScanner s.b = src kv := &c.bufKV if !s.next(kv) { return errNoCookies } c.key = append(c.key[:0], kv.key...) c.value = append(c.value[:0], kv.value...) for s.next(kv) { if len(kv.key) != 0 { // Case insensitive switch on first cha...
go
{ "resource": "" }
q167835
appendResponseCookieBytes
validation
func appendResponseCookieBytes(dst []byte, cookies []argsKV) []byte { for i, n := 0, len(cookies); i < n; i++ { kv := &cookies[i] dst = append(dst, kv.value...) if i+1 < n { dst = append(dst, ';', ' ') } } return dst }
go
{ "resource": "" }
q167836
AcquireTimer
validation
func AcquireTimer(timeout time.Duration) *time.Timer { v := timerPool.Get() if v == nil { return time.NewTimer(timeout) } t := v.(*time.Timer) initTimer(t, timeout) return t }
go
{ "resource": "" }
q167837
Accept
validation
func (ln *InmemoryListener) Accept() (net.Conn, error) { c, ok := <-ln.conns if !ok { return nil, fmt.Errorf("InmemoryListener is already closed: use of closed network connection") } close(c.accepted) return c.conn, nil }
go
{ "resource": "" }
q167838
Close
validation
func (ln *InmemoryListener) Close() error { var err error ln.lock.Lock() if !ln.closed { close(ln.conns) ln.closed = true } else { err = fmt.Errorf("InmemoryListener is already closed") } ln.lock.Unlock() return err }
go
{ "resource": "" }
q167839
FileServer
validation
func FileServer(r chi.Router, path string, root http.FileSystem) { if strings.ContainsAny(path, "{}*") { panic("FileServer does not permit URL parameters.") } fs := http.StripPrefix(path, http.FileServer(root)) if path != "/" && path[len(path)-1] != '/' { r.Get(path, http.RedirectHandler(path+"/", 301).ServeH...
go
{ "resource": "" }
q167840
Reset
validation
func (x *Context) Reset() { x.Routes = nil x.RoutePath = "" x.RouteMethod = "" x.RoutePatterns = x.RoutePatterns[:0] x.URLParams.Keys = x.URLParams.Keys[:0] x.URLParams.Values = x.URLParams.Values[:0] x.routePattern = "" x.routeParams.Keys = x.routeParams.Keys[:0] x.routeParams.Values = x.routeParams.Values[:...
go
{ "resource": "" }
q167841
URLParam
validation
func (x *Context) URLParam(key string) string { for k := len(x.URLParams.Keys) - 1; k >= 0; k-- { if x.URLParams.Keys[k] == key { return x.URLParams.Values[k] } } return "" }
go
{ "resource": "" }
q167842
URLParam
validation
func URLParam(r *http.Request, key string) string { if rctx := RouteContext(r.Context()); rctx != nil { return rctx.URLParam(key) } return "" }
go
{ "resource": "" }
q167843
URLParamFromCtx
validation
func URLParamFromCtx(ctx context.Context, key string) string { if rctx := RouteContext(ctx); rctx != nil { return rctx.URLParam(key) } return "" }
go
{ "resource": "" }
q167844
Add
validation
func (s *RouteParams) Add(key, value string) { (*s).Keys = append((*s).Keys, key) (*s).Values = append((*s).Values, value) }
go
{ "resource": "" }
q167845
ServerBaseContext
validation
func ServerBaseContext(baseCtx context.Context, h http.Handler) http.Handler { fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() baseCtx := baseCtx // Copy over default net/http server context keys if v, ok := ctx.Value(http.ServerContextKey).(*http.Server); ok { base...
go
{ "resource": "" }
q167846
GetHead
validation
func GetHead(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { rctx := chi.RouteContext(r.Context()) routePath := rctx.RoutePath if routePath == "" { if r.URL.RawPath != "" { routePath = r.URL.RawPath } else { r...
go
{ "resource": "" }
q167847
Ping
validation
func Ping(w http.ResponseWriter, r *http.Request) { w.Write([]byte("pong")) }
go
{ "resource": "" }
q167848
StripSlashes
validation
func StripSlashes(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { var path string rctx := chi.RouteContext(r.Context()) if rctx.RoutePath != "" { path = rctx.RoutePath } else { path = r.URL.Path } if len(path) > 1 && path[len(path)-1] == '/' { rctx.RoutePath ...
go
{ "resource": "" }
q167849
AllowContentType
validation
func AllowContentType(contentTypes ...string) func(next http.Handler) http.Handler { cT := []string{} for _, t := range contentTypes { cT = append(cT, strings.ToLower(t)) } return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { if r.ContentLength == 0 { // ski...
go
{ "resource": "" }
q167850
GetReqID
validation
func GetReqID(ctx context.Context) string { if ctx == nil { return "" } if reqID, ok := ctx.Value(RequestIDKey).(string); ok { return reqID } return "" }
go
{ "resource": "" }
q167851
HandlerFunc
validation
func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler { return &ChainHandler{mws, h, chain(mws, h)} }
go
{ "resource": "" }
q167852
chain
validation
func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler { // Return ahead of time if there aren't any middlewares for the chain if len(middlewares) == 0 { return endpoint } // Wrap the end handler with the middleware chain h := middlewares[len(middlewares)-1](endpoint) for...
go
{ "resource": "" }
q167853
NewMux
validation
func NewMux() *Mux { mux := &Mux{tree: &node{}, pool: &sync.Pool{}} mux.pool.New = func() interface{} { return NewRouteContext() } return mux }
go
{ "resource": "" }
q167854
ServeHTTP
validation
func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Ensure the mux has some routes defined on the mux if mx.handler == nil { mx.NotFoundHandler().ServeHTTP(w, r) return } // Check if a routing context already exists from a parent router. rctx, _ := r.Context().Value(RouteCtxKey).(*Context) ...
go
{ "resource": "" }
q167855
Use
validation
func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler) { if mx.handler != nil { panic("chi: all middlewares must be defined before routes on a mux") } mx.middlewares = append(mx.middlewares, middlewares...) }
go
{ "resource": "" }
q167856
Handle
validation
func (mx *Mux) Handle(pattern string, handler http.Handler) { mx.handle(mALL, pattern, handler) }
go
{ "resource": "" }
q167857
HandleFunc
validation
func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc) { mx.handle(mALL, pattern, handlerFn) }
go
{ "resource": "" }
q167858
Method
validation
func (mx *Mux) Method(method, pattern string, handler http.Handler) { m, ok := methodMap[strings.ToUpper(method)] if !ok { panic(fmt.Sprintf("chi: '%s' http method is not supported.", method)) } mx.handle(m, pattern, handler) }
go
{ "resource": "" }
q167859
MethodFunc
validation
func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc) { mx.Method(method, pattern, handlerFn) }
go
{ "resource": "" }
q167860
Connect
validation
func (mx *Mux) Connect(pattern string, handlerFn http.HandlerFunc) { mx.handle(mCONNECT, pattern, handlerFn) }
go
{ "resource": "" }
q167861
Delete
validation
func (mx *Mux) Delete(pattern string, handlerFn http.HandlerFunc) { mx.handle(mDELETE, pattern, handlerFn) }
go
{ "resource": "" }
q167862
Get
validation
func (mx *Mux) Get(pattern string, handlerFn http.HandlerFunc) { mx.handle(mGET, pattern, handlerFn) }
go
{ "resource": "" }
q167863
Head
validation
func (mx *Mux) Head(pattern string, handlerFn http.HandlerFunc) { mx.handle(mHEAD, pattern, handlerFn) }
go
{ "resource": "" }
q167864
Options
validation
func (mx *Mux) Options(pattern string, handlerFn http.HandlerFunc) { mx.handle(mOPTIONS, pattern, handlerFn) }
go
{ "resource": "" }
q167865
Patch
validation
func (mx *Mux) Patch(pattern string, handlerFn http.HandlerFunc) { mx.handle(mPATCH, pattern, handlerFn) }
go
{ "resource": "" }
q167866
Post
validation
func (mx *Mux) Post(pattern string, handlerFn http.HandlerFunc) { mx.handle(mPOST, pattern, handlerFn) }
go
{ "resource": "" }
q167867
Put
validation
func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc) { mx.handle(mPUT, pattern, handlerFn) }
go
{ "resource": "" }
q167868
Trace
validation
func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc) { mx.handle(mTRACE, pattern, handlerFn) }
go
{ "resource": "" }
q167869
NotFound
validation
func (mx *Mux) NotFound(handlerFn http.HandlerFunc) { // Build NotFound handler chain m := mx hFn := handlerFn if mx.inline && mx.parent != nil { m = mx.parent hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP } // Update the notFoundHandler from this point forward m.notFoundHandler = hFn m.updateS...
go
{ "resource": "" }
q167870
MethodNotAllowed
validation
func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc) { // Build MethodNotAllowed handler chain m := mx hFn := handlerFn if mx.inline && mx.parent != nil { m = mx.parent hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP } // Update the methodNotAllowedHandler from this point forward m.methodNo...
go
{ "resource": "" }
q167871
With
validation
func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router { // Similarly as in handle(), we must build the mux handler once further // middleware registration isn't allowed for this stack, like now. if !mx.inline && mx.handler == nil { mx.buildRouteHandler() } // Copy middlewares from parent in...
go
{ "resource": "" }
q167872
NotFoundHandler
validation
func (mx *Mux) NotFoundHandler() http.HandlerFunc { if mx.notFoundHandler != nil { return mx.notFoundHandler } return http.NotFound }
go
{ "resource": "" }
q167873
MethodNotAllowedHandler
validation
func (mx *Mux) MethodNotAllowedHandler() http.HandlerFunc { if mx.methodNotAllowedHandler != nil { return mx.methodNotAllowedHandler } return methodNotAllowedHandler }
go
{ "resource": "" }
q167874
handle
validation
func (mx *Mux) handle(method methodTyp, pattern string, handler http.Handler) *node { if len(pattern) == 0 || pattern[0] != '/' { panic(fmt.Sprintf("chi: routing pattern must begin with '/' in '%s'", pattern)) } // Build the final routing handler for this Mux. if !mx.inline && mx.handler == nil { mx.buildRoute...
go
{ "resource": "" }
q167875
routeHTTP
validation
func (mx *Mux) routeHTTP(w http.ResponseWriter, r *http.Request) { // Grab the route context object rctx := r.Context().Value(RouteCtxKey).(*Context) // The request routing path routePath := rctx.RoutePath if routePath == "" { if r.URL.RawPath != "" { routePath = r.URL.RawPath } else { routePath = r.URL...
go
{ "resource": "" }
q167876
updateSubRoutes
validation
func (mx *Mux) updateSubRoutes(fn func(subMux *Mux)) { for _, r := range mx.tree.routes() { subMux, ok := r.SubRoutes.(*Mux) if !ok { continue } fn(subMux) } }
go
{ "resource": "" }
q167877
methodNotAllowedHandler
validation
func methodNotAllowedHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(405) w.Write(nil) }
go
{ "resource": "" }
q167878
RequestLogger
validation
func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { entry := f.NewLogEntry(r) ww := NewWrapResponseWriter(w, r.ProtoMajor) t1 := time.Now() defer func() { entry.Write(ww.Status(),...
go
{ "resource": "" }
q167879
GetLogEntry
validation
func GetLogEntry(r *http.Request) LogEntry { entry, _ := r.Context().Value(LogEntryCtxKey).(LogEntry) return entry }
go
{ "resource": "" }
q167880
WithLogEntry
validation
func WithLogEntry(r *http.Request, entry LogEntry) *http.Request { r = r.WithContext(context.WithValue(r.Context(), LogEntryCtxKey, entry)) return r }
go
{ "resource": "" }
q167881
NewLogEntry
validation
func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry { useColor := !l.NoColor entry := &defaultLogEntry{ DefaultLogFormatter: l, request: r, buf: &bytes.Buffer{}, useColor: useColor, } reqID := GetReqID(r.Context()) if reqID != "" { cW(entry.buf, use...
go
{ "resource": "" }
q167882
ContentCharset
validation
func ContentCharset(charsets ...string) func(next http.Handler) http.Handler { for i, c := range charsets { charsets[i] = strings.ToLower(c) } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !contentEncoding(r.Header.Get("Content-Type"),...
go
{ "resource": "" }
q167883
contentEncoding
validation
func contentEncoding(ce string, charsets ...string) bool { _, ce = split(strings.ToLower(ce), ";") _, ce = split(ce, "charset=") ce, _ = split(ce, ";") for _, c := range charsets { if ce == c { return true } } return false }
go
{ "resource": "" }
q167884
split
validation
func split(str, sep string) (string, string) { var a, b string var parts = strings.SplitN(str, sep, 2) a = strings.TrimSpace(parts[0]) if len(parts) == 2 { b = strings.TrimSpace(parts[1]) } return a, b }
go
{ "resource": "" }
q167885
addChild
validation
func (n *node) addChild(child *node, prefix string) *node { search := prefix // handler leaf node added to the tree is the child. // this may be overridden later down the flow hn := child // Parse next segment segTyp, _, segRexpat, segTail, segStartIdx, segEndIdx := patNextSegment(search) // Add child dependi...
go
{ "resource": "" }
q167886
findRoute
validation
func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node { nn := n search := path for t, nds := range nn.children { ntyp := nodeTyp(t) if len(nds) == 0 { continue } var xn *node xsearch := search var label byte if search != "" { label = search[0] } switch ntyp { case...
go
{ "resource": "" }
q167887
ArticleCtx
validation
func ArticleCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var article *Article var err error if articleID := chi.URLParam(r, "articleID"); articleID != "" { article, err = dbGetArticle(articleID) } else if articleSlug := chi.URLParam(r, "articl...
go
{ "resource": "" }
q167888
SearchArticles
validation
func SearchArticles(w http.ResponseWriter, r *http.Request) { render.RenderList(w, r, NewArticleListResponse(articles)) }
go
{ "resource": "" }
q167889
CreateArticle
validation
func CreateArticle(w http.ResponseWriter, r *http.Request) { data := &ArticleRequest{} if err := render.Bind(r, data); err != nil { render.Render(w, r, ErrInvalidRequest(err)) return } article := data.Article dbNewArticle(article) render.Status(r, http.StatusCreated) render.Render(w, r, NewArticleResponse(...
go
{ "resource": "" }
q167890
GetArticle
validation
func GetArticle(w http.ResponseWriter, r *http.Request) { // Assume if we've reach this far, we can access the article // context because this handler is a child of the ArticleCtx // middleware. The worst case, the recoverer middleware will save us. article := r.Context().Value("article").(*Article) if err := ren...
go
{ "resource": "" }
q167891
UpdateArticle
validation
func UpdateArticle(w http.ResponseWriter, r *http.Request) { article := r.Context().Value("article").(*Article) data := &ArticleRequest{Article: article} if err := render.Bind(r, data); err != nil { render.Render(w, r, ErrInvalidRequest(err)) return } article = data.Article dbUpdateArticle(article.ID, articl...
go
{ "resource": "" }
q167892
DeleteArticle
validation
func DeleteArticle(w http.ResponseWriter, r *http.Request) { var err error // Assume if we've reach this far, we can access the article // context because this handler is a child of the ArticleCtx // middleware. The worst case, the recoverer middleware will save us. article := r.Context().Value("article").(*Artic...
go
{ "resource": "" }
q167893
adminRouter
validation
func adminRouter() chi.Router { r := chi.NewRouter() r.Use(AdminOnly) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("admin: index")) }) r.Get("/accounts", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("admin: list accounts..")) }) r.Get("/users/{userId}", func(w htt...
go
{ "resource": "" }
q167894
AdminOnly
validation
func AdminOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { isAdmin, ok := r.Context().Value("acl.admin").(bool) if !ok || !isAdmin { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } next.ServeHTTP(w, r) }) }
go
{ "resource": "" }
q167895
paginate
validation
func paginate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // just a stub.. some ideas are to look at URL query params for something like // the page number, or the limit, and send a query cursor down the chain next.ServeHTTP(w, r) }) }
go
{ "resource": "" }
q167896
init
validation
func init() { render.Respond = func(w http.ResponseWriter, r *http.Request, v interface{}) { if err, ok := v.(error); ok { // We set a default error status response code if one hasn't been set. if _, ok := r.Context().Value(render.StatusCtxKey).(int); !ok { w.WriteHeader(400) } // We log the error ...
go
{ "resource": "" }
q167897
NewCompressor
validation
func NewCompressor(level int, types ...string) *Compressor { // If types are provided, set those as the allowed types. If none are // provided, use the default list. allowedTypes := make(map[string]bool) if len(types) > 0 { for _, t := range types { allowedTypes[t] = true } } else { for _, t := range defa...
go
{ "resource": "" }
q167898
Handler
validation
func (c *Compressor) Handler() func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { encoder, encoding, cleanup := c.selectEncoder(r.Header, w) cw := &compressResponseWriter{ ResponseWriter: w, w: w, c...
go
{ "resource": "" }
q167899
selectEncoder
validation
func (c *Compressor) selectEncoder(h http.Header, w io.Writer) (io.Writer, string, func()) { header := h.Get("Accept-Encoding") // Parse the names of all accepted algorithms from the header. accepted := strings.Split(strings.ToLower(header), ",") // Find supported encoder by accepted list by precedence for _, na...
go
{ "resource": "" }