DEV Community

Discussion on: Reverse a string: awful answers only

Collapse
yoursunny profile image
Junxiao Shi

We need a computer network.

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
    "strings"
    "sync"
    "time"
)

func reverseString(s string) string {
    server := http.Server{
        Addr: ":8080",
        Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            q := r.URL.Query()
            t, _ := strconv.Atoi(q.Get("t"))
            c, _ := strconv.Atoi(q.Get("c"))
            time.Sleep(time.Duration(len(s)-t) * 100 * time.Millisecond)
            w.Write([]byte{byte(c)})
        }),
    }
    go server.ListenAndServe()
    defer server.Close()
    time.Sleep(time.Second)

    client := http.Client{
        Timeout: time.Duration(len(s)) * time.Second,
    }
    var wg sync.WaitGroup
    var lock sync.Mutex
    var b strings.Builder
    for t, c := range []byte(s) {
        wg.Add(1)
        go func(t int, c byte) {
            defer wg.Done()
            res, e := client.Get(fmt.Sprintf("http://localhost:8080/?t=%d&c=%d", t, c))
            if e != nil {
                panic(e)
            }

            defer res.Body.Close()
            body, e := ioutil.ReadAll(res.Body)
            if e != nil {
                panic(e)
            }

            lock.Lock()
            defer lock.Unlock()
            b.Write(body)
        }(t, c)
    }

    wg.Wait()
    return b.String()
}

func main() {
    fmt.Println(reverseString("Use Markdown to write and format posts."))
    fmt.Println(reverseString("You can use Liquid tags to add rich content such as Tweets, YouTube videos, etc."))
    fmt.Println(reverseString("In addition to images for the post's content, you can also drag and drop a cover image"))
    fmt.Println(reverseString(""))
}
Enter fullscreen mode Exit fullscreen mode