* Fix new release creation API to allow empty target * Add more test cases * Update swaggertags/v1.9.0-dev
| @@ -11,11 +11,11 @@ | |||||
| [[projects]] | [[projects]] | ||||
| branch = "master" | branch = "master" | ||||
| digest = "1:8a559f110defa54f847a3efa2734297571d960b476699579f2008e4a37b62a1a" | |||||
| digest = "1:8df1f0527f30a02b76d0ac397118d71c0e9093c7dfa59723762a88fce6ac1170" | |||||
| name = "code.gitea.io/sdk" | name = "code.gitea.io/sdk" | ||||
| packages = ["gitea"] | packages = ["gitea"] | ||||
| pruneopts = "NUT" | pruneopts = "NUT" | ||||
| revision = "140e9fcba7583e1c6f22eb57676bb00794ef14a8" | |||||
| revision = "d5a42771e7e851e8a89c5c6ffa0f5b075342f9df" | |||||
| [[projects]] | [[projects]] | ||||
| digest = "1:3fcef06a1a6561955c94af6c7757a6fa37605eb653f0d06ab960e5bb80092195" | digest = "1:3fcef06a1a6561955c94af6c7757a6fa37605eb653f0d06ab960e5bb80092195" | ||||
| @@ -340,14 +340,6 @@ | |||||
| pruneopts = "NUT" | pruneopts = "NUT" | ||||
| revision = "503617c6b37257a55dff6293ec28556506c3a9a8" | revision = "503617c6b37257a55dff6293ec28556506c3a9a8" | ||||
| [[projects]] | |||||
| branch = "master" | |||||
| digest = "1:6326b27f8e0c8e135c8674ddbc619fae879664ac832e8e6fa6a23ce0d279ed4d" | |||||
| name = "github.com/go-macaron/gzip" | |||||
| packages = ["."] | |||||
| pruneopts = "NUT" | |||||
| revision = "cad1c6580a07c56f5f6bc52d66002a05985c5854" | |||||
| [[projects]] | [[projects]] | ||||
| branch = "master" | branch = "master" | ||||
| digest = "1:d09d3c94e1bd444464c221be961ba4005e119308f1bcd57aa5f49046fb6affd2" | digest = "1:d09d3c94e1bd444464c221be961ba4005e119308f1bcd57aa5f49046fb6affd2" | ||||
| @@ -1155,7 +1147,6 @@ | |||||
| "github.com/go-macaron/cache/redis", | "github.com/go-macaron/cache/redis", | ||||
| "github.com/go-macaron/captcha", | "github.com/go-macaron/captcha", | ||||
| "github.com/go-macaron/csrf", | "github.com/go-macaron/csrf", | ||||
| "github.com/go-macaron/gzip", | |||||
| "github.com/go-macaron/i18n", | "github.com/go-macaron/i18n", | ||||
| "github.com/go-macaron/inject", | "github.com/go-macaron/inject", | ||||
| "github.com/go-macaron/session", | "github.com/go-macaron/session", | ||||
| @@ -16,31 +16,16 @@ import ( | |||||
| "github.com/stretchr/testify/assert" | "github.com/stretchr/testify/assert" | ||||
| ) | ) | ||||
| func TestAPICreateRelease(t *testing.T) { | |||||
| prepareTestEnv(t) | |||||
| repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) | |||||
| owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) | |||||
| session := loginUser(t, owner.LowerName) | |||||
| token := getTokenForLoggedInUser(t, session) | |||||
| gitRepo, err := git.OpenRepository(repo.RepoPath()) | |||||
| assert.NoError(t, err) | |||||
| err = gitRepo.CreateTag("v0.0.1", "master") | |||||
| assert.NoError(t, err) | |||||
| commitID, err := gitRepo.GetTagCommitID("v0.0.1") | |||||
| assert.NoError(t, err) | |||||
| func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, owner *models.User, repo *models.Repository, name, target, title, desc string) *api.Release { | |||||
| urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases?token=%s", | urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases?token=%s", | ||||
| owner.Name, repo.Name, token) | owner.Name, repo.Name, token) | ||||
| req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateReleaseOption{ | req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateReleaseOption{ | ||||
| TagName: "v0.0.1", | |||||
| Title: "v0.0.1", | |||||
| Note: "test", | |||||
| TagName: name, | |||||
| Title: title, | |||||
| Note: desc, | |||||
| IsDraft: false, | IsDraft: false, | ||||
| IsPrerelease: false, | IsPrerelease: false, | ||||
| Target: commitID, | |||||
| Target: target, | |||||
| }) | }) | ||||
| resp := session.MakeRequest(t, req, http.StatusCreated) | resp := session.MakeRequest(t, req, http.StatusCreated) | ||||
| @@ -53,10 +38,32 @@ func TestAPICreateRelease(t *testing.T) { | |||||
| Note: newRelease.Note, | Note: newRelease.Note, | ||||
| }) | }) | ||||
| urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d?token=%s", | |||||
| return &newRelease | |||||
| } | |||||
| func TestAPICreateAndUpdateRelease(t *testing.T) { | |||||
| prepareTestEnv(t) | |||||
| repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) | |||||
| owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) | |||||
| session := loginUser(t, owner.LowerName) | |||||
| token := getTokenForLoggedInUser(t, session) | |||||
| gitRepo, err := git.OpenRepository(repo.RepoPath()) | |||||
| assert.NoError(t, err) | |||||
| err = gitRepo.CreateTag("v0.0.1", "master") | |||||
| assert.NoError(t, err) | |||||
| target, err := gitRepo.GetTagCommitID("v0.0.1") | |||||
| assert.NoError(t, err) | |||||
| newRelease := createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", target, "v0.0.1", "test") | |||||
| urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d?token=%s", | |||||
| owner.Name, repo.Name, newRelease.ID, token) | owner.Name, repo.Name, newRelease.ID, token) | ||||
| req = NewRequest(t, "GET", urlStr) | |||||
| resp = session.MakeRequest(t, req, http.StatusOK) | |||||
| req := NewRequest(t, "GET", urlStr) | |||||
| resp := session.MakeRequest(t, req, http.StatusOK) | |||||
| var release api.Release | var release api.Release | ||||
| DecodeJSON(t, resp, &release) | DecodeJSON(t, resp, &release) | ||||
| @@ -83,3 +90,31 @@ func TestAPICreateRelease(t *testing.T) { | |||||
| Note: newRelease.Note, | Note: newRelease.Note, | ||||
| }) | }) | ||||
| } | } | ||||
| func TestAPICreateReleaseToDefaultBranch(t *testing.T) { | |||||
| prepareTestEnv(t) | |||||
| repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) | |||||
| owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) | |||||
| session := loginUser(t, owner.LowerName) | |||||
| token := getTokenForLoggedInUser(t, session) | |||||
| createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", "", "v0.0.1", "test") | |||||
| } | |||||
| func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { | |||||
| prepareTestEnv(t) | |||||
| repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) | |||||
| owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) | |||||
| session := loginUser(t, owner.LowerName) | |||||
| token := getTokenForLoggedInUser(t, session) | |||||
| gitRepo, err := git.OpenRepository(repo.RepoPath()) | |||||
| assert.NoError(t, err) | |||||
| err = gitRepo.CreateTag("v0.0.1", "master") | |||||
| assert.NoError(t, err) | |||||
| createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", "", "v0.0.1", "test") | |||||
| } | |||||
| @@ -152,6 +152,10 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) { | |||||
| ctx.ServerError("GetRelease", err) | ctx.ServerError("GetRelease", err) | ||||
| return | return | ||||
| } | } | ||||
| // If target is not provided use default branch | |||||
| if len(form.Target) == 0 { | |||||
| form.Target = ctx.Repo.Repository.DefaultBranch | |||||
| } | |||||
| rel = &models.Release{ | rel = &models.Release{ | ||||
| RepoID: ctx.Repo.Repository.ID, | RepoID: ctx.Repo.Repository.ID, | ||||
| PublisherID: ctx.User.ID, | PublisherID: ctx.User.ID, | ||||
| @@ -7570,6 +7570,13 @@ | |||||
| "description": "PayloadCommit represents a commit", | "description": "PayloadCommit represents a commit", | ||||
| "type": "object", | "type": "object", | ||||
| "properties": { | "properties": { | ||||
| "added": { | |||||
| "type": "array", | |||||
| "items": { | |||||
| "type": "string" | |||||
| }, | |||||
| "x-go-name": "Added" | |||||
| }, | |||||
| "author": { | "author": { | ||||
| "$ref": "#/definitions/PayloadUser" | "$ref": "#/definitions/PayloadUser" | ||||
| }, | }, | ||||
| @@ -7585,6 +7592,20 @@ | |||||
| "type": "string", | "type": "string", | ||||
| "x-go-name": "Message" | "x-go-name": "Message" | ||||
| }, | }, | ||||
| "modified": { | |||||
| "type": "array", | |||||
| "items": { | |||||
| "type": "string" | |||||
| }, | |||||
| "x-go-name": "Modified" | |||||
| }, | |||||
| "removed": { | |||||
| "type": "array", | |||||
| "items": { | |||||
| "type": "string" | |||||
| }, | |||||
| "x-go-name": "Removed" | |||||
| }, | |||||
| "timestamp": { | "timestamp": { | ||||
| "type": "string", | "type": "string", | ||||
| "format": "date-time", | "format": "date-time", | ||||
| @@ -70,6 +70,8 @@ func (c *Client) getResponse(method, path string, header http.Header, body io.Re | |||||
| return nil, errors.New("403 Forbidden") | return nil, errors.New("403 Forbidden") | ||||
| case 404: | case 404: | ||||
| return nil, errors.New("404 Not Found") | return nil, errors.New("404 Not Found") | ||||
| case 409: | |||||
| return nil, errors.New("409 Conflict") | |||||
| case 422: | case 422: | ||||
| return nil, fmt.Errorf("422 Unprocessable Entity: %s", string(data)) | return nil, fmt.Errorf("422 Unprocessable Entity: %s", string(data)) | ||||
| } | } | ||||
| @@ -77,7 +79,9 @@ func (c *Client) getResponse(method, path string, header http.Header, body io.Re | |||||
| if resp.StatusCode/100 != 2 { | if resp.StatusCode/100 != 2 { | ||||
| errMap := make(map[string]interface{}) | errMap := make(map[string]interface{}) | ||||
| if err = json.Unmarshal(data, &errMap); err != nil { | if err = json.Unmarshal(data, &errMap); err != nil { | ||||
| return nil, err | |||||
| // when the JSON can't be parsed, data was probably empty or a plain string, | |||||
| // so we try to return a helpful error anyway | |||||
| return nil, fmt.Errorf("Unknown API Error: %d %s", resp.StatusCode, string(data)) | |||||
| } | } | ||||
| return nil, errors.New(errMap["message"].(string)) | return nil, errors.New(errMap["message"].(string)) | ||||
| } | } | ||||
| @@ -160,6 +160,9 @@ type PayloadCommit struct { | |||||
| Verification *PayloadCommitVerification `json:"verification"` | Verification *PayloadCommitVerification `json:"verification"` | ||||
| // swagger:strfmt date-time | // swagger:strfmt date-time | ||||
| Timestamp time.Time `json:"timestamp"` | Timestamp time.Time `json:"timestamp"` | ||||
| Added []string `json:"added"` | |||||
| Removed []string `json:"removed"` | |||||
| Modified []string `json:"modified"` | |||||
| } | } | ||||
| // PayloadCommitVerification represents the GPG verification of a commit | // PayloadCommitVerification represents the GPG verification of a commit | ||||
| @@ -53,7 +53,7 @@ func (c *Client) GetRelease(user, repo string, id int64) (*Release, error) { | |||||
| type CreateReleaseOption struct { | type CreateReleaseOption struct { | ||||
| // required: true | // required: true | ||||
| TagName string `json:"tag_name" binding:"Required"` | TagName string `json:"tag_name" binding:"Required"` | ||||
| Target string `json:"target_commitish" binding:"Required"` | |||||
| Target string `json:"target_commitish"` | |||||
| Title string `json:"name"` | Title string `json:"name"` | ||||
| Note string `json:"body"` | Note string `json:"body"` | ||||
| IsDraft bool `json:"draft"` | IsDraft bool `json:"draft"` | ||||
| @@ -0,0 +1,48 @@ | |||||
| // Copyright 2018 The Gogs Authors. All rights reserved. | |||||
| // Copyright 2019 The Gitea Authors. All rights reserved. | |||||
| // Use of this source code is governed by a MIT-style | |||||
| // license that can be found in the LICENSE file. | |||||
| package gitea | |||||
| import ( | |||||
| "fmt" | |||||
| ) | |||||
| // CommitMeta contains meta information of a commit in terms of API. | |||||
| type CommitMeta struct { | |||||
| URL string `json:"url"` | |||||
| SHA string `json:"sha"` | |||||
| } | |||||
| // CommitUser contains information of a user in the context of a commit. | |||||
| type CommitUser struct { | |||||
| Name string `json:"name"` | |||||
| Email string `json:"email"` | |||||
| Date string `json:"date"` | |||||
| } | |||||
| // RepoCommit contains information of a commit in the context of a repository. | |||||
| type RepoCommit struct { | |||||
| URL string `json:"url"` | |||||
| Author *CommitUser `json:"author"` | |||||
| Committer *CommitUser `json:"committer"` | |||||
| Message string `json:"message"` | |||||
| Tree *CommitMeta `json:"tree"` | |||||
| } | |||||
| // Commit contains information generated from a Git commit. | |||||
| type Commit struct { | |||||
| *CommitMeta | |||||
| HTMLURL string `json:"html_url"` | |||||
| RepoCommit *RepoCommit `json:"commit"` | |||||
| Author *User `json:"author"` | |||||
| Committer *User `json:"committer"` | |||||
| Parents []*CommitMeta `json:"parents"` | |||||
| } | |||||
| // GetSingleCommit returns a single commit | |||||
| func (c *Client) GetSingleCommit(user, repo, commitID string) (*Commit, error) { | |||||
| commit := new(Commit) | |||||
| return commit, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s", user, repo, commitID), nil, nil, &commit) | |||||
| } | |||||
| @@ -0,0 +1,26 @@ | |||||
| // Copyright 2019 The Gitea Authors. All rights reserved. | |||||
| // Use of this source code is governed by a MIT-style | |||||
| // license that can be found in the LICENSE file. | |||||
| package gitea | |||||
| import ( | |||||
| "fmt" | |||||
| ) | |||||
| // Tag represents a repository tag | |||||
| type Tag struct { | |||||
| Name string `json:"name"` | |||||
| Commit struct { | |||||
| SHA string `json:"sha"` | |||||
| URL string `json:"url"` | |||||
| } `json:"commit"` | |||||
| ZipballURL string `json:"zipball_url"` | |||||
| TarballURL string `json:"tarball_url"` | |||||
| } | |||||
| // ListRepoTags list all the branches of one repository | |||||
| func (c *Client) ListRepoTags(user, repo string) ([]*Tag, error) { | |||||
| tags := make([]*Tag, 0, 10) | |||||
| return tags, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/tags", user, repo), nil, nil, &tags) | |||||
| } | |||||
| @@ -1,191 +0,0 @@ | |||||
| Apache License | |||||
| Version 2.0, January 2004 | |||||
| http://www.apache.org/licenses/ | |||||
| TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION | |||||
| 1. Definitions. | |||||
| "License" shall mean the terms and conditions for use, reproduction, and | |||||
| distribution as defined by Sections 1 through 9 of this document. | |||||
| "Licensor" shall mean the copyright owner or entity authorized by the copyright | |||||
| owner that is granting the License. | |||||
| "Legal Entity" shall mean the union of the acting entity and all other entities | |||||
| that control, are controlled by, or are under common control with that entity. | |||||
| For the purposes of this definition, "control" means (i) the power, direct or | |||||
| indirect, to cause the direction or management of such entity, whether by | |||||
| contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the | |||||
| outstanding shares, or (iii) beneficial ownership of such entity. | |||||
| "You" (or "Your") shall mean an individual or Legal Entity exercising | |||||
| permissions granted by this License. | |||||
| "Source" form shall mean the preferred form for making modifications, including | |||||
| but not limited to software source code, documentation source, and configuration | |||||
| files. | |||||
| "Object" form shall mean any form resulting from mechanical transformation or | |||||
| translation of a Source form, including but not limited to compiled object code, | |||||
| generated documentation, and conversions to other media types. | |||||
| "Work" shall mean the work of authorship, whether in Source or Object form, made | |||||
| available under the License, as indicated by a copyright notice that is included | |||||
| in or attached to the work (an example is provided in the Appendix below). | |||||
| "Derivative Works" shall mean any work, whether in Source or Object form, that | |||||
| is based on (or derived from) the Work and for which the editorial revisions, | |||||
| annotations, elaborations, or other modifications represent, as a whole, an | |||||
| original work of authorship. For the purposes of this License, Derivative Works | |||||
| shall not include works that remain separable from, or merely link (or bind by | |||||
| name) to the interfaces of, the Work and Derivative Works thereof. | |||||
| "Contribution" shall mean any work of authorship, including the original version | |||||
| of the Work and any modifications or additions to that Work or Derivative Works | |||||
| thereof, that is intentionally submitted to Licensor for inclusion in the Work | |||||
| by the copyright owner or by an individual or Legal Entity authorized to submit | |||||
| on behalf of the copyright owner. For the purposes of this definition, | |||||
| "submitted" means any form of electronic, verbal, or written communication sent | |||||
| to the Licensor or its representatives, including but not limited to | |||||
| communication on electronic mailing lists, source code control systems, and | |||||
| issue tracking systems that are managed by, or on behalf of, the Licensor for | |||||
| the purpose of discussing and improving the Work, but excluding communication | |||||
| that is conspicuously marked or otherwise designated in writing by the copyright | |||||
| owner as "Not a Contribution." | |||||
| "Contributor" shall mean Licensor and any individual or Legal Entity on behalf | |||||
| of whom a Contribution has been received by Licensor and subsequently | |||||
| incorporated within the Work. | |||||
| 2. Grant of Copyright License. | |||||
| Subject to the terms and conditions of this License, each Contributor hereby | |||||
| grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, | |||||
| irrevocable copyright license to reproduce, prepare Derivative Works of, | |||||
| publicly display, publicly perform, sublicense, and distribute the Work and such | |||||
| Derivative Works in Source or Object form. | |||||
| 3. Grant of Patent License. | |||||
| Subject to the terms and conditions of this License, each Contributor hereby | |||||
| grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, | |||||
| irrevocable (except as stated in this section) patent license to make, have | |||||
| made, use, offer to sell, sell, import, and otherwise transfer the Work, where | |||||
| such license applies only to those patent claims licensable by such Contributor | |||||
| that are necessarily infringed by their Contribution(s) alone or by combination | |||||
| of their Contribution(s) with the Work to which such Contribution(s) was | |||||
| submitted. If You institute patent litigation against any entity (including a | |||||
| cross-claim or counterclaim in a lawsuit) alleging that the Work or a | |||||
| Contribution incorporated within the Work constitutes direct or contributory | |||||
| patent infringement, then any patent licenses granted to You under this License | |||||
| for that Work shall terminate as of the date such litigation is filed. | |||||
| 4. Redistribution. | |||||
| You may reproduce and distribute copies of the Work or Derivative Works thereof | |||||
| in any medium, with or without modifications, and in Source or Object form, | |||||
| provided that You meet the following conditions: | |||||
| You must give any other recipients of the Work or Derivative Works a copy of | |||||
| this License; and | |||||
| You must cause any modified files to carry prominent notices stating that You | |||||
| changed the files; and | |||||
| You must retain, in the Source form of any Derivative Works that You distribute, | |||||
| all copyright, patent, trademark, and attribution notices from the Source form | |||||
| of the Work, excluding those notices that do not pertain to any part of the | |||||
| Derivative Works; and | |||||
| If the Work includes a "NOTICE" text file as part of its distribution, then any | |||||
| Derivative Works that You distribute must include a readable copy of the | |||||
| attribution notices contained within such NOTICE file, excluding those notices | |||||
| that do not pertain to any part of the Derivative Works, in at least one of the | |||||
| following places: within a NOTICE text file distributed as part of the | |||||
| Derivative Works; within the Source form or documentation, if provided along | |||||
| with the Derivative Works; or, within a display generated by the Derivative | |||||
| Works, if and wherever such third-party notices normally appear. The contents of | |||||
| the NOTICE file are for informational purposes only and do not modify the | |||||
| License. You may add Your own attribution notices within Derivative Works that | |||||
| You distribute, alongside or as an addendum to the NOTICE text from the Work, | |||||
| provided that such additional attribution notices cannot be construed as | |||||
| modifying the License. | |||||
| You may add Your own copyright statement to Your modifications and may provide | |||||
| additional or different license terms and conditions for use, reproduction, or | |||||
| distribution of Your modifications, or for any such Derivative Works as a whole, | |||||
| provided Your use, reproduction, and distribution of the Work otherwise complies | |||||
| with the conditions stated in this License. | |||||
| 5. Submission of Contributions. | |||||
| Unless You explicitly state otherwise, any Contribution intentionally submitted | |||||
| for inclusion in the Work by You to the Licensor shall be under the terms and | |||||
| conditions of this License, without any additional terms or conditions. | |||||
| Notwithstanding the above, nothing herein shall supersede or modify the terms of | |||||
| any separate license agreement you may have executed with Licensor regarding | |||||
| such Contributions. | |||||
| 6. Trademarks. | |||||
| This License does not grant permission to use the trade names, trademarks, | |||||
| service marks, or product names of the Licensor, except as required for | |||||
| reasonable and customary use in describing the origin of the Work and | |||||
| reproducing the content of the NOTICE file. | |||||
| 7. Disclaimer of Warranty. | |||||
| Unless required by applicable law or agreed to in writing, Licensor provides the | |||||
| Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, | |||||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, | |||||
| including, without limitation, any warranties or conditions of TITLE, | |||||
| NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are | |||||
| solely responsible for determining the appropriateness of using or | |||||
| redistributing the Work and assume any risks associated with Your exercise of | |||||
| permissions under this License. | |||||
| 8. Limitation of Liability. | |||||
| In no event and under no legal theory, whether in tort (including negligence), | |||||
| contract, or otherwise, unless required by applicable law (such as deliberate | |||||
| and grossly negligent acts) or agreed to in writing, shall any Contributor be | |||||
| liable to You for damages, including any direct, indirect, special, incidental, | |||||
| or consequential damages of any character arising as a result of this License or | |||||
| out of the use or inability to use the Work (including but not limited to | |||||
| damages for loss of goodwill, work stoppage, computer failure or malfunction, or | |||||
| any and all other commercial damages or losses), even if such Contributor has | |||||
| been advised of the possibility of such damages. | |||||
| 9. Accepting Warranty or Additional Liability. | |||||
| While redistributing the Work or Derivative Works thereof, You may choose to | |||||
| offer, and charge a fee for, acceptance of support, warranty, indemnity, or | |||||
| other liability obligations and/or rights consistent with this License. However, | |||||
| in accepting such obligations, You may act only on Your own behalf and on Your | |||||
| sole responsibility, not on behalf of any other Contributor, and only if You | |||||
| agree to indemnify, defend, and hold each Contributor harmless for any liability | |||||
| incurred by, or claims asserted against, such Contributor by reason of your | |||||
| accepting any such warranty or additional liability. | |||||
| END OF TERMS AND CONDITIONS | |||||
| APPENDIX: How to apply the Apache License to your work | |||||
| To apply the Apache License to your work, attach the following boilerplate | |||||
| notice, with the fields enclosed by brackets "[]" replaced with your own | |||||
| identifying information. (Don't include the brackets!) The text should be | |||||
| enclosed in the appropriate comment syntax for the file format. We also | |||||
| recommend that a file or class name and description of purpose be included on | |||||
| the same "printed page" as the copyright notice for easier identification within | |||||
| third-party archives. | |||||
| Copyright [yyyy] [name of copyright owner] | |||||
| Licensed under the Apache License, Version 2.0 (the "License"); | |||||
| you may not use this file except in compliance with the License. | |||||
| You may obtain a copy of the License at | |||||
| http://www.apache.org/licenses/LICENSE-2.0 | |||||
| Unless required by applicable law or agreed to in writing, software | |||||
| distributed under the License is distributed on an "AS IS" BASIS, | |||||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |||||
| See the License for the specific language governing permissions and | |||||
| limitations under the License. | |||||
| @@ -1,121 +0,0 @@ | |||||
| // Copyright 2013 Martini Authors | |||||
| // Copyright 2015 The Macaron Authors | |||||
| // | |||||
| // Licensed under the Apache License, Version 2.0 (the "License"): you may | |||||
| // not use this file except in compliance with the License. You may obtain | |||||
| // a copy of the License at | |||||
| // | |||||
| // http://www.apache.org/licenses/LICENSE-2.0 | |||||
| // | |||||
| // Unless required by applicable law or agreed to in writing, software | |||||
| // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | |||||
| // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | |||||
| // License for the specific language governing permissions and limitations | |||||
| // under the License. | |||||
| package gzip | |||||
| import ( | |||||
| "bufio" | |||||
| "fmt" | |||||
| "net" | |||||
| "net/http" | |||||
| "strings" | |||||
| "github.com/klauspost/compress/gzip" | |||||
| "gopkg.in/macaron.v1" | |||||
| ) | |||||
| const ( | |||||
| _HEADER_ACCEPT_ENCODING = "Accept-Encoding" | |||||
| _HEADER_CONTENT_ENCODING = "Content-Encoding" | |||||
| _HEADER_CONTENT_LENGTH = "Content-Length" | |||||
| _HEADER_CONTENT_TYPE = "Content-Type" | |||||
| _HEADER_VARY = "Vary" | |||||
| ) | |||||
| // Options represents a struct for specifying configuration options for the GZip middleware. | |||||
| type Options struct { | |||||
| // Compression level. Can be DefaultCompression(-1), ConstantCompression(-2) | |||||
| // or any integer value between BestSpeed(1) and BestCompression(9) inclusive. | |||||
| CompressionLevel int | |||||
| } | |||||
| func isCompressionLevelValid(level int) bool { | |||||
| return level == gzip.DefaultCompression || | |||||
| level == gzip.ConstantCompression || | |||||
| (level >= gzip.BestSpeed && level <= gzip.BestCompression) | |||||
| } | |||||
| func prepareOptions(options []Options) Options { | |||||
| var opt Options | |||||
| if len(options) > 0 { | |||||
| opt = options[0] | |||||
| } | |||||
| if !isCompressionLevelValid(opt.CompressionLevel) { | |||||
| // For web content, level 4 seems to be a sweet spot. | |||||
| opt.CompressionLevel = 4 | |||||
| } | |||||
| return opt | |||||
| } | |||||
| // Gziper returns a Handler that adds gzip compression to all requests. | |||||
| // Make sure to include the Gzip middleware above other middleware | |||||
| // that alter the response body (like the render middleware). | |||||
| func Gziper(options ...Options) macaron.Handler { | |||||
| opt := prepareOptions(options) | |||||
| return func(ctx *macaron.Context) { | |||||
| if !strings.Contains(ctx.Req.Header.Get(_HEADER_ACCEPT_ENCODING), "gzip") { | |||||
| return | |||||
| } | |||||
| headers := ctx.Resp.Header() | |||||
| headers.Set(_HEADER_CONTENT_ENCODING, "gzip") | |||||
| headers.Set(_HEADER_VARY, _HEADER_ACCEPT_ENCODING) | |||||
| // We've made sure compression level is valid in prepareGzipOptions, | |||||
| // no need to check same error again. | |||||
| gz, err := gzip.NewWriterLevel(ctx.Resp, opt.CompressionLevel) | |||||
| if err != nil { | |||||
| panic(err.Error()) | |||||
| } | |||||
| defer gz.Close() | |||||
| gzw := gzipResponseWriter{gz, ctx.Resp} | |||||
| ctx.Resp = gzw | |||||
| ctx.MapTo(gzw, (*http.ResponseWriter)(nil)) | |||||
| // Check if render middleware has been registered, | |||||
| // if yes, we need to modify ResponseWriter for it as well. | |||||
| if _, ok := ctx.Render.(*macaron.DummyRender); !ok { | |||||
| ctx.Render.SetResponseWriter(gzw) | |||||
| } | |||||
| ctx.Next() | |||||
| // delete content length after we know we have been written to | |||||
| gzw.Header().Del("Content-Length") | |||||
| } | |||||
| } | |||||
| type gzipResponseWriter struct { | |||||
| w *gzip.Writer | |||||
| macaron.ResponseWriter | |||||
| } | |||||
| func (grw gzipResponseWriter) Write(p []byte) (int, error) { | |||||
| if len(grw.Header().Get(_HEADER_CONTENT_TYPE)) == 0 { | |||||
| grw.Header().Set(_HEADER_CONTENT_TYPE, http.DetectContentType(p)) | |||||
| } | |||||
| return grw.w.Write(p) | |||||
| } | |||||
| func (grw gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { | |||||
| hijacker, ok := grw.ResponseWriter.(http.Hijacker) | |||||
| if !ok { | |||||
| return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface") | |||||
| } | |||||
| return hijacker.Hijack() | |||||
| } | |||||