In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail the example analysis of the Golang language HTTP client. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
HTTP client encapsulation
Package taskimport ("bytes"encoding/json"fmt"io/ioutil"net/http"net/url"strings"time") var Client http.Client = clients () / / Res simulated response structure / / @ Description:type Res struct {Have string `json: "Have" `} / / Get get GET request / / @ Description:// @ param uri// @ param args// @ return * http.Requestfunc Get (uri string Args mapping [string] interface {}) * http.Request {uri = uri + "?" + ToValues (args) request, _: = http.NewRequest ("get", uri, nil) return request} / / PostForm POST interface form form / / @ Description:// @ param path// @ param args// @ return * http.Requestfunc PostForm (path string, args mapping [string] interface {}) * http.Request {request, _: = http.NewRequest ("post", path) Strings.NewReader (ToValues (args)) return request} / / PostJson POST request, JSON parameter / / @ Description:// @ param path// @ return * http.Requestfunc PostJson (path string, args map [string] interface {}) * http.Request {marshal, _: = json.Marshal (args) request, _: = http.NewRequest ("post", path, bytes.NewReader (marshal) return request} / / ToValues parses map into HTTP parameter For GET and POST form forms / / @ Description:// @ param args// @ return stringfunc ToValues (args map [string] interface {}) string {if args! = nil & & len (args) > 0 {params: = url.Values {} for k, v: = range args {params.Set (k, fmt.Sprintf ("% v", v))} return params.Encode ()} return ""} / / Response to get response details Default [] byte format / / @ Description:// @ param request// @ return [] bytefunc Response (request * http.Request) [] byte {res, err: = Client.Do (request) if err! = nil {return nil} body, _: = ioutil.ReadAll (res.Body) / / read response body Return [] byte defer res.Body.Close () return body} / / clients initialization request client / / @ Description:// @ return http.Clientfunc clients () http.Client {return http.Client {Timeout: time.Duration (5) * time.Second, / / timeout Transport: & http.Transport {MaxIdleConnsPerHost: 5, / / maximum idle connections for a single route MaxConnsPerHost: 100 / / maximum number of connections to a single route IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second,},} / / ParseRes resolution response / / @ Description:// @ receiver r _ param resfunc / @ param resfunc (r * Res) ParseRes (res [] byte) {json.Unmarshal (res, r)} / / ParseRes resolution response Convert [] byte to an incoming object / / @ Description:// @ param res// @ param r//func ParseRes (res [] byte, r interface {}) {json.Unmarshal (res, r)} test script
Package mainimport ("fmt"funtester/src/task"io"log"net/http"os"time") const (a = iota b c d e) func init () {os.Mkdir (". / log/", 0777) os.Mkdir (". / long/", 0777) file: = ". / log/" + string (time.Now (). Format ("20060102")) + ".log" openFile, _: = os.OpenFile (file) Os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666) writer: = io.MultiWriter (os.Stdout, openFile) log.SetOutput (writer) log.SetFlags (log.LstdFlags | log.Lshortfile | log.Ldate)} func main () {url: = "http://localhost:12345/test" args: = map [string] interface {} {" name ":" FunTester "," fun ":" fdsafj ",} cookie: = & http.Cookie {Name:" token ", Value:" fsjej09u0934jtej " } get: = task.Get (url, args) get.Header.Add ("user_agent", "FunTester") get.AddCookie (cookie) response: = task.Response (get) fmt.Println (string (response)) form: = task.PostForm (url, args) bytes: = task.Response (form) fmt.Println (string (bytes) json: = task.PostJson (url, args) res: = task.Response (json) fmt.Println (string (res))}
Console output
GOROOT=/usr/local/go # gosetup
GOPATH=/Users/oker/go # gosetup
/ usr/local/go/bin/go build-o / private/var/folders/7b/0djfgf7j7p9ch_hgm9wx9n6w0000gn/T/GoLand/___go_build_funtester_src_m funtester/src/m # gosetup
/ private/var/folders/7b/0djfgf7j7p9ch_hgm9wx9n6w0000gn/T/GoLand/___go_build_funtester_src_m
Get request
Post request form form
Post request json form
Process finished with the exit code 0
Test service
It is still implemented using the moco_FunTester testing framework.
Package com.mocofun.moco.mainimport com.funtester.utils.ArgsUtilimport com.mocofun.moco.MocoServerclass Share extends MocoServer {static void main (String [] args) {def util = new ArgsUtil (args) / / def server = getServerNoLog (util.getIntOrdefault (0meme 12345)) def server = getServer (util.getIntOrdefault (0) 12345) server.get (urlStartsWith ("/ test"). Response ("get request") server.post (both (urlStartsWith ("/ test"), existForm ("fun")) .response ("post request form form") server.post (both (urlStartsWith ("/ test")) ExistParams ("fun")) .response ("post request json form") server.get (urlStartsWith ("/ qps")) .response (qps ("Congratulations to QPS!", 1)) / / server.response (jsonRes (getJson ("Have=Fun ~ Tester!")) , 1000) server.response ("Have Fun ~ Tester!") Def run = run (server) waitForKey ("fan") run.stop ()} this article ends here. I hope the above content can be helpful to you, so that you can learn more knowledge. If you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 202
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.