[daily] Go language Bible -- JSON exercise 2

Keywords: Go JSON encoding

Exercise 4.12: the popular web comic service xkcd also provides a JSON interface. For example, an https://xkcd.com/571/info.0.json request will return a detailed description of the 571 number that many people love.
Download each link (only once) and create an offline index. Write an xkcd tool that uses these offline indexes to print the URL of the comic that matches the search term entered on the command line.
1. Index is not saved temporarily
2. It is realized by using the cooperation process, and it is very fast

 

package main

import (
        "fmt"
        "net/http"
        "os"
        //"io/ioutil"
        "encoding/json"
        "strings"
)

type Xvcd struct {
        Title string
        Img   string
        Transcript string
}
/*
Exercise 4.12: the popular web comic service xkcd also provides a JSON interface. For example, an https://xkcd.com/571/info.0.json request will return a detailed description of the 571 number that many people love. Download each link (only once) and create an offline index. Compile >
An xkcd tool that uses these offline indexes to print the URL of the comic that matches the search term entered on the command line.
1.There is no index temporarily
2.It can be realized by using the cooperation process, and it will be very fast
*/
func main() {
        var urls []string
        for i := 0; i < 1000; i++ {
                url := fmt.Sprintf("https://xkcd.com/%d/info.0.json", i)
                urls = append(urls, url)
        }   
        //var content []Xvcd
        ch := make(chan string)
        for _, url := range urls {
                go fetch(url, ch) 
        }   
        fmt.Println(<-ch)
}
func fetch(url string, ch chan<- string) {
        var result Xvcd
        resp, _ := http.Get(url)
        if resp.StatusCode != http.StatusOK {
                resp.Body.Close()
                os.Exit(1)
        }   
        json.NewDecoder(resp.Body).Decode(&result)
        titles := strings.Split(result.Transcript, " ")

        for _, v := range titles {
                if v == string(os.Args[1]) {
                        ch <- result.Img
                        break
                }   
        }   
}

  

Posted by vigour on Wed, 01 Apr 2020 07:44:17 -0700