Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Aug 30, 2024. It is now read-only.
/coder-v1-cliPublic archive

Commitfe41093

Browse files
committed
Cleanup:
- Scope errors when possible.- Fix nil pointers in unmarshal.- Align struct tags for readability.- Explicitly discard errors with a comment on why.- Import package order.- Fmt verb for types.- More comments.Signed-off-by: Guillaume J. Charmes <guillaume@coder.com>
1 parent04a201f commitfe41093

File tree

28 files changed

+440
-370
lines changed

28 files changed

+440
-370
lines changed

‎ci/integration/setup_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ func init() {
3232

3333
// build the coder-cli binary and move to the integration testing bin directory
3434
funcbuild(pathstring)error {
35-
tar:=fmt.Sprintf("coder-cli-linux-amd64.tar.gz")
35+
tar:="coder-cli-linux-amd64.tar.gz"
3636
dir:=filepath.Dir(path)
3737
cmd:=exec.Command(
3838
"sh","-c",

‎cmd/coder/main.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@ import (
1515
"go.coder.com/flog"
1616
)
1717

18-
var (
19-
versionstring="unknown"
20-
)
18+
// Using a global for the version so it can be set at build time using ldflags.
19+
varversion="unknown"
2120

2221
funcmain() {
2322
ctx,cancel:=context.WithCancel(context.Background())
2423
defercancel()
2524

25+
// If requested, spin up the pprof webserver.
2626
ifos.Getenv("PPROF")!="" {
2727
gofunc() {
2828
log.Println(http.ListenAndServe("localhost:6060",nil))
@@ -31,15 +31,19 @@ func main() {
3131

3232
stdoutState,err:=xterminal.MakeOutputRaw(os.Stdout.Fd())
3333
iferr!=nil {
34-
flog.Fatal("set output to raw: %v",err)
34+
flog.Fatal("set output to raw: %s",err)
3535
}
36-
deferxterminal.Restore(os.Stdout.Fd(),stdoutState)
36+
deferfunc() {
37+
// Best effort. Would result in broken terminal on window but nothing we can do about it.
38+
_=xterminal.Restore(os.Stdout.Fd(),stdoutState)
39+
}()
3740

3841
app:=cmd.Make()
3942
app.Version=fmt.Sprintf("%s %s %s/%s",version,runtime.Version(),runtime.GOOS,runtime.GOARCH)
4043

41-
err=app.ExecuteContext(ctx)
42-
iferr!=nil {
44+
iferr:=app.ExecuteContext(ctx);err!=nil {
45+
// NOTE: The returned error is already handled and logged by the cmd lib (cobra), so no need to re-handle it here.
46+
// As we are in the main, if there was an error, exit the process with an error code.
4347
os.Exit(1)
4448
}
4549
}

‎coder-sdk/activity.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,23 @@ import (
55
"net/http"
66
)
77

8+
typeactivityRequeststruct {
9+
Sourcestring`json:"source"`
10+
EnvironmentIDstring`json:"environment_id"`
11+
}
12+
813
// PushActivity pushes CLI activity to Coder.
9-
func (cClient)PushActivity(ctx context.Context,sourcestring,envIDstring)error {
10-
res,err:=c.request(ctx,http.MethodPost,"/api/metrics/usage/push",map[string]string{
11-
"source":source,
12-
"environment_id":envID,
14+
func (cClient)PushActivity(ctx context.Context,source,envIDstring)error {
15+
resp,err:=c.request(ctx,http.MethodPost,"/api/metrics/usage/push",activityRequest{
16+
Source:source,
17+
EnvironmentID:envID,
1318
})
1419
iferr!=nil {
1520
returnerr
1621
}
1722

18-
ifres.StatusCode!=http.StatusOK {
19-
returnbodyError(res)
23+
ifresp.StatusCode!=http.StatusOK {
24+
returnbodyError(resp)
2025
}
2126
returnnil
2227
}

‎coder-sdk/client.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,17 @@ type Client struct {
1515
Tokenstring
1616
}
1717

18-
func (cClient)copyURL()*url.URL {
19-
swp:=*c.BaseURL
20-
return&swp
21-
}
22-
23-
func (c*Client)http() (*http.Client,error) {
18+
// newHTTPClient creates a default underlying http client and sets the auth cookie.
19+
//
20+
// NOTE: As we do not specify a custom transport, the default one from the stdlib will be used,
21+
// resulting in a persistent connection pool.
22+
// We do not set a timeout here as it could cause issue with the websocket.
23+
// The caller is expected to set it when needed.
24+
//
25+
// WARNING: If the caller sets a custom transport to set TLS settings or a custom CA, the default
26+
// pool will not be used and it might result in a new dns lookup/tls session/socket begin
27+
// established each time.
28+
func (c*Client)newHTTPClient() (*http.Client,error) {
2429
jar,err:=cookiejar.New(nil)
2530
iferr!=nil {
2631
returnnil,err
@@ -36,5 +41,6 @@ func (c *Client) http() (*http.Client, error) {
3641
Secure:c.BaseURL.Scheme=="https",
3742
},
3843
})
44+
3945
return&http.Client{Jar:jar},nil
4046
}

‎coder-sdk/devurl.go

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"net/http"
77
)
88

9-
// DevURL is the parsed json response record for a devURL from cemanager
9+
// DevURL is the parsed json response record for a devURL from cemanager.
1010
typeDevURLstruct {
1111
IDstring`json:"id" tab:"ID"`
1212
URLstring`json:"url" tab:"URL"`
@@ -20,21 +20,21 @@ type delDevURLRequest struct {
2020
DevURLIDstring`json:"url_id"`
2121
}
2222

23-
// DelDevURL deletes the specified devurl
23+
// DelDevURL deletes the specified devurl.
2424
func (cClient)DelDevURL(ctx context.Context,envID,urlIDstring)error {
2525
reqURL:=fmt.Sprintf("/api/environments/%s/devurls/%s",envID,urlID)
2626

27-
res,err:=c.request(ctx,http.MethodDelete,reqURL,delDevURLRequest{
27+
resp,err:=c.request(ctx,http.MethodDelete,reqURL,delDevURLRequest{
2828
EnvID:envID,
2929
DevURLID:urlID,
3030
})
3131
iferr!=nil {
3232
returnerr
3333
}
34-
deferres.Body.Close()
34+
deferfunc() {_=resp.Body.Close() }()// Best effort. Likely connection drop.
3535

36-
ifres.StatusCode!=http.StatusOK {
37-
returnbodyError(res)
36+
ifresp.StatusCode!=http.StatusOK {
37+
returnbodyError(resp)
3838
}
3939

4040
returnnil
@@ -47,11 +47,11 @@ type createDevURLRequest struct {
4747
Namestring`json:"name"`
4848
}
4949

50-
// InsertDevURL inserts a new devurl for the authenticated user
50+
// InsertDevURL inserts a new devurl for the authenticated user.
5151
func (cClient)InsertDevURL(ctx context.Context,envIDstring,portint,name,accessstring)error {
5252
reqURL:=fmt.Sprintf("/api/environments/%s/devurls",envID)
5353

54-
res,err:=c.request(ctx,http.MethodPost,reqURL,createDevURLRequest{
54+
resp,err:=c.request(ctx,http.MethodPost,reqURL,createDevURLRequest{
5555
EnvID:envID,
5656
Port:port,
5757
Access:access,
@@ -60,22 +60,22 @@ func (c Client) InsertDevURL(ctx context.Context, envID string, port int, name,
6060
iferr!=nil {
6161
returnerr
6262
}
63-
deferres.Body.Close()
63+
deferfunc() {_=resp.Body.Close() }()// Best effort. Likely connection drop.
6464

65-
ifres.StatusCode!=http.StatusOK {
66-
returnbodyError(res)
65+
ifresp.StatusCode!=http.StatusOK {
66+
returnbodyError(resp)
6767
}
6868

6969
returnnil
7070
}
7171

7272
typeupdateDevURLRequestcreateDevURLRequest
7373

74-
// UpdateDevURL updates an existing devurl for the authenticated user
74+
// UpdateDevURL updates an existing devurl for the authenticated user.
7575
func (cClient)UpdateDevURL(ctx context.Context,envID,urlIDstring,portint,name,accessstring)error {
7676
reqURL:=fmt.Sprintf("/api/environments/%s/devurls/%s",envID,urlID)
7777

78-
res,err:=c.request(ctx,http.MethodPut,reqURL,updateDevURLRequest{
78+
resp,err:=c.request(ctx,http.MethodPut,reqURL,updateDevURLRequest{
7979
EnvID:envID,
8080
Port:port,
8181
Access:access,
@@ -84,10 +84,10 @@ func (c Client) UpdateDevURL(ctx context.Context, envID, urlID string, port int,
8484
iferr!=nil {
8585
returnerr
8686
}
87-
deferres.Body.Close()
87+
deferfunc() {_=resp.Body.Close() }()// Best effort. Likefly connection drop.
8888

89-
ifres.StatusCode!=http.StatusOK {
90-
returnbodyError(res)
89+
ifresp.StatusCode!=http.StatusOK {
90+
returnbodyError(resp)
9191
}
9292

9393
returnnil

‎coder-sdk/env.go

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,18 @@ type Environment struct {
3131
UpdatedAt time.Time`json:"updated_at" tab:"-"`
3232
LastOpenedAt time.Time`json:"last_opened_at" tab:"-"`
3333
LastConnectionAt time.Time`json:"last_connection_at" tab:"-"`
34-
AutoOffThreshold xjson.Duration`json:"auto_off_threshold" tab:"-"`
34+
AutoOffThreshold xjson.MSDuration`json:"auto_off_threshold" tab:"-"`
3535
}
3636

3737
// RebuildMessage defines the message shown when an Environment requires a rebuild for it can be accessed.
3838
typeRebuildMessagestruct {
39-
Textstring`json:"text"`
40-
Requiredbool`json:"required"`
39+
Textstring`json:"text"`
40+
Requiredbool`json:"required"`
41+
AutoOffThreshold xjson.MSDuration`json:"auto_off_threshold" tab:"-"`
42+
RebuildMessages []struct {
43+
Textstring`json:"text"`
44+
Requiredbool`json:"required"`
45+
}`json:"rebuild_messages" tab:"-"`
4146
}
4247

4348
// EnvironmentStat represents the state of an environment
@@ -53,9 +58,7 @@ type EnvironmentStat struct {
5358
DiskUsedint64`json:"disk_used"`
5459
}
5560

56-
func (eEnvironmentStat)String()string {
57-
returnstring(e.ContainerStatus)
58-
}
61+
func (eEnvironmentStat)String()string {returnstring(e.ContainerStatus) }
5962

6063
// EnvironmentStatus refers to the states of an environment.
6164
typeEnvironmentStatusstring
@@ -69,7 +72,7 @@ const (
6972
EnvironmentUnknownEnvironmentStatus="UNKNOWN"
7073
)
7174

72-
// CreateEnvironmentRequest is used to configure a new environment
75+
// CreateEnvironmentRequest is used to configure a new environment.
7376
typeCreateEnvironmentRequeststruct {
7477
Namestring`json:"name"`
7578
ImageIDstring`json:"image_id"`
@@ -84,56 +87,55 @@ type CreateEnvironmentRequest struct {
8487
// CreateEnvironment sends a request to create an environment.
8588
func (cClient)CreateEnvironment(ctx context.Context,orgIDstring,reqCreateEnvironmentRequest) (*Environment,error) {
8689
varenvEnvironment
90+
<<<<<<<HEAD
8791
err:=c.requestBody(
8892
ctx,
8993
http.MethodPost,"/api/orgs/"+orgID+"/environments",
9094
req,
9195
&env,
9296
)
9397
return&env,err
98+
=======
99+
iferr:=c.requestBody(ctx,http.MethodPost,"/api/orgs/"+orgID+"/environments",req,&env);err!=nil {
100+
returnnil,err
101+
}
102+
return&env,nil
103+
>>>>>>> Cleanup:
94104
}
95105

96106
// EnvironmentsByOrganization gets the list of environments owned by the given user.
97107
func (cClient)EnvironmentsByOrganization(ctx context.Context,userID,orgIDstring) ([]Environment,error) {
98108
varenvs []Environment
99-
err:=c.requestBody(
100-
ctx,
101-
http.MethodGet,"/api/orgs/"+orgID+"/members/"+userID+"/environments",
102-
nil,
103-
&envs,
104-
)
105-
returnenvs,err
109+
iferr:=c.requestBody(ctx,http.MethodGet,"/api/orgs/"+orgID+"/members/"+userID+"/environments",nil,&envs);err!=nil {
110+
returnnil,err
111+
}
112+
returnenvs,nil
106113
}
107114

108115
// DeleteEnvironment deletes the environment.
109116
func (cClient)DeleteEnvironment(ctx context.Context,envIDstring)error {
110-
returnc.requestBody(
111-
ctx,
112-
http.MethodDelete,"/api/environments/"+envID,
113-
nil,
114-
nil,
115-
)
117+
returnc.requestBody(ctx,http.MethodDelete,"/api/environments/"+envID,nil,nil)
116118
}
117119

118120
// DialWsep dials an environments command execution interface
119-
// See github.com/cdr/wsep for details
121+
// Seehttps://github.com/cdr/wsep for details.
120122
func (cClient)DialWsep(ctx context.Context,env*Environment) (*websocket.Conn,error) {
121-
returnc.dialWs(ctx,"/proxy/environments/"+env.ID+"/wsep")
123+
returnc.dialWebsocket(ctx,"/proxy/environments/"+env.ID+"/wsep")
122124
}
123125

124126
// DialIDEStatus opens a websocket connection for cpu load metrics on the environment
125127
func (cClient)DialIDEStatus(ctx context.Context,envIDstring) (*websocket.Conn,error) {
126128
returnc.dialWs(ctx,"/proxy/environments/"+envID+"/ide/api/status")
127129
}
128130

129-
// DialEnvironmentBuildLog opens a websocket connection for the environment build log messages
131+
// DialEnvironmentBuildLog opens a websocket connection for the environment build log messages.
130132
func (cClient)DialEnvironmentBuildLog(ctx context.Context,envIDstring) (*websocket.Conn,error) {
131-
returnc.dialWs(ctx,"/api/environments/"+envID+"/watch-update")
133+
returnc.dialWebsocket(ctx,"/api/environments/"+envID+"/watch-update")
132134
}
133135

134-
// DialEnvironmentStats opens a websocket connection for environment stats
136+
// DialEnvironmentStats opens a websocket connection for environment stats.
135137
func (cClient)DialEnvironmentStats(ctx context.Context,envIDstring) (*websocket.Conn,error) {
136-
returnc.dialWs(ctx,"/api/environments/"+envID+"/watch-stats")
138+
returnc.dialWebsocket(ctx,"/api/environments/"+envID+"/watch-stats")
137139
}
138140

139141
// DialResourceLoad opens a websocket connection for cpu load metrics on the environment

‎coder-sdk/error.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ import (
1111
// ErrNotFound describes an error case in which the requested resource could not be found
1212
varErrNotFound=xerrors.Errorf("resource not found")
1313

14+
// apiError is the expected payload format for our errors.
1415
typeapiErrorstruct {
1516
Errstruct {
16-
Msgstring`json:"msg,required"`
17+
Msgstring`json:"msg"`// Required.
1718
}`json:"error"`
1819
}
1920

@@ -24,9 +25,12 @@ func bodyError(resp *http.Response) error {
2425
}
2526

2627
varmsgapiError
27-
err=json.NewDecoder(resp.Body).Decode(&msg)
28-
iferr!=nil||msg.Err.Msg=="" {
28+
// Try to decode the payload as an error, if it fails or if there is no error message,
29+
// return the response URL with the dump.
30+
iferr:=json.NewDecoder(resp.Body).Decode(&msg);err!=nil||msg.Err.Msg=="" {
2931
returnxerrors.Errorf("%s\n%s",resp.Request.URL,byt)
3032
}
33+
34+
// If the payload was a in the expected error format with a message, include it.
3135
returnxerrors.Errorf("%s\n%s%s",resp.Request.URL,byt,msg.Err.Msg)
3236
}

‎coder-sdk/image.go

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ type Image struct {
1111
OrganizationIDstring`json:"organization_id"`
1212
Repositorystring`json:"repository"`
1313
Descriptionstring`json:"description"`
14-
URLstring`json:"url"`//user-supplied URL for image
14+
URLstring`json:"url"`//User-supplied URL for image.
1515
DefaultCPUCoresfloat32`json:"default_cpu_cores"`
1616
DefaultMemoryGBint`json:"default_memory_gb"`
1717
DefaultDiskGBint`json:"default_disk_gb"`
@@ -28,28 +28,22 @@ type NewRegistryRequest struct {
2828

2929
// ImportImageRequest is used to import new images and registries into Coder
3030
typeImportImageRequeststruct {
31-
// RegistryID is used to import images to existing registries.
32-
RegistryID*string`json:"registry_id"`
33-
// NewRegistry is used when adding a new registry.
34-
NewRegistry*NewRegistryRequest`json:"new_registry"`
35-
// Repository refers to the image. For example: "codercom/ubuntu".
36-
Repositorystring`json:"repository"`
37-
Tagstring`json:"tag"`
38-
DefaultCPUCoresfloat32`json:"default_cpu_cores"`
39-
DefaultMemoryGBint`json:"default_memory_gb"`
40-
DefaultDiskGBint`json:"default_disk_gb"`
41-
Descriptionstring`json:"description"`
42-
URLstring`json:"url"`
31+
RegistryID*string`json:"registry_id"`// Used to import images to existing registries.
32+
NewRegistry*NewRegistryRequest`json:"new_registry"`// Used when adding a new registry.
33+
Repositorystring`json:"repository"`// Refers to the image. Ex: "codercom/ubuntu".
34+
Tagstring`json:"tag"`
35+
DefaultCPUCoresfloat32`json:"default_cpu_cores"`
36+
DefaultMemoryGBint`json:"default_memory_gb"`
37+
DefaultDiskGBint`json:"default_disk_gb"`
38+
Descriptionstring`json:"description"`
39+
URLstring`json:"url"`
4340
}
4441

4542
// ImportImage creates a new image and optionally a new registry
4643
func (cClient)ImportImage(ctx context.Context,orgIDstring,reqImportImageRequest) (*Image,error) {
47-
varimg*Image
48-
err:=c.requestBody(
49-
ctx,
50-
http.MethodPost,"/api/orgs/"+orgID+"/images",
51-
req,
52-
img,
53-
)
54-
returnimg,err
44+
varimgImage
45+
iferr:=c.requestBody(ctx,http.MethodPost,"/api/orgs/"+orgID+"/images",req,&img);err!=nil {
46+
returnnil,err
47+
}
48+
return&img,nil
5549
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp