T
T
to_east2018-03-08 01:25:04
go
to_east, 2018-03-08 01:25:04

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)
}

In the ClientInit function, I omitted some actions for brevity, in general, I only need two actions: initialization of the custom HttpRequest structure with a url parameter, and an action on this Perform structure that takes url_path and returns http.Response. The code smells, but what recommendations for improvement can you advise in terms of architecture. Even in the course of writing this topic, there was a desire to combine RequestInit and ClientInit into one function.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
to_east, 2018-03-09
@to_east

Solution from rustler2000 in the comments

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question