- Read the code and explain it.
- Will it compile or not?
- Find any possible issues.
- Explain how would you refactor it and why.
Last active
March 4, 2024 21:09
-
-
Save amanbolat/aa97337eca2cffd1fe04ddd7cb0abdf1 to your computer and use it in GitHub Desktop.
Go Interview Question #1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"bytes" | |
"flag" | |
"io" | |
"net/http" | |
"os" | |
) | |
func main() { | |
inputFilePath := flag.String("in", "in.txt", "a file with URLs") | |
outputFilePath := flag.String("ou", "out.txt", "a file with URLs") | |
flag.Parse() | |
b, err := os.ReadFile(*inputFilePath) | |
if err != nil { | |
panic(err) | |
} | |
buf := bytes.NewBuffer(b) | |
var urls []string | |
fileScanner := bufio.NewScanner(buf) | |
for fileScanner.Scan() { | |
urls = append(urls, fileScanner.Text()) | |
} | |
if err := fileScanner.Err(); err != nil { | |
panic(err) | |
} | |
contents, err := getContent(urls) | |
if err != nil { | |
panic(err) | |
} | |
singleContent := bytes.Join(contents, []byte("\n====================\n")) | |
err = os.WriteFile(*outputFilePath, singleContent, 0644) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func getContent(urls []string) ([][]byte, error) { | |
var contents [][]byte | |
for _, url := range urls { | |
res, err := http.DefaultClient.Get(url) | |
if err != nil { | |
return nil, err | |
} | |
b, err := io.ReadAll(res.Body) | |
if err != nil { | |
return nil, err | |
} | |
contents = append(contents, b) | |
} | |
return contents, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment