text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_suffix|>orizeOptions.
AuthorizeOption func(opts *AuthorizeOptions)
)
// Authorize returns an authorization middleware.
func Authorize(secret string, opts ...AuthorizeOption) func(http.Handler) http.Handler {
var authOpts AuthorizeOptions
for _, opt := range opts {
opt(&authOpts)
}
parser := token.NewToke... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"bufio"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/stretchr/testify/assert"
)
func TestAuthHandlerFailed(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://localhost", htt<|fim_suffix|>
_, err := ... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"fmt"
"net/http"
"strings"
"github.com/zeromicro/go-zero/core/breaker"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/internal/response"
)
const breakerSepara... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stat"
)
func init() {
stat.SetReporter(nil)
}
func TestBreakerHandlerAccept(t *testing.T) {
metrics := stat.NewMetrics("unit-test")
breakerHandler :=... | fim | zeromicro/go-zero | go |
<|fim_suffix|>uteCallbacks(w, r, next, strict, code, callbacks)
} else if r.ContentLength > 0 && header.Encrypted() {
LimitCryptionHandler(limitBytes, header.Key)(next).ServeHTTP(w, r)
} else {
next.ServeHTTP(w, r)
}
default:
next.ServeHTTP(w, r)
}
})
}
}
func executeCallbacks(w http... | fim | zeromicro/go-zero | go |
<|fim_suffix|>(string, error) {
tmpFile, err := os.CreateTemp(os.TempDir(), "go-unit-*.tmp")
if err != nil {
return "", err
}
tmpFile.Close()
if err = os.WriteFile(tmpFile.Name(), body, os.ModePerm); err != nil {
return "", err
}
return tmpFile.Name(), nil
}
<|fim_prefix|>package handler
import (
"bytes"... | fim | zeromicro/go-zero | go |
<|fim_suffix|>erlying http.ResponseWriter supports it.
func (w *cryptionResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacked, ok := w.ResponseWriter.(http.Hijacker); ok {
return hijacked.Hijack()
}
return nil, nil, errors.New("server doesn't support hijacking")
}
func (w *cryptionResponseW... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/iotest"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/codec"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
const (
req... | fim | zeromicro/go-zero | go |
<|fim_suffix|>}
next.ServeHTTP(w, r)
})
}
<|fim_prefix|>package handler
import (
"compress/gzip"
"net/http"
"strings"
"github.com/zeromicro/go-zero/rest/httpx"
)
const gzipEncoding = "gzip"
// GunzipHandler returns a middleware to gunzip http request body.
func GunzipHandler(next http.Handler) http.Handler ... | fim | zeromicro/go-zero | go |
<|fim_suffix|>(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
req := httptest.NewRequest(http.MethodPost, "http://localhost",
strings.NewReader(message))
req.Header.Set(httpx.ContentEncoding, gzipEncoding)
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, req)
assert.Equal(t, http.Status... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"strconv"
"time"
"github.com/zeromicro/go-zero/core/color"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/syncx"
"github.c... | fim | zeromicro/go-zero | go |
<|fim_suffix|>r {
return nil
}
<|fim_prefix|>package handler
import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
"github.com/zeromicro/go-zero/rest/internal"
"github.com/zeromicro/go-zero/rest/... | fim | zeromicro/go-zero | go |
<|fim_suffix|> })
}
}
<|fim_prefix|>package handler
import (
"net/http"
"github.com/zeromicro/go-zero/rest/internal"
)
// MaxBytesHandler returns a middleware that limit reading of http request body.
func MaxBytesHandler(n int64) func(http.Handler) http.Handler {
if n <= 0 {
return func(next http.Handler) htt... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestMaxBytesHandler(t *testing.T) {
maxb := MaxBytesHandler(10)
handler := maxb(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
req := httptest.NewRequest(ht... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/rest/internal"
)
// MaxConnsHandler returns a middleware that limit the concurrent connections.
func MaxConnsHandler(n int) func(http.Handler) http.Ha... | fim | zeromicro/go-zero | go |
package handler
import (
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/lang"
)
const conns = 4
func TestMaxConnsHandler(t *testing.T) {
var waitGroup sync.WaitGroup
waitGroup.Add(conns)
done := make(chan lang.PlaceholderType)
defer ... | fim | zeromicro/go-zero | go |
package handler
import (
"net/http"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/timex"
)
// MetricHandler returns a middleware that stat the metrics.
func MetricHandler(metrics *stat.Metrics) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return ... | fim | zeromicro/go-zero | go |
package handler
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stat"
)
func TestMetricHandler(t *testing.T) {
metrics := stat.NewMetrics("unit-test")
metricHandler := MetricHandler(metrics)
handler := metricHandler(http.HandlerFunc(fu... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"net/http"
"strconv"
"github.com/zeromicro/go-zero/core/metric"
"github.com/zeromicro/go-zero/core/timex"
"github.com/zeromicro/go-zero/rest/internal/respon<|fim_suffix|>rtTime).Milliseconds(), path, method, code)
metricServerReqCodeTotal.Inc(path, method, code)
}()
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>) {
promMetricHandler := PrometheusHandler("/user/login", http.MethodGet)
handler := promMetricHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody)
resp := httptest.NewRe... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"fmt"
"net/http"
"runtime/debug"
"github.com/zeromicro/go-zero/rest/internal"
)
// RecoverHandler returns a middleware that recovers if panic happens.
func RecoverHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)... | fim | zeromicro/go-zero | go |
<|fim_suffix|>stWithoutPanic(t *testing.T) {
handler := RecoverHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))
req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody)
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, req)
assert.Equal(t, http.StatusOK, resp.Co... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"net/http"
"sync"
"github.com/zeromicro/go-zero/core/load"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/internal/response"
)
const serviceType = "api"
var (... | fim | zeromicro/go-zero | go |
<|fim_suffix|>= httptest.NewRecorder()
handler.ServeHTTP(resp, req)
assert.Equal(t, http.StatusOK, resp.Code)
}
type mockShedder struct {
allow bool
}
func (s mockShedder) Allow() (load.Promise, error) {
if s.allow {
return mockPromise{}, nil
}
return nil, load.ErrServiceOverloaded
}
type mockPromise struct... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ttpx.ErrorCtx(r.Context(), w, ctx.Err(), func(w http.ResponseWriter, err error) {
if errors.Is(err, context.Canceled) {
w.WriteHeader(statusClientClosedRequest)
} else {
w.WriteHeader(http.StatusServiceUnavailable)
}
_, _ = io.WriteString(w, h.errorBody())
})
tw.timedOut = true
}
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"bufio"
"context"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
"github.com/zeromicro/go-zero/rest/internal/response"
)
func TestTimeoutWriteFlushOutput... | fim | zeromicro/go-zero | go |
<|fim_suffix|> TraceHandler.
func WithTraceIgnorePaths(traceIgnorePaths []string) TraceOption {
return func(options *traceOptions) {
options.traceIgnorePaths = append(options.traceIgnorePaths, traceIgnorePaths...)
}
}
<|fim_prefix|>package handler
import (
"net/http"
"github.com/zeromicro/go-zero/core/collectio... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package handler
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
ztrace "github.com/zeromicro/go-zero/core/trace"
"github.com/zeromicro/go-zero/core/trace/tracetest"
"github.com/zeromicro/go-zero/rest/chain"
"go.opentelemetry.io/o... | fim | zeromicro/go-zero | go |
package internal
import "net/http"
type (
Interceptor func(r *http.Request) (*http.Request, ResponseHandler)
ResponseHandler func(resp *http.Response, err error)
)
<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|> isOkResponse(resp.StatusCode) {
logger.Infof("[HTTP] %d - %s %s", resp.StatusCode, r.Method, r.URL)
} else {
logger.Errorf("[HTTP] %d - %s %s", resp.StatusCode, r.Method, r.URL)
}
}
}
func isOkResponse(code int) bool {
return code < http.StatusBadRequest
}
<|fim_prefix|>package internal
imp... | fim | zeromicro/go-zero | go |
package internal
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLogInterceptor(t *testing.T) {
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))
defer svr.Close()
req, err := http.NewRequest(http.MethodGet, svr.URL... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package internal
i<|fim_suffix|>2000, 5000, 10000, 15000},
})
MetricClientReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
Namespace: clientNamespace,
Subsystem: "requests",
Name: "code_total",
Help: "http client requests code count.",
Labels: []string{"name", "method... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package internal
imp<|fim_suffix|>equest) {
time.Sleep(100 * time.Millisecond)
w.WriteHeader(http.StatusInternalServerError)
}))
defer svr.Close()
req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
assert.NotNil(t, req)
assert.Nil(t, err)
interceptor := MetricsInterceptor("test", nil)
... | fim | zeromicro/go-zero | go |
package httpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
nurl "net/url"
"strings"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/mapping"
"github.com/zeromicro/go-zero/core/trace"
"github.com/zeromicro/go-zero/rest/httpc/internal"
"github.com/zeromicro/g... | fim | zeromicro/go-zero | go |
<|fim_suffix|> testName: "OPTIONS Request with Body",
method: http.MethodOptions,
url: "/ping",
body: testBody,
wantedErr: nil,
},
{
testName: "TRACE Request with Body",
method: http.MethodTrace,
url: "/ping",
body: testBody,
wantedErr: nil,
},
}
for _,... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package httpc
import (
"bytes"
"io"
"net/http"
"strings"
"github.com/zeromicro/go-zero/core/mapping"
"github.com/zeromicro/go-zero/rest/internal/encoding"
"github.com/zeromicro/go-zero/rest/internal/header"
)
// Parse parses the response.
func Parse(resp *http.Response, val any) error {
if err ... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package httpc
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/rest/internal/header"
)
func TestParse(t *testing.T) {
var val struct {
Foo string `header:"foo"`
Name string `json:"name"`
Value int `json:"val... | fim | zeromicro/go-zero | go |
<|fim_suffix|> Returns true (acceptable) for:
// - HTTP status codes < 500 (2xx, 3xx, 4xx)
// - Context cancellation (user-initiated)
// - Non-network errors (application-level errors)
//
// Returns false (not acceptable, triggers breaker) for:
// - HTTP status codes >= 500 (server errors)
// - context.Deadli... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package httpc
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/rest/internal/header"
)
func TestNamedService_DoRequest(t *testing.T) {
svr := httptest.NewServer(http.RedirectHandler(... | fim | zeromicro/go-zero | go |
<|fim_suffix|>
ErrHeadWithBody = errors.New("HTTP HEAD should not have body")
)
<|fim_prefix|>package httpc
import "errors"
const (
pathKey = "path"
formKey = "form"
headerKey = "header"
jsonKey = "json"
slash = "/"
colon = ':'
)
var (
// ErrGetWithBody indicates that GET request with body.
Er... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package httpx
import (
"io"
"net/http"
"reflect"
"strings"
"sync"
"github.com/zeromicro/go-zero/core/mapping"
"github.com/zeromicro/go-zero/core/validation"
"github.com/zeromicro/go-zero/rest/internal/encoding"
"github.com/zeromicro/go-zero/rest/internal/header"
"github.com/zeromicro/go-zero/r... | fim | zeromicro/go-zero | go |
<|fim_suffix|>Accept)
}
func TestParseHeaders_Error(t *testing.T) {
v := struct {
Name string `header:"name"`
Age int `header:"age"`
}{}
r := httptest.NewRequest("POST", "/", http.NoBody)
r.Header.Set("name", "foo")
assert.NotNil(t, Parse(r, &v))
}
func TestParseWithValidator(t *testing.T) {
SetValidat... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package httpx
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"sync"
"github.com/zeromicro/go-zero/core/jsonx"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/internal/errcode"
"github.com/zeromicro/go-zero/rest/internal/h... | fim | zeromicro/go-zero | go |
<|fim_suffix|>string]any{
"Data": complex(0, 0),
})
assert.Equal(t, http.StatusInternalServerError, w.code)
}
<|fim_prefix|>package httpx
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/... | fim | zeromicro/go-zero | go |
<|fim_suffix|>andler(handler http.Handler)
}
<|fim_prefix|>package httpx
import "<|fim_middle|>net/http"
// Router interface represents a http router that handles http requests.
type Router interface {
http.Handler
Handle(method, path string, handler http.Handler) error
SetNotFoundHandler(handler http.Handler)
Se... | fim | zeromicro/go-zero | go |
<|fim_suffix|> most servers and clients have a limit of 8192 bytes (8 KB)
// one parameter at least take 4 chars, for example `?a=b&c=d`
maxFormParamCount = 2048
)
// GetFormValues returns the form values supporting three array notation formats:
// 1. Standard notation: /api?names=alice&names=bob
// 2. Comma notat... | fim | zeromicro/go-zero | go |
<|fim_suffix|>(t, err)
r.Header.Set(xForwardedFor, host)
assert.Equal(t, host, GetRemoteAddr(r))
}
func TestGetRemoteAddrNoHeader(t *testing.T) {
r, err := http.NewRequest(http.MethodGet, "/", strings.NewReader(""))
assert.Nil(t, err)
assert.True(t, len(GetRemoteAddr(r)) == 0)
}
func TestGetFormValues_TooManyV... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package httpx
import "github.com/zeromicro/go-zero/rest/internal/header"
const (
// ContentEncoding means Content-Encoding.
ContentEncoding = "Content-Encoding"
// ContentSecurity means X-Content-Security.
ContentSecurity = "X-Content-Security"
// ContentType means Content-Type.
ContentType = head... | fim | zeromicro/go-zero | go |
package cors
import (
"net/http"
"strings"
"github.com/zeromicro/go-zero/rest/internal/response"
)
const (
allowOrigin = "Access-Control-Allow-Origin"
allOrigins = "*"
allowMethods = "Access-Control-Allow-Methods"
allowHeaders = "Access-Control-Allow-Headers"
allowCredentials = "Access-Con... | fim | zeromicro/go-zero | go |
package cors
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAddAllowHeaders(t *testing.T) {
tests := []struct {
name string
initial string
headers []string
expected string
}{
{
name: "single header",
initial: "",
header... | fim | zeromicro/go-zero | go |
<|fim_suffix|>map[string]any{}
for k, v := range header {
if len(v) == 1 {
m[k] = v[0]
} else {
m[k] = v
}
}
return headerUnmarshaler.Unmarshal(m, v)
}
<|fim_prefix|>package encoding
import (
"net/http"
"net/textproto"
"github.com<|fim_middle|>/zeromicro/go-zero/core/mapping"
)
const headerKey = "... | fim | zeromicro/go-zero | go |
<|fim_suffix|>)
assert.Nil(t, ParseHeaders(r.Header, &val))
assert.Equal(t, "bar", val.Foo)
assert.Equal(t, 1, val.Baz)
assert.True(t, val.Qux)
}
func TestParseHeadersMulti(t *testing.T) {
var val struct {
Foo []string `header:"foo"`
Baz int `header:"baz"`
Qux bool `header:"qux,default=true"`
}
r... | fim | zeromicro/go-zero | go |
<|fim_suffix|>s.FailedPrecondition, codes.OutOfRange:
return http.StatusBadRequest
case codes.Unauthenticated:
return http.StatusUnauthorized
case codes.PermissionDenied:
return http.StatusForbidden
case codes.NotFound:
return http.StatusNotFound
case codes.Canceled:
return http.StatusRequestTimeout
case... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package errcode
import (
"errors"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestCodeFromGrpcError(t *testing.T) {
tests := []struct {
name string
code codes.Code
want int
}{
{
name: "OK",
code: c... | fim | zeromicro/go-zero | go |
package fileserver
import (
"net/http"
"path"
"strings"
"sync"
)
// Middleware returns a middleware that serves files from the given file system.
func Middleware(upath string, fs http.FileSystem) func(http.HandlerFunc) http.HandlerFunc {
fileServer := http.FileServer(fs)
pathWithoutTrailSlash := ensureNoTrailin... | fim | zeromicro/go-zero | go |
<|fim_suffix|> requestPath: "/example.txt",
expectedStatus: http.StatusOK,
expectedContent: "1",
},
{
name: "Pass through non-matching path",
path: "/static/",
requestPath: "/other/path",
expectedStatus: http.StatusAlreadyReported,
},
{
name: "Not exis... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package header
const (
// ApplicationJson stands for application/json.
ApplicationJson = "application/json"
/<|fim_suffix|>cheControlNoCache is the value for Cache-Control: no-cache.
CacheControlNoCache = "no-cache"
// Connection is the header key for Connection.
Connection = "Connection"
// Conne... | fim | zeromicro/go-zero | go |
package internal
import (
"bytes"
"context"
"fmt"
"net/http"
"sync"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
)
// logContextKey is a context key.
var logContextKey = contextKey("request_logs")
type (
// LogCollector is used to collect logs.
LogCollector struct {
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package internal
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func TestInfo(t *testing.T) {
collector := new(LogCollector)
req := httptest.NewRequest(http.MethodGet, "http://localho... | fim | zeromicro/go-zero | go |
package response
import (
"bufio"
"errors"
"net"
"net/http"
)
// HeaderOnceResponseWriter is a http.ResponseWriter implementation
// that only the first WriterHeader takes effect.
type HeaderOnceResponseWriter struct {
w http.ResponseWriter
wroteHeader bool
}
// NewHeaderOnceResponseWriter returns a ... | fim | zeromicro/go-zero | go |
<|fim_suffix|>onseRecorder
}
func (m mockedHijackable) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return nil, nil, nil
}
<|fim_prefix|>package response
import (
"bufio"
"net"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestHeaderOnceResponseWriter_Flush(t *testin... | fim | zeromicro/go-zero | go |
<|fim_suffix|>riter {
switch w := writer.(type) {
case *WithCodeResponseWriter:
return w
default:
return &WithCodeResponseWriter{
Writer: writer,
Code: http.StatusOK,
}
}
}
// Flush flushes the response writer.
func (w *WithCodeResponseWriter) Flush() {
if flusher, ok := w.Writer.(http.Flusher); ok ... | fim | zeromicro/go-zero | go |
<|fim_suffix|>mockedHijackable{resp},
}
assert.NotPanics(t, func() {
writer.Hijack()
})
}
func TestWithCodeResponseWriter_Unwrap(t *testing.T) {
resp := httptest.NewRecorder()
writer := NewWithCodeResponseWriter(resp)
unwrapped := writer.Unwrap()
assert.Equal(t, resp, unwrapped)
// Test with a nested WithCo... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package security
import (
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/zeromicro/go-zero/core/codec"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/rest/http... | fim | zeromicro/go-zero | go |
<|fim_suffix|> assert.Equal(t, test.code, VerifySignature(r, header, time.Minute))
})
}
}
func fingerprint(key string) string {
h := md5.New()
io.WriteString(h, key)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func hs256(key []byte, body string) string {
h := hmac.New(sha256.New, key)
io.WriteStr... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package internal
import (
"context"
"errors"
"fmt"
"net/http"<|fim_suffix|>proc.AddShutdownListener(func() {
healthManager.MarkNotReady()
if e := server.Shutdown(context.Background()); e != nil {
logx.Error(e)
}
})
defer func() {
if errors.Is(err, http.ErrServerClosed) {
waitForCalled... | fim | zeromicro/go-zero | go |
<|fim_suffix|>, err)
proc.WrapUp()
}
<|fim_prefix|>package internal
import (
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/c<|fim_middle|>ore/proc"
)
func TestStartHttp(t *testing.T) {
svr := httptest.NewUnstartedServer(http.N... | fim | zeromicro/go-zero | go |
<|fim_suffix|>contextKey string
func (c contextKey) String() string {
return "rest/pathvar/context key: " + string(c)
}
<|fim_prefix|>package pathvar
import (
"context"
"net/http"
)
var pathVars = contextKey("pathVars")
// Vars parses path variables and returns a map.
func Vars(r *http.Request) map[string]string... | fim | zeromicro/go-zero | go |
<|fim_suffix|>il)
assert.Nil(t, err)
assert.Nil(t, Vars(r))
}
func TestContextKey(t *testing.T) {
ck := contextKey("hello")
assert.True(t, strings.Contains(ck.String(), "hello"))
}
<|fim_prefix|>package pathvar
import (
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestVars(t *t... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ttp.ResponseWriter, r *http.Request) {
if pr.notFound != nil {
pr.notFound.ServeHTTP(w, r)
} else {
http.NotFound(w, r)
}
}
func (pr *patRouter) methodsAllowed(method, path string) (string, bool) {
var allows []string
for treeMethod, tree := range pr.trees {
if treeMethod == method {
conti... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package router
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/internal/header"
"github.com/zeromicro/go-zero/rest/pathvar"
)
const contentLength =... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ite the same option.
func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
if err := c.SetUp(); err != nil {
return nil, err
}
server := &Server{
ngin: newEngine(c),
router: router.NewRouter(),
}
opts = append([]RunOption{WithNotFoundHandler(nil)}, opts...)
for _, opt := range o... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ttptest.NewRecorder()
serve(server, rr, req)
assert.Equal(t, sampleContent, rr.Body.String())
}
// serve is for test purpose, allow developer to do a unit test with
// all defined routes without starting an HTTP Server.
//
// For example:
//
// server := MustNewServer(...)
// server.addRoute(...) // ro... | fim | zeromicro/go-zero | go |
<|fim_suffix|>
return &Serverless{
server: server,
}, nil
}
// Serve handles HTTP requests by delegating them to the underlying Server instance.
func (s *Serverless) Serve(w http.ResponseWriter, r *http.Request) {
s.server.serve(w, r)
}
<|fim_prefix|>package rest
import "net/http"
// Serverless is a wrapper ar... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ss(svr)
assert.Error(t, err)
}
<|fim_prefix|>package rest
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func TestNewServerless(t *testing.T) {
logtest.Discard(t)
... | fim | zeromicro/go-zero | go |
package token
import (
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/golang-jwt/jwt/v4/request"
"github.com/zeromicro/go-zero/core/timex"
)
const claimHistoryResetDuration = time.Hour * 24
type (
// ParseOption defines the method to customize a TokenParser.
ParseOption f... | fim | zeromicro/go-zero | go |
package token
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/timex"
)
func TestTokenParser(t *testing.T) {
const (
key = "14F17379-EB8F-411B-8F12-6929002DCA76"
prevKey = "B63F477D-BBA3-4E5... | fim | zeromicro/go-zero | go |
<|fim_suffix|>Func) http.HandlerFunc
// A Route is a http route.
Route struct {
Method string
Path string
Handler http.HandlerFunc
}
// RouteOption defines the method to customize a featured route.
RouteOption func(r *featuredRoutes)
jwtSetting struct {
enabled bool
secret string
prevSec... | fim | zeromicro/go-zero | go |
<|fim_suffix|>plate.New("etcTemplate").Parse(text))
if err := t.Execute(fp, map[string]string{
"gitUser": getGitName(),
"gitEmail": getGitEmail(),
"serviceName": baseName + "-api",
}); err != nil {
return err
}
fmt.Println(color.Green.Render("Done."))
return nil
}
<|fim_prefix|>package apigen
impo... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package apigen
import (
"fmt"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
category = "api"
apiTemplateFile = "template.tpl"
)
var templates = map[string]string{
apiTemplateFile: apiTemplate,
}
// <|fim_suffix|>eateTemplate(category, name, content)
}
// Update updates ... | fim | zeromicro/go-zero | go |
<|fim_suffix|>mmand("git", "config", "user.email")
out, err := cmd.CombinedOutput()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}
<|fim_prefix|>package apigen
import (
"os/exec"
"strings<|fim_middle|>"
)
func getGitName() string {
cmd := exec.Command("git", "config", "user.name")
out,... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package api
import (
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/api/apigen"
"github.com/zeromicro/go-zero/tools/goctl/api/dartgen"
"github.com/zeromicro/go-zero/tools/goctl/api/docgen"
"github.com/zeromicro/go-zero/tools/goctl/api/format"
"github.com/zeromicro/go-zero/tools... | fim | zeromicro/go-zero | go |
<|fim_suffix|> nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
<|fim_prefix|>package dartgen
import (
"fmt"
"os"
"os/exec"
)
const dartExec = "dart"
func formatDir(dir string) error {
ok, err := dirctoryExists(dir)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("format... | fim | zeromicro/go-zero | go |
<|fim_suffix|>a(dir+"data/", api, isLegacy))
logx.Must(genApi(dir+"api/", api, isLegacy))
logx.Must(genVars(dir+"vars/", isLegacy, scheme, hostname))
if err := formatDir(dir); err != nil {
logx.Errorf("failed to format, %v", err)
}
return nil
}
<|fim_prefix|>package dartgen
import (
"errors"
"fmt"
"strings"
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>rn err
}
defer apiFile.Close()
tpl := apiFileContentV2
if isLegacy {
tpl = apiFileContent
}
_, err = apiFile.WriteString(tpl)
return err
}
<|fim_prefix|>package dartgen
import (
"os"
"strings"
"text/template"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
)
const apiTemplate = `impor... | fim | zeromicro/go-zero | go |
<|fim_suffix|>os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
defer tokensFile.Close()
tpl := tokensFileContentV2
if isLeagcy {
tpl = tokensFileContent
}
_, err = tokensFile.WriteString(tpl)
return err
}
func convertDataType(api *spec.ApiSpec, isLegacy bool) (error, *DartSpec) {
v... | fim | zeromicro/go-zero | go |
<|fim_suffix|>okenKey, jsonEncode(tokens.toJson()));
}
/// remove tokens
Future<bool> removeTokens() async {
var sp = await SharedPreferences.getInstance();
return sp.remove(_tokenKey);
}
/// Reads tokens
Future<Tokens?> getTokens() async {
try {
var sp = await SharedPreferences.getInstance();
var str =... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package dartgen
import (
"errors"
"fmt"
"os"
"path"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/api/util"
)
const (
formTagKey = "form"
pathTagKey = "path"
headerTagKey = "header"
)
func normalizeHandlerName(handlerName string) ... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package dartgen
import (
"testing"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
)
func Test_getPropertyFromMember(t *testing.T) {
tests := []struct {
name string
member spec.Member
want string
}{
{
name: "json tag should be ok",
member: spec.Member{
Tag: "`json:\"foo\"... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package dartgen
import "text/template"
var funcMap = template.FuncMap{
"appendNullCoalescing": appendNullCoalescing,
"appendDefaultEmptyValue": appendDefaultEmptyValue,
"extractPositionalParamsFromPath": extractPositionalParamsFromPath,
"getBaseName": getBaseNa... | fim | zeromicro/go-zero | go |
<|fim_suffix|>dTypes(definedType, &tps)
}
value, err := buildTypes(tps, types)
if err != nil {
return "", err
}
return fmt.Sprintf("\n\n```golang\n%s\n```\n", value), nil
}
func associatedTypes(tp spec.DefineStruct, tps *[]spec.Type) {
hasAdded := false
for _, item := range *tps {
if item.Name() == tp.Name... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package docgen
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
// VarStringDir describes a directory.
VarStringDir string
// VarStringOutput des... | fim | zeromicro/go-zero | go |
<|fim_suffix|>CommentLine, leftBrace) {
*token++
return insertStruct()
}
if strings.HasSuffix(noCommentLine, rightBrace) {
noCommentLine = strings.TrimSuffix(noCommentLine, rightBrace)
noCommentLine = util.RemoveComment(noCommentLine)
if strings.HasSuffix(noCommentLine, leftBrace) {
return insertStruct()... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package format
import (
"fmt"
"io/fs"
"os"
"path"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
notFormattedStr = `
type Request struct {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response struct {
Message <|fim_suff... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package gogen
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/gookit/color"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/core/logx"
apiformat "github.com/zeromicro/go-zero/tools/goctl/api/format"
"github.com/zeromicro/go-zero/tool... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package gogen
import (
_ "embed"
"go/ast"
goformat "go/format"
"go/importer"
goparser "go/parser"
"go/token"
"go/types"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
"github.com/zeromicro/go-zero/tools/go... | fim | zeromicro/go-zero | go |
<|fim_suffix|> require.NoError(t, err, "Failed to read file: %s", filePath)
contentStr := string(content)
lines := strings.Split(contentStr, "\n")
// Check that the file starts with proper generation comments
require.GreaterOrEqual(t, len(lines), 2, "File %s should have at least 2 lines", filePath)
if expe... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package gogen
import (
_ "embed"
"fmt"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
"github.com/<|fim_suffix|>= ge... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package gogen
import (
_ "embed"
"fmt"
"strconv"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
)
const (
defaultPort = 8888
etcDir = "etc"
)
//go:embed etc.tpl
var etcTemplate st... | fim | zeromicro/go-zero | go |
<|fim_suffix|>Route) string {
handler, err := getHandlerBaseName(route)
if err != nil {
panic(err)
}
return handler + "Handler"
}
func getLogicName(route spec.Route) string {
handler, err := getHandlerBaseName(route)
if err != nil {
panic(err)
}
return handler + "Logic"
}
<|fim_prefix|>package gogen
imp... | fim | zeromicro/go-zero | go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.