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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
tsuru/tsuru
|
builder/builder.go
|
GetForProvisioner
|
func GetForProvisioner(p provision.Provisioner) (Builder, error) {
builder, err := get(p.GetName())
if err != nil {
if _, ok := p.(provision.BuilderDeployDockerClient); ok {
return get("docker")
} else if _, ok := p.(provision.BuilderDeployKubeClient); ok {
return get("kubernetes")
}
}
return builder, err
}
|
go
|
func GetForProvisioner(p provision.Provisioner) (Builder, error) {
builder, err := get(p.GetName())
if err != nil {
if _, ok := p.(provision.BuilderDeployDockerClient); ok {
return get("docker")
} else if _, ok := p.(provision.BuilderDeployKubeClient); ok {
return get("kubernetes")
}
}
return builder, err
}
|
[
"func",
"GetForProvisioner",
"(",
"p",
"provision",
".",
"Provisioner",
")",
"(",
"Builder",
",",
"error",
")",
"{",
"builder",
",",
"err",
":=",
"get",
"(",
"p",
".",
"GetName",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"(",
"provision",
".",
"BuilderDeployDockerClient",
")",
";",
"ok",
"{",
"return",
"get",
"(",
"\"docker\"",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"(",
"provision",
".",
"BuilderDeployKubeClient",
")",
";",
"ok",
"{",
"return",
"get",
"(",
"\"kubernetes\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"builder",
",",
"err",
"\n",
"}"
] |
// GetForProvisioner gets the builder required by the provisioner.
|
[
"GetForProvisioner",
"gets",
"the",
"builder",
"required",
"by",
"the",
"provisioner",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/builder/builder.go#L55-L65
|
test
|
tsuru/tsuru
|
builder/builder.go
|
get
|
func get(name string) (Builder, error) {
b, ok := builders[name]
if !ok {
return nil, errors.Errorf("unknown builder: %q", name)
}
return b, nil
}
|
go
|
func get(name string) (Builder, error) {
b, ok := builders[name]
if !ok {
return nil, errors.Errorf("unknown builder: %q", name)
}
return b, nil
}
|
[
"func",
"get",
"(",
"name",
"string",
")",
"(",
"Builder",
",",
"error",
")",
"{",
"b",
",",
"ok",
":=",
"builders",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"unknown builder: %q\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] |
// get gets the named builder from the registry.
|
[
"get",
"gets",
"the",
"named",
"builder",
"from",
"the",
"registry",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/builder/builder.go#L68-L74
|
test
|
tsuru/tsuru
|
builder/builder.go
|
Registry
|
func Registry() ([]Builder, error) {
registry := make([]Builder, 0, len(builders))
for _, b := range builders {
registry = append(registry, b)
}
return registry, nil
}
|
go
|
func Registry() ([]Builder, error) {
registry := make([]Builder, 0, len(builders))
for _, b := range builders {
registry = append(registry, b)
}
return registry, nil
}
|
[
"func",
"Registry",
"(",
")",
"(",
"[",
"]",
"Builder",
",",
"error",
")",
"{",
"registry",
":=",
"make",
"(",
"[",
"]",
"Builder",
",",
"0",
",",
"len",
"(",
"builders",
")",
")",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"builders",
"{",
"registry",
"=",
"append",
"(",
"registry",
",",
"b",
")",
"\n",
"}",
"\n",
"return",
"registry",
",",
"nil",
"\n",
"}"
] |
// Registry returns the list of registered builders.
|
[
"Registry",
"returns",
"the",
"list",
"of",
"registered",
"builders",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/builder/builder.go#L77-L83
|
test
|
tsuru/tsuru
|
provision/docker/nodecontainer/queue.go
|
RegisterQueueTask
|
func RegisterQueueTask(p DockerProvisioner) error {
q, err := queue.Queue()
if err != nil {
return err
}
return q.RegisterTask(&runBs{provisioner: p})
}
|
go
|
func RegisterQueueTask(p DockerProvisioner) error {
q, err := queue.Queue()
if err != nil {
return err
}
return q.RegisterTask(&runBs{provisioner: p})
}
|
[
"func",
"RegisterQueueTask",
"(",
"p",
"DockerProvisioner",
")",
"error",
"{",
"q",
",",
"err",
":=",
"queue",
".",
"Queue",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"q",
".",
"RegisterTask",
"(",
"&",
"runBs",
"{",
"provisioner",
":",
"p",
"}",
")",
"\n",
"}"
] |
// RegisterQueueTask registers the internal bs queue task for later execution.
|
[
"RegisterQueueTask",
"registers",
"the",
"internal",
"bs",
"queue",
"task",
"for",
"later",
"execution",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/docker/nodecontainer/queue.go#L20-L26
|
test
|
tsuru/tsuru
|
provision/kubernetes/pkg/client/informers/externalversions/tsuru/v1/interface.go
|
Apps
|
func (v *version) Apps() AppInformer {
return &appInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}
|
go
|
func (v *version) Apps() AppInformer {
return &appInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}
|
[
"func",
"(",
"v",
"*",
"version",
")",
"Apps",
"(",
")",
"AppInformer",
"{",
"return",
"&",
"appInformer",
"{",
"factory",
":",
"v",
".",
"factory",
",",
"namespace",
":",
"v",
".",
"namespace",
",",
"tweakListOptions",
":",
"v",
".",
"tweakListOptions",
"}",
"\n",
"}"
] |
// Apps returns a AppInformer.
|
[
"Apps",
"returns",
"a",
"AppInformer",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/informers/externalversions/tsuru/v1/interface.go#L33-L35
|
test
|
tsuru/tsuru
|
provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go
|
DeepCopy
|
func (in *App) DeepCopy() *App {
if in == nil {
return nil
}
out := new(App)
in.DeepCopyInto(out)
return out
}
|
go
|
func (in *App) DeepCopy() *App {
if in == nil {
return nil
}
out := new(App)
in.DeepCopyInto(out)
return out
}
|
[
"func",
"(",
"in",
"*",
"App",
")",
"DeepCopy",
"(",
")",
"*",
"App",
"{",
"if",
"in",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"out",
":=",
"new",
"(",
"App",
")",
"\n",
"in",
".",
"DeepCopyInto",
"(",
"out",
")",
"\n",
"return",
"out",
"\n",
"}"
] |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new App.
|
[
"DeepCopy",
"is",
"an",
"autogenerated",
"deepcopy",
"function",
"copying",
"the",
"receiver",
"creating",
"a",
"new",
"App",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go#L25-L32
|
test
|
tsuru/tsuru
|
provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go
|
DeepCopy
|
func (in *AppList) DeepCopy() *AppList {
if in == nil {
return nil
}
out := new(AppList)
in.DeepCopyInto(out)
return out
}
|
go
|
func (in *AppList) DeepCopy() *AppList {
if in == nil {
return nil
}
out := new(AppList)
in.DeepCopyInto(out)
return out
}
|
[
"func",
"(",
"in",
"*",
"AppList",
")",
"DeepCopy",
"(",
")",
"*",
"AppList",
"{",
"if",
"in",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"out",
":=",
"new",
"(",
"AppList",
")",
"\n",
"in",
".",
"DeepCopyInto",
"(",
"out",
")",
"\n",
"return",
"out",
"\n",
"}"
] |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AppList.
|
[
"DeepCopy",
"is",
"an",
"autogenerated",
"deepcopy",
"function",
"copying",
"the",
"receiver",
"creating",
"a",
"new",
"AppList",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go#L58-L65
|
test
|
tsuru/tsuru
|
provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go
|
DeepCopy
|
func (in *AppSpec) DeepCopy() *AppSpec {
if in == nil {
return nil
}
out := new(AppSpec)
in.DeepCopyInto(out)
return out
}
|
go
|
func (in *AppSpec) DeepCopy() *AppSpec {
if in == nil {
return nil
}
out := new(AppSpec)
in.DeepCopyInto(out)
return out
}
|
[
"func",
"(",
"in",
"*",
"AppSpec",
")",
"DeepCopy",
"(",
")",
"*",
"AppSpec",
"{",
"if",
"in",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"out",
":=",
"new",
"(",
"AppSpec",
")",
"\n",
"in",
".",
"DeepCopyInto",
"(",
"out",
")",
"\n",
"return",
"out",
"\n",
"}"
] |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AppSpec.
|
[
"DeepCopy",
"is",
"an",
"autogenerated",
"deepcopy",
"function",
"copying",
"the",
"receiver",
"creating",
"a",
"new",
"AppSpec",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go#L106-L113
|
test
|
tsuru/tsuru
|
app/writer.go
|
Write
|
func (w *LogWriter) Write(data []byte) (int, error) {
w.finLk.RLock()
defer w.finLk.RUnlock()
if w.closed {
return len(data), nil
}
if w.msgCh == nil {
return len(data), w.write(data)
}
copied := make([]byte, len(data))
copy(copied, data)
w.msgCh <- copied
return len(data), nil
}
|
go
|
func (w *LogWriter) Write(data []byte) (int, error) {
w.finLk.RLock()
defer w.finLk.RUnlock()
if w.closed {
return len(data), nil
}
if w.msgCh == nil {
return len(data), w.write(data)
}
copied := make([]byte, len(data))
copy(copied, data)
w.msgCh <- copied
return len(data), nil
}
|
[
"func",
"(",
"w",
"*",
"LogWriter",
")",
"Write",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"w",
".",
"finLk",
".",
"RLock",
"(",
")",
"\n",
"defer",
"w",
".",
"finLk",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"w",
".",
"closed",
"{",
"return",
"len",
"(",
"data",
")",
",",
"nil",
"\n",
"}",
"\n",
"if",
"w",
".",
"msgCh",
"==",
"nil",
"{",
"return",
"len",
"(",
"data",
")",
",",
"w",
".",
"write",
"(",
"data",
")",
"\n",
"}",
"\n",
"copied",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"data",
")",
")",
"\n",
"copy",
"(",
"copied",
",",
"data",
")",
"\n",
"w",
".",
"msgCh",
"<-",
"copied",
"\n",
"return",
"len",
"(",
"data",
")",
",",
"nil",
"\n",
"}"
] |
// Write writes and logs the data.
|
[
"Write",
"writes",
"and",
"logs",
"the",
"data",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/writer.go#L64-L77
|
test
|
tsuru/tsuru
|
auth/native/native.go
|
ResetPassword
|
func (s NativeScheme) ResetPassword(user *auth.User, resetToken string) error {
if resetToken == "" {
return auth.ErrInvalidToken
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
passToken, err := getPasswordToken(resetToken)
if err != nil {
return err
}
if passToken.UserEmail != user.Email {
return auth.ErrInvalidToken
}
password := generatePassword(12)
user.Password = password
hashPassword(user)
go sendNewPassword(user, password)
passToken.Used = true
conn.PasswordTokens().UpdateId(passToken.Token, passToken)
return user.Update()
}
|
go
|
func (s NativeScheme) ResetPassword(user *auth.User, resetToken string) error {
if resetToken == "" {
return auth.ErrInvalidToken
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
passToken, err := getPasswordToken(resetToken)
if err != nil {
return err
}
if passToken.UserEmail != user.Email {
return auth.ErrInvalidToken
}
password := generatePassword(12)
user.Password = password
hashPassword(user)
go sendNewPassword(user, password)
passToken.Used = true
conn.PasswordTokens().UpdateId(passToken.Token, passToken)
return user.Update()
}
|
[
"func",
"(",
"s",
"NativeScheme",
")",
"ResetPassword",
"(",
"user",
"*",
"auth",
".",
"User",
",",
"resetToken",
"string",
")",
"error",
"{",
"if",
"resetToken",
"==",
"\"\"",
"{",
"return",
"auth",
".",
"ErrInvalidToken",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"passToken",
",",
"err",
":=",
"getPasswordToken",
"(",
"resetToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"passToken",
".",
"UserEmail",
"!=",
"user",
".",
"Email",
"{",
"return",
"auth",
".",
"ErrInvalidToken",
"\n",
"}",
"\n",
"password",
":=",
"generatePassword",
"(",
"12",
")",
"\n",
"user",
".",
"Password",
"=",
"password",
"\n",
"hashPassword",
"(",
"user",
")",
"\n",
"go",
"sendNewPassword",
"(",
"user",
",",
"password",
")",
"\n",
"passToken",
".",
"Used",
"=",
"true",
"\n",
"conn",
".",
"PasswordTokens",
"(",
")",
".",
"UpdateId",
"(",
"passToken",
".",
"Token",
",",
"passToken",
")",
"\n",
"return",
"user",
".",
"Update",
"(",
")",
"\n",
"}"
] |
// ResetPassword actually resets the password of the user. It needs the token
// string. The new password will be a random string, that will be then sent to
// the user email.
|
[
"ResetPassword",
"actually",
"resets",
"the",
"password",
"of",
"the",
"user",
".",
"It",
"needs",
"the",
"token",
"string",
".",
"The",
"new",
"password",
"will",
"be",
"a",
"random",
"string",
"that",
"will",
"be",
"then",
"sent",
"to",
"the",
"user",
"email",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/auth/native/native.go#L112-L135
|
test
|
tsuru/tsuru
|
provision/kubernetes/pkg/apis/tsuru/v1/register.go
|
addKnownTypes
|
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&App{},
&AppList{},
)
scheme.AddKnownTypes(SchemeGroupVersion,
&metav1.Status{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
|
go
|
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&App{},
&AppList{},
)
scheme.AddKnownTypes(SchemeGroupVersion,
&metav1.Status{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
|
[
"func",
"addKnownTypes",
"(",
"scheme",
"*",
"runtime",
".",
"Scheme",
")",
"error",
"{",
"scheme",
".",
"AddKnownTypes",
"(",
"SchemeGroupVersion",
",",
"&",
"App",
"{",
"}",
",",
"&",
"AppList",
"{",
"}",
",",
")",
"\n",
"scheme",
".",
"AddKnownTypes",
"(",
"SchemeGroupVersion",
",",
"&",
"metav1",
".",
"Status",
"{",
"}",
",",
")",
"\n",
"metav1",
".",
"AddToGroupVersion",
"(",
"scheme",
",",
"SchemeGroupVersion",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Adds the list of known types to the given scheme.
|
[
"Adds",
"the",
"list",
"of",
"known",
"types",
"to",
"the",
"given",
"scheme",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/apis/tsuru/v1/register.go#L34-L45
|
test
|
tsuru/tsuru
|
api/shutdown/shutdown.go
|
Register
|
func Register(s Shutdownable) {
lock.Lock()
defer lock.Unlock()
registered = append(registered, s)
}
|
go
|
func Register(s Shutdownable) {
lock.Lock()
defer lock.Unlock()
registered = append(registered, s)
}
|
[
"func",
"Register",
"(",
"s",
"Shutdownable",
")",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"registered",
"=",
"append",
"(",
"registered",
",",
"s",
")",
"\n",
"}"
] |
// Register registers an item as shutdownable
|
[
"Register",
"registers",
"an",
"item",
"as",
"shutdownable"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/shutdown/shutdown.go#L26-L30
|
test
|
tsuru/tsuru
|
api/shutdown/shutdown.go
|
Do
|
func Do(ctx context.Context, w io.Writer) error {
lock.Lock()
defer lock.Unlock()
done := make(chan bool)
wg := sync.WaitGroup{}
for _, h := range registered {
wg.Add(1)
go func(h Shutdownable) {
defer wg.Done()
var name string
if _, ok := h.(fmt.Stringer); ok {
name = fmt.Sprintf("%s", h)
} else {
name = fmt.Sprintf("%T", h)
}
fmt.Fprintf(w, "[shutdown] running shutdown for %s...\n", name)
err := h.Shutdown(ctx)
if err != nil {
fmt.Fprintf(w, "[shutdown] running shutdown for %s. ERROED: %v", name, err)
return
}
fmt.Fprintf(w, "[shutdown] running shutdown for %s. DONE.\n", name)
}(h)
}
go func() {
wg.Wait()
close(done)
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
}
return nil
}
|
go
|
func Do(ctx context.Context, w io.Writer) error {
lock.Lock()
defer lock.Unlock()
done := make(chan bool)
wg := sync.WaitGroup{}
for _, h := range registered {
wg.Add(1)
go func(h Shutdownable) {
defer wg.Done()
var name string
if _, ok := h.(fmt.Stringer); ok {
name = fmt.Sprintf("%s", h)
} else {
name = fmt.Sprintf("%T", h)
}
fmt.Fprintf(w, "[shutdown] running shutdown for %s...\n", name)
err := h.Shutdown(ctx)
if err != nil {
fmt.Fprintf(w, "[shutdown] running shutdown for %s. ERROED: %v", name, err)
return
}
fmt.Fprintf(w, "[shutdown] running shutdown for %s. DONE.\n", name)
}(h)
}
go func() {
wg.Wait()
close(done)
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
}
return nil
}
|
[
"func",
"Do",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"done",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"registered",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"h",
"Shutdownable",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"var",
"name",
"string",
"\n",
"if",
"_",
",",
"ok",
":=",
"h",
".",
"(",
"fmt",
".",
"Stringer",
")",
";",
"ok",
"{",
"name",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s\"",
",",
"h",
")",
"\n",
"}",
"else",
"{",
"name",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%T\"",
",",
"h",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"[shutdown] running shutdown for %s...\\n\"",
",",
"\\n",
")",
"\n",
"name",
"\n",
"err",
":=",
"h",
".",
"Shutdown",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"[shutdown] running shutdown for %s. ERROED: %v\"",
",",
"name",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"[shutdown] running shutdown for %s. DONE.\\n\"",
",",
"\\n",
")",
"\n",
"}",
"\n",
"name",
"\n",
"(",
"h",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"done",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] |
// Do shutdowns All registered Shutdownable items
|
[
"Do",
"shutdowns",
"All",
"registered",
"Shutdownable",
"items"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/shutdown/shutdown.go#L33-L67
|
test
|
tsuru/tsuru
|
app/image/platform.go
|
ListImagesOrDefault
|
func (s *platformImageService) ListImagesOrDefault(platformName string) ([]string, error) {
imgs, err := s.ListImages(platformName)
if err != nil && err == imageTypes.ErrPlatformImageNotFound {
return []string{platformBasicImageName(platformName)}, nil
}
return imgs, err
}
|
go
|
func (s *platformImageService) ListImagesOrDefault(platformName string) ([]string, error) {
imgs, err := s.ListImages(platformName)
if err != nil && err == imageTypes.ErrPlatformImageNotFound {
return []string{platformBasicImageName(platformName)}, nil
}
return imgs, err
}
|
[
"func",
"(",
"s",
"*",
"platformImageService",
")",
"ListImagesOrDefault",
"(",
"platformName",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"imgs",
",",
"err",
":=",
"s",
".",
"ListImages",
"(",
"platformName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"==",
"imageTypes",
".",
"ErrPlatformImageNotFound",
"{",
"return",
"[",
"]",
"string",
"{",
"platformBasicImageName",
"(",
"platformName",
")",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"imgs",
",",
"err",
"\n",
"}"
] |
// PlatformListImagesOrDefault returns basicImageName when platform is empty
// for backwards compatibility
|
[
"PlatformListImagesOrDefault",
"returns",
"basicImageName",
"when",
"platform",
"is",
"empty",
"for",
"backwards",
"compatibility"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/image/platform.go#L81-L87
|
test
|
tsuru/tsuru
|
provision/kubernetes/migrate/migrate.go
|
MigrateAppsCRDs
|
func MigrateAppsCRDs() error {
config.Set("kubernetes:use-pool-namespaces", false)
defer config.Unset("kubernetes:use-pool-namespaces")
prov := kubernetes.GetProvisioner()
pools, err := pool.ListAllPools()
if err != nil {
return errors.Wrap(err, "failed to list pools")
}
var kubePools []string
for _, p := range pools {
if p.Provisioner == prov.GetName() {
kubePools = append(kubePools, p.Name)
}
}
apps, err := app.List(&app.Filter{Pools: kubePools})
if err != nil {
return errors.Wrap(err, "failed to list apps")
}
multiErr := tsuruerrors.NewMultiError()
for _, a := range apps {
errProv := prov.Provision(&a)
if errProv != nil {
multiErr.Add(errProv)
}
}
return multiErr.ToError()
}
|
go
|
func MigrateAppsCRDs() error {
config.Set("kubernetes:use-pool-namespaces", false)
defer config.Unset("kubernetes:use-pool-namespaces")
prov := kubernetes.GetProvisioner()
pools, err := pool.ListAllPools()
if err != nil {
return errors.Wrap(err, "failed to list pools")
}
var kubePools []string
for _, p := range pools {
if p.Provisioner == prov.GetName() {
kubePools = append(kubePools, p.Name)
}
}
apps, err := app.List(&app.Filter{Pools: kubePools})
if err != nil {
return errors.Wrap(err, "failed to list apps")
}
multiErr := tsuruerrors.NewMultiError()
for _, a := range apps {
errProv := prov.Provision(&a)
if errProv != nil {
multiErr.Add(errProv)
}
}
return multiErr.ToError()
}
|
[
"func",
"MigrateAppsCRDs",
"(",
")",
"error",
"{",
"config",
".",
"Set",
"(",
"\"kubernetes:use-pool-namespaces\"",
",",
"false",
")",
"\n",
"defer",
"config",
".",
"Unset",
"(",
"\"kubernetes:use-pool-namespaces\"",
")",
"\n",
"prov",
":=",
"kubernetes",
".",
"GetProvisioner",
"(",
")",
"\n",
"pools",
",",
"err",
":=",
"pool",
".",
"ListAllPools",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to list pools\"",
")",
"\n",
"}",
"\n",
"var",
"kubePools",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"pools",
"{",
"if",
"p",
".",
"Provisioner",
"==",
"prov",
".",
"GetName",
"(",
")",
"{",
"kubePools",
"=",
"append",
"(",
"kubePools",
",",
"p",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"apps",
",",
"err",
":=",
"app",
".",
"List",
"(",
"&",
"app",
".",
"Filter",
"{",
"Pools",
":",
"kubePools",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to list apps\"",
")",
"\n",
"}",
"\n",
"multiErr",
":=",
"tsuruerrors",
".",
"NewMultiError",
"(",
")",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"apps",
"{",
"errProv",
":=",
"prov",
".",
"Provision",
"(",
"&",
"a",
")",
"\n",
"if",
"errProv",
"!=",
"nil",
"{",
"multiErr",
".",
"Add",
"(",
"errProv",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"multiErr",
".",
"ToError",
"(",
")",
"\n",
"}"
] |
// MigrateAppsCRDs creates the necessary CRDs for every application
// on a Kubernetes cluster. This is done by re-provisioning the App
// on the cluster.
|
[
"MigrateAppsCRDs",
"creates",
"the",
"necessary",
"CRDs",
"for",
"every",
"application",
"on",
"a",
"Kubernetes",
"cluster",
".",
"This",
"is",
"done",
"by",
"re",
"-",
"provisioning",
"the",
"App",
"on",
"the",
"cluster",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/migrate/migrate.go#L15-L41
|
test
|
tsuru/tsuru
|
migration/migration.go
|
Register
|
func Register(name string, fn MigrateFunc) error {
return register(name, false, fn)
}
|
go
|
func Register(name string, fn MigrateFunc) error {
return register(name, false, fn)
}
|
[
"func",
"Register",
"(",
"name",
"string",
",",
"fn",
"MigrateFunc",
")",
"error",
"{",
"return",
"register",
"(",
"name",
",",
"false",
",",
"fn",
")",
"\n",
"}"
] |
// Register register a new migration for later execution with the Run
// functions.
|
[
"Register",
"register",
"a",
"new",
"migration",
"for",
"later",
"execution",
"with",
"the",
"Run",
"functions",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/migration/migration.go#L65-L67
|
test
|
tsuru/tsuru
|
migration/migration.go
|
RegisterOptional
|
func RegisterOptional(name string, fn MigrateFunc) error {
return register(name, true, fn)
}
|
go
|
func RegisterOptional(name string, fn MigrateFunc) error {
return register(name, true, fn)
}
|
[
"func",
"RegisterOptional",
"(",
"name",
"string",
",",
"fn",
"MigrateFunc",
")",
"error",
"{",
"return",
"register",
"(",
"name",
",",
"true",
",",
"fn",
")",
"\n",
"}"
] |
// RegisterOptional register a new migration that will not run automatically
// when calling the Run funcition.
|
[
"RegisterOptional",
"register",
"a",
"new",
"migration",
"that",
"will",
"not",
"run",
"automatically",
"when",
"calling",
"the",
"Run",
"funcition",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/migration/migration.go#L71-L73
|
test
|
tsuru/tsuru
|
migration/migration.go
|
Run
|
func Run(args RunArgs) error {
if args.Name != "" {
return runOptional(args)
}
if args.Force {
return ErrCannotForceMandatory
}
return run(args)
}
|
go
|
func Run(args RunArgs) error {
if args.Name != "" {
return runOptional(args)
}
if args.Force {
return ErrCannotForceMandatory
}
return run(args)
}
|
[
"func",
"Run",
"(",
"args",
"RunArgs",
")",
"error",
"{",
"if",
"args",
".",
"Name",
"!=",
"\"\"",
"{",
"return",
"runOptional",
"(",
"args",
")",
"\n",
"}",
"\n",
"if",
"args",
".",
"Force",
"{",
"return",
"ErrCannotForceMandatory",
"\n",
"}",
"\n",
"return",
"run",
"(",
"args",
")",
"\n",
"}"
] |
// Run runs all registered non optional migrations if no ".Name" is informed.
// Migrations are executed in the order that they were registered. If ".Name"
// is informed, an optional migration with the given name is executed.
|
[
"Run",
"runs",
"all",
"registered",
"non",
"optional",
"migrations",
"if",
"no",
".",
"Name",
"is",
"informed",
".",
"Migrations",
"are",
"executed",
"in",
"the",
"order",
"that",
"they",
"were",
"registered",
".",
"If",
".",
"Name",
"is",
"informed",
"an",
"optional",
"migration",
"with",
"the",
"given",
"name",
"is",
"executed",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/migration/migration.go#L88-L96
|
test
|
tsuru/tsuru
|
app/app.go
|
Units
|
func (app *App) Units() ([]provision.Unit, error) {
prov, err := app.getProvisioner()
if err != nil {
return []provision.Unit{}, err
}
units, err := prov.Units(app)
if units == nil {
// This is unusual but was done because previously this method didn't
// return an error. This ensures we always return an empty list instead
// of nil to preserve compatibility with old clients.
units = []provision.Unit{}
}
return units, err
}
|
go
|
func (app *App) Units() ([]provision.Unit, error) {
prov, err := app.getProvisioner()
if err != nil {
return []provision.Unit{}, err
}
units, err := prov.Units(app)
if units == nil {
// This is unusual but was done because previously this method didn't
// return an error. This ensures we always return an empty list instead
// of nil to preserve compatibility with old clients.
units = []provision.Unit{}
}
return units, err
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"Units",
"(",
")",
"(",
"[",
"]",
"provision",
".",
"Unit",
",",
"error",
")",
"{",
"prov",
",",
"err",
":=",
"app",
".",
"getProvisioner",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"provision",
".",
"Unit",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"units",
",",
"err",
":=",
"prov",
".",
"Units",
"(",
"app",
")",
"\n",
"if",
"units",
"==",
"nil",
"{",
"units",
"=",
"[",
"]",
"provision",
".",
"Unit",
"{",
"}",
"\n",
"}",
"\n",
"return",
"units",
",",
"err",
"\n",
"}"
] |
// Units returns the list of units.
|
[
"Units",
"returns",
"the",
"list",
"of",
"units",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L181-L194
|
test
|
tsuru/tsuru
|
app/app.go
|
MarshalJSON
|
func (app *App) MarshalJSON() ([]byte, error) {
repo, _ := repository.Manager().GetRepository(app.Name)
result := make(map[string]interface{})
result["name"] = app.Name
result["platform"] = app.Platform
if version := app.GetPlatformVersion(); version != "latest" {
result["platform"] = fmt.Sprintf("%s:%s", app.Platform, version)
}
result["teams"] = app.Teams
units, err := app.Units()
result["units"] = units
var errMsgs []string
if err != nil {
errMsgs = append(errMsgs, fmt.Sprintf("unable to list app units: %+v", err))
}
result["repository"] = repo.ReadWriteURL
plan := map[string]interface{}{
"name": app.Plan.Name,
"memory": app.Plan.Memory,
"swap": app.Plan.Swap,
"cpushare": app.Plan.CpuShare,
}
routers, err := app.GetRoutersWithAddr()
if err != nil {
errMsgs = append(errMsgs, fmt.Sprintf("unable to get app addresses: %+v", err))
}
if len(routers) > 0 {
result["ip"] = routers[0].Address
plan["router"] = routers[0].Name
result["router"] = routers[0].Name
result["routeropts"] = routers[0].Opts
}
result["cname"] = app.CName
result["owner"] = app.Owner
result["pool"] = app.Pool
result["description"] = app.Description
result["deploys"] = app.Deploys
result["teamowner"] = app.TeamOwner
result["plan"] = plan
result["lock"] = app.Lock
result["tags"] = app.Tags
result["routers"] = routers
if len(errMsgs) > 0 {
result["error"] = strings.Join(errMsgs, "\n")
}
return json.Marshal(&result)
}
|
go
|
func (app *App) MarshalJSON() ([]byte, error) {
repo, _ := repository.Manager().GetRepository(app.Name)
result := make(map[string]interface{})
result["name"] = app.Name
result["platform"] = app.Platform
if version := app.GetPlatformVersion(); version != "latest" {
result["platform"] = fmt.Sprintf("%s:%s", app.Platform, version)
}
result["teams"] = app.Teams
units, err := app.Units()
result["units"] = units
var errMsgs []string
if err != nil {
errMsgs = append(errMsgs, fmt.Sprintf("unable to list app units: %+v", err))
}
result["repository"] = repo.ReadWriteURL
plan := map[string]interface{}{
"name": app.Plan.Name,
"memory": app.Plan.Memory,
"swap": app.Plan.Swap,
"cpushare": app.Plan.CpuShare,
}
routers, err := app.GetRoutersWithAddr()
if err != nil {
errMsgs = append(errMsgs, fmt.Sprintf("unable to get app addresses: %+v", err))
}
if len(routers) > 0 {
result["ip"] = routers[0].Address
plan["router"] = routers[0].Name
result["router"] = routers[0].Name
result["routeropts"] = routers[0].Opts
}
result["cname"] = app.CName
result["owner"] = app.Owner
result["pool"] = app.Pool
result["description"] = app.Description
result["deploys"] = app.Deploys
result["teamowner"] = app.TeamOwner
result["plan"] = plan
result["lock"] = app.Lock
result["tags"] = app.Tags
result["routers"] = routers
if len(errMsgs) > 0 {
result["error"] = strings.Join(errMsgs, "\n")
}
return json.Marshal(&result)
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"repo",
",",
"_",
":=",
"repository",
".",
"Manager",
"(",
")",
".",
"GetRepository",
"(",
"app",
".",
"Name",
")",
"\n",
"result",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"result",
"[",
"\"name\"",
"]",
"=",
"app",
".",
"Name",
"\n",
"result",
"[",
"\"platform\"",
"]",
"=",
"app",
".",
"Platform",
"\n",
"if",
"version",
":=",
"app",
".",
"GetPlatformVersion",
"(",
")",
";",
"version",
"!=",
"\"latest\"",
"{",
"result",
"[",
"\"platform\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s:%s\"",
",",
"app",
".",
"Platform",
",",
"version",
")",
"\n",
"}",
"\n",
"result",
"[",
"\"teams\"",
"]",
"=",
"app",
".",
"Teams",
"\n",
"units",
",",
"err",
":=",
"app",
".",
"Units",
"(",
")",
"\n",
"result",
"[",
"\"units\"",
"]",
"=",
"units",
"\n",
"var",
"errMsgs",
"[",
"]",
"string",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errMsgs",
"=",
"append",
"(",
"errMsgs",
",",
"fmt",
".",
"Sprintf",
"(",
"\"unable to list app units: %+v\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"result",
"[",
"\"repository\"",
"]",
"=",
"repo",
".",
"ReadWriteURL",
"\n",
"plan",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"name\"",
":",
"app",
".",
"Plan",
".",
"Name",
",",
"\"memory\"",
":",
"app",
".",
"Plan",
".",
"Memory",
",",
"\"swap\"",
":",
"app",
".",
"Plan",
".",
"Swap",
",",
"\"cpushare\"",
":",
"app",
".",
"Plan",
".",
"CpuShare",
",",
"}",
"\n",
"routers",
",",
"err",
":=",
"app",
".",
"GetRoutersWithAddr",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errMsgs",
"=",
"append",
"(",
"errMsgs",
",",
"fmt",
".",
"Sprintf",
"(",
"\"unable to get app addresses: %+v\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"routers",
")",
">",
"0",
"{",
"result",
"[",
"\"ip\"",
"]",
"=",
"routers",
"[",
"0",
"]",
".",
"Address",
"\n",
"plan",
"[",
"\"router\"",
"]",
"=",
"routers",
"[",
"0",
"]",
".",
"Name",
"\n",
"result",
"[",
"\"router\"",
"]",
"=",
"routers",
"[",
"0",
"]",
".",
"Name",
"\n",
"result",
"[",
"\"routeropts\"",
"]",
"=",
"routers",
"[",
"0",
"]",
".",
"Opts",
"\n",
"}",
"\n",
"result",
"[",
"\"cname\"",
"]",
"=",
"app",
".",
"CName",
"\n",
"result",
"[",
"\"owner\"",
"]",
"=",
"app",
".",
"Owner",
"\n",
"result",
"[",
"\"pool\"",
"]",
"=",
"app",
".",
"Pool",
"\n",
"result",
"[",
"\"description\"",
"]",
"=",
"app",
".",
"Description",
"\n",
"result",
"[",
"\"deploys\"",
"]",
"=",
"app",
".",
"Deploys",
"\n",
"result",
"[",
"\"teamowner\"",
"]",
"=",
"app",
".",
"TeamOwner",
"\n",
"result",
"[",
"\"plan\"",
"]",
"=",
"plan",
"\n",
"result",
"[",
"\"lock\"",
"]",
"=",
"app",
".",
"Lock",
"\n",
"result",
"[",
"\"tags\"",
"]",
"=",
"app",
".",
"Tags",
"\n",
"result",
"[",
"\"routers\"",
"]",
"=",
"routers",
"\n",
"if",
"len",
"(",
"errMsgs",
")",
">",
"0",
"{",
"result",
"[",
"\"error\"",
"]",
"=",
"strings",
".",
"Join",
"(",
"errMsgs",
",",
"\"\\n\"",
")",
"\n",
"}",
"\n",
"\\n",
"\n",
"}"
] |
// MarshalJSON marshals the app in json format.
|
[
"MarshalJSON",
"marshals",
"the",
"app",
"in",
"json",
"format",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L197-L243
|
test
|
tsuru/tsuru
|
app/app.go
|
AcquireApplicationLockWait
|
func AcquireApplicationLockWait(appName string, owner string, reason string, timeout time.Duration) (bool, error) {
timeoutChan := time.After(timeout)
for {
appLock := appTypes.AppLock{
Locked: true,
Reason: reason,
Owner: owner,
AcquireDate: time.Now().In(time.UTC),
}
conn, err := db.Conn()
if err != nil {
return false, err
}
err = conn.Apps().Update(bson.M{"name": appName, "lock.locked": bson.M{"$in": []interface{}{false, nil}}}, bson.M{"$set": bson.M{"lock": appLock}})
conn.Close()
if err == nil {
return true, nil
}
if err != mgo.ErrNotFound {
return false, err
}
select {
case <-timeoutChan:
return false, nil
case <-time.After(300 * time.Millisecond):
}
}
}
|
go
|
func AcquireApplicationLockWait(appName string, owner string, reason string, timeout time.Duration) (bool, error) {
timeoutChan := time.After(timeout)
for {
appLock := appTypes.AppLock{
Locked: true,
Reason: reason,
Owner: owner,
AcquireDate: time.Now().In(time.UTC),
}
conn, err := db.Conn()
if err != nil {
return false, err
}
err = conn.Apps().Update(bson.M{"name": appName, "lock.locked": bson.M{"$in": []interface{}{false, nil}}}, bson.M{"$set": bson.M{"lock": appLock}})
conn.Close()
if err == nil {
return true, nil
}
if err != mgo.ErrNotFound {
return false, err
}
select {
case <-timeoutChan:
return false, nil
case <-time.After(300 * time.Millisecond):
}
}
}
|
[
"func",
"AcquireApplicationLockWait",
"(",
"appName",
"string",
",",
"owner",
"string",
",",
"reason",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"bool",
",",
"error",
")",
"{",
"timeoutChan",
":=",
"time",
".",
"After",
"(",
"timeout",
")",
"\n",
"for",
"{",
"appLock",
":=",
"appTypes",
".",
"AppLock",
"{",
"Locked",
":",
"true",
",",
"Reason",
":",
"reason",
",",
"Owner",
":",
"owner",
",",
"AcquireDate",
":",
"time",
".",
"Now",
"(",
")",
".",
"In",
"(",
"time",
".",
"UTC",
")",
",",
"}",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"appName",
",",
"\"lock.locked\"",
":",
"bson",
".",
"M",
"{",
"\"$in\"",
":",
"[",
"]",
"interface",
"{",
"}",
"{",
"false",
",",
"nil",
"}",
"}",
"}",
",",
"bson",
".",
"M",
"{",
"\"$set\"",
":",
"bson",
".",
"M",
"{",
"\"lock\"",
":",
"appLock",
"}",
"}",
")",
"\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"timeoutChan",
":",
"return",
"false",
",",
"nil",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"300",
"*",
"time",
".",
"Millisecond",
")",
":",
"}",
"\n",
"}",
"\n",
"}"
] |
// Same as AcquireApplicationLock but it keeps trying to acquire the lock
// until timeout is reached.
|
[
"Same",
"as",
"AcquireApplicationLock",
"but",
"it",
"keeps",
"trying",
"to",
"acquire",
"the",
"lock",
"until",
"timeout",
"is",
"reached",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L264-L291
|
test
|
tsuru/tsuru
|
app/app.go
|
ReleaseApplicationLock
|
func ReleaseApplicationLock(appName string) {
var err error
retries := 3
for i := 0; i < retries; i++ {
err = releaseApplicationLockOnce(appName)
if err == nil {
return
}
time.Sleep(time.Second * time.Duration(i+1))
}
log.Error(err)
}
|
go
|
func ReleaseApplicationLock(appName string) {
var err error
retries := 3
for i := 0; i < retries; i++ {
err = releaseApplicationLockOnce(appName)
if err == nil {
return
}
time.Sleep(time.Second * time.Duration(i+1))
}
log.Error(err)
}
|
[
"func",
"ReleaseApplicationLock",
"(",
"appName",
"string",
")",
"{",
"var",
"err",
"error",
"\n",
"retries",
":=",
"3",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"retries",
";",
"i",
"++",
"{",
"err",
"=",
"releaseApplicationLockOnce",
"(",
"appName",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Second",
"*",
"time",
".",
"Duration",
"(",
"i",
"+",
"1",
")",
")",
"\n",
"}",
"\n",
"log",
".",
"Error",
"(",
"err",
")",
"\n",
"}"
] |
// ReleaseApplicationLock releases a lock hold on an app, currently it's called
// by a middleware, however, ideally, it should be called individually by each
// handler since they might be doing operations in background.
|
[
"ReleaseApplicationLock",
"releases",
"a",
"lock",
"hold",
"on",
"an",
"app",
"currently",
"it",
"s",
"called",
"by",
"a",
"middleware",
"however",
"ideally",
"it",
"should",
"be",
"called",
"individually",
"by",
"each",
"handler",
"since",
"they",
"might",
"be",
"doing",
"operations",
"in",
"background",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L335-L346
|
test
|
tsuru/tsuru
|
app/app.go
|
GetByName
|
func GetByName(name string) (*App, error) {
var app App
conn, err := db.Conn()
if err != nil {
return nil, err
}
defer conn.Close()
err = conn.Apps().Find(bson.M{"name": name}).One(&app)
if err == mgo.ErrNotFound {
return nil, appTypes.ErrAppNotFound
}
return &app, err
}
|
go
|
func GetByName(name string) (*App, error) {
var app App
conn, err := db.Conn()
if err != nil {
return nil, err
}
defer conn.Close()
err = conn.Apps().Find(bson.M{"name": name}).One(&app)
if err == mgo.ErrNotFound {
return nil, appTypes.ErrAppNotFound
}
return &app, err
}
|
[
"func",
"GetByName",
"(",
"name",
"string",
")",
"(",
"*",
"App",
",",
"error",
")",
"{",
"var",
"app",
"App",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"name",
"}",
")",
".",
"One",
"(",
"&",
"app",
")",
"\n",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"nil",
",",
"appTypes",
".",
"ErrAppNotFound",
"\n",
"}",
"\n",
"return",
"&",
"app",
",",
"err",
"\n",
"}"
] |
// GetByName queries the database to find an app identified by the given
// name.
|
[
"GetByName",
"queries",
"the",
"database",
"to",
"find",
"an",
"app",
"identified",
"by",
"the",
"given",
"name",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L363-L375
|
test
|
tsuru/tsuru
|
app/app.go
|
AddUnits
|
func (app *App) AddUnits(n uint, process string, w io.Writer) error {
if n == 0 {
return errors.New("Cannot add zero units.")
}
units, err := app.Units()
if err != nil {
return err
}
for _, u := range units {
if (u.Status == provision.StatusAsleep) || (u.Status == provision.StatusStopped) {
return errors.New("Cannot add units to an app that has stopped or sleeping units")
}
}
w = app.withLogWriter(w)
err = action.NewPipeline(
&reserveUnitsToAdd,
&provisionAddUnits,
).Execute(app, n, w, process)
rebuild.RoutesRebuildOrEnqueue(app.Name)
quotaErr := app.fixQuota()
if err != nil {
return err
}
return quotaErr
}
|
go
|
func (app *App) AddUnits(n uint, process string, w io.Writer) error {
if n == 0 {
return errors.New("Cannot add zero units.")
}
units, err := app.Units()
if err != nil {
return err
}
for _, u := range units {
if (u.Status == provision.StatusAsleep) || (u.Status == provision.StatusStopped) {
return errors.New("Cannot add units to an app that has stopped or sleeping units")
}
}
w = app.withLogWriter(w)
err = action.NewPipeline(
&reserveUnitsToAdd,
&provisionAddUnits,
).Execute(app, n, w, process)
rebuild.RoutesRebuildOrEnqueue(app.Name)
quotaErr := app.fixQuota()
if err != nil {
return err
}
return quotaErr
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"AddUnits",
"(",
"n",
"uint",
",",
"process",
"string",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"n",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"Cannot add zero units.\"",
")",
"\n",
"}",
"\n",
"units",
",",
"err",
":=",
"app",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"u",
":=",
"range",
"units",
"{",
"if",
"(",
"u",
".",
"Status",
"==",
"provision",
".",
"StatusAsleep",
")",
"||",
"(",
"u",
".",
"Status",
"==",
"provision",
".",
"StatusStopped",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"Cannot add units to an app that has stopped or sleeping units\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"w",
"=",
"app",
".",
"withLogWriter",
"(",
"w",
")",
"\n",
"err",
"=",
"action",
".",
"NewPipeline",
"(",
"&",
"reserveUnitsToAdd",
",",
"&",
"provisionAddUnits",
",",
")",
".",
"Execute",
"(",
"app",
",",
"n",
",",
"w",
",",
"process",
")",
"\n",
"rebuild",
".",
"RoutesRebuildOrEnqueue",
"(",
"app",
".",
"Name",
")",
"\n",
"quotaErr",
":=",
"app",
".",
"fixQuota",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"quotaErr",
"\n",
"}"
] |
// AddUnits creates n new units within the provisioner, saves new units in the
// database and enqueues the apprc serialization.
|
[
"AddUnits",
"creates",
"n",
"new",
"units",
"within",
"the",
"provisioner",
"saves",
"new",
"units",
"in",
"the",
"database",
"and",
"enqueues",
"the",
"apprc",
"serialization",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L823-L847
|
test
|
tsuru/tsuru
|
app/app.go
|
SetUnitStatus
|
func (app *App) SetUnitStatus(unitName string, status provision.Status) error {
units, err := app.Units()
if err != nil {
return err
}
for _, unit := range units {
if strings.HasPrefix(unit.ID, unitName) {
prov, err := app.getProvisioner()
if err != nil {
return err
}
unitProv, ok := prov.(provision.UnitStatusProvisioner)
if !ok {
return nil
}
return unitProv.SetUnitStatus(unit, status)
}
}
return &provision.UnitNotFoundError{ID: unitName}
}
|
go
|
func (app *App) SetUnitStatus(unitName string, status provision.Status) error {
units, err := app.Units()
if err != nil {
return err
}
for _, unit := range units {
if strings.HasPrefix(unit.ID, unitName) {
prov, err := app.getProvisioner()
if err != nil {
return err
}
unitProv, ok := prov.(provision.UnitStatusProvisioner)
if !ok {
return nil
}
return unitProv.SetUnitStatus(unit, status)
}
}
return &provision.UnitNotFoundError{ID: unitName}
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"SetUnitStatus",
"(",
"unitName",
"string",
",",
"status",
"provision",
".",
"Status",
")",
"error",
"{",
"units",
",",
"err",
":=",
"app",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"unit",
":=",
"range",
"units",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"unit",
".",
"ID",
",",
"unitName",
")",
"{",
"prov",
",",
"err",
":=",
"app",
".",
"getProvisioner",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"unitProv",
",",
"ok",
":=",
"prov",
".",
"(",
"provision",
".",
"UnitStatusProvisioner",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"unitProv",
".",
"SetUnitStatus",
"(",
"unit",
",",
"status",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"provision",
".",
"UnitNotFoundError",
"{",
"ID",
":",
"unitName",
"}",
"\n",
"}"
] |
// SetUnitStatus changes the status of the given unit.
|
[
"SetUnitStatus",
"changes",
"the",
"status",
"of",
"the",
"given",
"unit",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L886-L905
|
test
|
tsuru/tsuru
|
app/app.go
|
UpdateNodeStatus
|
func UpdateNodeStatus(nodeData provision.NodeStatusData) ([]UpdateUnitsResult, error) {
node, findNodeErr := findNodeForNodeData(nodeData)
var nodeAddresses []string
if findNodeErr == nil {
nodeAddresses = []string{node.Address()}
} else {
nodeAddresses = nodeData.Addrs
}
if healer.HealerInstance != nil {
err := healer.HealerInstance.UpdateNodeData(nodeAddresses, nodeData.Checks)
if err != nil {
log.Errorf("[update node status] unable to set node status in healer: %s", err)
}
}
if findNodeErr == provision.ErrNodeNotFound {
counterNodesNotFound.Inc()
log.Errorf("[update node status] node not found with nodedata: %#v", nodeData)
result := make([]UpdateUnitsResult, len(nodeData.Units))
for i, unitData := range nodeData.Units {
result[i] = UpdateUnitsResult{ID: unitData.ID, Found: false}
}
return result, nil
}
if findNodeErr != nil {
return nil, findNodeErr
}
unitProv, ok := node.Provisioner().(provision.UnitStatusProvisioner)
if !ok {
return []UpdateUnitsResult{}, nil
}
result := make([]UpdateUnitsResult, len(nodeData.Units))
for i, unitData := range nodeData.Units {
unit := provision.Unit{ID: unitData.ID, Name: unitData.Name}
err := unitProv.SetUnitStatus(unit, unitData.Status)
_, isNotFound := err.(*provision.UnitNotFoundError)
if err != nil && !isNotFound {
return nil, err
}
result[i] = UpdateUnitsResult{ID: unitData.ID, Found: !isNotFound}
}
return result, nil
}
|
go
|
func UpdateNodeStatus(nodeData provision.NodeStatusData) ([]UpdateUnitsResult, error) {
node, findNodeErr := findNodeForNodeData(nodeData)
var nodeAddresses []string
if findNodeErr == nil {
nodeAddresses = []string{node.Address()}
} else {
nodeAddresses = nodeData.Addrs
}
if healer.HealerInstance != nil {
err := healer.HealerInstance.UpdateNodeData(nodeAddresses, nodeData.Checks)
if err != nil {
log.Errorf("[update node status] unable to set node status in healer: %s", err)
}
}
if findNodeErr == provision.ErrNodeNotFound {
counterNodesNotFound.Inc()
log.Errorf("[update node status] node not found with nodedata: %#v", nodeData)
result := make([]UpdateUnitsResult, len(nodeData.Units))
for i, unitData := range nodeData.Units {
result[i] = UpdateUnitsResult{ID: unitData.ID, Found: false}
}
return result, nil
}
if findNodeErr != nil {
return nil, findNodeErr
}
unitProv, ok := node.Provisioner().(provision.UnitStatusProvisioner)
if !ok {
return []UpdateUnitsResult{}, nil
}
result := make([]UpdateUnitsResult, len(nodeData.Units))
for i, unitData := range nodeData.Units {
unit := provision.Unit{ID: unitData.ID, Name: unitData.Name}
err := unitProv.SetUnitStatus(unit, unitData.Status)
_, isNotFound := err.(*provision.UnitNotFoundError)
if err != nil && !isNotFound {
return nil, err
}
result[i] = UpdateUnitsResult{ID: unitData.ID, Found: !isNotFound}
}
return result, nil
}
|
[
"func",
"UpdateNodeStatus",
"(",
"nodeData",
"provision",
".",
"NodeStatusData",
")",
"(",
"[",
"]",
"UpdateUnitsResult",
",",
"error",
")",
"{",
"node",
",",
"findNodeErr",
":=",
"findNodeForNodeData",
"(",
"nodeData",
")",
"\n",
"var",
"nodeAddresses",
"[",
"]",
"string",
"\n",
"if",
"findNodeErr",
"==",
"nil",
"{",
"nodeAddresses",
"=",
"[",
"]",
"string",
"{",
"node",
".",
"Address",
"(",
")",
"}",
"\n",
"}",
"else",
"{",
"nodeAddresses",
"=",
"nodeData",
".",
"Addrs",
"\n",
"}",
"\n",
"if",
"healer",
".",
"HealerInstance",
"!=",
"nil",
"{",
"err",
":=",
"healer",
".",
"HealerInstance",
".",
"UpdateNodeData",
"(",
"nodeAddresses",
",",
"nodeData",
".",
"Checks",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"[update node status] unable to set node status in healer: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"findNodeErr",
"==",
"provision",
".",
"ErrNodeNotFound",
"{",
"counterNodesNotFound",
".",
"Inc",
"(",
")",
"\n",
"log",
".",
"Errorf",
"(",
"\"[update node status] node not found with nodedata: %#v\"",
",",
"nodeData",
")",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"UpdateUnitsResult",
",",
"len",
"(",
"nodeData",
".",
"Units",
")",
")",
"\n",
"for",
"i",
",",
"unitData",
":=",
"range",
"nodeData",
".",
"Units",
"{",
"result",
"[",
"i",
"]",
"=",
"UpdateUnitsResult",
"{",
"ID",
":",
"unitData",
".",
"ID",
",",
"Found",
":",
"false",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}",
"\n",
"if",
"findNodeErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"findNodeErr",
"\n",
"}",
"\n",
"unitProv",
",",
"ok",
":=",
"node",
".",
"Provisioner",
"(",
")",
".",
"(",
"provision",
".",
"UnitStatusProvisioner",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"[",
"]",
"UpdateUnitsResult",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"UpdateUnitsResult",
",",
"len",
"(",
"nodeData",
".",
"Units",
")",
")",
"\n",
"for",
"i",
",",
"unitData",
":=",
"range",
"nodeData",
".",
"Units",
"{",
"unit",
":=",
"provision",
".",
"Unit",
"{",
"ID",
":",
"unitData",
".",
"ID",
",",
"Name",
":",
"unitData",
".",
"Name",
"}",
"\n",
"err",
":=",
"unitProv",
".",
"SetUnitStatus",
"(",
"unit",
",",
"unitData",
".",
"Status",
")",
"\n",
"_",
",",
"isNotFound",
":=",
"err",
".",
"(",
"*",
"provision",
".",
"UnitNotFoundError",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"isNotFound",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"result",
"[",
"i",
"]",
"=",
"UpdateUnitsResult",
"{",
"ID",
":",
"unitData",
".",
"ID",
",",
"Found",
":",
"!",
"isNotFound",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// UpdateNodeStatus updates the status of the given node and its units,
// returning a map which units were found during the update.
|
[
"UpdateNodeStatus",
"updates",
"the",
"status",
"of",
"the",
"given",
"node",
"and",
"its",
"units",
"returning",
"a",
"map",
"which",
"units",
"were",
"found",
"during",
"the",
"update",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L942-L983
|
test
|
tsuru/tsuru
|
app/app.go
|
available
|
func (app *App) available() bool {
units, err := app.Units()
if err != nil {
return false
}
for _, unit := range units {
if unit.Available() {
return true
}
}
return false
}
|
go
|
func (app *App) available() bool {
units, err := app.Units()
if err != nil {
return false
}
for _, unit := range units {
if unit.Available() {
return true
}
}
return false
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"available",
"(",
")",
"bool",
"{",
"units",
",",
"err",
":=",
"app",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"_",
",",
"unit",
":=",
"range",
"units",
"{",
"if",
"unit",
".",
"Available",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// available returns true if at least one of N units is started or unreachable.
|
[
"available",
"returns",
"true",
"if",
"at",
"least",
"one",
"of",
"N",
"units",
"is",
"started",
"or",
"unreachable",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L986-L997
|
test
|
tsuru/tsuru
|
app/app.go
|
Grant
|
func (app *App) Grant(team *authTypes.Team) error {
if _, found := app.findTeam(team); found {
return ErrAlreadyHaveAccess
}
app.Teams = append(app.Teams, team.Name)
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
if err != nil {
return err
}
users, err := auth.ListUsersWithPermissions(permission.Permission{
Scheme: permission.PermAppDeploy,
Context: permission.Context(permTypes.CtxTeam, team.Name),
})
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
return err
}
for _, user := range users {
err = repository.Manager().GrantAccess(app.Name, user.Email)
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
return err
}
}
return nil
}
|
go
|
func (app *App) Grant(team *authTypes.Team) error {
if _, found := app.findTeam(team); found {
return ErrAlreadyHaveAccess
}
app.Teams = append(app.Teams, team.Name)
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
if err != nil {
return err
}
users, err := auth.ListUsersWithPermissions(permission.Permission{
Scheme: permission.PermAppDeploy,
Context: permission.Context(permTypes.CtxTeam, team.Name),
})
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
return err
}
for _, user := range users {
err = repository.Manager().GrantAccess(app.Name, user.Email)
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
return err
}
}
return nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"Grant",
"(",
"team",
"*",
"authTypes",
".",
"Team",
")",
"error",
"{",
"if",
"_",
",",
"found",
":=",
"app",
".",
"findTeam",
"(",
"team",
")",
";",
"found",
"{",
"return",
"ErrAlreadyHaveAccess",
"\n",
"}",
"\n",
"app",
".",
"Teams",
"=",
"append",
"(",
"app",
".",
"Teams",
",",
"team",
".",
"Name",
")",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$addToSet\"",
":",
"bson",
".",
"M",
"{",
"\"teams\"",
":",
"team",
".",
"Name",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"users",
",",
"err",
":=",
"auth",
".",
"ListUsersWithPermissions",
"(",
"permission",
".",
"Permission",
"{",
"Scheme",
":",
"permission",
".",
"PermAppDeploy",
",",
"Context",
":",
"permission",
".",
"Context",
"(",
"permTypes",
".",
"CtxTeam",
",",
"team",
".",
"Name",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$pull\"",
":",
"bson",
".",
"M",
"{",
"\"teams\"",
":",
"team",
".",
"Name",
"}",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"user",
":=",
"range",
"users",
"{",
"err",
"=",
"repository",
".",
"Manager",
"(",
")",
".",
"GrantAccess",
"(",
"app",
".",
"Name",
",",
"user",
".",
"Email",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$pull\"",
":",
"bson",
".",
"M",
"{",
"\"teams\"",
":",
"team",
".",
"Name",
"}",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Grant allows a team to have access to an app. It returns an error if the
// team already have access to the app.
|
[
"Grant",
"allows",
"a",
"team",
"to",
"have",
"access",
"to",
"an",
"app",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"team",
"already",
"have",
"access",
"to",
"the",
"app",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1010-L1040
|
test
|
tsuru/tsuru
|
app/app.go
|
Revoke
|
func (app *App) Revoke(team *authTypes.Team) error {
if len(app.Teams) == 1 {
return ErrCannotOrphanApp
}
index, found := app.findTeam(team)
if !found {
return ErrNoAccess
}
last := len(app.Teams) - 1
app.Teams[index] = app.Teams[last]
app.Teams = app.Teams[:last]
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
if err != nil {
return err
}
users, err := auth.ListUsersWithPermissions(permission.Permission{
Scheme: permission.PermAppDeploy,
Context: permission.Context(permTypes.CtxTeam, team.Name),
})
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
return err
}
for _, user := range users {
perms, err := user.Permissions()
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
return err
}
canDeploy := permission.CheckFromPermList(perms, permission.PermAppDeploy,
append(permission.Contexts(permTypes.CtxTeam, app.Teams),
permission.Context(permTypes.CtxApp, app.Name),
permission.Context(permTypes.CtxPool, app.Pool),
)...,
)
if canDeploy {
continue
}
err = repository.Manager().RevokeAccess(app.Name, user.Email)
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
return err
}
}
return nil
}
|
go
|
func (app *App) Revoke(team *authTypes.Team) error {
if len(app.Teams) == 1 {
return ErrCannotOrphanApp
}
index, found := app.findTeam(team)
if !found {
return ErrNoAccess
}
last := len(app.Teams) - 1
app.Teams[index] = app.Teams[last]
app.Teams = app.Teams[:last]
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$pull": bson.M{"teams": team.Name}})
if err != nil {
return err
}
users, err := auth.ListUsersWithPermissions(permission.Permission{
Scheme: permission.PermAppDeploy,
Context: permission.Context(permTypes.CtxTeam, team.Name),
})
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
return err
}
for _, user := range users {
perms, err := user.Permissions()
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
return err
}
canDeploy := permission.CheckFromPermList(perms, permission.PermAppDeploy,
append(permission.Contexts(permTypes.CtxTeam, app.Teams),
permission.Context(permTypes.CtxApp, app.Name),
permission.Context(permTypes.CtxPool, app.Pool),
)...,
)
if canDeploy {
continue
}
err = repository.Manager().RevokeAccess(app.Name, user.Email)
if err != nil {
conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$addToSet": bson.M{"teams": team.Name}})
return err
}
}
return nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"Revoke",
"(",
"team",
"*",
"authTypes",
".",
"Team",
")",
"error",
"{",
"if",
"len",
"(",
"app",
".",
"Teams",
")",
"==",
"1",
"{",
"return",
"ErrCannotOrphanApp",
"\n",
"}",
"\n",
"index",
",",
"found",
":=",
"app",
".",
"findTeam",
"(",
"team",
")",
"\n",
"if",
"!",
"found",
"{",
"return",
"ErrNoAccess",
"\n",
"}",
"\n",
"last",
":=",
"len",
"(",
"app",
".",
"Teams",
")",
"-",
"1",
"\n",
"app",
".",
"Teams",
"[",
"index",
"]",
"=",
"app",
".",
"Teams",
"[",
"last",
"]",
"\n",
"app",
".",
"Teams",
"=",
"app",
".",
"Teams",
"[",
":",
"last",
"]",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$pull\"",
":",
"bson",
".",
"M",
"{",
"\"teams\"",
":",
"team",
".",
"Name",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"users",
",",
"err",
":=",
"auth",
".",
"ListUsersWithPermissions",
"(",
"permission",
".",
"Permission",
"{",
"Scheme",
":",
"permission",
".",
"PermAppDeploy",
",",
"Context",
":",
"permission",
".",
"Context",
"(",
"permTypes",
".",
"CtxTeam",
",",
"team",
".",
"Name",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$addToSet\"",
":",
"bson",
".",
"M",
"{",
"\"teams\"",
":",
"team",
".",
"Name",
"}",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"user",
":=",
"range",
"users",
"{",
"perms",
",",
"err",
":=",
"user",
".",
"Permissions",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$addToSet\"",
":",
"bson",
".",
"M",
"{",
"\"teams\"",
":",
"team",
".",
"Name",
"}",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"canDeploy",
":=",
"permission",
".",
"CheckFromPermList",
"(",
"perms",
",",
"permission",
".",
"PermAppDeploy",
",",
"append",
"(",
"permission",
".",
"Contexts",
"(",
"permTypes",
".",
"CtxTeam",
",",
"app",
".",
"Teams",
")",
",",
"permission",
".",
"Context",
"(",
"permTypes",
".",
"CtxApp",
",",
"app",
".",
"Name",
")",
",",
"permission",
".",
"Context",
"(",
"permTypes",
".",
"CtxPool",
",",
"app",
".",
"Pool",
")",
",",
")",
"...",
",",
")",
"\n",
"if",
"canDeploy",
"{",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"repository",
".",
"Manager",
"(",
")",
".",
"RevokeAccess",
"(",
"app",
".",
"Name",
",",
"user",
".",
"Email",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$addToSet\"",
":",
"bson",
".",
"M",
"{",
"\"teams\"",
":",
"team",
".",
"Name",
"}",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Revoke removes the access from a team. It returns an error if the team do
// not have access to the app.
|
[
"Revoke",
"removes",
"the",
"access",
"from",
"a",
"team",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"team",
"do",
"not",
"have",
"access",
"to",
"the",
"app",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1044-L1094
|
test
|
tsuru/tsuru
|
app/app.go
|
GetTeams
|
func (app *App) GetTeams() []authTypes.Team {
t, _ := servicemanager.Team.FindByNames(app.Teams)
return t
}
|
go
|
func (app *App) GetTeams() []authTypes.Team {
t, _ := servicemanager.Team.FindByNames(app.Teams)
return t
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"GetTeams",
"(",
")",
"[",
"]",
"authTypes",
".",
"Team",
"{",
"t",
",",
"_",
":=",
"servicemanager",
".",
"Team",
".",
"FindByNames",
"(",
"app",
".",
"Teams",
")",
"\n",
"return",
"t",
"\n",
"}"
] |
// GetTeams returns a slice of teams that have access to the app.
|
[
"GetTeams",
"returns",
"a",
"slice",
"of",
"teams",
"that",
"have",
"access",
"to",
"the",
"app",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1097-L1100
|
test
|
tsuru/tsuru
|
app/app.go
|
setEnv
|
func (app *App) setEnv(env bind.EnvVar) {
if app.Env == nil {
app.Env = make(map[string]bind.EnvVar)
}
app.Env[env.Name] = env
if env.Public {
app.Log(fmt.Sprintf("setting env %s with value %s", env.Name, env.Value), "tsuru", "api")
}
}
|
go
|
func (app *App) setEnv(env bind.EnvVar) {
if app.Env == nil {
app.Env = make(map[string]bind.EnvVar)
}
app.Env[env.Name] = env
if env.Public {
app.Log(fmt.Sprintf("setting env %s with value %s", env.Name, env.Value), "tsuru", "api")
}
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"setEnv",
"(",
"env",
"bind",
".",
"EnvVar",
")",
"{",
"if",
"app",
".",
"Env",
"==",
"nil",
"{",
"app",
".",
"Env",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bind",
".",
"EnvVar",
")",
"\n",
"}",
"\n",
"app",
".",
"Env",
"[",
"env",
".",
"Name",
"]",
"=",
"env",
"\n",
"if",
"env",
".",
"Public",
"{",
"app",
".",
"Log",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"setting env %s with value %s\"",
",",
"env",
".",
"Name",
",",
"env",
".",
"Value",
")",
",",
"\"tsuru\"",
",",
"\"api\"",
")",
"\n",
"}",
"\n",
"}"
] |
// setEnv sets the given environment variable in the app.
|
[
"setEnv",
"sets",
"the",
"given",
"environment",
"variable",
"in",
"the",
"app",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1153-L1161
|
test
|
tsuru/tsuru
|
app/app.go
|
getEnv
|
func (app *App) getEnv(name string) (bind.EnvVar, error) {
if env, ok := app.Env[name]; ok {
return env, nil
}
return bind.EnvVar{}, errors.New("Environment variable not declared for this app.")
}
|
go
|
func (app *App) getEnv(name string) (bind.EnvVar, error) {
if env, ok := app.Env[name]; ok {
return env, nil
}
return bind.EnvVar{}, errors.New("Environment variable not declared for this app.")
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"getEnv",
"(",
"name",
"string",
")",
"(",
"bind",
".",
"EnvVar",
",",
"error",
")",
"{",
"if",
"env",
",",
"ok",
":=",
"app",
".",
"Env",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"env",
",",
"nil",
"\n",
"}",
"\n",
"return",
"bind",
".",
"EnvVar",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"Environment variable not declared for this app.\"",
")",
"\n",
"}"
] |
// getEnv returns the environment variable if it's declared in the app. It will
// return an error if the variable is not defined in this app.
|
[
"getEnv",
"returns",
"the",
"environment",
"variable",
"if",
"it",
"s",
"declared",
"in",
"the",
"app",
".",
"It",
"will",
"return",
"an",
"error",
"if",
"the",
"variable",
"is",
"not",
"defined",
"in",
"this",
"app",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1165-L1170
|
test
|
tsuru/tsuru
|
app/app.go
|
validateNew
|
func (app *App) validateNew() error {
if app.Name == InternalAppName || !validation.ValidateName(app.Name) {
msg := "Invalid app name, your app should have at most 40 " +
"characters, containing only lower case letters, numbers or dashes, " +
"starting with a letter."
return &tsuruErrors.ValidationError{Message: msg}
}
return app.validate()
}
|
go
|
func (app *App) validateNew() error {
if app.Name == InternalAppName || !validation.ValidateName(app.Name) {
msg := "Invalid app name, your app should have at most 40 " +
"characters, containing only lower case letters, numbers or dashes, " +
"starting with a letter."
return &tsuruErrors.ValidationError{Message: msg}
}
return app.validate()
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"validateNew",
"(",
")",
"error",
"{",
"if",
"app",
".",
"Name",
"==",
"InternalAppName",
"||",
"!",
"validation",
".",
"ValidateName",
"(",
"app",
".",
"Name",
")",
"{",
"msg",
":=",
"\"Invalid app name, your app should have at most 40 \"",
"+",
"\"characters, containing only lower case letters, numbers or dashes, \"",
"+",
"\"starting with a letter.\"",
"\n",
"return",
"&",
"tsuruErrors",
".",
"ValidationError",
"{",
"Message",
":",
"msg",
"}",
"\n",
"}",
"\n",
"return",
"app",
".",
"validate",
"(",
")",
"\n",
"}"
] |
// validateNew checks app name format, pool and plan
|
[
"validateNew",
"checks",
"app",
"name",
"format",
"pool",
"and",
"plan"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1173-L1181
|
test
|
tsuru/tsuru
|
app/app.go
|
validate
|
func (app *App) validate() error {
err := app.validatePool()
if err != nil {
return err
}
return app.validatePlan()
}
|
go
|
func (app *App) validate() error {
err := app.validatePool()
if err != nil {
return err
}
return app.validatePlan()
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"validate",
"(",
")",
"error",
"{",
"err",
":=",
"app",
".",
"validatePool",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"app",
".",
"validatePlan",
"(",
")",
"\n",
"}"
] |
// validate checks app pool and plan
|
[
"validate",
"checks",
"app",
"pool",
"and",
"plan"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1184-L1190
|
test
|
tsuru/tsuru
|
app/app.go
|
InstanceEnvs
|
func (app *App) InstanceEnvs(serviceName, instanceName string) map[string]bind.EnvVar {
envs := make(map[string]bind.EnvVar)
for _, env := range app.ServiceEnvs {
if env.ServiceName == serviceName && env.InstanceName == instanceName {
envs[env.Name] = env.EnvVar
}
}
return envs
}
|
go
|
func (app *App) InstanceEnvs(serviceName, instanceName string) map[string]bind.EnvVar {
envs := make(map[string]bind.EnvVar)
for _, env := range app.ServiceEnvs {
if env.ServiceName == serviceName && env.InstanceName == instanceName {
envs[env.Name] = env.EnvVar
}
}
return envs
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"InstanceEnvs",
"(",
"serviceName",
",",
"instanceName",
"string",
")",
"map",
"[",
"string",
"]",
"bind",
".",
"EnvVar",
"{",
"envs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bind",
".",
"EnvVar",
")",
"\n",
"for",
"_",
",",
"env",
":=",
"range",
"app",
".",
"ServiceEnvs",
"{",
"if",
"env",
".",
"ServiceName",
"==",
"serviceName",
"&&",
"env",
".",
"InstanceName",
"==",
"instanceName",
"{",
"envs",
"[",
"env",
".",
"Name",
"]",
"=",
"env",
".",
"EnvVar",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"envs",
"\n",
"}"
] |
// InstanceEnvs returns a map of environment variables that belongs to the
// given service and service instance.
|
[
"InstanceEnvs",
"returns",
"a",
"map",
"of",
"environment",
"variables",
"that",
"belongs",
"to",
"the",
"given",
"service",
"and",
"service",
"instance",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1282-L1290
|
test
|
tsuru/tsuru
|
app/app.go
|
Run
|
func (app *App) Run(cmd string, w io.Writer, args provision.RunArgs) error {
if !args.Isolated && !app.available() {
return errors.New("App must be available to run non-isolated commands")
}
app.Log(fmt.Sprintf("running '%s'", cmd), "tsuru", "api")
logWriter := LogWriter{App: app, Source: "app-run"}
logWriter.Async()
defer logWriter.Close()
return app.run(cmd, io.MultiWriter(w, &logWriter), args)
}
|
go
|
func (app *App) Run(cmd string, w io.Writer, args provision.RunArgs) error {
if !args.Isolated && !app.available() {
return errors.New("App must be available to run non-isolated commands")
}
app.Log(fmt.Sprintf("running '%s'", cmd), "tsuru", "api")
logWriter := LogWriter{App: app, Source: "app-run"}
logWriter.Async()
defer logWriter.Close()
return app.run(cmd, io.MultiWriter(w, &logWriter), args)
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"Run",
"(",
"cmd",
"string",
",",
"w",
"io",
".",
"Writer",
",",
"args",
"provision",
".",
"RunArgs",
")",
"error",
"{",
"if",
"!",
"args",
".",
"Isolated",
"&&",
"!",
"app",
".",
"available",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"App must be available to run non-isolated commands\"",
")",
"\n",
"}",
"\n",
"app",
".",
"Log",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"running '%s'\"",
",",
"cmd",
")",
",",
"\"tsuru\"",
",",
"\"api\"",
")",
"\n",
"logWriter",
":=",
"LogWriter",
"{",
"App",
":",
"app",
",",
"Source",
":",
"\"app-run\"",
"}",
"\n",
"logWriter",
".",
"Async",
"(",
")",
"\n",
"defer",
"logWriter",
".",
"Close",
"(",
")",
"\n",
"return",
"app",
".",
"run",
"(",
"cmd",
",",
"io",
".",
"MultiWriter",
"(",
"w",
",",
"&",
"logWriter",
")",
",",
"args",
")",
"\n",
"}"
] |
// Run executes the command in app units, sourcing apprc before running the
// command.
|
[
"Run",
"executes",
"the",
"command",
"in",
"app",
"units",
"sourcing",
"apprc",
"before",
"running",
"the",
"command",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1294-L1303
|
test
|
tsuru/tsuru
|
app/app.go
|
GetUnits
|
func (app *App) GetUnits() ([]bind.Unit, error) {
provUnits, err := app.Units()
if err != nil {
return nil, err
}
units := make([]bind.Unit, len(provUnits))
for i := range provUnits {
units[i] = &provUnits[i]
}
return units, nil
}
|
go
|
func (app *App) GetUnits() ([]bind.Unit, error) {
provUnits, err := app.Units()
if err != nil {
return nil, err
}
units := make([]bind.Unit, len(provUnits))
for i := range provUnits {
units[i] = &provUnits[i]
}
return units, nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"GetUnits",
"(",
")",
"(",
"[",
"]",
"bind",
".",
"Unit",
",",
"error",
")",
"{",
"provUnits",
",",
"err",
":=",
"app",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"units",
":=",
"make",
"(",
"[",
"]",
"bind",
".",
"Unit",
",",
"len",
"(",
"provUnits",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"provUnits",
"{",
"units",
"[",
"i",
"]",
"=",
"&",
"provUnits",
"[",
"i",
"]",
"\n",
"}",
"\n",
"return",
"units",
",",
"nil",
"\n",
"}"
] |
// GetUnits returns the internal list of units converted to bind.Unit.
|
[
"GetUnits",
"returns",
"the",
"internal",
"list",
"of",
"units",
"converted",
"to",
"bind",
".",
"Unit",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1431-L1441
|
test
|
tsuru/tsuru
|
app/app.go
|
GetUUID
|
func (app *App) GetUUID() (string, error) {
if app.UUID != "" {
return app.UUID, nil
}
uuidV4, err := uuid.NewV4()
if err != nil {
return "", errors.WithMessage(err, "failed to generate uuid v4")
}
conn, err := db.Conn()
if err != nil {
return "", err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$set": bson.M{"uuid": uuidV4.String()}})
if err != nil {
return "", err
}
app.UUID = uuidV4.String()
return app.UUID, nil
}
|
go
|
func (app *App) GetUUID() (string, error) {
if app.UUID != "" {
return app.UUID, nil
}
uuidV4, err := uuid.NewV4()
if err != nil {
return "", errors.WithMessage(err, "failed to generate uuid v4")
}
conn, err := db.Conn()
if err != nil {
return "", err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$set": bson.M{"uuid": uuidV4.String()}})
if err != nil {
return "", err
}
app.UUID = uuidV4.String()
return app.UUID, nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"GetUUID",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"app",
".",
"UUID",
"!=",
"\"\"",
"{",
"return",
"app",
".",
"UUID",
",",
"nil",
"\n",
"}",
"\n",
"uuidV4",
",",
"err",
":=",
"uuid",
".",
"NewV4",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errors",
".",
"WithMessage",
"(",
"err",
",",
"\"failed to generate uuid v4\"",
")",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$set\"",
":",
"bson",
".",
"M",
"{",
"\"uuid\"",
":",
"uuidV4",
".",
"String",
"(",
")",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"app",
".",
"UUID",
"=",
"uuidV4",
".",
"String",
"(",
")",
"\n",
"return",
"app",
".",
"UUID",
",",
"nil",
"\n",
"}"
] |
// GetUUID returns the app v4 UUID. An UUID will be generated
// if it does not exist.
|
[
"GetUUID",
"returns",
"the",
"app",
"v4",
"UUID",
".",
"An",
"UUID",
"will",
"be",
"generated",
"if",
"it",
"does",
"not",
"exist",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1450-L1469
|
test
|
tsuru/tsuru
|
app/app.go
|
Envs
|
func (app *App) Envs() map[string]bind.EnvVar {
mergedEnvs := make(map[string]bind.EnvVar, len(app.Env)+len(app.ServiceEnvs)+1)
for _, e := range app.Env {
mergedEnvs[e.Name] = e
}
for _, e := range app.ServiceEnvs {
mergedEnvs[e.Name] = e.EnvVar
}
mergedEnvs[TsuruServicesEnvVar] = serviceEnvsFromEnvVars(app.ServiceEnvs)
return mergedEnvs
}
|
go
|
func (app *App) Envs() map[string]bind.EnvVar {
mergedEnvs := make(map[string]bind.EnvVar, len(app.Env)+len(app.ServiceEnvs)+1)
for _, e := range app.Env {
mergedEnvs[e.Name] = e
}
for _, e := range app.ServiceEnvs {
mergedEnvs[e.Name] = e.EnvVar
}
mergedEnvs[TsuruServicesEnvVar] = serviceEnvsFromEnvVars(app.ServiceEnvs)
return mergedEnvs
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"Envs",
"(",
")",
"map",
"[",
"string",
"]",
"bind",
".",
"EnvVar",
"{",
"mergedEnvs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bind",
".",
"EnvVar",
",",
"len",
"(",
"app",
".",
"Env",
")",
"+",
"len",
"(",
"app",
".",
"ServiceEnvs",
")",
"+",
"1",
")",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"app",
".",
"Env",
"{",
"mergedEnvs",
"[",
"e",
".",
"Name",
"]",
"=",
"e",
"\n",
"}",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"app",
".",
"ServiceEnvs",
"{",
"mergedEnvs",
"[",
"e",
".",
"Name",
"]",
"=",
"e",
".",
"EnvVar",
"\n",
"}",
"\n",
"mergedEnvs",
"[",
"TsuruServicesEnvVar",
"]",
"=",
"serviceEnvsFromEnvVars",
"(",
"app",
".",
"ServiceEnvs",
")",
"\n",
"return",
"mergedEnvs",
"\n",
"}"
] |
// Envs returns a map representing the apps environment variables.
|
[
"Envs",
"returns",
"a",
"map",
"representing",
"the",
"apps",
"environment",
"variables",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1554-L1564
|
test
|
tsuru/tsuru
|
app/app.go
|
SetEnvs
|
func (app *App) SetEnvs(setEnvs bind.SetEnvArgs) error {
if len(setEnvs.Envs) == 0 {
return nil
}
for _, env := range setEnvs.Envs {
err := validateEnv(env.Name)
if err != nil {
return err
}
}
if setEnvs.Writer != nil {
fmt.Fprintf(setEnvs.Writer, "---- Setting %d new environment variables ----\n", len(setEnvs.Envs))
}
for _, env := range setEnvs.Envs {
app.setEnv(env)
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$set": bson.M{"env": app.Env}})
if err != nil {
return err
}
if setEnvs.ShouldRestart {
return app.restartIfUnits(setEnvs.Writer)
}
return nil
}
|
go
|
func (app *App) SetEnvs(setEnvs bind.SetEnvArgs) error {
if len(setEnvs.Envs) == 0 {
return nil
}
for _, env := range setEnvs.Envs {
err := validateEnv(env.Name)
if err != nil {
return err
}
}
if setEnvs.Writer != nil {
fmt.Fprintf(setEnvs.Writer, "---- Setting %d new environment variables ----\n", len(setEnvs.Envs))
}
for _, env := range setEnvs.Envs {
app.setEnv(env)
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$set": bson.M{"env": app.Env}})
if err != nil {
return err
}
if setEnvs.ShouldRestart {
return app.restartIfUnits(setEnvs.Writer)
}
return nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"SetEnvs",
"(",
"setEnvs",
"bind",
".",
"SetEnvArgs",
")",
"error",
"{",
"if",
"len",
"(",
"setEnvs",
".",
"Envs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"env",
":=",
"range",
"setEnvs",
".",
"Envs",
"{",
"err",
":=",
"validateEnv",
"(",
"env",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"setEnvs",
".",
"Writer",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"setEnvs",
".",
"Writer",
",",
"\"---- Setting %d new environment variables ----\\n\"",
",",
"\\n",
")",
"\n",
"}",
"\n",
"len",
"(",
"setEnvs",
".",
"Envs",
")",
"\n",
"for",
"_",
",",
"env",
":=",
"range",
"setEnvs",
".",
"Envs",
"{",
"app",
".",
"setEnv",
"(",
"env",
")",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$set\"",
":",
"bson",
".",
"M",
"{",
"\"env\"",
":",
"app",
".",
"Env",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"setEnvs",
".",
"ShouldRestart",
"{",
"return",
"app",
".",
"restartIfUnits",
"(",
"setEnvs",
".",
"Writer",
")",
"\n",
"}",
"\n",
"}"
] |
// SetEnvs saves a list of environment variables in the app.
|
[
"SetEnvs",
"saves",
"a",
"list",
"of",
"environment",
"variables",
"in",
"the",
"app",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1567-L1596
|
test
|
tsuru/tsuru
|
app/app.go
|
UnsetEnvs
|
func (app *App) UnsetEnvs(unsetEnvs bind.UnsetEnvArgs) error {
if len(unsetEnvs.VariableNames) == 0 {
return nil
}
if unsetEnvs.Writer != nil {
fmt.Fprintf(unsetEnvs.Writer, "---- Unsetting %d environment variables ----\n", len(unsetEnvs.VariableNames))
}
for _, name := range unsetEnvs.VariableNames {
delete(app.Env, name)
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$set": bson.M{"env": app.Env}})
if err != nil {
return err
}
if unsetEnvs.ShouldRestart {
return app.restartIfUnits(unsetEnvs.Writer)
}
return nil
}
|
go
|
func (app *App) UnsetEnvs(unsetEnvs bind.UnsetEnvArgs) error {
if len(unsetEnvs.VariableNames) == 0 {
return nil
}
if unsetEnvs.Writer != nil {
fmt.Fprintf(unsetEnvs.Writer, "---- Unsetting %d environment variables ----\n", len(unsetEnvs.VariableNames))
}
for _, name := range unsetEnvs.VariableNames {
delete(app.Env, name)
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
err = conn.Apps().Update(bson.M{"name": app.Name}, bson.M{"$set": bson.M{"env": app.Env}})
if err != nil {
return err
}
if unsetEnvs.ShouldRestart {
return app.restartIfUnits(unsetEnvs.Writer)
}
return nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"UnsetEnvs",
"(",
"unsetEnvs",
"bind",
".",
"UnsetEnvArgs",
")",
"error",
"{",
"if",
"len",
"(",
"unsetEnvs",
".",
"VariableNames",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"unsetEnvs",
".",
"Writer",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"unsetEnvs",
".",
"Writer",
",",
"\"---- Unsetting %d environment variables ----\\n\"",
",",
"\\n",
")",
"\n",
"}",
"\n",
"len",
"(",
"unsetEnvs",
".",
"VariableNames",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"unsetEnvs",
".",
"VariableNames",
"{",
"delete",
"(",
"app",
".",
"Env",
",",
"name",
")",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$set\"",
":",
"bson",
".",
"M",
"{",
"\"env\"",
":",
"app",
".",
"Env",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"unsetEnvs",
".",
"ShouldRestart",
"{",
"return",
"app",
".",
"restartIfUnits",
"(",
"unsetEnvs",
".",
"Writer",
")",
"\n",
"}",
"\n",
"}"
] |
// UnsetEnvs removes environment variables from an app, serializing the
// remaining list of environment variables to all units of the app.
|
[
"UnsetEnvs",
"removes",
"environment",
"variables",
"from",
"an",
"app",
"serializing",
"the",
"remaining",
"list",
"of",
"environment",
"variables",
"to",
"all",
"units",
"of",
"the",
"app",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1600-L1623
|
test
|
tsuru/tsuru
|
app/app.go
|
AddCName
|
func (app *App) AddCName(cnames ...string) error {
actions := []*action.Action{
&validateNewCNames,
&setNewCNamesToProvisioner,
&saveCNames,
&updateApp,
}
err := action.NewPipeline(actions...).Execute(app, cnames)
rebuild.RoutesRebuildOrEnqueue(app.Name)
return err
}
|
go
|
func (app *App) AddCName(cnames ...string) error {
actions := []*action.Action{
&validateNewCNames,
&setNewCNamesToProvisioner,
&saveCNames,
&updateApp,
}
err := action.NewPipeline(actions...).Execute(app, cnames)
rebuild.RoutesRebuildOrEnqueue(app.Name)
return err
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"AddCName",
"(",
"cnames",
"...",
"string",
")",
"error",
"{",
"actions",
":=",
"[",
"]",
"*",
"action",
".",
"Action",
"{",
"&",
"validateNewCNames",
",",
"&",
"setNewCNamesToProvisioner",
",",
"&",
"saveCNames",
",",
"&",
"updateApp",
",",
"}",
"\n",
"err",
":=",
"action",
".",
"NewPipeline",
"(",
"actions",
"...",
")",
".",
"Execute",
"(",
"app",
",",
"cnames",
")",
"\n",
"rebuild",
".",
"RoutesRebuildOrEnqueue",
"(",
"app",
".",
"Name",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// AddCName adds a CName to app. It updates the attribute,
// calls the SetCName function on the provisioner and saves
// the app in the database, returning an error when it cannot save the change
// in the database or add the CName on the provisioner.
|
[
"AddCName",
"adds",
"a",
"CName",
"to",
"app",
".",
"It",
"updates",
"the",
"attribute",
"calls",
"the",
"SetCName",
"function",
"on",
"the",
"provisioner",
"and",
"saves",
"the",
"app",
"in",
"the",
"database",
"returning",
"an",
"error",
"when",
"it",
"cannot",
"save",
"the",
"change",
"in",
"the",
"database",
"or",
"add",
"the",
"CName",
"on",
"the",
"provisioner",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1644-L1654
|
test
|
tsuru/tsuru
|
app/app.go
|
Log
|
func (app *App) Log(message, source, unit string) error {
messages := strings.Split(message, "\n")
logs := make([]interface{}, 0, len(messages))
for _, msg := range messages {
if msg != "" {
l := Applog{
Date: time.Now().In(time.UTC),
Message: msg,
Source: source,
AppName: app.Name,
Unit: unit,
}
logs = append(logs, l)
}
}
if len(logs) > 0 {
conn, err := db.LogConn()
if err != nil {
return err
}
defer conn.Close()
return conn.AppLogCollection(app.Name).Insert(logs...)
}
return nil
}
|
go
|
func (app *App) Log(message, source, unit string) error {
messages := strings.Split(message, "\n")
logs := make([]interface{}, 0, len(messages))
for _, msg := range messages {
if msg != "" {
l := Applog{
Date: time.Now().In(time.UTC),
Message: msg,
Source: source,
AppName: app.Name,
Unit: unit,
}
logs = append(logs, l)
}
}
if len(logs) > 0 {
conn, err := db.LogConn()
if err != nil {
return err
}
defer conn.Close()
return conn.AppLogCollection(app.Name).Insert(logs...)
}
return nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"Log",
"(",
"message",
",",
"source",
",",
"unit",
"string",
")",
"error",
"{",
"messages",
":=",
"strings",
".",
"Split",
"(",
"message",
",",
"\"\\n\"",
")",
"\n",
"\\n",
"\n",
"logs",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"len",
"(",
"messages",
")",
")",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"messages",
"{",
"if",
"msg",
"!=",
"\"\"",
"{",
"l",
":=",
"Applog",
"{",
"Date",
":",
"time",
".",
"Now",
"(",
")",
".",
"In",
"(",
"time",
".",
"UTC",
")",
",",
"Message",
":",
"msg",
",",
"Source",
":",
"source",
",",
"AppName",
":",
"app",
".",
"Name",
",",
"Unit",
":",
"unit",
",",
"}",
"\n",
"logs",
"=",
"append",
"(",
"logs",
",",
"l",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"logs",
")",
">",
"0",
"{",
"conn",
",",
"err",
":=",
"db",
".",
"LogConn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"conn",
".",
"AppLogCollection",
"(",
"app",
".",
"Name",
")",
".",
"Insert",
"(",
"logs",
"...",
")",
"\n",
"}",
"\n",
"}"
] |
// Log adds a log message to the app. Specifying a good source is good so the
// user can filter where the message come from.
|
[
"Log",
"adds",
"a",
"log",
"message",
"to",
"the",
"app",
".",
"Specifying",
"a",
"good",
"source",
"is",
"good",
"so",
"the",
"user",
"can",
"filter",
"where",
"the",
"message",
"come",
"from",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1754-L1778
|
test
|
tsuru/tsuru
|
app/app.go
|
LastLogs
|
func (app *App) LastLogs(lines int, filterLog Applog) ([]Applog, error) {
return app.lastLogs(lines, filterLog, false)
}
|
go
|
func (app *App) LastLogs(lines int, filterLog Applog) ([]Applog, error) {
return app.lastLogs(lines, filterLog, false)
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"LastLogs",
"(",
"lines",
"int",
",",
"filterLog",
"Applog",
")",
"(",
"[",
"]",
"Applog",
",",
"error",
")",
"{",
"return",
"app",
".",
"lastLogs",
"(",
"lines",
",",
"filterLog",
",",
"false",
")",
"\n",
"}"
] |
// LastLogs returns a list of the last `lines` log of the app, matching the
// fields in the log instance received as an example.
|
[
"LastLogs",
"returns",
"a",
"list",
"of",
"the",
"last",
"lines",
"log",
"of",
"the",
"app",
"matching",
"the",
"fields",
"in",
"the",
"log",
"instance",
"received",
"as",
"an",
"example",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1782-L1784
|
test
|
tsuru/tsuru
|
app/app.go
|
List
|
func List(filter *Filter) ([]App, error) {
apps := []App{}
query := filter.Query()
conn, err := db.Conn()
if err != nil {
return nil, err
}
err = conn.Apps().Find(query).All(&apps)
conn.Close()
if err != nil {
return nil, err
}
if filter != nil && len(filter.Statuses) > 0 {
appsProvisionerMap := make(map[string][]provision.App)
var prov provision.Provisioner
for i := range apps {
a := &apps[i]
prov, err = a.getProvisioner()
if err != nil {
return nil, err
}
appsProvisionerMap[prov.GetName()] = append(appsProvisionerMap[prov.GetName()], a)
}
var provisionApps []provision.App
for provName, apps := range appsProvisionerMap {
prov, err = provision.Get(provName)
if err != nil {
return nil, err
}
if filterProv, ok := prov.(provision.AppFilterProvisioner); ok {
apps, err = filterProv.FilterAppsByUnitStatus(apps, filter.Statuses)
if err != nil {
return nil, err
}
}
provisionApps = append(provisionApps, apps...)
}
for i := range provisionApps {
apps[i] = *(provisionApps[i].(*App))
}
apps = apps[:len(provisionApps)]
}
err = loadCachedAddrsInApps(apps)
if err != nil {
return nil, err
}
return apps, nil
}
|
go
|
func List(filter *Filter) ([]App, error) {
apps := []App{}
query := filter.Query()
conn, err := db.Conn()
if err != nil {
return nil, err
}
err = conn.Apps().Find(query).All(&apps)
conn.Close()
if err != nil {
return nil, err
}
if filter != nil && len(filter.Statuses) > 0 {
appsProvisionerMap := make(map[string][]provision.App)
var prov provision.Provisioner
for i := range apps {
a := &apps[i]
prov, err = a.getProvisioner()
if err != nil {
return nil, err
}
appsProvisionerMap[prov.GetName()] = append(appsProvisionerMap[prov.GetName()], a)
}
var provisionApps []provision.App
for provName, apps := range appsProvisionerMap {
prov, err = provision.Get(provName)
if err != nil {
return nil, err
}
if filterProv, ok := prov.(provision.AppFilterProvisioner); ok {
apps, err = filterProv.FilterAppsByUnitStatus(apps, filter.Statuses)
if err != nil {
return nil, err
}
}
provisionApps = append(provisionApps, apps...)
}
for i := range provisionApps {
apps[i] = *(provisionApps[i].(*App))
}
apps = apps[:len(provisionApps)]
}
err = loadCachedAddrsInApps(apps)
if err != nil {
return nil, err
}
return apps, nil
}
|
[
"func",
"List",
"(",
"filter",
"*",
"Filter",
")",
"(",
"[",
"]",
"App",
",",
"error",
")",
"{",
"apps",
":=",
"[",
"]",
"App",
"{",
"}",
"\n",
"query",
":=",
"filter",
".",
"Query",
"(",
")",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"conn",
".",
"Apps",
"(",
")",
".",
"Find",
"(",
"query",
")",
".",
"All",
"(",
"&",
"apps",
")",
"\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"filter",
"!=",
"nil",
"&&",
"len",
"(",
"filter",
".",
"Statuses",
")",
">",
"0",
"{",
"appsProvisionerMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"provision",
".",
"App",
")",
"\n",
"var",
"prov",
"provision",
".",
"Provisioner",
"\n",
"for",
"i",
":=",
"range",
"apps",
"{",
"a",
":=",
"&",
"apps",
"[",
"i",
"]",
"\n",
"prov",
",",
"err",
"=",
"a",
".",
"getProvisioner",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"appsProvisionerMap",
"[",
"prov",
".",
"GetName",
"(",
")",
"]",
"=",
"append",
"(",
"appsProvisionerMap",
"[",
"prov",
".",
"GetName",
"(",
")",
"]",
",",
"a",
")",
"\n",
"}",
"\n",
"var",
"provisionApps",
"[",
"]",
"provision",
".",
"App",
"\n",
"for",
"provName",
",",
"apps",
":=",
"range",
"appsProvisionerMap",
"{",
"prov",
",",
"err",
"=",
"provision",
".",
"Get",
"(",
"provName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"filterProv",
",",
"ok",
":=",
"prov",
".",
"(",
"provision",
".",
"AppFilterProvisioner",
")",
";",
"ok",
"{",
"apps",
",",
"err",
"=",
"filterProv",
".",
"FilterAppsByUnitStatus",
"(",
"apps",
",",
"filter",
".",
"Statuses",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"provisionApps",
"=",
"append",
"(",
"provisionApps",
",",
"apps",
"...",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"provisionApps",
"{",
"apps",
"[",
"i",
"]",
"=",
"*",
"(",
"provisionApps",
"[",
"i",
"]",
".",
"(",
"*",
"App",
")",
")",
"\n",
"}",
"\n",
"apps",
"=",
"apps",
"[",
":",
"len",
"(",
"provisionApps",
")",
"]",
"\n",
"}",
"\n",
"err",
"=",
"loadCachedAddrsInApps",
"(",
"apps",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"apps",
",",
"nil",
"\n",
"}"
] |
// List returns the list of apps filtered through the filter parameter.
|
[
"List",
"returns",
"the",
"list",
"of",
"apps",
"filtered",
"through",
"the",
"filter",
"parameter",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1975-L2022
|
test
|
tsuru/tsuru
|
app/app.go
|
Swap
|
func Swap(app1, app2 *App, cnameOnly bool) error {
a1Routers := app1.GetRouters()
a2Routers := app2.GetRouters()
if len(a1Routers) != 1 || len(a2Routers) != 1 {
return errors.New("swapping apps with multiple routers is not supported")
}
r1, err := router.Get(a1Routers[0].Name)
if err != nil {
return err
}
r2, err := router.Get(a2Routers[0].Name)
if err != nil {
return err
}
defer func(app1, app2 *App) {
rebuild.RoutesRebuildOrEnqueue(app1.Name)
rebuild.RoutesRebuildOrEnqueue(app2.Name)
app1.GetRoutersWithAddr()
app2.GetRoutersWithAddr()
}(app1, app2)
err = r1.Swap(app1.Name, app2.Name, cnameOnly)
if err != nil {
return err
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
app1.CName, app2.CName = app2.CName, app1.CName
updateCName := func(app *App, r router.Router) error {
return conn.Apps().Update(
bson.M{"name": app.Name},
bson.M{"$set": bson.M{"cname": app.CName}},
)
}
err = updateCName(app1, r1)
if err != nil {
return err
}
return updateCName(app2, r2)
}
|
go
|
func Swap(app1, app2 *App, cnameOnly bool) error {
a1Routers := app1.GetRouters()
a2Routers := app2.GetRouters()
if len(a1Routers) != 1 || len(a2Routers) != 1 {
return errors.New("swapping apps with multiple routers is not supported")
}
r1, err := router.Get(a1Routers[0].Name)
if err != nil {
return err
}
r2, err := router.Get(a2Routers[0].Name)
if err != nil {
return err
}
defer func(app1, app2 *App) {
rebuild.RoutesRebuildOrEnqueue(app1.Name)
rebuild.RoutesRebuildOrEnqueue(app2.Name)
app1.GetRoutersWithAddr()
app2.GetRoutersWithAddr()
}(app1, app2)
err = r1.Swap(app1.Name, app2.Name, cnameOnly)
if err != nil {
return err
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
app1.CName, app2.CName = app2.CName, app1.CName
updateCName := func(app *App, r router.Router) error {
return conn.Apps().Update(
bson.M{"name": app.Name},
bson.M{"$set": bson.M{"cname": app.CName}},
)
}
err = updateCName(app1, r1)
if err != nil {
return err
}
return updateCName(app2, r2)
}
|
[
"func",
"Swap",
"(",
"app1",
",",
"app2",
"*",
"App",
",",
"cnameOnly",
"bool",
")",
"error",
"{",
"a1Routers",
":=",
"app1",
".",
"GetRouters",
"(",
")",
"\n",
"a2Routers",
":=",
"app2",
".",
"GetRouters",
"(",
")",
"\n",
"if",
"len",
"(",
"a1Routers",
")",
"!=",
"1",
"||",
"len",
"(",
"a2Routers",
")",
"!=",
"1",
"{",
"return",
"errors",
".",
"New",
"(",
"\"swapping apps with multiple routers is not supported\"",
")",
"\n",
"}",
"\n",
"r1",
",",
"err",
":=",
"router",
".",
"Get",
"(",
"a1Routers",
"[",
"0",
"]",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"r2",
",",
"err",
":=",
"router",
".",
"Get",
"(",
"a2Routers",
"[",
"0",
"]",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
"app1",
",",
"app2",
"*",
"App",
")",
"{",
"rebuild",
".",
"RoutesRebuildOrEnqueue",
"(",
"app1",
".",
"Name",
")",
"\n",
"rebuild",
".",
"RoutesRebuildOrEnqueue",
"(",
"app2",
".",
"Name",
")",
"\n",
"app1",
".",
"GetRoutersWithAddr",
"(",
")",
"\n",
"app2",
".",
"GetRoutersWithAddr",
"(",
")",
"\n",
"}",
"(",
"app1",
",",
"app2",
")",
"\n",
"err",
"=",
"r1",
".",
"Swap",
"(",
"app1",
".",
"Name",
",",
"app2",
".",
"Name",
",",
"cnameOnly",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Conn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"app1",
".",
"CName",
",",
"app2",
".",
"CName",
"=",
"app2",
".",
"CName",
",",
"app1",
".",
"CName",
"\n",
"updateCName",
":=",
"func",
"(",
"app",
"*",
"App",
",",
"r",
"router",
".",
"Router",
")",
"error",
"{",
"return",
"conn",
".",
"Apps",
"(",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"app",
".",
"Name",
"}",
",",
"bson",
".",
"M",
"{",
"\"$set\"",
":",
"bson",
".",
"M",
"{",
"\"cname\"",
":",
"app",
".",
"CName",
"}",
"}",
",",
")",
"\n",
"}",
"\n",
"err",
"=",
"updateCName",
"(",
"app1",
",",
"r1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"updateCName",
"(",
"app2",
",",
"r2",
")",
"\n",
"}"
] |
// Swap calls the Router.Swap and updates the app.CName in the database.
|
[
"Swap",
"calls",
"the",
"Router",
".",
"Swap",
"and",
"updates",
"the",
"app",
".",
"CName",
"in",
"the",
"database",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L2063-L2104
|
test
|
tsuru/tsuru
|
app/app.go
|
Start
|
func (app *App) Start(w io.Writer, process string) error {
w = app.withLogWriter(w)
msg := fmt.Sprintf("\n ---> Starting the process %q", process)
if process == "" {
msg = fmt.Sprintf("\n ---> Starting the app %q", app.Name)
}
fmt.Fprintf(w, "%s\n", msg)
prov, err := app.getProvisioner()
if err != nil {
return err
}
err = prov.Start(app, process)
if err != nil {
log.Errorf("[start] error on start the app %s - %s", app.Name, err)
return err
}
rebuild.RoutesRebuildOrEnqueue(app.Name)
return err
}
|
go
|
func (app *App) Start(w io.Writer, process string) error {
w = app.withLogWriter(w)
msg := fmt.Sprintf("\n ---> Starting the process %q", process)
if process == "" {
msg = fmt.Sprintf("\n ---> Starting the app %q", app.Name)
}
fmt.Fprintf(w, "%s\n", msg)
prov, err := app.getProvisioner()
if err != nil {
return err
}
err = prov.Start(app, process)
if err != nil {
log.Errorf("[start] error on start the app %s - %s", app.Name, err)
return err
}
rebuild.RoutesRebuildOrEnqueue(app.Name)
return err
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"Start",
"(",
"w",
"io",
".",
"Writer",
",",
"process",
"string",
")",
"error",
"{",
"w",
"=",
"app",
".",
"withLogWriter",
"(",
"w",
")",
"\n",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"\\n -",
",",
"\\n",
")",
"\n",
"process",
"\n",
"if",
"process",
"==",
"\"\"",
"{",
"msg",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"\\n -",
",",
"\\n",
")",
"\n",
"}",
"\n",
"app",
".",
"Name",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"%s\\n\"",
",",
"\\n",
")",
"\n",
"msg",
"\n",
"prov",
",",
"err",
":=",
"app",
".",
"getProvisioner",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"prov",
".",
"Start",
"(",
"app",
",",
"process",
")",
"\n",
"}"
] |
// Start starts the app calling the provisioner.Start method and
// changing the units state to StatusStarted.
|
[
"Start",
"starts",
"the",
"app",
"calling",
"the",
"provisioner",
".",
"Start",
"method",
"and",
"changing",
"the",
"units",
"state",
"to",
"StatusStarted",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L2108-L2126
|
test
|
tsuru/tsuru
|
storage/driver.go
|
GetDbDriver
|
func GetDbDriver(name string) (*DbDriver, error) {
driver, ok := dbDrivers[name]
if !ok {
return nil, errors.Errorf("Unknown database driver: %q.", name)
}
return &driver, nil
}
|
go
|
func GetDbDriver(name string) (*DbDriver, error) {
driver, ok := dbDrivers[name]
if !ok {
return nil, errors.Errorf("Unknown database driver: %q.", name)
}
return &driver, nil
}
|
[
"func",
"GetDbDriver",
"(",
"name",
"string",
")",
"(",
"*",
"DbDriver",
",",
"error",
")",
"{",
"driver",
",",
"ok",
":=",
"dbDrivers",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"Unknown database driver: %q.\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"&",
"driver",
",",
"nil",
"\n",
"}"
] |
// GetDbDriver returns the DB driver that was registered with a specific name
|
[
"GetDbDriver",
"returns",
"the",
"DB",
"driver",
"that",
"was",
"registered",
"with",
"a",
"specific",
"name"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/storage/driver.go#L50-L56
|
test
|
tsuru/tsuru
|
storage/driver.go
|
GetCurrentDbDriver
|
func GetCurrentDbDriver() (*DbDriver, error) {
driverLock.RLock()
if currentDbDriver != nil {
driverLock.RUnlock()
return currentDbDriver, nil
}
driverLock.RUnlock()
driverLock.Lock()
defer driverLock.Unlock()
if currentDbDriver != nil {
return currentDbDriver, nil
}
dbDriverName, err := config.GetString("database:driver")
if err != nil || dbDriverName == "" {
dbDriverName = DefaultDbDriverName
}
currentDbDriver, err = GetDbDriver(dbDriverName)
if err != nil {
return nil, err
}
return currentDbDriver, nil
}
|
go
|
func GetCurrentDbDriver() (*DbDriver, error) {
driverLock.RLock()
if currentDbDriver != nil {
driverLock.RUnlock()
return currentDbDriver, nil
}
driverLock.RUnlock()
driverLock.Lock()
defer driverLock.Unlock()
if currentDbDriver != nil {
return currentDbDriver, nil
}
dbDriverName, err := config.GetString("database:driver")
if err != nil || dbDriverName == "" {
dbDriverName = DefaultDbDriverName
}
currentDbDriver, err = GetDbDriver(dbDriverName)
if err != nil {
return nil, err
}
return currentDbDriver, nil
}
|
[
"func",
"GetCurrentDbDriver",
"(",
")",
"(",
"*",
"DbDriver",
",",
"error",
")",
"{",
"driverLock",
".",
"RLock",
"(",
")",
"\n",
"if",
"currentDbDriver",
"!=",
"nil",
"{",
"driverLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"currentDbDriver",
",",
"nil",
"\n",
"}",
"\n",
"driverLock",
".",
"RUnlock",
"(",
")",
"\n",
"driverLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"driverLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"currentDbDriver",
"!=",
"nil",
"{",
"return",
"currentDbDriver",
",",
"nil",
"\n",
"}",
"\n",
"dbDriverName",
",",
"err",
":=",
"config",
".",
"GetString",
"(",
"\"database:driver\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"dbDriverName",
"==",
"\"\"",
"{",
"dbDriverName",
"=",
"DefaultDbDriverName",
"\n",
"}",
"\n",
"currentDbDriver",
",",
"err",
"=",
"GetDbDriver",
"(",
"dbDriverName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"currentDbDriver",
",",
"nil",
"\n",
"}"
] |
// GetCurrentDbDriver returns the DB driver specified in the configuration file.
// If this configuration was omitted, it returns the default DB driver
|
[
"GetCurrentDbDriver",
"returns",
"the",
"DB",
"driver",
"specified",
"in",
"the",
"configuration",
"file",
".",
"If",
"this",
"configuration",
"was",
"omitted",
"it",
"returns",
"the",
"default",
"DB",
"driver"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/storage/driver.go#L60-L81
|
test
|
tsuru/tsuru
|
provision/kubernetes/pkg/client/clientset/versioned/clientset.go
|
NewForConfig
|
func NewForConfig(c *rest.Config) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset
var err error
cs.tsuruV1, err = tsuruv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
if err != nil {
glog.Errorf("failed to create the DiscoveryClient: %v", err)
return nil, err
}
return &cs, nil
}
|
go
|
func NewForConfig(c *rest.Config) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset
var err error
cs.tsuruV1, err = tsuruv1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
if err != nil {
glog.Errorf("failed to create the DiscoveryClient: %v", err)
return nil, err
}
return &cs, nil
}
|
[
"func",
"NewForConfig",
"(",
"c",
"*",
"rest",
".",
"Config",
")",
"(",
"*",
"Clientset",
",",
"error",
")",
"{",
"configShallowCopy",
":=",
"*",
"c",
"\n",
"if",
"configShallowCopy",
".",
"RateLimiter",
"==",
"nil",
"&&",
"configShallowCopy",
".",
"QPS",
">",
"0",
"{",
"configShallowCopy",
".",
"RateLimiter",
"=",
"flowcontrol",
".",
"NewTokenBucketRateLimiter",
"(",
"configShallowCopy",
".",
"QPS",
",",
"configShallowCopy",
".",
"Burst",
")",
"\n",
"}",
"\n",
"var",
"cs",
"Clientset",
"\n",
"var",
"err",
"error",
"\n",
"cs",
".",
"tsuruV1",
",",
"err",
"=",
"tsuruv1",
".",
"NewForConfig",
"(",
"&",
"configShallowCopy",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cs",
".",
"DiscoveryClient",
",",
"err",
"=",
"discovery",
".",
"NewDiscoveryClientForConfig",
"(",
"&",
"configShallowCopy",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"glog",
".",
"Errorf",
"(",
"\"failed to create the DiscoveryClient: %v\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"cs",
",",
"nil",
"\n",
"}"
] |
// NewForConfig creates a new Clientset for the given config.
|
[
"NewForConfig",
"creates",
"a",
"new",
"Clientset",
"for",
"the",
"given",
"config",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/clientset.go#L51-L69
|
test
|
tsuru/tsuru
|
provision/docker/provisioner.go
|
GetAppFromUnitID
|
func (p *dockerProvisioner) GetAppFromUnitID(unitID string) (provision.App, error) {
cnt, err := p.GetContainer(unitID)
if err != nil {
return nil, err
}
a, err := app.GetByName(cnt.AppName)
if err != nil {
return nil, err
}
return a, nil
}
|
go
|
func (p *dockerProvisioner) GetAppFromUnitID(unitID string) (provision.App, error) {
cnt, err := p.GetContainer(unitID)
if err != nil {
return nil, err
}
a, err := app.GetByName(cnt.AppName)
if err != nil {
return nil, err
}
return a, nil
}
|
[
"func",
"(",
"p",
"*",
"dockerProvisioner",
")",
"GetAppFromUnitID",
"(",
"unitID",
"string",
")",
"(",
"provision",
".",
"App",
",",
"error",
")",
"{",
"cnt",
",",
"err",
":=",
"p",
".",
"GetContainer",
"(",
"unitID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"a",
",",
"err",
":=",
"app",
".",
"GetByName",
"(",
"cnt",
".",
"AppName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] |
// GetAppFromUnitID returns app from unit id
|
[
"GetAppFromUnitID",
"returns",
"app",
"from",
"unit",
"id"
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/docker/provisioner.go#L760-L770
|
test
|
tsuru/tsuru
|
action/action.go
|
NewPipeline
|
func NewPipeline(actions ...*Action) *Pipeline {
// Actions are usually global functions, copying them
// guarantees each copy has an isolated Result.
newActions := make([]*Action, len(actions))
for i, action := range actions {
newAction := &Action{
Name: action.Name,
Forward: action.Forward,
Backward: action.Backward,
MinParams: action.MinParams,
OnError: action.OnError,
}
newActions[i] = newAction
}
return &Pipeline{actions: newActions}
}
|
go
|
func NewPipeline(actions ...*Action) *Pipeline {
// Actions are usually global functions, copying them
// guarantees each copy has an isolated Result.
newActions := make([]*Action, len(actions))
for i, action := range actions {
newAction := &Action{
Name: action.Name,
Forward: action.Forward,
Backward: action.Backward,
MinParams: action.MinParams,
OnError: action.OnError,
}
newActions[i] = newAction
}
return &Pipeline{actions: newActions}
}
|
[
"func",
"NewPipeline",
"(",
"actions",
"...",
"*",
"Action",
")",
"*",
"Pipeline",
"{",
"newActions",
":=",
"make",
"(",
"[",
"]",
"*",
"Action",
",",
"len",
"(",
"actions",
")",
")",
"\n",
"for",
"i",
",",
"action",
":=",
"range",
"actions",
"{",
"newAction",
":=",
"&",
"Action",
"{",
"Name",
":",
"action",
".",
"Name",
",",
"Forward",
":",
"action",
".",
"Forward",
",",
"Backward",
":",
"action",
".",
"Backward",
",",
"MinParams",
":",
"action",
".",
"MinParams",
",",
"OnError",
":",
"action",
".",
"OnError",
",",
"}",
"\n",
"newActions",
"[",
"i",
"]",
"=",
"newAction",
"\n",
"}",
"\n",
"return",
"&",
"Pipeline",
"{",
"actions",
":",
"newActions",
"}",
"\n",
"}"
] |
// NewPipeline creates a new pipeline instance with the given list of actions.
|
[
"NewPipeline",
"creates",
"a",
"new",
"pipeline",
"instance",
"with",
"the",
"given",
"list",
"of",
"actions",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/action/action.go#L98-L114
|
test
|
tsuru/tsuru
|
action/action.go
|
Result
|
func (p *Pipeline) Result() Result {
action := p.actions[len(p.actions)-1]
action.rMutex.Lock()
defer action.rMutex.Unlock()
return action.result
}
|
go
|
func (p *Pipeline) Result() Result {
action := p.actions[len(p.actions)-1]
action.rMutex.Lock()
defer action.rMutex.Unlock()
return action.result
}
|
[
"func",
"(",
"p",
"*",
"Pipeline",
")",
"Result",
"(",
")",
"Result",
"{",
"action",
":=",
"p",
".",
"actions",
"[",
"len",
"(",
"p",
".",
"actions",
")",
"-",
"1",
"]",
"\n",
"action",
".",
"rMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"action",
".",
"rMutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"action",
".",
"result",
"\n",
"}"
] |
// Result returns the result of the last action.
|
[
"Result",
"returns",
"the",
"result",
"of",
"the",
"last",
"action",
"."
] |
2f7fd515c5dc25a58aec80f0e497c49e49581b3e
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/action/action.go#L117-L122
|
test
|
ant0ine/go-json-rest
|
rest/request.go
|
DecodeJsonPayload
|
func (r *Request) DecodeJsonPayload(v interface{}) error {
content, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
if len(content) == 0 {
return ErrJsonPayloadEmpty
}
err = json.Unmarshal(content, v)
if err != nil {
return err
}
return nil
}
|
go
|
func (r *Request) DecodeJsonPayload(v interface{}) error {
content, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
if len(content) == 0 {
return ErrJsonPayloadEmpty
}
err = json.Unmarshal(content, v)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"Request",
")",
"DecodeJsonPayload",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"content",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"content",
")",
"==",
"0",
"{",
"return",
"ErrJsonPayloadEmpty",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"content",
",",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DecodeJsonPayload reads the request body and decodes the JSON using json.Unmarshal.
|
[
"DecodeJsonPayload",
"reads",
"the",
"request",
"body",
"and",
"decodes",
"the",
"JSON",
"using",
"json",
".",
"Unmarshal",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/request.go#L34-L48
|
test
|
ant0ine/go-json-rest
|
rest/request.go
|
UrlFor
|
func (r *Request) UrlFor(path string, queryParams map[string][]string) *url.URL {
baseUrl := r.BaseUrl()
baseUrl.Path = path
if queryParams != nil {
query := url.Values{}
for k, v := range queryParams {
for _, vv := range v {
query.Add(k, vv)
}
}
baseUrl.RawQuery = query.Encode()
}
return baseUrl
}
|
go
|
func (r *Request) UrlFor(path string, queryParams map[string][]string) *url.URL {
baseUrl := r.BaseUrl()
baseUrl.Path = path
if queryParams != nil {
query := url.Values{}
for k, v := range queryParams {
for _, vv := range v {
query.Add(k, vv)
}
}
baseUrl.RawQuery = query.Encode()
}
return baseUrl
}
|
[
"func",
"(",
"r",
"*",
"Request",
")",
"UrlFor",
"(",
"path",
"string",
",",
"queryParams",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"*",
"url",
".",
"URL",
"{",
"baseUrl",
":=",
"r",
".",
"BaseUrl",
"(",
")",
"\n",
"baseUrl",
".",
"Path",
"=",
"path",
"\n",
"if",
"queryParams",
"!=",
"nil",
"{",
"query",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"queryParams",
"{",
"for",
"_",
",",
"vv",
":=",
"range",
"v",
"{",
"query",
".",
"Add",
"(",
"k",
",",
"vv",
")",
"\n",
"}",
"\n",
"}",
"\n",
"baseUrl",
".",
"RawQuery",
"=",
"query",
".",
"Encode",
"(",
")",
"\n",
"}",
"\n",
"return",
"baseUrl",
"\n",
"}"
] |
// UrlFor returns the URL object from UriBase with the Path set to path, and the query
// string built with queryParams.
|
[
"UrlFor",
"returns",
"the",
"URL",
"object",
"from",
"UriBase",
"with",
"the",
"Path",
"set",
"to",
"path",
"and",
"the",
"query",
"string",
"built",
"with",
"queryParams",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/request.go#L77-L90
|
test
|
ant0ine/go-json-rest
|
rest/request.go
|
GetCorsInfo
|
func (r *Request) GetCorsInfo() *CorsInfo {
origin := r.Header.Get("Origin")
var originUrl *url.URL
var isCors bool
if origin == "" {
isCors = false
} else if origin == "null" {
isCors = true
} else {
var err error
originUrl, err = url.ParseRequestURI(origin)
isCors = err == nil && r.Host != originUrl.Host
}
reqMethod := r.Header.Get("Access-Control-Request-Method")
reqHeaders := []string{}
rawReqHeaders := r.Header[http.CanonicalHeaderKey("Access-Control-Request-Headers")]
for _, rawReqHeader := range rawReqHeaders {
if len(rawReqHeader) == 0 {
continue
}
// net/http does not handle comma delimited headers for us
for _, reqHeader := range strings.Split(rawReqHeader, ",") {
reqHeaders = append(reqHeaders, http.CanonicalHeaderKey(strings.TrimSpace(reqHeader)))
}
}
isPreflight := isCors && r.Method == "OPTIONS" && reqMethod != ""
return &CorsInfo{
IsCors: isCors,
IsPreflight: isPreflight,
Origin: origin,
OriginUrl: originUrl,
AccessControlRequestMethod: strings.ToUpper(reqMethod),
AccessControlRequestHeaders: reqHeaders,
}
}
|
go
|
func (r *Request) GetCorsInfo() *CorsInfo {
origin := r.Header.Get("Origin")
var originUrl *url.URL
var isCors bool
if origin == "" {
isCors = false
} else if origin == "null" {
isCors = true
} else {
var err error
originUrl, err = url.ParseRequestURI(origin)
isCors = err == nil && r.Host != originUrl.Host
}
reqMethod := r.Header.Get("Access-Control-Request-Method")
reqHeaders := []string{}
rawReqHeaders := r.Header[http.CanonicalHeaderKey("Access-Control-Request-Headers")]
for _, rawReqHeader := range rawReqHeaders {
if len(rawReqHeader) == 0 {
continue
}
// net/http does not handle comma delimited headers for us
for _, reqHeader := range strings.Split(rawReqHeader, ",") {
reqHeaders = append(reqHeaders, http.CanonicalHeaderKey(strings.TrimSpace(reqHeader)))
}
}
isPreflight := isCors && r.Method == "OPTIONS" && reqMethod != ""
return &CorsInfo{
IsCors: isCors,
IsPreflight: isPreflight,
Origin: origin,
OriginUrl: originUrl,
AccessControlRequestMethod: strings.ToUpper(reqMethod),
AccessControlRequestHeaders: reqHeaders,
}
}
|
[
"func",
"(",
"r",
"*",
"Request",
")",
"GetCorsInfo",
"(",
")",
"*",
"CorsInfo",
"{",
"origin",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"Origin\"",
")",
"\n",
"var",
"originUrl",
"*",
"url",
".",
"URL",
"\n",
"var",
"isCors",
"bool",
"\n",
"if",
"origin",
"==",
"\"\"",
"{",
"isCors",
"=",
"false",
"\n",
"}",
"else",
"if",
"origin",
"==",
"\"null\"",
"{",
"isCors",
"=",
"true",
"\n",
"}",
"else",
"{",
"var",
"err",
"error",
"\n",
"originUrl",
",",
"err",
"=",
"url",
".",
"ParseRequestURI",
"(",
"origin",
")",
"\n",
"isCors",
"=",
"err",
"==",
"nil",
"&&",
"r",
".",
"Host",
"!=",
"originUrl",
".",
"Host",
"\n",
"}",
"\n",
"reqMethod",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"Access-Control-Request-Method\"",
")",
"\n",
"reqHeaders",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"rawReqHeaders",
":=",
"r",
".",
"Header",
"[",
"http",
".",
"CanonicalHeaderKey",
"(",
"\"Access-Control-Request-Headers\"",
")",
"]",
"\n",
"for",
"_",
",",
"rawReqHeader",
":=",
"range",
"rawReqHeaders",
"{",
"if",
"len",
"(",
"rawReqHeader",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"reqHeader",
":=",
"range",
"strings",
".",
"Split",
"(",
"rawReqHeader",
",",
"\",\"",
")",
"{",
"reqHeaders",
"=",
"append",
"(",
"reqHeaders",
",",
"http",
".",
"CanonicalHeaderKey",
"(",
"strings",
".",
"TrimSpace",
"(",
"reqHeader",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"isPreflight",
":=",
"isCors",
"&&",
"r",
".",
"Method",
"==",
"\"OPTIONS\"",
"&&",
"reqMethod",
"!=",
"\"\"",
"\n",
"return",
"&",
"CorsInfo",
"{",
"IsCors",
":",
"isCors",
",",
"IsPreflight",
":",
"isPreflight",
",",
"Origin",
":",
"origin",
",",
"OriginUrl",
":",
"originUrl",
",",
"AccessControlRequestMethod",
":",
"strings",
".",
"ToUpper",
"(",
"reqMethod",
")",
",",
"AccessControlRequestHeaders",
":",
"reqHeaders",
",",
"}",
"\n",
"}"
] |
// GetCorsInfo derives CorsInfo from Request.
|
[
"GetCorsInfo",
"derives",
"CorsInfo",
"from",
"Request",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/request.go#L107-L148
|
test
|
ant0ine/go-json-rest
|
rest/cors.go
|
MiddlewareFunc
|
func (mw *CorsMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
// precompute as much as possible at init time
mw.allowedMethods = map[string]bool{}
normedMethods := []string{}
for _, allowedMethod := range mw.AllowedMethods {
normed := strings.ToUpper(allowedMethod)
mw.allowedMethods[normed] = true
normedMethods = append(normedMethods, normed)
}
mw.allowedMethodsCsv = strings.Join(normedMethods, ",")
mw.allowedHeaders = map[string]bool{}
normedHeaders := []string{}
for _, allowedHeader := range mw.AllowedHeaders {
normed := http.CanonicalHeaderKey(allowedHeader)
mw.allowedHeaders[normed] = true
normedHeaders = append(normedHeaders, normed)
}
mw.allowedHeadersCsv = strings.Join(normedHeaders, ",")
return func(writer ResponseWriter, request *Request) {
corsInfo := request.GetCorsInfo()
// non CORS requests
if !corsInfo.IsCors {
if mw.RejectNonCorsRequests {
Error(writer, "Non CORS request", http.StatusForbidden)
return
}
// continue, execute the wrapped middleware
handler(writer, request)
return
}
// Validate the Origin
if mw.OriginValidator(corsInfo.Origin, request) == false {
Error(writer, "Invalid Origin", http.StatusForbidden)
return
}
if corsInfo.IsPreflight {
// check the request methods
if mw.allowedMethods[corsInfo.AccessControlRequestMethod] == false {
Error(writer, "Invalid Preflight Request", http.StatusForbidden)
return
}
// check the request headers
for _, requestedHeader := range corsInfo.AccessControlRequestHeaders {
if mw.allowedHeaders[requestedHeader] == false {
Error(writer, "Invalid Preflight Request", http.StatusForbidden)
return
}
}
writer.Header().Set("Access-Control-Allow-Methods", mw.allowedMethodsCsv)
writer.Header().Set("Access-Control-Allow-Headers", mw.allowedHeadersCsv)
writer.Header().Set("Access-Control-Allow-Origin", corsInfo.Origin)
if mw.AccessControlAllowCredentials == true {
writer.Header().Set("Access-Control-Allow-Credentials", "true")
}
writer.Header().Set("Access-Control-Max-Age", strconv.Itoa(mw.AccessControlMaxAge))
writer.WriteHeader(http.StatusOK)
return
}
// Non-preflight requests
for _, exposed := range mw.AccessControlExposeHeaders {
writer.Header().Add("Access-Control-Expose-Headers", exposed)
}
writer.Header().Set("Access-Control-Allow-Origin", corsInfo.Origin)
if mw.AccessControlAllowCredentials == true {
writer.Header().Set("Access-Control-Allow-Credentials", "true")
}
// continure, execute the wrapped middleware
handler(writer, request)
return
}
}
|
go
|
func (mw *CorsMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
// precompute as much as possible at init time
mw.allowedMethods = map[string]bool{}
normedMethods := []string{}
for _, allowedMethod := range mw.AllowedMethods {
normed := strings.ToUpper(allowedMethod)
mw.allowedMethods[normed] = true
normedMethods = append(normedMethods, normed)
}
mw.allowedMethodsCsv = strings.Join(normedMethods, ",")
mw.allowedHeaders = map[string]bool{}
normedHeaders := []string{}
for _, allowedHeader := range mw.AllowedHeaders {
normed := http.CanonicalHeaderKey(allowedHeader)
mw.allowedHeaders[normed] = true
normedHeaders = append(normedHeaders, normed)
}
mw.allowedHeadersCsv = strings.Join(normedHeaders, ",")
return func(writer ResponseWriter, request *Request) {
corsInfo := request.GetCorsInfo()
// non CORS requests
if !corsInfo.IsCors {
if mw.RejectNonCorsRequests {
Error(writer, "Non CORS request", http.StatusForbidden)
return
}
// continue, execute the wrapped middleware
handler(writer, request)
return
}
// Validate the Origin
if mw.OriginValidator(corsInfo.Origin, request) == false {
Error(writer, "Invalid Origin", http.StatusForbidden)
return
}
if corsInfo.IsPreflight {
// check the request methods
if mw.allowedMethods[corsInfo.AccessControlRequestMethod] == false {
Error(writer, "Invalid Preflight Request", http.StatusForbidden)
return
}
// check the request headers
for _, requestedHeader := range corsInfo.AccessControlRequestHeaders {
if mw.allowedHeaders[requestedHeader] == false {
Error(writer, "Invalid Preflight Request", http.StatusForbidden)
return
}
}
writer.Header().Set("Access-Control-Allow-Methods", mw.allowedMethodsCsv)
writer.Header().Set("Access-Control-Allow-Headers", mw.allowedHeadersCsv)
writer.Header().Set("Access-Control-Allow-Origin", corsInfo.Origin)
if mw.AccessControlAllowCredentials == true {
writer.Header().Set("Access-Control-Allow-Credentials", "true")
}
writer.Header().Set("Access-Control-Max-Age", strconv.Itoa(mw.AccessControlMaxAge))
writer.WriteHeader(http.StatusOK)
return
}
// Non-preflight requests
for _, exposed := range mw.AccessControlExposeHeaders {
writer.Header().Add("Access-Control-Expose-Headers", exposed)
}
writer.Header().Set("Access-Control-Allow-Origin", corsInfo.Origin)
if mw.AccessControlAllowCredentials == true {
writer.Header().Set("Access-Control-Allow-Credentials", "true")
}
// continure, execute the wrapped middleware
handler(writer, request)
return
}
}
|
[
"func",
"(",
"mw",
"*",
"CorsMiddleware",
")",
"MiddlewareFunc",
"(",
"handler",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"mw",
".",
"allowedMethods",
"=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"normedMethods",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"allowedMethod",
":=",
"range",
"mw",
".",
"AllowedMethods",
"{",
"normed",
":=",
"strings",
".",
"ToUpper",
"(",
"allowedMethod",
")",
"\n",
"mw",
".",
"allowedMethods",
"[",
"normed",
"]",
"=",
"true",
"\n",
"normedMethods",
"=",
"append",
"(",
"normedMethods",
",",
"normed",
")",
"\n",
"}",
"\n",
"mw",
".",
"allowedMethodsCsv",
"=",
"strings",
".",
"Join",
"(",
"normedMethods",
",",
"\",\"",
")",
"\n",
"mw",
".",
"allowedHeaders",
"=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"normedHeaders",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"allowedHeader",
":=",
"range",
"mw",
".",
"AllowedHeaders",
"{",
"normed",
":=",
"http",
".",
"CanonicalHeaderKey",
"(",
"allowedHeader",
")",
"\n",
"mw",
".",
"allowedHeaders",
"[",
"normed",
"]",
"=",
"true",
"\n",
"normedHeaders",
"=",
"append",
"(",
"normedHeaders",
",",
"normed",
")",
"\n",
"}",
"\n",
"mw",
".",
"allowedHeadersCsv",
"=",
"strings",
".",
"Join",
"(",
"normedHeaders",
",",
"\",\"",
")",
"\n",
"return",
"func",
"(",
"writer",
"ResponseWriter",
",",
"request",
"*",
"Request",
")",
"{",
"corsInfo",
":=",
"request",
".",
"GetCorsInfo",
"(",
")",
"\n",
"if",
"!",
"corsInfo",
".",
"IsCors",
"{",
"if",
"mw",
".",
"RejectNonCorsRequests",
"{",
"Error",
"(",
"writer",
",",
"\"Non CORS request\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"handler",
"(",
"writer",
",",
"request",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"mw",
".",
"OriginValidator",
"(",
"corsInfo",
".",
"Origin",
",",
"request",
")",
"==",
"false",
"{",
"Error",
"(",
"writer",
",",
"\"Invalid Origin\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"corsInfo",
".",
"IsPreflight",
"{",
"if",
"mw",
".",
"allowedMethods",
"[",
"corsInfo",
".",
"AccessControlRequestMethod",
"]",
"==",
"false",
"{",
"Error",
"(",
"writer",
",",
"\"Invalid Preflight Request\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"requestedHeader",
":=",
"range",
"corsInfo",
".",
"AccessControlRequestHeaders",
"{",
"if",
"mw",
".",
"allowedHeaders",
"[",
"requestedHeader",
"]",
"==",
"false",
"{",
"Error",
"(",
"writer",
",",
"\"Invalid Preflight Request\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Access-Control-Allow-Methods\"",
",",
"mw",
".",
"allowedMethodsCsv",
")",
"\n",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Access-Control-Allow-Headers\"",
",",
"mw",
".",
"allowedHeadersCsv",
")",
"\n",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Access-Control-Allow-Origin\"",
",",
"corsInfo",
".",
"Origin",
")",
"\n",
"if",
"mw",
".",
"AccessControlAllowCredentials",
"==",
"true",
"{",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Access-Control-Allow-Credentials\"",
",",
"\"true\"",
")",
"\n",
"}",
"\n",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Access-Control-Max-Age\"",
",",
"strconv",
".",
"Itoa",
"(",
"mw",
".",
"AccessControlMaxAge",
")",
")",
"\n",
"writer",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"exposed",
":=",
"range",
"mw",
".",
"AccessControlExposeHeaders",
"{",
"writer",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"Access-Control-Expose-Headers\"",
",",
"exposed",
")",
"\n",
"}",
"\n",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Access-Control-Allow-Origin\"",
",",
"corsInfo",
".",
"Origin",
")",
"\n",
"if",
"mw",
".",
"AccessControlAllowCredentials",
"==",
"true",
"{",
"writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Access-Control-Allow-Credentials\"",
",",
"\"true\"",
")",
"\n",
"}",
"\n",
"handler",
"(",
"writer",
",",
"request",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes CorsMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"CorsMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/cors.go#L53-L135
|
test
|
ant0ine/go-json-rest
|
rest/recorder.go
|
MiddlewareFunc
|
func (mw *RecorderMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
writer := &recorderResponseWriter{w, 0, false, 0}
// call the handler
h(writer, r)
r.Env["STATUS_CODE"] = writer.statusCode
r.Env["BYTES_WRITTEN"] = writer.bytesWritten
}
}
|
go
|
func (mw *RecorderMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
writer := &recorderResponseWriter{w, 0, false, 0}
// call the handler
h(writer, r)
r.Env["STATUS_CODE"] = writer.statusCode
r.Env["BYTES_WRITTEN"] = writer.bytesWritten
}
}
|
[
"func",
"(",
"mw",
"*",
"RecorderMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"writer",
":=",
"&",
"recorderResponseWriter",
"{",
"w",
",",
"0",
",",
"false",
",",
"0",
"}",
"\n",
"h",
"(",
"writer",
",",
"r",
")",
"\n",
"r",
".",
"Env",
"[",
"\"STATUS_CODE\"",
"]",
"=",
"writer",
".",
"statusCode",
"\n",
"r",
".",
"Env",
"[",
"\"BYTES_WRITTEN\"",
"]",
"=",
"writer",
".",
"bytesWritten",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes RecorderMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"RecorderMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/recorder.go#L16-L27
|
test
|
ant0ine/go-json-rest
|
rest/recorder.go
|
WriteHeader
|
func (w *recorderResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
if w.wroteHeader {
return
}
w.statusCode = code
w.wroteHeader = true
}
|
go
|
func (w *recorderResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
if w.wroteHeader {
return
}
w.statusCode = code
w.wroteHeader = true
}
|
[
"func",
"(",
"w",
"*",
"recorderResponseWriter",
")",
"WriteHeader",
"(",
"code",
"int",
")",
"{",
"w",
".",
"ResponseWriter",
".",
"WriteHeader",
"(",
"code",
")",
"\n",
"if",
"w",
".",
"wroteHeader",
"{",
"return",
"\n",
"}",
"\n",
"w",
".",
"statusCode",
"=",
"code",
"\n",
"w",
".",
"wroteHeader",
"=",
"true",
"\n",
"}"
] |
// Record the status code.
|
[
"Record",
"the",
"status",
"code",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/recorder.go#L45-L52
|
test
|
ant0ine/go-json-rest
|
rest/router.go
|
MakeRouter
|
func MakeRouter(routes ...*Route) (App, error) {
r := &router{
Routes: routes,
}
err := r.start()
if err != nil {
return nil, err
}
return r, nil
}
|
go
|
func MakeRouter(routes ...*Route) (App, error) {
r := &router{
Routes: routes,
}
err := r.start()
if err != nil {
return nil, err
}
return r, nil
}
|
[
"func",
"MakeRouter",
"(",
"routes",
"...",
"*",
"Route",
")",
"(",
"App",
",",
"error",
")",
"{",
"r",
":=",
"&",
"router",
"{",
"Routes",
":",
"routes",
",",
"}",
"\n",
"err",
":=",
"r",
".",
"start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] |
// MakeRouter returns the router app. Given a set of Routes, it dispatches the request to the
// HandlerFunc of the first route that matches. The order of the Routes matters.
|
[
"MakeRouter",
"returns",
"the",
"router",
"app",
".",
"Given",
"a",
"set",
"of",
"Routes",
"it",
"dispatches",
"the",
"request",
"to",
"the",
"HandlerFunc",
"of",
"the",
"first",
"route",
"that",
"matches",
".",
"The",
"order",
"of",
"the",
"Routes",
"matters",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L21-L30
|
test
|
ant0ine/go-json-rest
|
rest/router.go
|
AppFunc
|
func (rt *router) AppFunc() HandlerFunc {
return func(writer ResponseWriter, request *Request) {
// find the route
route, params, pathMatched := rt.findRouteFromURL(request.Method, request.URL)
if route == nil {
if pathMatched {
// no route found, but path was matched: 405 Method Not Allowed
Error(writer, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// no route found, the path was not matched: 404 Not Found
NotFound(writer, request)
return
}
// a route was found, set the PathParams
request.PathParams = params
// run the user code
handler := route.Func
handler(writer, request)
}
}
|
go
|
func (rt *router) AppFunc() HandlerFunc {
return func(writer ResponseWriter, request *Request) {
// find the route
route, params, pathMatched := rt.findRouteFromURL(request.Method, request.URL)
if route == nil {
if pathMatched {
// no route found, but path was matched: 405 Method Not Allowed
Error(writer, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// no route found, the path was not matched: 404 Not Found
NotFound(writer, request)
return
}
// a route was found, set the PathParams
request.PathParams = params
// run the user code
handler := route.Func
handler(writer, request)
}
}
|
[
"func",
"(",
"rt",
"*",
"router",
")",
"AppFunc",
"(",
")",
"HandlerFunc",
"{",
"return",
"func",
"(",
"writer",
"ResponseWriter",
",",
"request",
"*",
"Request",
")",
"{",
"route",
",",
"params",
",",
"pathMatched",
":=",
"rt",
".",
"findRouteFromURL",
"(",
"request",
".",
"Method",
",",
"request",
".",
"URL",
")",
"\n",
"if",
"route",
"==",
"nil",
"{",
"if",
"pathMatched",
"{",
"Error",
"(",
"writer",
",",
"\"Method not allowed\"",
",",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"return",
"\n",
"}",
"\n",
"NotFound",
"(",
"writer",
",",
"request",
")",
"\n",
"return",
"\n",
"}",
"\n",
"request",
".",
"PathParams",
"=",
"params",
"\n",
"handler",
":=",
"route",
".",
"Func",
"\n",
"handler",
"(",
"writer",
",",
"request",
")",
"\n",
"}",
"\n",
"}"
] |
// Handle the REST routing and run the user code.
|
[
"Handle",
"the",
"REST",
"routing",
"and",
"run",
"the",
"user",
"code",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L33-L58
|
test
|
ant0ine/go-json-rest
|
rest/router.go
|
escapedPath
|
func escapedPath(urlObj *url.URL) string {
// the escape method of url.URL should be public
// that would avoid this split.
parts := strings.SplitN(urlObj.RequestURI(), "?", 2)
return parts[0]
}
|
go
|
func escapedPath(urlObj *url.URL) string {
// the escape method of url.URL should be public
// that would avoid this split.
parts := strings.SplitN(urlObj.RequestURI(), "?", 2)
return parts[0]
}
|
[
"func",
"escapedPath",
"(",
"urlObj",
"*",
"url",
".",
"URL",
")",
"string",
"{",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"urlObj",
".",
"RequestURI",
"(",
")",
",",
"\"?\"",
",",
"2",
")",
"\n",
"return",
"parts",
"[",
"0",
"]",
"\n",
"}"
] |
// This is run for each new request, perf is important.
|
[
"This",
"is",
"run",
"for",
"each",
"new",
"request",
"perf",
"is",
"important",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L61-L66
|
test
|
ant0ine/go-json-rest
|
rest/router.go
|
escapedPathExp
|
func escapedPathExp(pathExp string) (string, error) {
// PathExp validation
if pathExp == "" {
return "", errors.New("empty PathExp")
}
if pathExp[0] != '/' {
return "", errors.New("PathExp must start with /")
}
if strings.Contains(pathExp, "?") {
return "", errors.New("PathExp must not contain the query string")
}
// Get the right escaping
// XXX a bit hacky
pathExp = preEscape.Replace(pathExp)
urlObj, err := url.Parse(pathExp)
if err != nil {
return "", err
}
// get the same escaping as find requests
pathExp = urlObj.RequestURI()
pathExp = postEscape.Replace(pathExp)
return pathExp, nil
}
|
go
|
func escapedPathExp(pathExp string) (string, error) {
// PathExp validation
if pathExp == "" {
return "", errors.New("empty PathExp")
}
if pathExp[0] != '/' {
return "", errors.New("PathExp must start with /")
}
if strings.Contains(pathExp, "?") {
return "", errors.New("PathExp must not contain the query string")
}
// Get the right escaping
// XXX a bit hacky
pathExp = preEscape.Replace(pathExp)
urlObj, err := url.Parse(pathExp)
if err != nil {
return "", err
}
// get the same escaping as find requests
pathExp = urlObj.RequestURI()
pathExp = postEscape.Replace(pathExp)
return pathExp, nil
}
|
[
"func",
"escapedPathExp",
"(",
"pathExp",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"pathExp",
"==",
"\"\"",
"{",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"empty PathExp\"",
")",
"\n",
"}",
"\n",
"if",
"pathExp",
"[",
"0",
"]",
"!=",
"'/'",
"{",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"PathExp must start with /\"",
")",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"pathExp",
",",
"\"?\"",
")",
"{",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"PathExp must not contain the query string\"",
")",
"\n",
"}",
"\n",
"pathExp",
"=",
"preEscape",
".",
"Replace",
"(",
"pathExp",
")",
"\n",
"urlObj",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"pathExp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"pathExp",
"=",
"urlObj",
".",
"RequestURI",
"(",
")",
"\n",
"pathExp",
"=",
"postEscape",
".",
"Replace",
"(",
"pathExp",
")",
"\n",
"return",
"pathExp",
",",
"nil",
"\n",
"}"
] |
// This is run at init time only.
|
[
"This",
"is",
"run",
"at",
"init",
"time",
"only",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L73-L102
|
test
|
ant0ine/go-json-rest
|
rest/router.go
|
start
|
func (rt *router) start() error {
rt.trie = trie.New()
rt.index = map[*Route]int{}
for i, route := range rt.Routes {
// work with the PathExp urlencoded.
pathExp, err := escapedPathExp(route.PathExp)
if err != nil {
return err
}
// insert in the Trie
err = rt.trie.AddRoute(
strings.ToUpper(route.HttpMethod), // work with the HttpMethod in uppercase
pathExp,
route,
)
if err != nil {
return err
}
// index
rt.index[route] = i
}
if rt.disableTrieCompression == false {
rt.trie.Compress()
}
return nil
}
|
go
|
func (rt *router) start() error {
rt.trie = trie.New()
rt.index = map[*Route]int{}
for i, route := range rt.Routes {
// work with the PathExp urlencoded.
pathExp, err := escapedPathExp(route.PathExp)
if err != nil {
return err
}
// insert in the Trie
err = rt.trie.AddRoute(
strings.ToUpper(route.HttpMethod), // work with the HttpMethod in uppercase
pathExp,
route,
)
if err != nil {
return err
}
// index
rt.index[route] = i
}
if rt.disableTrieCompression == false {
rt.trie.Compress()
}
return nil
}
|
[
"func",
"(",
"rt",
"*",
"router",
")",
"start",
"(",
")",
"error",
"{",
"rt",
".",
"trie",
"=",
"trie",
".",
"New",
"(",
")",
"\n",
"rt",
".",
"index",
"=",
"map",
"[",
"*",
"Route",
"]",
"int",
"{",
"}",
"\n",
"for",
"i",
",",
"route",
":=",
"range",
"rt",
".",
"Routes",
"{",
"pathExp",
",",
"err",
":=",
"escapedPathExp",
"(",
"route",
".",
"PathExp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"rt",
".",
"trie",
".",
"AddRoute",
"(",
"strings",
".",
"ToUpper",
"(",
"route",
".",
"HttpMethod",
")",
",",
"pathExp",
",",
"route",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rt",
".",
"index",
"[",
"route",
"]",
"=",
"i",
"\n",
"}",
"\n",
"if",
"rt",
".",
"disableTrieCompression",
"==",
"false",
"{",
"rt",
".",
"trie",
".",
"Compress",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// This validates the Routes and prepares the Trie data structure.
// It must be called once the Routes are defined and before trying to find Routes.
// The order matters, if multiple Routes match, the first defined will be used.
|
[
"This",
"validates",
"the",
"Routes",
"and",
"prepares",
"the",
"Trie",
"data",
"structure",
".",
"It",
"must",
"be",
"called",
"once",
"the",
"Routes",
"are",
"defined",
"and",
"before",
"trying",
"to",
"find",
"Routes",
".",
"The",
"order",
"matters",
"if",
"multiple",
"Routes",
"match",
"the",
"first",
"defined",
"will",
"be",
"used",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L107-L139
|
test
|
ant0ine/go-json-rest
|
rest/router.go
|
ofFirstDefinedRoute
|
func (rt *router) ofFirstDefinedRoute(matches []*trie.Match) *trie.Match {
minIndex := -1
var bestMatch *trie.Match
for _, result := range matches {
route := result.Route.(*Route)
routeIndex := rt.index[route]
if minIndex == -1 || routeIndex < minIndex {
minIndex = routeIndex
bestMatch = result
}
}
return bestMatch
}
|
go
|
func (rt *router) ofFirstDefinedRoute(matches []*trie.Match) *trie.Match {
minIndex := -1
var bestMatch *trie.Match
for _, result := range matches {
route := result.Route.(*Route)
routeIndex := rt.index[route]
if minIndex == -1 || routeIndex < minIndex {
minIndex = routeIndex
bestMatch = result
}
}
return bestMatch
}
|
[
"func",
"(",
"rt",
"*",
"router",
")",
"ofFirstDefinedRoute",
"(",
"matches",
"[",
"]",
"*",
"trie",
".",
"Match",
")",
"*",
"trie",
".",
"Match",
"{",
"minIndex",
":=",
"-",
"1",
"\n",
"var",
"bestMatch",
"*",
"trie",
".",
"Match",
"\n",
"for",
"_",
",",
"result",
":=",
"range",
"matches",
"{",
"route",
":=",
"result",
".",
"Route",
".",
"(",
"*",
"Route",
")",
"\n",
"routeIndex",
":=",
"rt",
".",
"index",
"[",
"route",
"]",
"\n",
"if",
"minIndex",
"==",
"-",
"1",
"||",
"routeIndex",
"<",
"minIndex",
"{",
"minIndex",
"=",
"routeIndex",
"\n",
"bestMatch",
"=",
"result",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"bestMatch",
"\n",
"}"
] |
// return the result that has the route defined the earliest
|
[
"return",
"the",
"result",
"that",
"has",
"the",
"route",
"defined",
"the",
"earliest"
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L142-L156
|
test
|
ant0ine/go-json-rest
|
rest/router.go
|
findRouteFromURL
|
func (rt *router) findRouteFromURL(httpMethod string, urlObj *url.URL) (*Route, map[string]string, bool) {
// lookup the routes in the Trie
matches, pathMatched := rt.trie.FindRoutesAndPathMatched(
strings.ToUpper(httpMethod), // work with the httpMethod in uppercase
escapedPath(urlObj), // work with the path urlencoded
)
// short cuts
if len(matches) == 0 {
// no route found
return nil, nil, pathMatched
}
if len(matches) == 1 {
// one route found
return matches[0].Route.(*Route), matches[0].Params, pathMatched
}
// multiple routes found, pick the first defined
result := rt.ofFirstDefinedRoute(matches)
return result.Route.(*Route), result.Params, pathMatched
}
|
go
|
func (rt *router) findRouteFromURL(httpMethod string, urlObj *url.URL) (*Route, map[string]string, bool) {
// lookup the routes in the Trie
matches, pathMatched := rt.trie.FindRoutesAndPathMatched(
strings.ToUpper(httpMethod), // work with the httpMethod in uppercase
escapedPath(urlObj), // work with the path urlencoded
)
// short cuts
if len(matches) == 0 {
// no route found
return nil, nil, pathMatched
}
if len(matches) == 1 {
// one route found
return matches[0].Route.(*Route), matches[0].Params, pathMatched
}
// multiple routes found, pick the first defined
result := rt.ofFirstDefinedRoute(matches)
return result.Route.(*Route), result.Params, pathMatched
}
|
[
"func",
"(",
"rt",
"*",
"router",
")",
"findRouteFromURL",
"(",
"httpMethod",
"string",
",",
"urlObj",
"*",
"url",
".",
"URL",
")",
"(",
"*",
"Route",
",",
"map",
"[",
"string",
"]",
"string",
",",
"bool",
")",
"{",
"matches",
",",
"pathMatched",
":=",
"rt",
".",
"trie",
".",
"FindRoutesAndPathMatched",
"(",
"strings",
".",
"ToUpper",
"(",
"httpMethod",
")",
",",
"escapedPath",
"(",
"urlObj",
")",
",",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
",",
"pathMatched",
"\n",
"}",
"\n",
"if",
"len",
"(",
"matches",
")",
"==",
"1",
"{",
"return",
"matches",
"[",
"0",
"]",
".",
"Route",
".",
"(",
"*",
"Route",
")",
",",
"matches",
"[",
"0",
"]",
".",
"Params",
",",
"pathMatched",
"\n",
"}",
"\n",
"result",
":=",
"rt",
".",
"ofFirstDefinedRoute",
"(",
"matches",
")",
"\n",
"return",
"result",
".",
"Route",
".",
"(",
"*",
"Route",
")",
",",
"result",
".",
"Params",
",",
"pathMatched",
"\n",
"}"
] |
// Return the first matching Route and the corresponding parameters for a given URL object.
|
[
"Return",
"the",
"first",
"matching",
"Route",
"and",
"the",
"corresponding",
"parameters",
"for",
"a",
"given",
"URL",
"object",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L159-L181
|
test
|
ant0ine/go-json-rest
|
rest/content_type_checker.go
|
MiddlewareFunc
|
func (mw *ContentTypeCheckerMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
mediatype, params, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
charset, ok := params["charset"]
if !ok {
charset = "UTF-8"
}
// per net/http doc, means that the length is known and non-null
if r.ContentLength > 0 &&
!(mediatype == "application/json" && strings.ToUpper(charset) == "UTF-8") {
Error(w,
"Bad Content-Type or charset, expected 'application/json'",
http.StatusUnsupportedMediaType,
)
return
}
// call the wrapped handler
handler(w, r)
}
}
|
go
|
func (mw *ContentTypeCheckerMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
mediatype, params, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
charset, ok := params["charset"]
if !ok {
charset = "UTF-8"
}
// per net/http doc, means that the length is known and non-null
if r.ContentLength > 0 &&
!(mediatype == "application/json" && strings.ToUpper(charset) == "UTF-8") {
Error(w,
"Bad Content-Type or charset, expected 'application/json'",
http.StatusUnsupportedMediaType,
)
return
}
// call the wrapped handler
handler(w, r)
}
}
|
[
"func",
"(",
"mw",
"*",
"ContentTypeCheckerMiddleware",
")",
"MiddlewareFunc",
"(",
"handler",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"mediatype",
",",
"params",
",",
"_",
":=",
"mime",
".",
"ParseMediaType",
"(",
"r",
".",
"Header",
".",
"Get",
"(",
"\"Content-Type\"",
")",
")",
"\n",
"charset",
",",
"ok",
":=",
"params",
"[",
"\"charset\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"charset",
"=",
"\"UTF-8\"",
"\n",
"}",
"\n",
"if",
"r",
".",
"ContentLength",
">",
"0",
"&&",
"!",
"(",
"mediatype",
"==",
"\"application/json\"",
"&&",
"strings",
".",
"ToUpper",
"(",
"charset",
")",
"==",
"\"UTF-8\"",
")",
"{",
"Error",
"(",
"w",
",",
"\"Bad Content-Type or charset, expected 'application/json'\"",
",",
"http",
".",
"StatusUnsupportedMediaType",
",",
")",
"\n",
"return",
"\n",
"}",
"\n",
"handler",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes ContentTypeCheckerMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"ContentTypeCheckerMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/content_type_checker.go#L16-L40
|
test
|
ant0ine/go-json-rest
|
rest/response.go
|
CloseNotify
|
func (w *responseWriter) CloseNotify() <-chan bool {
notifier := w.ResponseWriter.(http.CloseNotifier)
return notifier.CloseNotify()
}
|
go
|
func (w *responseWriter) CloseNotify() <-chan bool {
notifier := w.ResponseWriter.(http.CloseNotifier)
return notifier.CloseNotify()
}
|
[
"func",
"(",
"w",
"*",
"responseWriter",
")",
"CloseNotify",
"(",
")",
"<-",
"chan",
"bool",
"{",
"notifier",
":=",
"w",
".",
"ResponseWriter",
".",
"(",
"http",
".",
"CloseNotifier",
")",
"\n",
"return",
"notifier",
".",
"CloseNotify",
"(",
")",
"\n",
"}"
] |
// Provided in order to implement the http.CloseNotifier interface.
|
[
"Provided",
"in",
"order",
"to",
"implement",
"the",
"http",
".",
"CloseNotifier",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/response.go#L118-L121
|
test
|
ant0ine/go-json-rest
|
rest/access_log_apache.go
|
MiddlewareFunc
|
func (mw *AccessLogApacheMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
// set default format
if mw.Format == "" {
mw.Format = DefaultLogFormat
}
mw.convertFormat()
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
util := &accessLogUtil{w, r}
mw.Logger.Print(mw.executeTextTemplate(util))
}
}
|
go
|
func (mw *AccessLogApacheMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
// set default format
if mw.Format == "" {
mw.Format = DefaultLogFormat
}
mw.convertFormat()
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
util := &accessLogUtil{w, r}
mw.Logger.Print(mw.executeTextTemplate(util))
}
}
|
[
"func",
"(",
"mw",
"*",
"AccessLogApacheMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"if",
"mw",
".",
"Logger",
"==",
"nil",
"{",
"mw",
".",
"Logger",
"=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"\"",
",",
"0",
")",
"\n",
"}",
"\n",
"if",
"mw",
".",
"Format",
"==",
"\"\"",
"{",
"mw",
".",
"Format",
"=",
"DefaultLogFormat",
"\n",
"}",
"\n",
"mw",
".",
"convertFormat",
"(",
")",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"h",
"(",
"w",
",",
"r",
")",
"\n",
"util",
":=",
"&",
"accessLogUtil",
"{",
"w",
",",
"r",
"}",
"\n",
"mw",
".",
"Logger",
".",
"Print",
"(",
"mw",
".",
"executeTextTemplate",
"(",
"util",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes AccessLogApacheMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"AccessLogApacheMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L71-L94
|
test
|
ant0ine/go-json-rest
|
rest/access_log_apache.go
|
executeTextTemplate
|
func (mw *AccessLogApacheMiddleware) executeTextTemplate(util *accessLogUtil) string {
buf := bytes.NewBufferString("")
err := mw.textTemplate.Execute(buf, util)
if err != nil {
panic(err)
}
return buf.String()
}
|
go
|
func (mw *AccessLogApacheMiddleware) executeTextTemplate(util *accessLogUtil) string {
buf := bytes.NewBufferString("")
err := mw.textTemplate.Execute(buf, util)
if err != nil {
panic(err)
}
return buf.String()
}
|
[
"func",
"(",
"mw",
"*",
"AccessLogApacheMiddleware",
")",
"executeTextTemplate",
"(",
"util",
"*",
"accessLogUtil",
")",
"string",
"{",
"buf",
":=",
"bytes",
".",
"NewBufferString",
"(",
"\"\"",
")",
"\n",
"err",
":=",
"mw",
".",
"textTemplate",
".",
"Execute",
"(",
"buf",
",",
"util",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// Execute the text template with the data derived from the request, and return a string.
|
[
"Execute",
"the",
"text",
"template",
"with",
"the",
"data",
"derived",
"from",
"the",
"request",
"and",
"return",
"a",
"string",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L158-L165
|
test
|
ant0ine/go-json-rest
|
rest/access_log_apache.go
|
RemoteUser
|
func (u *accessLogUtil) RemoteUser() string {
if u.R.Env["REMOTE_USER"] != nil {
return u.R.Env["REMOTE_USER"].(string)
}
return ""
}
|
go
|
func (u *accessLogUtil) RemoteUser() string {
if u.R.Env["REMOTE_USER"] != nil {
return u.R.Env["REMOTE_USER"].(string)
}
return ""
}
|
[
"func",
"(",
"u",
"*",
"accessLogUtil",
")",
"RemoteUser",
"(",
")",
"string",
"{",
"if",
"u",
".",
"R",
".",
"Env",
"[",
"\"REMOTE_USER\"",
"]",
"!=",
"nil",
"{",
"return",
"u",
".",
"R",
".",
"Env",
"[",
"\"REMOTE_USER\"",
"]",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// As stored by the auth middlewares.
|
[
"As",
"stored",
"by",
"the",
"auth",
"middlewares",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L175-L180
|
test
|
ant0ine/go-json-rest
|
rest/access_log_apache.go
|
ApacheQueryString
|
func (u *accessLogUtil) ApacheQueryString() string {
if u.R.URL.RawQuery != "" {
return "?" + u.R.URL.RawQuery
}
return ""
}
|
go
|
func (u *accessLogUtil) ApacheQueryString() string {
if u.R.URL.RawQuery != "" {
return "?" + u.R.URL.RawQuery
}
return ""
}
|
[
"func",
"(",
"u",
"*",
"accessLogUtil",
")",
"ApacheQueryString",
"(",
")",
"string",
"{",
"if",
"u",
".",
"R",
".",
"URL",
".",
"RawQuery",
"!=",
"\"\"",
"{",
"return",
"\"?\"",
"+",
"u",
".",
"R",
".",
"URL",
".",
"RawQuery",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// If qs exists then return it with a leadin "?", apache log style.
|
[
"If",
"qs",
"exists",
"then",
"return",
"it",
"with",
"a",
"leadin",
"?",
"apache",
"log",
"style",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L183-L188
|
test
|
ant0ine/go-json-rest
|
rest/access_log_apache.go
|
StartTime
|
func (u *accessLogUtil) StartTime() *time.Time {
if u.R.Env["START_TIME"] != nil {
return u.R.Env["START_TIME"].(*time.Time)
}
return nil
}
|
go
|
func (u *accessLogUtil) StartTime() *time.Time {
if u.R.Env["START_TIME"] != nil {
return u.R.Env["START_TIME"].(*time.Time)
}
return nil
}
|
[
"func",
"(",
"u",
"*",
"accessLogUtil",
")",
"StartTime",
"(",
")",
"*",
"time",
".",
"Time",
"{",
"if",
"u",
".",
"R",
".",
"Env",
"[",
"\"START_TIME\"",
"]",
"!=",
"nil",
"{",
"return",
"u",
".",
"R",
".",
"Env",
"[",
"\"START_TIME\"",
"]",
".",
"(",
"*",
"time",
".",
"Time",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// When the request entered the timer middleware.
|
[
"When",
"the",
"request",
"entered",
"the",
"timer",
"middleware",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L191-L196
|
test
|
ant0ine/go-json-rest
|
rest/access_log_apache.go
|
ApacheRemoteAddr
|
func (u *accessLogUtil) ApacheRemoteAddr() string {
remoteAddr := u.R.RemoteAddr
if remoteAddr != "" {
if ip, _, err := net.SplitHostPort(remoteAddr); err == nil {
return ip
}
}
return ""
}
|
go
|
func (u *accessLogUtil) ApacheRemoteAddr() string {
remoteAddr := u.R.RemoteAddr
if remoteAddr != "" {
if ip, _, err := net.SplitHostPort(remoteAddr); err == nil {
return ip
}
}
return ""
}
|
[
"func",
"(",
"u",
"*",
"accessLogUtil",
")",
"ApacheRemoteAddr",
"(",
")",
"string",
"{",
"remoteAddr",
":=",
"u",
".",
"R",
".",
"RemoteAddr",
"\n",
"if",
"remoteAddr",
"!=",
"\"\"",
"{",
"if",
"ip",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"remoteAddr",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"ip",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// If remoteAddr is set then return is without the port number, apache log style.
|
[
"If",
"remoteAddr",
"is",
"set",
"then",
"return",
"is",
"without",
"the",
"port",
"number",
"apache",
"log",
"style",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L199-L207
|
test
|
ant0ine/go-json-rest
|
rest/access_log_apache.go
|
ResponseTime
|
func (u *accessLogUtil) ResponseTime() *time.Duration {
if u.R.Env["ELAPSED_TIME"] != nil {
return u.R.Env["ELAPSED_TIME"].(*time.Duration)
}
return nil
}
|
go
|
func (u *accessLogUtil) ResponseTime() *time.Duration {
if u.R.Env["ELAPSED_TIME"] != nil {
return u.R.Env["ELAPSED_TIME"].(*time.Duration)
}
return nil
}
|
[
"func",
"(",
"u",
"*",
"accessLogUtil",
")",
"ResponseTime",
"(",
")",
"*",
"time",
".",
"Duration",
"{",
"if",
"u",
".",
"R",
".",
"Env",
"[",
"\"ELAPSED_TIME\"",
"]",
"!=",
"nil",
"{",
"return",
"u",
".",
"R",
".",
"Env",
"[",
"\"ELAPSED_TIME\"",
"]",
".",
"(",
"*",
"time",
".",
"Duration",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// As mesured by the timer middleware.
|
[
"As",
"mesured",
"by",
"the",
"timer",
"middleware",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L218-L223
|
test
|
ant0ine/go-json-rest
|
rest/json_indent.go
|
MiddlewareFunc
|
func (mw *JsonIndentMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
if mw.Indent == "" {
mw.Indent = " "
}
return func(w ResponseWriter, r *Request) {
writer := &jsonIndentResponseWriter{w, false, mw.Prefix, mw.Indent}
// call the wrapped handler
handler(writer, r)
}
}
|
go
|
func (mw *JsonIndentMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
if mw.Indent == "" {
mw.Indent = " "
}
return func(w ResponseWriter, r *Request) {
writer := &jsonIndentResponseWriter{w, false, mw.Prefix, mw.Indent}
// call the wrapped handler
handler(writer, r)
}
}
|
[
"func",
"(",
"mw",
"*",
"JsonIndentMiddleware",
")",
"MiddlewareFunc",
"(",
"handler",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"if",
"mw",
".",
"Indent",
"==",
"\"\"",
"{",
"mw",
".",
"Indent",
"=",
"\" \"",
"\n",
"}",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"writer",
":=",
"&",
"jsonIndentResponseWriter",
"{",
"w",
",",
"false",
",",
"mw",
".",
"Prefix",
",",
"mw",
".",
"Indent",
"}",
"\n",
"handler",
"(",
"writer",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes JsonIndentMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"JsonIndentMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/json_indent.go#L25-L37
|
test
|
ant0ine/go-json-rest
|
rest/json_indent.go
|
EncodeJson
|
func (w *jsonIndentResponseWriter) EncodeJson(v interface{}) ([]byte, error) {
b, err := json.MarshalIndent(v, w.prefix, w.indent)
if err != nil {
return nil, err
}
return b, nil
}
|
go
|
func (w *jsonIndentResponseWriter) EncodeJson(v interface{}) ([]byte, error) {
b, err := json.MarshalIndent(v, w.prefix, w.indent)
if err != nil {
return nil, err
}
return b, nil
}
|
[
"func",
"(",
"w",
"*",
"jsonIndentResponseWriter",
")",
"EncodeJson",
"(",
"v",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"v",
",",
"w",
".",
"prefix",
",",
"w",
".",
"indent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] |
// Replace the parent EncodeJson to provide indentation.
|
[
"Replace",
"the",
"parent",
"EncodeJson",
"to",
"provide",
"indentation",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/json_indent.go#L54-L60
|
test
|
ant0ine/go-json-rest
|
rest/json_indent.go
|
WriteHeader
|
func (w *jsonIndentResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
w.wroteHeader = true
}
|
go
|
func (w *jsonIndentResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
w.wroteHeader = true
}
|
[
"func",
"(",
"w",
"*",
"jsonIndentResponseWriter",
")",
"WriteHeader",
"(",
"code",
"int",
")",
"{",
"w",
".",
"ResponseWriter",
".",
"WriteHeader",
"(",
"code",
")",
"\n",
"w",
".",
"wroteHeader",
"=",
"true",
"\n",
"}"
] |
// Call the parent WriteHeader.
|
[
"Call",
"the",
"parent",
"WriteHeader",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/json_indent.go#L77-L80
|
test
|
ant0ine/go-json-rest
|
rest/route.go
|
MakePath
|
func (route *Route) MakePath(pathParams map[string]string) string {
path := route.PathExp
for paramName, paramValue := range pathParams {
paramPlaceholder := ":" + paramName
relaxedPlaceholder := "#" + paramName
splatPlaceholder := "*" + paramName
r := strings.NewReplacer(paramPlaceholder, paramValue, splatPlaceholder, paramValue, relaxedPlaceholder, paramValue)
path = r.Replace(path)
}
return path
}
|
go
|
func (route *Route) MakePath(pathParams map[string]string) string {
path := route.PathExp
for paramName, paramValue := range pathParams {
paramPlaceholder := ":" + paramName
relaxedPlaceholder := "#" + paramName
splatPlaceholder := "*" + paramName
r := strings.NewReplacer(paramPlaceholder, paramValue, splatPlaceholder, paramValue, relaxedPlaceholder, paramValue)
path = r.Replace(path)
}
return path
}
|
[
"func",
"(",
"route",
"*",
"Route",
")",
"MakePath",
"(",
"pathParams",
"map",
"[",
"string",
"]",
"string",
")",
"string",
"{",
"path",
":=",
"route",
".",
"PathExp",
"\n",
"for",
"paramName",
",",
"paramValue",
":=",
"range",
"pathParams",
"{",
"paramPlaceholder",
":=",
"\":\"",
"+",
"paramName",
"\n",
"relaxedPlaceholder",
":=",
"\"#\"",
"+",
"paramName",
"\n",
"splatPlaceholder",
":=",
"\"*\"",
"+",
"paramName",
"\n",
"r",
":=",
"strings",
".",
"NewReplacer",
"(",
"paramPlaceholder",
",",
"paramValue",
",",
"splatPlaceholder",
",",
"paramValue",
",",
"relaxedPlaceholder",
",",
"paramValue",
")",
"\n",
"path",
"=",
"r",
".",
"Replace",
"(",
"path",
")",
"\n",
"}",
"\n",
"return",
"path",
"\n",
"}"
] |
// MakePath generates the path corresponding to this Route and the provided path parameters.
// This is used for reverse route resolution.
|
[
"MakePath",
"generates",
"the",
"path",
"corresponding",
"to",
"this",
"Route",
"and",
"the",
"provided",
"path",
"parameters",
".",
"This",
"is",
"used",
"for",
"reverse",
"route",
"resolution",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/route.go#L28-L38
|
test
|
ant0ine/go-json-rest
|
rest/recover.go
|
MiddlewareFunc
|
func (mw *RecoverMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
return func(w ResponseWriter, r *Request) {
// catch user code's panic, and convert to http response
defer func() {
if reco := recover(); reco != nil {
trace := debug.Stack()
// log the trace
message := fmt.Sprintf("%s\n%s", reco, trace)
mw.logError(message)
// write error response
if mw.EnableResponseStackTrace {
Error(w, message, http.StatusInternalServerError)
} else {
Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
}()
// call the handler
h(w, r)
}
}
|
go
|
func (mw *RecoverMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
return func(w ResponseWriter, r *Request) {
// catch user code's panic, and convert to http response
defer func() {
if reco := recover(); reco != nil {
trace := debug.Stack()
// log the trace
message := fmt.Sprintf("%s\n%s", reco, trace)
mw.logError(message)
// write error response
if mw.EnableResponseStackTrace {
Error(w, message, http.StatusInternalServerError)
} else {
Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
}()
// call the handler
h(w, r)
}
}
|
[
"func",
"(",
"mw",
"*",
"RecoverMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"if",
"mw",
".",
"Logger",
"==",
"nil",
"{",
"mw",
".",
"Logger",
"=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"\"",
",",
"0",
")",
"\n",
"}",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"reco",
":=",
"recover",
"(",
")",
";",
"reco",
"!=",
"nil",
"{",
"trace",
":=",
"debug",
".",
"Stack",
"(",
")",
"\n",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s\\n%s\"",
",",
"\\n",
",",
"reco",
")",
"\n",
"trace",
"\n",
"mw",
".",
"logError",
"(",
"message",
")",
"\n",
"}",
"\n",
"}",
"if",
"mw",
".",
"EnableResponseStackTrace",
"{",
"Error",
"(",
"w",
",",
"message",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"else",
"{",
"Error",
"(",
"w",
",",
"\"Internal Server Error\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes RecoverMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"RecoverMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/recover.go#L29-L59
|
test
|
ant0ine/go-json-rest
|
rest/middleware.go
|
WrapMiddlewares
|
func WrapMiddlewares(middlewares []Middleware, handler HandlerFunc) HandlerFunc {
wrapped := handler
for i := len(middlewares) - 1; i >= 0; i-- {
wrapped = middlewares[i].MiddlewareFunc(wrapped)
}
return wrapped
}
|
go
|
func WrapMiddlewares(middlewares []Middleware, handler HandlerFunc) HandlerFunc {
wrapped := handler
for i := len(middlewares) - 1; i >= 0; i-- {
wrapped = middlewares[i].MiddlewareFunc(wrapped)
}
return wrapped
}
|
[
"func",
"WrapMiddlewares",
"(",
"middlewares",
"[",
"]",
"Middleware",
",",
"handler",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"wrapped",
":=",
"handler",
"\n",
"for",
"i",
":=",
"len",
"(",
"middlewares",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"wrapped",
"=",
"middlewares",
"[",
"i",
"]",
".",
"MiddlewareFunc",
"(",
"wrapped",
")",
"\n",
"}",
"\n",
"return",
"wrapped",
"\n",
"}"
] |
// WrapMiddlewares calls the MiddlewareFunc methods in the reverse order and returns an HandlerFunc
// ready to be executed. This can be used to wrap a set of middlewares, post routing, on a per Route
// basis.
|
[
"WrapMiddlewares",
"calls",
"the",
"MiddlewareFunc",
"methods",
"in",
"the",
"reverse",
"order",
"and",
"returns",
"an",
"HandlerFunc",
"ready",
"to",
"be",
"executed",
".",
"This",
"can",
"be",
"used",
"to",
"wrap",
"a",
"set",
"of",
"middlewares",
"post",
"routing",
"on",
"a",
"per",
"Route",
"basis",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/middleware.go#L43-L49
|
test
|
ant0ine/go-json-rest
|
rest/gzip.go
|
MiddlewareFunc
|
func (mw *GzipMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
// gzip support enabled
canGzip := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
// client accepts gzip ?
writer := &gzipResponseWriter{w, false, canGzip, nil}
defer func() {
// need to close gzip writer
if writer.gzipWriter != nil {
writer.gzipWriter.Close()
}
}()
// call the handler with the wrapped writer
h(writer, r)
}
}
|
go
|
func (mw *GzipMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
// gzip support enabled
canGzip := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
// client accepts gzip ?
writer := &gzipResponseWriter{w, false, canGzip, nil}
defer func() {
// need to close gzip writer
if writer.gzipWriter != nil {
writer.gzipWriter.Close()
}
}()
// call the handler with the wrapped writer
h(writer, r)
}
}
|
[
"func",
"(",
"mw",
"*",
"GzipMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"canGzip",
":=",
"strings",
".",
"Contains",
"(",
"r",
".",
"Header",
".",
"Get",
"(",
"\"Accept-Encoding\"",
")",
",",
"\"gzip\"",
")",
"\n",
"writer",
":=",
"&",
"gzipResponseWriter",
"{",
"w",
",",
"false",
",",
"canGzip",
",",
"nil",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"writer",
".",
"gzipWriter",
"!=",
"nil",
"{",
"writer",
".",
"gzipWriter",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"h",
"(",
"writer",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes GzipMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"GzipMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/gzip.go#L18-L33
|
test
|
ant0ine/go-json-rest
|
rest/gzip.go
|
WriteHeader
|
func (w *gzipResponseWriter) WriteHeader(code int) {
// Always set the Vary header, even if this particular request
// is not gzipped.
w.Header().Add("Vary", "Accept-Encoding")
if w.canGzip {
w.Header().Set("Content-Encoding", "gzip")
}
w.ResponseWriter.WriteHeader(code)
w.wroteHeader = true
}
|
go
|
func (w *gzipResponseWriter) WriteHeader(code int) {
// Always set the Vary header, even if this particular request
// is not gzipped.
w.Header().Add("Vary", "Accept-Encoding")
if w.canGzip {
w.Header().Set("Content-Encoding", "gzip")
}
w.ResponseWriter.WriteHeader(code)
w.wroteHeader = true
}
|
[
"func",
"(",
"w",
"*",
"gzipResponseWriter",
")",
"WriteHeader",
"(",
"code",
"int",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"Vary\"",
",",
"\"Accept-Encoding\"",
")",
"\n",
"if",
"w",
".",
"canGzip",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Encoding\"",
",",
"\"gzip\"",
")",
"\n",
"}",
"\n",
"w",
".",
"ResponseWriter",
".",
"WriteHeader",
"(",
"code",
")",
"\n",
"w",
".",
"wroteHeader",
"=",
"true",
"\n",
"}"
] |
// Set the right headers for gzip encoded responses.
|
[
"Set",
"the",
"right",
"headers",
"for",
"gzip",
"encoded",
"responses",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/gzip.go#L51-L63
|
test
|
ant0ine/go-json-rest
|
rest/gzip.go
|
Hijack
|
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker := w.ResponseWriter.(http.Hijacker)
return hijacker.Hijack()
}
|
go
|
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker := w.ResponseWriter.(http.Hijacker)
return hijacker.Hijack()
}
|
[
"func",
"(",
"w",
"*",
"gzipResponseWriter",
")",
"Hijack",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"*",
"bufio",
".",
"ReadWriter",
",",
"error",
")",
"{",
"hijacker",
":=",
"w",
".",
"ResponseWriter",
".",
"(",
"http",
".",
"Hijacker",
")",
"\n",
"return",
"hijacker",
".",
"Hijack",
"(",
")",
"\n",
"}"
] |
// Provided in order to implement the http.Hijacker interface.
|
[
"Provided",
"in",
"order",
"to",
"implement",
"the",
"http",
".",
"Hijacker",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/gzip.go#L96-L99
|
test
|
ant0ine/go-json-rest
|
rest/gzip.go
|
Write
|
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
writer := w.ResponseWriter.(http.ResponseWriter)
if w.canGzip {
// Write can be called multiple times for a given response.
// (see the streaming example:
// https://github.com/ant0ine/go-json-rest-examples/tree/master/streaming)
// The gzipWriter is instantiated only once, and flushed after
// each write.
if w.gzipWriter == nil {
w.gzipWriter = gzip.NewWriter(writer)
}
count, errW := w.gzipWriter.Write(b)
errF := w.gzipWriter.Flush()
if errW != nil {
return count, errW
}
if errF != nil {
return count, errF
}
return count, nil
}
return writer.Write(b)
}
|
go
|
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
writer := w.ResponseWriter.(http.ResponseWriter)
if w.canGzip {
// Write can be called multiple times for a given response.
// (see the streaming example:
// https://github.com/ant0ine/go-json-rest-examples/tree/master/streaming)
// The gzipWriter is instantiated only once, and flushed after
// each write.
if w.gzipWriter == nil {
w.gzipWriter = gzip.NewWriter(writer)
}
count, errW := w.gzipWriter.Write(b)
errF := w.gzipWriter.Flush()
if errW != nil {
return count, errW
}
if errF != nil {
return count, errF
}
return count, nil
}
return writer.Write(b)
}
|
[
"func",
"(",
"w",
"*",
"gzipResponseWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"!",
"w",
".",
"wroteHeader",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n",
"writer",
":=",
"w",
".",
"ResponseWriter",
".",
"(",
"http",
".",
"ResponseWriter",
")",
"\n",
"if",
"w",
".",
"canGzip",
"{",
"if",
"w",
".",
"gzipWriter",
"==",
"nil",
"{",
"w",
".",
"gzipWriter",
"=",
"gzip",
".",
"NewWriter",
"(",
"writer",
")",
"\n",
"}",
"\n",
"count",
",",
"errW",
":=",
"w",
".",
"gzipWriter",
".",
"Write",
"(",
"b",
")",
"\n",
"errF",
":=",
"w",
".",
"gzipWriter",
".",
"Flush",
"(",
")",
"\n",
"if",
"errW",
"!=",
"nil",
"{",
"return",
"count",
",",
"errW",
"\n",
"}",
"\n",
"if",
"errF",
"!=",
"nil",
"{",
"return",
"count",
",",
"errF",
"\n",
"}",
"\n",
"return",
"count",
",",
"nil",
"\n",
"}",
"\n",
"return",
"writer",
".",
"Write",
"(",
"b",
")",
"\n",
"}"
] |
// Make sure the local WriteHeader is called, and encode the payload if necessary.
// Provided in order to implement the http.ResponseWriter interface.
|
[
"Make",
"sure",
"the",
"local",
"WriteHeader",
"is",
"called",
"and",
"encode",
"the",
"payload",
"if",
"necessary",
".",
"Provided",
"in",
"order",
"to",
"implement",
"the",
"http",
".",
"ResponseWriter",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/gzip.go#L103-L132
|
test
|
ant0ine/go-json-rest
|
rest/auth_basic.go
|
MiddlewareFunc
|
func (mw *AuthBasicMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
if mw.Realm == "" {
log.Fatal("Realm is required")
}
if mw.Authenticator == nil {
log.Fatal("Authenticator is required")
}
if mw.Authorizator == nil {
mw.Authorizator = func(userId string, request *Request) bool {
return true
}
}
return func(writer ResponseWriter, request *Request) {
authHeader := request.Header.Get("Authorization")
if authHeader == "" {
mw.unauthorized(writer)
return
}
providedUserId, providedPassword, err := mw.decodeBasicAuthHeader(authHeader)
if err != nil {
Error(writer, "Invalid authentication", http.StatusBadRequest)
return
}
if !mw.Authenticator(providedUserId, providedPassword) {
mw.unauthorized(writer)
return
}
if !mw.Authorizator(providedUserId, request) {
mw.unauthorized(writer)
return
}
request.Env["REMOTE_USER"] = providedUserId
handler(writer, request)
}
}
|
go
|
func (mw *AuthBasicMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
if mw.Realm == "" {
log.Fatal("Realm is required")
}
if mw.Authenticator == nil {
log.Fatal("Authenticator is required")
}
if mw.Authorizator == nil {
mw.Authorizator = func(userId string, request *Request) bool {
return true
}
}
return func(writer ResponseWriter, request *Request) {
authHeader := request.Header.Get("Authorization")
if authHeader == "" {
mw.unauthorized(writer)
return
}
providedUserId, providedPassword, err := mw.decodeBasicAuthHeader(authHeader)
if err != nil {
Error(writer, "Invalid authentication", http.StatusBadRequest)
return
}
if !mw.Authenticator(providedUserId, providedPassword) {
mw.unauthorized(writer)
return
}
if !mw.Authorizator(providedUserId, request) {
mw.unauthorized(writer)
return
}
request.Env["REMOTE_USER"] = providedUserId
handler(writer, request)
}
}
|
[
"func",
"(",
"mw",
"*",
"AuthBasicMiddleware",
")",
"MiddlewareFunc",
"(",
"handler",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"if",
"mw",
".",
"Realm",
"==",
"\"\"",
"{",
"log",
".",
"Fatal",
"(",
"\"Realm is required\"",
")",
"\n",
"}",
"\n",
"if",
"mw",
".",
"Authenticator",
"==",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"\"Authenticator is required\"",
")",
"\n",
"}",
"\n",
"if",
"mw",
".",
"Authorizator",
"==",
"nil",
"{",
"mw",
".",
"Authorizator",
"=",
"func",
"(",
"userId",
"string",
",",
"request",
"*",
"Request",
")",
"bool",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"func",
"(",
"writer",
"ResponseWriter",
",",
"request",
"*",
"Request",
")",
"{",
"authHeader",
":=",
"request",
".",
"Header",
".",
"Get",
"(",
"\"Authorization\"",
")",
"\n",
"if",
"authHeader",
"==",
"\"\"",
"{",
"mw",
".",
"unauthorized",
"(",
"writer",
")",
"\n",
"return",
"\n",
"}",
"\n",
"providedUserId",
",",
"providedPassword",
",",
"err",
":=",
"mw",
".",
"decodeBasicAuthHeader",
"(",
"authHeader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"Error",
"(",
"writer",
",",
"\"Invalid authentication\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"mw",
".",
"Authenticator",
"(",
"providedUserId",
",",
"providedPassword",
")",
"{",
"mw",
".",
"unauthorized",
"(",
"writer",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"mw",
".",
"Authorizator",
"(",
"providedUserId",
",",
"request",
")",
"{",
"mw",
".",
"unauthorized",
"(",
"writer",
")",
"\n",
"return",
"\n",
"}",
"\n",
"request",
".",
"Env",
"[",
"\"REMOTE_USER\"",
"]",
"=",
"providedUserId",
"\n",
"handler",
"(",
"writer",
",",
"request",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes AuthBasicMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"AuthBasicMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/auth_basic.go#L30-L75
|
test
|
ant0ine/go-json-rest
|
rest/trie/impl.go
|
printDebug
|
func (n *node) printDebug(level int) {
level++
// *splat branch
if n.SplatChild != nil {
printFPadding(level, "*splat\n")
n.SplatChild.printDebug(level)
}
// :param branch
if n.ParamChild != nil {
printFPadding(level, ":param\n")
n.ParamChild.printDebug(level)
}
// #param branch
if n.RelaxedChild != nil {
printFPadding(level, "#relaxed\n")
n.RelaxedChild.printDebug(level)
}
// main branch
for key, node := range n.Children {
printFPadding(level, "\"%s\"\n", key)
node.printDebug(level)
}
}
|
go
|
func (n *node) printDebug(level int) {
level++
// *splat branch
if n.SplatChild != nil {
printFPadding(level, "*splat\n")
n.SplatChild.printDebug(level)
}
// :param branch
if n.ParamChild != nil {
printFPadding(level, ":param\n")
n.ParamChild.printDebug(level)
}
// #param branch
if n.RelaxedChild != nil {
printFPadding(level, "#relaxed\n")
n.RelaxedChild.printDebug(level)
}
// main branch
for key, node := range n.Children {
printFPadding(level, "\"%s\"\n", key)
node.printDebug(level)
}
}
|
[
"func",
"(",
"n",
"*",
"node",
")",
"printDebug",
"(",
"level",
"int",
")",
"{",
"level",
"++",
"\n",
"if",
"n",
".",
"SplatChild",
"!=",
"nil",
"{",
"printFPadding",
"(",
"level",
",",
"\"*splat\\n\"",
")",
"\n",
"\\n",
"\n",
"}",
"\n",
"n",
".",
"SplatChild",
".",
"printDebug",
"(",
"level",
")",
"\n",
"if",
"n",
".",
"ParamChild",
"!=",
"nil",
"{",
"printFPadding",
"(",
"level",
",",
"\":param\\n\"",
")",
"\n",
"\\n",
"\n",
"}",
"\n",
"n",
".",
"ParamChild",
".",
"printDebug",
"(",
"level",
")",
"\n",
"}"
] |
// Private function for now
|
[
"Private",
"function",
"for",
"now"
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L217-L239
|
test
|
ant0ine/go-json-rest
|
rest/trie/impl.go
|
AddRoute
|
func (t *Trie) AddRoute(httpMethod, pathExp string, route interface{}) error {
return t.root.addRoute(httpMethod, pathExp, route, []string{})
}
|
go
|
func (t *Trie) AddRoute(httpMethod, pathExp string, route interface{}) error {
return t.root.addRoute(httpMethod, pathExp, route, []string{})
}
|
[
"func",
"(",
"t",
"*",
"Trie",
")",
"AddRoute",
"(",
"httpMethod",
",",
"pathExp",
"string",
",",
"route",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"t",
".",
"root",
".",
"addRoute",
"(",
"httpMethod",
",",
"pathExp",
",",
"route",
",",
"[",
"]",
"string",
"{",
"}",
")",
"\n",
"}"
] |
// Insert the route in the Trie following or creating the nodes corresponding to the path.
|
[
"Insert",
"the",
"route",
"in",
"the",
"Trie",
"following",
"or",
"creating",
"the",
"nodes",
"corresponding",
"to",
"the",
"path",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L349-L351
|
test
|
ant0ine/go-json-rest
|
rest/trie/impl.go
|
printDebug
|
func (t *Trie) printDebug() {
fmt.Print("<trie>\n")
t.root.printDebug(0)
fmt.Print("</trie>\n")
}
|
go
|
func (t *Trie) printDebug() {
fmt.Print("<trie>\n")
t.root.printDebug(0)
fmt.Print("</trie>\n")
}
|
[
"func",
"(",
"t",
"*",
"Trie",
")",
"printDebug",
"(",
")",
"{",
"fmt",
".",
"Print",
"(",
"\"<trie>\\n\"",
")",
"\n",
"\\n",
"\n",
"t",
".",
"root",
".",
"printDebug",
"(",
"0",
")",
"\n",
"}"
] |
// Private function for now.
|
[
"Private",
"function",
"for",
"now",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L359-L363
|
test
|
ant0ine/go-json-rest
|
rest/trie/impl.go
|
FindRoutes
|
func (t *Trie) FindRoutes(httpMethod, path string) []*Match {
context := newFindContext()
matches := []*Match{}
context.matchFunc = func(httpMethod, path string, node *node) {
if node.HttpMethodToRoute[httpMethod] != nil {
// path and method match, found a route !
matches = append(
matches,
&Match{
Route: node.HttpMethodToRoute[httpMethod],
Params: context.paramsAsMap(),
},
)
}
}
t.root.find(httpMethod, path, context)
return matches
}
|
go
|
func (t *Trie) FindRoutes(httpMethod, path string) []*Match {
context := newFindContext()
matches := []*Match{}
context.matchFunc = func(httpMethod, path string, node *node) {
if node.HttpMethodToRoute[httpMethod] != nil {
// path and method match, found a route !
matches = append(
matches,
&Match{
Route: node.HttpMethodToRoute[httpMethod],
Params: context.paramsAsMap(),
},
)
}
}
t.root.find(httpMethod, path, context)
return matches
}
|
[
"func",
"(",
"t",
"*",
"Trie",
")",
"FindRoutes",
"(",
"httpMethod",
",",
"path",
"string",
")",
"[",
"]",
"*",
"Match",
"{",
"context",
":=",
"newFindContext",
"(",
")",
"\n",
"matches",
":=",
"[",
"]",
"*",
"Match",
"{",
"}",
"\n",
"context",
".",
"matchFunc",
"=",
"func",
"(",
"httpMethod",
",",
"path",
"string",
",",
"node",
"*",
"node",
")",
"{",
"if",
"node",
".",
"HttpMethodToRoute",
"[",
"httpMethod",
"]",
"!=",
"nil",
"{",
"matches",
"=",
"append",
"(",
"matches",
",",
"&",
"Match",
"{",
"Route",
":",
"node",
".",
"HttpMethodToRoute",
"[",
"httpMethod",
"]",
",",
"Params",
":",
"context",
".",
"paramsAsMap",
"(",
")",
",",
"}",
",",
")",
"\n",
"}",
"\n",
"}",
"\n",
"t",
".",
"root",
".",
"find",
"(",
"httpMethod",
",",
"path",
",",
"context",
")",
"\n",
"return",
"matches",
"\n",
"}"
] |
// Given a path and an http method, return all the matching routes.
|
[
"Given",
"a",
"path",
"and",
"an",
"http",
"method",
"return",
"all",
"the",
"matching",
"routes",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L366-L383
|
test
|
ant0ine/go-json-rest
|
rest/trie/impl.go
|
FindRoutesAndPathMatched
|
func (t *Trie) FindRoutesAndPathMatched(httpMethod, path string) ([]*Match, bool) {
context := newFindContext()
pathMatched := false
matches := []*Match{}
context.matchFunc = func(httpMethod, path string, node *node) {
pathMatched = true
if node.HttpMethodToRoute[httpMethod] != nil {
// path and method match, found a route !
matches = append(
matches,
&Match{
Route: node.HttpMethodToRoute[httpMethod],
Params: context.paramsAsMap(),
},
)
}
}
t.root.find(httpMethod, path, context)
return matches, pathMatched
}
|
go
|
func (t *Trie) FindRoutesAndPathMatched(httpMethod, path string) ([]*Match, bool) {
context := newFindContext()
pathMatched := false
matches := []*Match{}
context.matchFunc = func(httpMethod, path string, node *node) {
pathMatched = true
if node.HttpMethodToRoute[httpMethod] != nil {
// path and method match, found a route !
matches = append(
matches,
&Match{
Route: node.HttpMethodToRoute[httpMethod],
Params: context.paramsAsMap(),
},
)
}
}
t.root.find(httpMethod, path, context)
return matches, pathMatched
}
|
[
"func",
"(",
"t",
"*",
"Trie",
")",
"FindRoutesAndPathMatched",
"(",
"httpMethod",
",",
"path",
"string",
")",
"(",
"[",
"]",
"*",
"Match",
",",
"bool",
")",
"{",
"context",
":=",
"newFindContext",
"(",
")",
"\n",
"pathMatched",
":=",
"false",
"\n",
"matches",
":=",
"[",
"]",
"*",
"Match",
"{",
"}",
"\n",
"context",
".",
"matchFunc",
"=",
"func",
"(",
"httpMethod",
",",
"path",
"string",
",",
"node",
"*",
"node",
")",
"{",
"pathMatched",
"=",
"true",
"\n",
"if",
"node",
".",
"HttpMethodToRoute",
"[",
"httpMethod",
"]",
"!=",
"nil",
"{",
"matches",
"=",
"append",
"(",
"matches",
",",
"&",
"Match",
"{",
"Route",
":",
"node",
".",
"HttpMethodToRoute",
"[",
"httpMethod",
"]",
",",
"Params",
":",
"context",
".",
"paramsAsMap",
"(",
")",
",",
"}",
",",
")",
"\n",
"}",
"\n",
"}",
"\n",
"t",
".",
"root",
".",
"find",
"(",
"httpMethod",
",",
"path",
",",
"context",
")",
"\n",
"return",
"matches",
",",
"pathMatched",
"\n",
"}"
] |
// Same as FindRoutes, but return in addition a boolean indicating if the path was matched.
// Useful to return 405
|
[
"Same",
"as",
"FindRoutes",
"but",
"return",
"in",
"addition",
"a",
"boolean",
"indicating",
"if",
"the",
"path",
"was",
"matched",
".",
"Useful",
"to",
"return",
"405"
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L387-L406
|
test
|
ant0ine/go-json-rest
|
rest/trie/impl.go
|
FindRoutesForPath
|
func (t *Trie) FindRoutesForPath(path string) []*Match {
context := newFindContext()
matches := []*Match{}
context.matchFunc = func(httpMethod, path string, node *node) {
params := context.paramsAsMap()
for _, route := range node.HttpMethodToRoute {
matches = append(
matches,
&Match{
Route: route,
Params: params,
},
)
}
}
t.root.find("", path, context)
return matches
}
|
go
|
func (t *Trie) FindRoutesForPath(path string) []*Match {
context := newFindContext()
matches := []*Match{}
context.matchFunc = func(httpMethod, path string, node *node) {
params := context.paramsAsMap()
for _, route := range node.HttpMethodToRoute {
matches = append(
matches,
&Match{
Route: route,
Params: params,
},
)
}
}
t.root.find("", path, context)
return matches
}
|
[
"func",
"(",
"t",
"*",
"Trie",
")",
"FindRoutesForPath",
"(",
"path",
"string",
")",
"[",
"]",
"*",
"Match",
"{",
"context",
":=",
"newFindContext",
"(",
")",
"\n",
"matches",
":=",
"[",
"]",
"*",
"Match",
"{",
"}",
"\n",
"context",
".",
"matchFunc",
"=",
"func",
"(",
"httpMethod",
",",
"path",
"string",
",",
"node",
"*",
"node",
")",
"{",
"params",
":=",
"context",
".",
"paramsAsMap",
"(",
")",
"\n",
"for",
"_",
",",
"route",
":=",
"range",
"node",
".",
"HttpMethodToRoute",
"{",
"matches",
"=",
"append",
"(",
"matches",
",",
"&",
"Match",
"{",
"Route",
":",
"route",
",",
"Params",
":",
"params",
",",
"}",
",",
")",
"\n",
"}",
"\n",
"}",
"\n",
"t",
".",
"root",
".",
"find",
"(",
"\"\"",
",",
"path",
",",
"context",
")",
"\n",
"return",
"matches",
"\n",
"}"
] |
// Given a path, and whatever the http method, return all the matching routes.
|
[
"Given",
"a",
"path",
"and",
"whatever",
"the",
"http",
"method",
"return",
"all",
"the",
"matching",
"routes",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L409-L426
|
test
|
ant0ine/go-json-rest
|
rest/api.go
|
Use
|
func (api *Api) Use(middlewares ...Middleware) {
api.stack = append(api.stack, middlewares...)
}
|
go
|
func (api *Api) Use(middlewares ...Middleware) {
api.stack = append(api.stack, middlewares...)
}
|
[
"func",
"(",
"api",
"*",
"Api",
")",
"Use",
"(",
"middlewares",
"...",
"Middleware",
")",
"{",
"api",
".",
"stack",
"=",
"append",
"(",
"api",
".",
"stack",
",",
"middlewares",
"...",
")",
"\n",
"}"
] |
// Use pushes one or multiple middlewares to the stack for middlewares
// maintained in the Api object.
|
[
"Use",
"pushes",
"one",
"or",
"multiple",
"middlewares",
"to",
"the",
"stack",
"for",
"middlewares",
"maintained",
"in",
"the",
"Api",
"object",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/api.go#L23-L25
|
test
|
ant0ine/go-json-rest
|
rest/api.go
|
MakeHandler
|
func (api *Api) MakeHandler() http.Handler {
var appFunc HandlerFunc
if api.app != nil {
appFunc = api.app.AppFunc()
} else {
appFunc = func(w ResponseWriter, r *Request) {}
}
return http.HandlerFunc(
adapterFunc(
WrapMiddlewares(api.stack, appFunc),
),
)
}
|
go
|
func (api *Api) MakeHandler() http.Handler {
var appFunc HandlerFunc
if api.app != nil {
appFunc = api.app.AppFunc()
} else {
appFunc = func(w ResponseWriter, r *Request) {}
}
return http.HandlerFunc(
adapterFunc(
WrapMiddlewares(api.stack, appFunc),
),
)
}
|
[
"func",
"(",
"api",
"*",
"Api",
")",
"MakeHandler",
"(",
")",
"http",
".",
"Handler",
"{",
"var",
"appFunc",
"HandlerFunc",
"\n",
"if",
"api",
".",
"app",
"!=",
"nil",
"{",
"appFunc",
"=",
"api",
".",
"app",
".",
"AppFunc",
"(",
")",
"\n",
"}",
"else",
"{",
"appFunc",
"=",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"}",
"\n",
"}",
"\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"adapterFunc",
"(",
"WrapMiddlewares",
"(",
"api",
".",
"stack",
",",
"appFunc",
")",
",",
")",
",",
")",
"\n",
"}"
] |
// MakeHandler wraps all the Middlewares of the stack and the App together, and returns an
// http.Handler ready to be used. If the Middleware stack is empty the App is used directly. If the
// App is nil, a HandlerFunc that does nothing is used instead.
|
[
"MakeHandler",
"wraps",
"all",
"the",
"Middlewares",
"of",
"the",
"stack",
"and",
"the",
"App",
"together",
"and",
"returns",
"an",
"http",
".",
"Handler",
"ready",
"to",
"be",
"used",
".",
"If",
"the",
"Middleware",
"stack",
"is",
"empty",
"the",
"App",
"is",
"used",
"directly",
".",
"If",
"the",
"App",
"is",
"nil",
"a",
"HandlerFunc",
"that",
"does",
"nothing",
"is",
"used",
"instead",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/api.go#L35-L47
|
test
|
ant0ine/go-json-rest
|
rest/powered_by.go
|
MiddlewareFunc
|
func (mw *PoweredByMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
poweredBy := xPoweredByDefault
if mw.XPoweredBy != "" {
poweredBy = mw.XPoweredBy
}
return func(w ResponseWriter, r *Request) {
w.Header().Add("X-Powered-By", poweredBy)
// call the handler
h(w, r)
}
}
|
go
|
func (mw *PoweredByMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
poweredBy := xPoweredByDefault
if mw.XPoweredBy != "" {
poweredBy = mw.XPoweredBy
}
return func(w ResponseWriter, r *Request) {
w.Header().Add("X-Powered-By", poweredBy)
// call the handler
h(w, r)
}
}
|
[
"func",
"(",
"mw",
"*",
"PoweredByMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"poweredBy",
":=",
"xPoweredByDefault",
"\n",
"if",
"mw",
".",
"XPoweredBy",
"!=",
"\"\"",
"{",
"poweredBy",
"=",
"mw",
".",
"XPoweredBy",
"\n",
"}",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"X-Powered-By\"",
",",
"poweredBy",
")",
"\n",
"h",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes PoweredByMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"PoweredByMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/powered_by.go#L14-L29
|
test
|
ant0ine/go-json-rest
|
rest/status.go
|
MiddlewareFunc
|
func (mw *StatusMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
mw.start = time.Now()
mw.pid = os.Getpid()
mw.responseCounts = map[string]int{}
mw.totalResponseTime = time.Time{}
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
if r.Env["STATUS_CODE"] == nil {
log.Fatal("StatusMiddleware: Env[\"STATUS_CODE\"] is nil, " +
"RecorderMiddleware may not be in the wrapped Middlewares.")
}
statusCode := r.Env["STATUS_CODE"].(int)
if r.Env["ELAPSED_TIME"] == nil {
log.Fatal("StatusMiddleware: Env[\"ELAPSED_TIME\"] is nil, " +
"TimerMiddleware may not be in the wrapped Middlewares.")
}
responseTime := r.Env["ELAPSED_TIME"].(*time.Duration)
mw.lock.Lock()
mw.responseCounts[fmt.Sprintf("%d", statusCode)]++
mw.totalResponseTime = mw.totalResponseTime.Add(*responseTime)
mw.lock.Unlock()
}
}
|
go
|
func (mw *StatusMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
mw.start = time.Now()
mw.pid = os.Getpid()
mw.responseCounts = map[string]int{}
mw.totalResponseTime = time.Time{}
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
if r.Env["STATUS_CODE"] == nil {
log.Fatal("StatusMiddleware: Env[\"STATUS_CODE\"] is nil, " +
"RecorderMiddleware may not be in the wrapped Middlewares.")
}
statusCode := r.Env["STATUS_CODE"].(int)
if r.Env["ELAPSED_TIME"] == nil {
log.Fatal("StatusMiddleware: Env[\"ELAPSED_TIME\"] is nil, " +
"TimerMiddleware may not be in the wrapped Middlewares.")
}
responseTime := r.Env["ELAPSED_TIME"].(*time.Duration)
mw.lock.Lock()
mw.responseCounts[fmt.Sprintf("%d", statusCode)]++
mw.totalResponseTime = mw.totalResponseTime.Add(*responseTime)
mw.lock.Unlock()
}
}
|
[
"func",
"(",
"mw",
"*",
"StatusMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"mw",
".",
"start",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"mw",
".",
"pid",
"=",
"os",
".",
"Getpid",
"(",
")",
"\n",
"mw",
".",
"responseCounts",
"=",
"map",
"[",
"string",
"]",
"int",
"{",
"}",
"\n",
"mw",
".",
"totalResponseTime",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"h",
"(",
"w",
",",
"r",
")",
"\n",
"if",
"r",
".",
"Env",
"[",
"\"STATUS_CODE\"",
"]",
"==",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"\"StatusMiddleware: Env[\\\"STATUS_CODE\\\"] is nil, \"",
"+",
"\\\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\"RecorderMiddleware may not be in the wrapped Middlewares.\"",
"\n",
"statusCode",
":=",
"r",
".",
"Env",
"[",
"\"STATUS_CODE\"",
"]",
".",
"(",
"int",
")",
"\n",
"if",
"r",
".",
"Env",
"[",
"\"ELAPSED_TIME\"",
"]",
"==",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"\"StatusMiddleware: Env[\\\"ELAPSED_TIME\\\"] is nil, \"",
"+",
"\\\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\"TimerMiddleware may not be in the wrapped Middlewares.\"",
"\n",
"responseTime",
":=",
"r",
".",
"Env",
"[",
"\"ELAPSED_TIME\"",
"]",
".",
"(",
"*",
"time",
".",
"Duration",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes StatusMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"StatusMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/status.go#L23-L52
|
test
|
ant0ine/go-json-rest
|
rest/status.go
|
GetStatus
|
func (mw *StatusMiddleware) GetStatus() *Status {
mw.lock.RLock()
now := time.Now()
uptime := now.Sub(mw.start)
totalCount := 0
for _, count := range mw.responseCounts {
totalCount += count
}
totalResponseTime := mw.totalResponseTime.Sub(time.Time{})
averageResponseTime := time.Duration(0)
if totalCount > 0 {
avgNs := int64(totalResponseTime) / int64(totalCount)
averageResponseTime = time.Duration(avgNs)
}
status := &Status{
Pid: mw.pid,
UpTime: uptime.String(),
UpTimeSec: uptime.Seconds(),
Time: now.String(),
TimeUnix: now.Unix(),
StatusCodeCount: mw.responseCounts,
TotalCount: totalCount,
TotalResponseTime: totalResponseTime.String(),
TotalResponseTimeSec: totalResponseTime.Seconds(),
AverageResponseTime: averageResponseTime.String(),
AverageResponseTimeSec: averageResponseTime.Seconds(),
}
mw.lock.RUnlock()
return status
}
|
go
|
func (mw *StatusMiddleware) GetStatus() *Status {
mw.lock.RLock()
now := time.Now()
uptime := now.Sub(mw.start)
totalCount := 0
for _, count := range mw.responseCounts {
totalCount += count
}
totalResponseTime := mw.totalResponseTime.Sub(time.Time{})
averageResponseTime := time.Duration(0)
if totalCount > 0 {
avgNs := int64(totalResponseTime) / int64(totalCount)
averageResponseTime = time.Duration(avgNs)
}
status := &Status{
Pid: mw.pid,
UpTime: uptime.String(),
UpTimeSec: uptime.Seconds(),
Time: now.String(),
TimeUnix: now.Unix(),
StatusCodeCount: mw.responseCounts,
TotalCount: totalCount,
TotalResponseTime: totalResponseTime.String(),
TotalResponseTimeSec: totalResponseTime.Seconds(),
AverageResponseTime: averageResponseTime.String(),
AverageResponseTimeSec: averageResponseTime.Seconds(),
}
mw.lock.RUnlock()
return status
}
|
[
"func",
"(",
"mw",
"*",
"StatusMiddleware",
")",
"GetStatus",
"(",
")",
"*",
"Status",
"{",
"mw",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"uptime",
":=",
"now",
".",
"Sub",
"(",
"mw",
".",
"start",
")",
"\n",
"totalCount",
":=",
"0",
"\n",
"for",
"_",
",",
"count",
":=",
"range",
"mw",
".",
"responseCounts",
"{",
"totalCount",
"+=",
"count",
"\n",
"}",
"\n",
"totalResponseTime",
":=",
"mw",
".",
"totalResponseTime",
".",
"Sub",
"(",
"time",
".",
"Time",
"{",
"}",
")",
"\n",
"averageResponseTime",
":=",
"time",
".",
"Duration",
"(",
"0",
")",
"\n",
"if",
"totalCount",
">",
"0",
"{",
"avgNs",
":=",
"int64",
"(",
"totalResponseTime",
")",
"/",
"int64",
"(",
"totalCount",
")",
"\n",
"averageResponseTime",
"=",
"time",
".",
"Duration",
"(",
"avgNs",
")",
"\n",
"}",
"\n",
"status",
":=",
"&",
"Status",
"{",
"Pid",
":",
"mw",
".",
"pid",
",",
"UpTime",
":",
"uptime",
".",
"String",
"(",
")",
",",
"UpTimeSec",
":",
"uptime",
".",
"Seconds",
"(",
")",
",",
"Time",
":",
"now",
".",
"String",
"(",
")",
",",
"TimeUnix",
":",
"now",
".",
"Unix",
"(",
")",
",",
"StatusCodeCount",
":",
"mw",
".",
"responseCounts",
",",
"TotalCount",
":",
"totalCount",
",",
"TotalResponseTime",
":",
"totalResponseTime",
".",
"String",
"(",
")",
",",
"TotalResponseTimeSec",
":",
"totalResponseTime",
".",
"Seconds",
"(",
")",
",",
"AverageResponseTime",
":",
"averageResponseTime",
".",
"String",
"(",
")",
",",
"AverageResponseTimeSec",
":",
"averageResponseTime",
".",
"Seconds",
"(",
")",
",",
"}",
"\n",
"mw",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"status",
"\n",
"}"
] |
// GetStatus computes and returns a Status object based on the request informations accumulated
// since the start of the process.
|
[
"GetStatus",
"computes",
"and",
"returns",
"a",
"Status",
"object",
"based",
"on",
"the",
"request",
"informations",
"accumulated",
"since",
"the",
"start",
"of",
"the",
"process",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/status.go#L91-L129
|
test
|
ant0ine/go-json-rest
|
rest/jsonp.go
|
MiddlewareFunc
|
func (mw *JsonpMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
if mw.CallbackNameKey == "" {
mw.CallbackNameKey = "callback"
}
return func(w ResponseWriter, r *Request) {
callbackName := r.URL.Query().Get(mw.CallbackNameKey)
// TODO validate the callbackName ?
if callbackName != "" {
// the client request JSONP, instantiate JsonpMiddleware.
writer := &jsonpResponseWriter{w, false, callbackName}
// call the handler with the wrapped writer
h(writer, r)
} else {
// do nothing special
h(w, r)
}
}
}
|
go
|
func (mw *JsonpMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
if mw.CallbackNameKey == "" {
mw.CallbackNameKey = "callback"
}
return func(w ResponseWriter, r *Request) {
callbackName := r.URL.Query().Get(mw.CallbackNameKey)
// TODO validate the callbackName ?
if callbackName != "" {
// the client request JSONP, instantiate JsonpMiddleware.
writer := &jsonpResponseWriter{w, false, callbackName}
// call the handler with the wrapped writer
h(writer, r)
} else {
// do nothing special
h(w, r)
}
}
}
|
[
"func",
"(",
"mw",
"*",
"JsonpMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"if",
"mw",
".",
"CallbackNameKey",
"==",
"\"\"",
"{",
"mw",
".",
"CallbackNameKey",
"=",
"\"callback\"",
"\n",
"}",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"callbackName",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"mw",
".",
"CallbackNameKey",
")",
"\n",
"if",
"callbackName",
"!=",
"\"\"",
"{",
"writer",
":=",
"&",
"jsonpResponseWriter",
"{",
"w",
",",
"false",
",",
"callbackName",
"}",
"\n",
"h",
"(",
"writer",
",",
"r",
")",
"\n",
"}",
"else",
"{",
"h",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc returns a HandlerFunc that implements the middleware.
|
[
"MiddlewareFunc",
"returns",
"a",
"HandlerFunc",
"that",
"implements",
"the",
"middleware",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/jsonp.go#L20-L42
|
test
|
ant0ine/go-json-rest
|
rest/jsonp.go
|
Flush
|
func (w *jsonpResponseWriter) Flush() {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
flusher := w.ResponseWriter.(http.Flusher)
flusher.Flush()
}
|
go
|
func (w *jsonpResponseWriter) Flush() {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
flusher := w.ResponseWriter.(http.Flusher)
flusher.Flush()
}
|
[
"func",
"(",
"w",
"*",
"jsonpResponseWriter",
")",
"Flush",
"(",
")",
"{",
"if",
"!",
"w",
".",
"wroteHeader",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n",
"flusher",
":=",
"w",
".",
"ResponseWriter",
".",
"(",
"http",
".",
"Flusher",
")",
"\n",
"flusher",
".",
"Flush",
"(",
")",
"\n",
"}"
] |
// Make sure the local WriteHeader is called, and call the parent Flush.
// Provided in order to implement the http.Flusher interface.
|
[
"Make",
"sure",
"the",
"local",
"WriteHeader",
"is",
"called",
"and",
"call",
"the",
"parent",
"Flush",
".",
"Provided",
"in",
"order",
"to",
"implement",
"the",
"http",
".",
"Flusher",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/jsonp.go#L84-L90
|
test
|
ant0ine/go-json-rest
|
rest/access_log_json.go
|
MiddlewareFunc
|
func (mw *AccessLogJsonMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
mw.Logger.Printf("%s", makeAccessLogJsonRecord(r).asJson())
}
}
|
go
|
func (mw *AccessLogJsonMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
mw.Logger.Printf("%s", makeAccessLogJsonRecord(r).asJson())
}
}
|
[
"func",
"(",
"mw",
"*",
"AccessLogJsonMiddleware",
")",
"MiddlewareFunc",
"(",
"h",
"HandlerFunc",
")",
"HandlerFunc",
"{",
"if",
"mw",
".",
"Logger",
"==",
"nil",
"{",
"mw",
".",
"Logger",
"=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"\"",
",",
"0",
")",
"\n",
"}",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"r",
"*",
"Request",
")",
"{",
"h",
"(",
"w",
",",
"r",
")",
"\n",
"mw",
".",
"Logger",
".",
"Printf",
"(",
"\"%s\"",
",",
"makeAccessLogJsonRecord",
"(",
"r",
")",
".",
"asJson",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// MiddlewareFunc makes AccessLogJsonMiddleware implement the Middleware interface.
|
[
"MiddlewareFunc",
"makes",
"AccessLogJsonMiddleware",
"implement",
"the",
"Middleware",
"interface",
"."
] |
ebb33769ae013bd5f518a8bac348c310dea768b8
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_json.go#L21-L35
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.