user1491250
user1491250

Reputation: 1961

How to read the Go docs?

I've created a simple go program (basically just example code):

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func getPage(url string) (body []byte, err error) {
    resp, err := http.Get(url)

    body = nil

    if (err != nil) {
        return
    }

    defer resp.Body.Close()
    body, err = ioutil.ReadAll(resp.Body)

    return
}

func main() {
    startUrl := "http://slashdot.org/"

    body, err := getPage(startUrl)

    if (err != nil) {
        fmt.Println("Error: " , err)
    }

    fmt.Println(body)
}

I'm trying to go through the docs to understand how it all fits together.

First issue: http.Get(). It's not in the docs (at http://golang.org/pkg/net/http/). Except it is, but under Response. However there are 2 other Get() functions. How do I know that net/http.Get is actually the Get() on the Response type?

Anyway, so http.Get() returns a Response with a Body of io.ReadCloser. ioutil.ReadAll() takes an io.Reader - but how can I find other functions that accept this as a parameter? It kind of seems like the docs are 'backwards' - if I know which function I want I can find docs, but if I have a type, how can I find what functions will work with it?

Upvotes: 5

Views: 1176

Answers (2)

tike
tike

Reputation: 2294

Concerning your io.Reader and io.ReadCloser question:

Those are interfaces, if you are not familiar with them read up on them here

Interfaces are basically sets of methods, these two are defined as follows:

type Reader interface{
     Read([]byte)(int, error)
}

type ReadCloser interface{
     Read([]byte)(int, error)
     Close()
}

This means any concrete datatype that has a Read Method with the above signature can be passed on as a io.Reader. A datatype that satisfies io.ReadCloser definitely does this, since it has to provide the Read method and an additional close Method.

So you can simply pass your ReadCloser on as Reader.

The way interfaces work in go is a little hard to grasp at the beginning since they are so implicit, however they are very powerful and give you lot's of possibilities. Definitely read the text I linked above. I read the whole thing down, when I was starting with go and it made things a lot easier.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382130

The functions are defined like this :

func (c *Client) Get(url string) (resp *Response, err error)
func (h Header) Get(key string) string
func Get(url string) (resp *Response, err error)

See how functions are declared.

Between func and the name of the function (Get), you have the receiver type and name (between parenthesis). Only one of those functions has no receiver and must be called directly prefixed by the package name (http). That's the one you need.

Upvotes: 8

Related Questions