Answer the question
In order to leave comments, you need to log in
Question about structures in Go?
Hello!
I recently started learning Go, and although everything is generally understandable, the new approach to a clear separation of data and logic is a bit daunting. Here is what I specifically need:
When using the net/http library, I need to abstract away some calls, do the initialization behind the scenes so to speak, the code will say more:
package main
import (
"fmt"
"net/http"
)
type HttpRequest struct {
url string
client http.Client
request http.Request
ready bool
}
func ClientInit() http.Client {
client := http.Client{}
return client
}
func RequestInit(url string) *http.Request {
req, _ := http.NewRequest("GET", url, nil)
ua := "Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.0.16"
req.Header.Add("User-Agent", ua)
return req
}
func (h_req *HttpRequest) Perform(path string) (*http.Response, error) {
if !h_req.ready {
h_req.client = ClientInit()
h_req.request = *RequestInit(h_req.url)
h_req.ready = true
}
h_req.request.URL.Path = path
return h_req.client.Do(&h_req.request)
}
func main() {
h_req := HttpRequest{ url: "http://example.com" }
resp, _ := h_req.Perform("/hello.html")
resp, _ = h_req.Perform("/world.html")
fmt.Println(resp)
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question