├── .gitignore ├── LICENSE ├── README.md ├── _config.yml ├── main.go ├── request.go ├── request_test.go ├── response.go ├── response_test.go └── utils.go /.gitignore: -------------------------------------------------------------------------------- 1 | *.swo 2 | *.swp 3 | .DS_Store 4 | .env 5 | .idea 6 | .vagrant 7 | vendor 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | HttpRequest 2 | ======= 3 | A simple `HTTP Request` package for golang. `GET` `POST` `DELETE` `PUT` 4 | 5 | 6 | 7 | ### Installation 8 | go get github.com/kirinlabs/HttpRequest 9 | 10 | 11 | ### How do we use HttpRequest? 12 | 13 | #### Create request object use http.DefaultTransport 14 | ```go 15 | resp, err := HttpRequest.Get("http://127.0.0.1:8000") 16 | resp, err := HttpRequest.SetTimeout(5).Get("http://127.0.0.1:8000") 17 | resp, err := HttpRequest.Debug(true).SetHeaders(map[string]string{}).Get("http://127.0.0.1:8000") 18 | 19 | OR 20 | 21 | req := HttpRequest.NewRequest() 22 | req := HttpRequest.NewRequest().Debug(true).SetTimeout(5*time.Second) 23 | resp, err := req.Get("http://127.0.0.1:8000") 24 | resp, err := req.Get("http://127.0.0.1:8000",nil) 25 | resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest") 26 | resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest","address=beijing") 27 | 28 | ``` 29 | 30 | #### Set headers 31 | ```go 32 | req.SetHeaders(map[string]string{ 33 | "Content-Type": "application/x-www-form-urlencoded", 34 | "Connection": "keep-alive", 35 | }) 36 | 37 | req.SetHeaders(map[string]string{ 38 | "Source":"api", 39 | }) 40 | ``` 41 | 42 | #### Set cookies 43 | ```go 44 | req.SetCookies(map[string]string{ 45 | "name":"json", 46 | "token":"", 47 | }) 48 | 49 | OR 50 | 51 | HttpRequest.SetCookies(map[string]string{ 52 | "age":"19", 53 | }).Post() 54 | ``` 55 | 56 | #### Set basic auth 57 | ```go 58 | req.SetBasicAuth("username","password") 59 | ``` 60 | 61 | #### Set timeout 62 | ```go 63 | req.SetTimeout(5) //default 30s 64 | ``` 65 | 66 | #### Transport 67 | If you want to customize the Client object and reuse TCP connections, you need to define a global http.RoundTripper or & http.Transport, because the reuse of the http connection pool is based on Transport. 68 | ```go 69 | var transport *http.Transport 70 | func init() { 71 | transport = &http.Transport{ 72 | DialContext: (&net.Dialer{ 73 | Timeout: 30 * time.Second, 74 | KeepAlive: 30 * time.Second, 75 | DualStack: true, 76 | }).DialContext, 77 | MaxIdleConns: 100, 78 | IdleConnTimeout: 90 * time.Second, 79 | TLSHandshakeTimeout: 5 * time.Second, 80 | ExpectContinueTimeout: 1 * time.Second, 81 | } 82 | } 83 | 84 | func demo(){ 85 | // Use http.DefaultTransport 86 | res, err := HttpRequest.Get("http://127.0.0.1:8080") 87 | // Use custom Transport 88 | res, err := HttpRequest.Transport(transport).Get("http://127.0.0.1:8080") 89 | } 90 | ``` 91 | 92 | #### Keep Alives,Only effective for custom Transport 93 | ```go 94 | req.DisableKeepAlives(false) 95 | 96 | HttpRequest.Transport(transport).DisableKeepAlives(false).Get("http://127.0.0.1:8080") 97 | ``` 98 | 99 | #### Ignore Https certificate validation,Only effective for custom Transport 100 | ```go 101 | req.SetTLSClient(&tls.Config{InsecureSkipVerify: true}) 102 | 103 | HttpRequest.Transport(transport).SetTLSClient(&tls.Config{InsecureSkipVerify: true}).Get("http://127.0.0.1:8080") 104 | ``` 105 | 106 | #### Object-oriented operation mode 107 | ```go 108 | req := HttpRequest.NewRequest(). 109 | Debug(true). 110 | SetHeaders(map[string]string{ 111 | "Content-Type": "application/x-www-form-urlencoded", 112 | }).SetTimeout(5) 113 | resp,err := req.Get("http://127.0.0.1") 114 | 115 | resp,err := HttpRequest.NewRequest().Get("http://127.0.0.1") 116 | ``` 117 | 118 | ### GET 119 | 120 | #### Query parameter 121 | ```go 122 | resp, err := req.Get("http://127.0.0.1:8000") 123 | resp, err := req.Get("http://127.0.0.1:8000",nil) 124 | resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest") 125 | resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest","address=beijing") 126 | 127 | OR 128 | 129 | resp, err := HttpRequest.Get("http://127.0.0.1:8000") 130 | resp, err := HttpRequest.Debug(true).SetHeaders(map[string]string{}).Get("http://127.0.0.1:8000") 131 | ``` 132 | 133 | 134 | #### Multi parameter 135 | ```go 136 | resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest",map[string]interface{}{ 137 | "name": "jason", 138 | "score": 100, 139 | }) 140 | defer resp.Close() 141 | 142 | body, err := resp.Body() 143 | if err != nil { 144 | return 145 | } 146 | 147 | return string(body) 148 | ``` 149 | 150 | 151 | ### POST 152 | 153 | ```go 154 | // Send nil 155 | resp, err := HttpRequest.Post("http://127.0.0.1:8000") 156 | 157 | // Send integer 158 | resp, err := HttpRequest.Post("http://127.0.0.1:8000", 100) 159 | 160 | // Send []byte 161 | resp, err := HttpRequest.Post("http://127.0.0.1:8000", []byte("bytes data")) 162 | 163 | // Send io.Reader 164 | resp, err := HttpRequest.Post("http://127.0.0.1:8000", bytes.NewReader(buf []byte)) 165 | resp, err := HttpRequest.Post("http://127.0.0.1:8000", strings.NewReader("string data")) 166 | resp, err := HttpRequest.Post("http://127.0.0.1:8000", bytes.NewBuffer(buf []byte)) 167 | 168 | // Send string 169 | resp, err := HttpRequest.Post("http://127.0.0.1:8000", "title=github&type=1") 170 | 171 | // Send JSON 172 | resp, err := HttpRequest.JSON().Post("http://127.0.0.1:8000", "{\"id\":10,\"title\":\"HttpRequest\"}") 173 | 174 | // Send map[string]interface{}{} 175 | resp, err := req.Post("http://127.0.0.1:8000", map[string]interface{}{ 176 | "id": 10, 177 | "title": "HttpRequest", 178 | }) 179 | defer resp.Close() 180 | 181 | body, err := resp.Body() 182 | if err != nil { 183 | return 184 | } 185 | return string(body) 186 | 187 | resp, err := HttpRequest.Post("http://127.0.0.1:8000") 188 | resp, err := HttpRequest.JSON().Post("http://127.0.0.1:8000",map[string]interface{}{"title":"github"}) 189 | resp, err := HttpRequest.Debug(true).SetHeaders(map[string]string{}).JSON().Post("http://127.0.0.1:8000","{\"title\":\"github\"}") 190 | ``` 191 | 192 | ### Jar 193 | ```go 194 | j, _ := cookiejar.New(nil) 195 | j.SetCookies(&url.URL{ 196 | Scheme: "http", 197 | Host: "127.0.0.1:8000", 198 | }, []*http.Cookie{ 199 | &http.Cookie{Name: "identity-user", Value: "83df5154d0ed31d166f5c54ddc"}, 200 | &http.Cookie{Name: "token_id", Value: "JSb99d0e7d809610186813583b4f802a37b99d"}, 201 | }) 202 | resp, err := HttpRequest.Jar(j).Get("http://127.0.0.1:8000/city/list") 203 | defer resp.Close() 204 | 205 | if err != nil { 206 | log.Fatalf("Request error:%v", err.Error()) 207 | } 208 | ``` 209 | 210 | ### Proxy 211 | ```go 212 | proxy, err := url.Parse("http://proxyip:proxyport") 213 | if err != nil { 214 | log.Println(err) 215 | } 216 | 217 | resp, err := HttpRequest.Proxy(http.ProxyURL(proxy)).Get("http://127.0.0.1:8000/ip") 218 | defer resp.Close() 219 | 220 | if err != nil { 221 | log.Println("Request error:%v", err.Error()) 222 | } 223 | 224 | body, err := resp.Body() 225 | if err != nil { 226 | log.Println("Get body error:%v", err.Error()) 227 | } 228 | log.Println(string(body)) 229 | ``` 230 | 231 | ### Upload 232 | Params: url, filename, fileinput 233 | 234 | ```go 235 | resp, err := req.Upload("http://127.0.0.1:8000/upload", "/root/demo.txt","uploadFile") 236 | body, err := resp.Body() 237 | defer resp.Close() 238 | if err != nil { 239 | return 240 | } 241 | return string(body) 242 | ``` 243 | 244 | 245 | ### Debug 246 | #### Default false 247 | 248 | ```go 249 | req.Debug(true) 250 | ``` 251 | 252 | #### Print in standard output: 253 | ```go 254 | [HttpRequest] 255 | ------------------------------------------------------------------- 256 | Request: GET http://127.0.0.1:8000?name=iceview&age=19&score=100 257 | Headers: map[Content-Type:application/x-www-form-urlencoded] 258 | Cookies: map[] 259 | Timeout: 30s 260 | ReqBody: map[age:19 score:100] 261 | ------------------------------------------------------------------- 262 | ``` 263 | 264 | 265 | ## Json 266 | Post JSON request 267 | 268 | #### Set header 269 | ```go 270 | req.SetHeaders(map[string]string{"Content-Type": "application/json"}) 271 | ``` 272 | Or 273 | ```go 274 | req.JSON().Post("http://127.0.0.1:8000", map[string]interface{}{ 275 | "id": 10, 276 | "title": "github", 277 | }) 278 | 279 | req.JSON().Post("http://127.0.0.1:8000", "{\"title\":\"github\",\"id\":10}") 280 | ``` 281 | 282 | #### Post request 283 | ```go 284 | resp, err := req.Post("http://127.0.0.1:8000", map[string]interface{}{ 285 | "id": 10, 286 | "title": "HttpRequest", 287 | }) 288 | ``` 289 | 290 | #### Print formatted JSON 291 | ```go 292 | str, err := resp.Export() 293 | if err != nil { 294 | return 295 | } 296 | ``` 297 | 298 | #### Unmarshal JSON 299 | ```go 300 | var u User 301 | err := resp.Json(&u) 302 | if err != nil { 303 | return err 304 | } 305 | 306 | var m map[string]interface{} 307 | err := resp.Json(&m) 308 | if err != nil { 309 | return err 310 | } 311 | ``` 312 | 313 | ### Response 314 | 315 | #### Response() *http.Response 316 | ```go 317 | resp, err := req.Post("http://127.0.0.1:8000/") //res is a http.Response object 318 | ``` 319 | 320 | #### StatusCode() int 321 | ```go 322 | resp.StatusCode() 323 | ``` 324 | 325 | #### Body() ([]byte, error) 326 | ```go 327 | body, err := resp.Body() 328 | log.Println(string(body)) 329 | ``` 330 | 331 | #### Close() error 332 | ```go 333 | resp.Close() 334 | ``` 335 | 336 | #### Time() string 337 | ```go 338 | resp.Time() //ms 339 | ``` 340 | 341 | #### Print formatted JSON 342 | ```go 343 | str, err := resp.Export() 344 | if err != nil { 345 | return 346 | } 347 | ``` 348 | 349 | #### Unmarshal JSON 350 | ```go 351 | var u User 352 | err := resp.Json(&u) 353 | if err != nil { 354 | return err 355 | } 356 | 357 | var m map[string]interface{} 358 | err := resp.Json(&m) 359 | if err != nil { 360 | return err 361 | } 362 | ``` 363 | 364 | #### Url() string 365 | ```go 366 | resp.Url() //return the requested url 367 | ``` 368 | 369 | #### Headers() http.Header 370 | ```go 371 | resp.Headers() //return the response headers 372 | resp.Headers().Get("Content-Type") 373 | ``` 374 | 375 | #### Cookies() []*http.Cookie 376 | ```go 377 | resp.Cookies() //return the response cookies 378 | ``` 379 | 380 | ### Advanced 381 | #### GET 382 | ```go 383 | import "github.com/kirinlabs/HttpRequest" 384 | 385 | resp,err := HttpRequest.Get("http://127.0.0.1:8000/") 386 | resp,err := HttpRequest.Get("http://127.0.0.1:8000/","title=github") 387 | resp,err := HttpRequest.Get("http://127.0.0.1:8000/?title=github") 388 | resp,err := HttpRequest.Debug(true).JSON().Get("http://127.0.0.1:8000/") 389 | ``` 390 | 391 | #### POST 392 | ```go 393 | import "github.com/kirinlabs/HttpRequest" 394 | 395 | resp,err := HttpRequest.Post("http://127.0.0.1:8000/") 396 | resp,err := HttpRequest.SetHeaders(map[string]string{ 397 | "title":"github", 398 | }).Post("http://127.0.0.1:8000/") 399 | resp,err := HttpRequest.Debug(true).JSON().Post("http://127.0.0.1:8000/") 400 | ``` 401 | 402 | 403 | ### Example 404 | ```go 405 | import "github.com/kirinlabs/HttpRequest" 406 | 407 | resp,err := HttpRequest.Get("http://127.0.0.1:8000/") 408 | resp,err := HttpRequest.Get("http://127.0.0.1:8000/","title=github") 409 | resp,err := HttpRequest.Get("http://127.0.0.1:8000/?title=github") 410 | resp,err := HttpRequest.Get("http://127.0.0.1:8000/",map[string]interface{}{ 411 | "title":"github", 412 | }) 413 | resp,err := HttpRequest.Debug(true).JSON().SetHeaders(map[string]string{ 414 | "source":"api", 415 | }).SetCookies(map[string]string{ 416 | "name":"httprequest", 417 | }).Post("http://127.0.0.1:8000/") 418 | 419 | 420 | //Or 421 | req := HttpRequest.NewRequest() 422 | req := req.Debug(true).SetHeaders() 423 | resp,err := req.Debug(true).JSON().SetHeaders(map[string]string{ 424 | "source":"api", 425 | }).SetCookies(map[string]string{ 426 | "name":"httprequest", 427 | }).Post("http://127.0.0.1:8000/") 428 | ``` 429 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package HttpRequest 2 | 3 | import ( 4 | "crypto/tls" 5 | "net/http" 6 | "net/url" 7 | "time" 8 | ) 9 | 10 | func NewRequest() *Request { 11 | r := &Request{ 12 | timeout: 30 * time.Second, 13 | headers: map[string]string{}, 14 | cookies: map[string]string{}, 15 | } 16 | return r 17 | } 18 | 19 | // Debug model 20 | func Debug(v bool) *Request { 21 | r := NewRequest() 22 | return r.Debug(v) 23 | } 24 | 25 | func Jar(v http.CookieJar) *Request { 26 | r := NewRequest() 27 | return r.Jar(v) 28 | } 29 | 30 | func DisableKeepAlives(v bool) *Request { 31 | r := NewRequest() 32 | return r.DisableKeepAlives(v) 33 | } 34 | 35 | func CheckRedirect(v func(req *http.Request, via []*http.Request) error) *Request { 36 | r := NewRequest() 37 | return r.CheckRedirect(v) 38 | } 39 | 40 | func TLSClient(v *tls.Config) *Request { 41 | r := NewRequest() 42 | return r.SetTLSClient(v) 43 | } 44 | 45 | func SetTLSClient(v *tls.Config) *Request { 46 | r := NewRequest() 47 | return r.SetTLSClient(v) 48 | } 49 | 50 | func SetHeaders(headers map[string]string) *Request { 51 | r := NewRequest() 52 | return r.SetHeaders(headers) 53 | } 54 | 55 | func SetCookies(cookies map[string]string) *Request { 56 | r := NewRequest() 57 | return r.SetCookies(cookies) 58 | } 59 | 60 | func SetBasicAuth(username, password string) *Request { 61 | r := NewRequest() 62 | return r.SetBasicAuth(username, password) 63 | } 64 | 65 | func JSON() *Request { 66 | r := NewRequest() 67 | return r.JSON() 68 | } 69 | 70 | func Proxy(v func(*http.Request) (*url.URL, error)) *Request { 71 | r := NewRequest() 72 | return r.Proxy(v) 73 | } 74 | 75 | func SetTimeout(d time.Duration) *Request { 76 | r := NewRequest() 77 | return r.SetTimeout(d) 78 | } 79 | 80 | func Transport(v *http.Transport) *Request { 81 | r := NewRequest() 82 | return r.Transport(v) 83 | } 84 | 85 | // Get is a get http request 86 | func Get(url string, data ...interface{}) (*Response, error) { 87 | r := NewRequest() 88 | return r.Get(url, data...) 89 | } 90 | 91 | func Post(url string, data ...interface{}) (*Response, error) { 92 | r := NewRequest() 93 | return r.Post(url, data...) 94 | } 95 | 96 | // Put is a put http request 97 | func Put(url string, data ...interface{}) (*Response, error) { 98 | r := NewRequest() 99 | return r.Put(url, data...) 100 | } 101 | 102 | // Delete is a delete http request 103 | func Delete(url string, data ...interface{}) (*Response, error) { 104 | r := NewRequest() 105 | return r.Delete(url, data...) 106 | } 107 | 108 | // Upload file 109 | func Upload(url, filename, fileinput string) (*Response, error) { 110 | r := NewRequest() 111 | return r.Upload(url, filename, fileinput) 112 | } 113 | -------------------------------------------------------------------------------- /request.go: -------------------------------------------------------------------------------- 1 | package HttpRequest 2 | 3 | import ( 4 | "bytes" 5 | "crypto/tls" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "mime/multipart" 11 | "net/http" 12 | "net/url" 13 | "os" 14 | "reflect" 15 | "strings" 16 | "time" 17 | ) 18 | 19 | type Request struct { 20 | cli *http.Client 21 | transport *http.Transport 22 | debug bool 23 | url string 24 | method string 25 | time int64 26 | timeout time.Duration 27 | headers map[string]string 28 | cookies map[string]string 29 | username string 30 | password string 31 | data interface{} 32 | disableKeepAlives bool 33 | tlsClientConfig *tls.Config 34 | jar http.CookieJar 35 | proxy func(*http.Request) (*url.URL, error) 36 | checkRedirect func(req *http.Request, via []*http.Request) error 37 | } 38 | 39 | func (r *Request) DisableKeepAlives(v bool) *Request { 40 | r.disableKeepAlives = v 41 | return r 42 | } 43 | 44 | func (r *Request) Jar(v http.CookieJar) *Request { 45 | r.jar = v 46 | return r 47 | } 48 | 49 | func (r *Request) CheckRedirect(v func(req *http.Request, via []*http.Request) error) *Request { 50 | r.checkRedirect = v 51 | return r 52 | } 53 | 54 | func (r *Request) TLSClient(v *tls.Config) *Request { 55 | return r.SetTLSClient(v) 56 | } 57 | 58 | func (r *Request) SetTLSClient(v *tls.Config) *Request { 59 | r.tlsClientConfig = v 60 | return r 61 | } 62 | 63 | func (r *Request) Proxy(v func(*http.Request) (*url.URL, error)) *Request { 64 | r.proxy = v 65 | return r 66 | } 67 | 68 | func (r *Request) Transport(v *http.Transport) *Request { 69 | r.transport = v 70 | return r 71 | } 72 | 73 | // Debug model 74 | func (r *Request) Debug(v bool) *Request { 75 | r.debug = v 76 | return r 77 | } 78 | 79 | // Get transport 80 | func (r *Request) getTransport() http.RoundTripper { 81 | if r.transport == nil { 82 | return http.DefaultTransport 83 | } 84 | 85 | r.transport.DisableKeepAlives = r.disableKeepAlives 86 | 87 | if r.tlsClientConfig != nil { 88 | r.transport.TLSClientConfig = r.tlsClientConfig 89 | } 90 | 91 | if r.proxy != nil { 92 | r.transport.Proxy = r.proxy 93 | } 94 | 95 | return http.RoundTripper(r.transport) 96 | } 97 | 98 | // Build client 99 | func (r *Request) buildClient() *http.Client { 100 | if r.cli == nil { 101 | r.cli = &http.Client{ 102 | Transport: r.getTransport(), 103 | Jar: r.jar, 104 | CheckRedirect: r.checkRedirect, 105 | Timeout: r.timeout, 106 | } 107 | } 108 | return r.cli 109 | } 110 | 111 | // Set headers 112 | func (r *Request) SetHeaders(headers map[string]string) *Request { 113 | if headers != nil || len(headers) > 0 { 114 | for k, v := range headers { 115 | r.headers[k] = v 116 | } 117 | } 118 | return r 119 | } 120 | 121 | // Init headers 122 | func (r *Request) initHeaders(req *http.Request) { 123 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") 124 | for k, v := range r.headers { 125 | req.Header.Set(k, v) 126 | } 127 | } 128 | 129 | // Set cookies 130 | func (r *Request) SetCookies(cookies map[string]string) *Request { 131 | if cookies != nil || len(cookies) > 0 { 132 | for k, v := range cookies { 133 | r.cookies[k] = v 134 | } 135 | } 136 | return r 137 | } 138 | 139 | // Init cookies 140 | func (r *Request) initCookies(req *http.Request) { 141 | for k, v := range r.cookies { 142 | req.AddCookie(&http.Cookie{ 143 | Name: k, 144 | Value: v, 145 | }) 146 | } 147 | } 148 | 149 | // Set basic auth 150 | func (r *Request) SetBasicAuth(username, password string) *Request { 151 | r.username = username 152 | r.password = password 153 | return r 154 | } 155 | 156 | func (r *Request) initBasicAuth(req *http.Request) { 157 | if r.username != "" && r.password != "" { 158 | req.SetBasicAuth(r.username, r.password) 159 | } 160 | } 161 | 162 | // Check application/json 163 | func (r *Request) isJson() bool { 164 | if len(r.headers) > 0 { 165 | for _, v := range r.headers { 166 | if strings.Contains(strings.ToLower(v), "application/json") { 167 | return true 168 | } 169 | } 170 | } 171 | return false 172 | } 173 | 174 | func (r *Request) JSON() *Request { 175 | r.SetHeaders(map[string]string{"Content-Type": "application/json"}) 176 | return r 177 | } 178 | 179 | // Build query data 180 | func (r *Request) buildBody(d ...interface{}) (io.Reader, error) { 181 | if r.method == "GET" || r.method == "DELETE" || len(d) == 0 || (len(d) > 0 && d[0] == nil) { 182 | return nil, nil 183 | } 184 | 185 | switch d[0].(type) { 186 | case string: 187 | return strings.NewReader(d[0].(string)), nil 188 | case []byte: 189 | return bytes.NewReader(d[0].([]byte)), nil 190 | case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: 191 | return bytes.NewReader(IntByte(d[0])), nil 192 | case *bytes.Reader: 193 | return d[0].(*bytes.Reader), nil 194 | case *strings.Reader: 195 | return d[0].(*strings.Reader), nil 196 | case *bytes.Buffer: 197 | return d[0].(*bytes.Buffer), nil 198 | default: 199 | if r.isJson() { 200 | b, err := json.Marshal(d[0]) 201 | if err != nil { 202 | return nil, err 203 | } 204 | return bytes.NewReader(b), nil 205 | } 206 | } 207 | 208 | t := reflect.TypeOf(d[0]).String() 209 | if !strings.Contains(t, "map[string]interface") { 210 | return nil, errors.New("Unsupported data type.") 211 | } 212 | 213 | data := make([]string, 0) 214 | for k, v := range d[0].(map[string]interface{}) { 215 | if s, ok := v.(string); ok { 216 | data = append(data, fmt.Sprintf("%s=%v", k, s)) 217 | continue 218 | } 219 | b, err := json.Marshal(v) 220 | if err != nil { 221 | return nil, err 222 | } 223 | data = append(data, fmt.Sprintf("%s=%s", k, string(b))) 224 | } 225 | 226 | return strings.NewReader(strings.Join(data, "&")), nil 227 | } 228 | 229 | func (r *Request) SetTimeout(d time.Duration) *Request { 230 | r.timeout = d 231 | return r 232 | } 233 | 234 | // Parse query for GET request 235 | func parseQuery(url string) ([]string, error) { 236 | urlList := strings.Split(url, "?") 237 | if len(urlList) < 2 { 238 | return make([]string, 0), nil 239 | } 240 | query := make([]string, 0) 241 | for _, val := range strings.Split(urlList[1], "&") { 242 | v := strings.Split(val, "=") 243 | if len(v) < 2 { 244 | return make([]string, 0), errors.New("query parameter error") 245 | } 246 | query = append(query, fmt.Sprintf("%s=%s", v[0], v[1])) 247 | } 248 | return query, nil 249 | } 250 | 251 | // Build GET request url 252 | func buildUrl(url string, data ...interface{}) (string, error) { 253 | query, err := parseQuery(url) 254 | if err != nil { 255 | return url, err 256 | } 257 | 258 | if len(data) > 0 && data[0] != nil { 259 | t := reflect.TypeOf(data[0]).String() 260 | switch t { 261 | case "map[string]interface {}": 262 | for k, v := range data[0].(map[string]interface{}) { 263 | vv := "" 264 | if reflect.TypeOf(v).String() == "string" { 265 | vv = v.(string) 266 | } else { 267 | b, err := json.Marshal(v) 268 | if err != nil { 269 | return url, err 270 | } 271 | vv = string(b) 272 | } 273 | query = append(query, fmt.Sprintf("%s=%s", k, vv)) 274 | } 275 | case "string": 276 | param := data[0].(string) 277 | if param != "" { 278 | query = append(query, param) 279 | } 280 | default: 281 | return url, errors.New("Unsupported data type.") 282 | } 283 | 284 | } 285 | 286 | list := strings.Split(url, "?") 287 | 288 | if len(query) > 0 { 289 | return fmt.Sprintf("%s?%s", list[0], strings.Join(query, "&")), nil 290 | } 291 | 292 | return list[0], nil 293 | } 294 | 295 | func (r *Request) elapsedTime(n int64, resp *Response) { 296 | end := time.Now().UnixNano() / 1e6 297 | resp.time = end - n 298 | } 299 | 300 | func (r *Request) log() { 301 | if r.debug { 302 | fmt.Printf("[HttpRequest]\n") 303 | //fmt.Printf("-------------------------------------------------------------------\n") 304 | fmt.Printf("Request: %s %s\nHeaders: %v\nCookies: %v\nTimeout: %ds\nReqBody: %v\n\n", r.method, r.url, r.headers, r.cookies, int64(r.timeout.Seconds()), r.data) 305 | //fmt.Printf("-------------------------------------------------------------------\n\n") 306 | } 307 | } 308 | 309 | // Get is a get http request 310 | func (r *Request) Get(url string, data ...interface{}) (*Response, error) { 311 | return r.request(http.MethodGet, url, data...) 312 | } 313 | 314 | // Post is a post http request 315 | func (r *Request) Post(url string, data ...interface{}) (*Response, error) { 316 | return r.request(http.MethodPost, url, data...) 317 | } 318 | 319 | // Put is a put http request 320 | func (r *Request) Put(url string, data ...interface{}) (*Response, error) { 321 | return r.request(http.MethodPut, url, data...) 322 | } 323 | 324 | // Delete is a delete http request 325 | func (r *Request) Delete(url string, data ...interface{}) (*Response, error) { 326 | return r.request(http.MethodDelete, url, data...) 327 | } 328 | 329 | // Upload file 330 | func (r *Request) Upload(url, filename, fileinput string) (*Response, error) { 331 | return r.sendFile(url, filename, fileinput) 332 | } 333 | 334 | // Send http request 335 | func (r *Request) request(method, url string, data ...interface{}) (*Response, error) { 336 | // Build Response 337 | response := &Response{} 338 | 339 | // Start time 340 | start := time.Now().UnixNano() / 1e6 341 | // Count elapsed time 342 | defer r.elapsedTime(start, response) 343 | 344 | if method == "" || url == "" { 345 | return nil, errors.New("parameter method and url is required") 346 | } 347 | 348 | // Debug infomation 349 | defer r.log() 350 | 351 | r.url = url 352 | if len(data) > 0 { 353 | r.data = data[0] 354 | } else { 355 | r.data = "" 356 | } 357 | 358 | var ( 359 | err error 360 | req *http.Request 361 | body io.Reader 362 | ) 363 | r.cli = r.buildClient() 364 | 365 | method = strings.ToUpper(method) 366 | r.method = method 367 | 368 | if method == "GET" || method == "DELETE" { 369 | url, err = buildUrl(url, data...) 370 | if err != nil { 371 | return nil, err 372 | } 373 | r.url = url 374 | } 375 | 376 | body, err = r.buildBody(data...) 377 | if err != nil { 378 | return nil, err 379 | } 380 | 381 | req, err = http.NewRequest(method, url, body) 382 | if err != nil { 383 | return nil, err 384 | } 385 | 386 | r.initHeaders(req) 387 | r.initCookies(req) 388 | r.initBasicAuth(req) 389 | 390 | resp, err := r.cli.Do(req) 391 | if err != nil { 392 | return nil, err 393 | } 394 | 395 | response.url = url 396 | response.resp = resp 397 | 398 | return response, nil 399 | } 400 | 401 | // Send file 402 | func (r *Request) sendFile(url, filename, fileinput string) (*Response, error) { 403 | if url == "" { 404 | return nil, errors.New("parameter url is required") 405 | } 406 | 407 | fileBuffer := &bytes.Buffer{} 408 | bodyWriter := multipart.NewWriter(fileBuffer) 409 | fileWriter, er := bodyWriter.CreateFormFile(fileinput, filename) 410 | if er != nil { 411 | return nil, er 412 | } 413 | 414 | f, er := os.Open(filename) 415 | if er != nil { 416 | return nil, er 417 | } 418 | defer f.Close() 419 | 420 | _, er = io.Copy(fileWriter, f) 421 | if er != nil { 422 | return nil, er 423 | } 424 | 425 | contentType := bodyWriter.FormDataContentType() 426 | bodyWriter.Close() 427 | 428 | // Build Response 429 | response := &Response{} 430 | 431 | // Start time 432 | start := time.Now().UnixNano() / 1e6 433 | // Count elapsed time 434 | defer r.elapsedTime(start, response) 435 | 436 | // Debug infomation 437 | defer r.log() 438 | 439 | r.url = url 440 | r.data = nil 441 | 442 | var ( 443 | err error 444 | req *http.Request 445 | ) 446 | r.cli = r.buildClient() 447 | r.method = "POST" 448 | 449 | req, err = http.NewRequest(r.method, url, fileBuffer) 450 | if err != nil { 451 | return nil, err 452 | } 453 | 454 | r.initHeaders(req) 455 | r.initCookies(req) 456 | r.initBasicAuth(req) 457 | req.Header.Set("Content-Type", contentType) 458 | 459 | resp, err := r.cli.Do(req) 460 | if err != nil { 461 | return nil, err 462 | } 463 | 464 | response.url = url 465 | response.resp = resp 466 | 467 | return response, nil 468 | } 469 | -------------------------------------------------------------------------------- /request_test.go: -------------------------------------------------------------------------------- 1 | package HttpRequest 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "testing" 7 | ) 8 | 9 | const localUrl = "http://localhost:8000" 10 | 11 | var data = map[string]interface{}{ 12 | "name": "HttpRequest", 13 | "version": "v1.0", 14 | } 15 | 16 | func TestGetRequest(t *testing.T) { 17 | req := NewRequest() 18 | 19 | test := []interface{}{ 20 | nil, 21 | data, 22 | "year=2018", 23 | } 24 | 25 | var resp *Response 26 | var err error 27 | 28 | for _, v := range test { 29 | resp, err = req.Get(localUrl, v) 30 | if err != nil { 31 | t.Error(err) 32 | return 33 | } 34 | } 35 | 36 | if resp.StatusCode() != 200 { 37 | t.Error("GET "+localUrl, "expected code 200", fmt.Sprintf("return code %d", resp.StatusCode())) 38 | } 39 | } 40 | 41 | func TestPostRequest(t *testing.T) { 42 | req := NewRequest() 43 | 44 | test := []interface{}{ 45 | data, 46 | bytes.NewReader([]byte{97}), 47 | []byte{97}, 48 | nil, 49 | "github", 50 | `{"name":"github","year":2018}`, 51 | 100, 52 | int8(100), 53 | int16(100), 54 | int32(100), 55 | int64(100), 56 | "title=github&type=1", 57 | } 58 | 59 | var resp *Response 60 | var err error 61 | 62 | for _, v := range test { 63 | resp, err = req.Post(localUrl, v) 64 | if err != nil { 65 | t.Error(err) 66 | return 67 | } 68 | } 69 | 70 | if resp.StatusCode() != 200 { 71 | t.Error("GET "+localUrl, "expected code 200", fmt.Sprintf("return code %d", resp.StatusCode())) 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /response.go: -------------------------------------------------------------------------------- 1 | package HttpRequest 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "net/http" 9 | ) 10 | 11 | type Response struct { 12 | time int64 13 | url string 14 | resp *http.Response 15 | body []byte 16 | } 17 | 18 | func (r *Response) Response() *http.Response { 19 | if r!=nil{ 20 | return r.resp 21 | } 22 | return nil 23 | } 24 | 25 | func (r *Response) StatusCode() int { 26 | if r.resp == nil { 27 | return 0 28 | } 29 | return r.resp.StatusCode 30 | } 31 | 32 | func (r *Response) Time() string { 33 | if r != nil { 34 | return fmt.Sprintf("%dms", r.time) 35 | } 36 | return "0ms" 37 | } 38 | 39 | func (r *Response) Url() string { 40 | if r != nil { 41 | return r.url 42 | } 43 | return "" 44 | } 45 | 46 | func (r *Response) Headers() http.Header { 47 | if r != nil { 48 | return r.resp.Header 49 | } 50 | return nil 51 | } 52 | 53 | func (r *Response) Cookies() []*http.Cookie { 54 | if r != nil { 55 | return r.resp.Cookies() 56 | } 57 | return []*http.Cookie{} 58 | } 59 | 60 | func (r *Response) Body() ([]byte, error) { 61 | if r == nil { 62 | return []byte{}, errors.New("HttpRequest.Response is nil.") 63 | } 64 | 65 | defer r.resp.Body.Close() 66 | 67 | if len(r.body) > 0 { 68 | return r.body, nil 69 | } 70 | 71 | if r.resp == nil || r.resp.Body == nil { 72 | return nil, errors.New("response or body is nil") 73 | } 74 | 75 | b, err := ioutil.ReadAll(r.resp.Body) 76 | if err != nil { 77 | return nil, err 78 | } 79 | r.body = b 80 | 81 | return b, nil 82 | } 83 | 84 | func (r *Response) Content() (string, error) { 85 | b, err := r.Body() 86 | if err != nil { 87 | return "", nil 88 | } 89 | return string(b), nil 90 | } 91 | 92 | func (r *Response) Json(v interface{}) error { 93 | return r.Unmarshal(v) 94 | } 95 | 96 | func (r *Response) Unmarshal(v interface{}) error { 97 | b, err := r.Body() 98 | if err != nil { 99 | return err 100 | } 101 | 102 | if err := json.Unmarshal(b, &v); err != nil { 103 | return err 104 | } 105 | 106 | return nil 107 | } 108 | 109 | func (r *Response) Close() error { 110 | if r != nil { 111 | return r.resp.Body.Close() 112 | } 113 | return nil 114 | } 115 | 116 | func (r *Response) Export() (string, error) { 117 | b, err := r.Body() 118 | if err != nil { 119 | return "", err 120 | } 121 | 122 | var i interface{} 123 | if err := json.Unmarshal(b, &i); err != nil { 124 | return "", errors.New("illegal json: " + err.Error()) 125 | } 126 | 127 | return Export(i), nil 128 | } 129 | -------------------------------------------------------------------------------- /response_test.go: -------------------------------------------------------------------------------- 1 | package HttpRequest 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestResponse(t *testing.T) { 8 | req := NewRequest() 9 | 10 | resp, err := req.Get(localUrl, nil) 11 | if err != nil { 12 | t.Error(err) 13 | return 14 | } 15 | 16 | if resp.Response() == nil { 17 | t.Error("For Response()", "return nil") 18 | } 19 | 20 | } 21 | 22 | func TestStatusCode(t *testing.T) { 23 | req := NewRequest() 24 | 25 | resp, err := req.Get(localUrl, nil) 26 | if err != nil { 27 | t.Error(err) 28 | return 29 | } 30 | 31 | if resp.StatusCode() == 0 { 32 | t.Error("For StatusCode()", "return code 0") 33 | } 34 | 35 | } 36 | 37 | func TestBody(t *testing.T) { 38 | req := NewRequest() 39 | 40 | resp, err := req.Get(localUrl, nil) 41 | if err != nil { 42 | t.Error(err) 43 | return 44 | } 45 | 46 | b, err := resp.Body() 47 | 48 | if err != nil { 49 | t.Error(err) 50 | return 51 | } 52 | 53 | if b == nil { 54 | t.Error("For Body()", "return nil") 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /utils.go: -------------------------------------------------------------------------------- 1 | package HttpRequest 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "encoding/json" 7 | ) 8 | 9 | func Export(v interface{}) string { 10 | b, err := json.Marshal(v) 11 | if err != nil { 12 | return "" 13 | } 14 | var buf bytes.Buffer 15 | err = json.Indent(&buf, b, "", "\t") 16 | if err != nil { 17 | return "" 18 | } 19 | return buf.String() 20 | } 21 | 22 | func Json(v interface{}) string { 23 | b, err := json.Marshal(v) 24 | if err != nil { 25 | return "" 26 | } 27 | return string(b) 28 | } 29 | 30 | func IntByte(v interface{}) []byte { 31 | b := bytes.NewBuffer([]byte{}) 32 | switch v.(type) { 33 | case int: 34 | binary.Write(b, binary.BigEndian, int64(v.(int))) 35 | case int8: 36 | binary.Write(b, binary.BigEndian, v.(int8)) 37 | case int16: 38 | binary.Write(b, binary.BigEndian, v.(int16)) 39 | case int32: 40 | binary.Write(b, binary.BigEndian, v.(int32)) 41 | case int64: 42 | binary.Write(b, binary.BigEndian, v.(int64)) 43 | case uint: 44 | binary.Write(b, binary.BigEndian, uint64(v.(uint))) 45 | case uint8: 46 | binary.Write(b, binary.BigEndian, v.(uint8)) 47 | case uint16: 48 | binary.Write(b, binary.BigEndian, v.(uint16)) 49 | case uint32: 50 | binary.Write(b, binary.BigEndian, v.(uint32)) 51 | case uint64: 52 | binary.Write(b, binary.BigEndian, v.(uint64)) 53 | } 54 | return b.Bytes() 55 | } 56 | --------------------------------------------------------------------------------