ronantakizawa/codereview-bench huggingface dataset:
Repository: syncthing/syncthing
File: lib/api/api.go (Go)

Code before:
		sendJSON(w, map[string]string{
			"error": err.Error(),
		})
	}
}

func (*service) getLang(w http.ResponseWriter, r *http.Request) {
	lang := r.Header.Get("Accept-Language")
	var langs []string
	for _, l := range strings.Split(lang, ",") {
		parts := strings.SplitN(l, ";", 2)
		langs = append(langs, strings.ToLower(strings.TrimSpace(parts[0])))
	}
	sendJSON(w, langs)
}

func (s *service) postSystemUpgrade(w http.ResponseWriter, _ *http.Request) {
	opts := s.cfg.Options()
	rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
	if err != nil {
		if err == upgrade.ErrUpgradeUnsupported {
			http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), http.StatusNotImplemented)
			return
		}
		l.Warnln("getting latest release:", err)
		http.Error(w, err.Error(), 500)
		return
	}

	if upgrade.CompareVersions(rel.Tag, build.Version) > upgrade.Equal {
		err = upgrade.To(rel)
		if err != nil {
			l.Warnln("upgrading:", err)
			http.Error(w, err.Error(), 500)
			return
		}

		s.flushResponse(`{"ok": "restarting"}`, w)
		s.fatal(&svcutil.FatalErr{
			Err:    errors.New("exit after upgrade initiated by rest API"),
			Status: svcutil.ExitUpgrade,
		})
	}
}

func (s *service) makeDevicePauseHandler(paused bool) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var qs = r.URL.Query()
		var deviceStr = qs.Get("device")

		var msg string

Review comment (suggestion):
Maybe break this whole thing into a `func httpError(w, err)` that does the right thing and can be reused below, plus take the opportunity to make the `500` literal `http.StatusInternalServerError`

Code after:
}

func (*service) getLang(w http.ResponseWriter, r *http.Request) {
	lang := r.Header.Get("Accept-Language")
	var langs []string
	for _, l := range strings.Split(lang, ",") {
		parts := strings.SplitN(l, ";", 2)
		langs = append(langs, strings.ToLower(strings.TrimSpace(parts[0])))
	}
	sendJSON(w, langs)
}

func (s *service) postSystemUpgrade(w http.ResponseWriter, _ *http.Request) {
	opts := s.cfg.Options()
	rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
	if err != nil {
		httpError(w, err)
		return
	}

	if upgrade.CompareVersions(rel.Tag, build.Version) > upgrade.Equal {
		err = upgrade.To(rel)
		if err != nil {
			l.Warnln("upgrading:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		s.flushResponse(`{"ok": "restarting"}`, w)
		s.fatal(&svcutil.FatalErr{
			Err:    errors.New("exit after upgrade initiated by rest API"),
			Status: svcutil.ExitUpgrade,
		})
	}
}

func (s *service) makeDevicePauseHandler(paused bool) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var qs = r.URL.Query()
		var deviceStr = qs.Get("device")

		var msg string
		var status int
		_, err := s.cfg.Modify(func(cfg *config.Configuration) {
			if deviceStr == "" {
				for i := range cfg.Devices {
					cfg.Devices[i].Paused = paused
				}
				return
			}
Repository: syncthing/syncthing
File: script/weblatedl.go (Go)

Code before:
	"log"
	"net/http"
	"os"
	"regexp"
	"sort"
	"strings"
)

type stat struct {
	Code       string `json:"code"`
	Name       string `json:"name"`
	Total      int    `json:"total"`
	Translated int    `json:"translated"`
	Fuzzy      int    `json:"fuzzy"`
}

type translation map[string]string

func main() {
	log.SetFlags(log.Lshortfile)

	if t := authToken(); t == "" {
		log.Fatal("Need environment variable WEBLATE_TOKEN")
	}

	curValidLangs := map[string]bool{}
	for _, lang := range loadValidLangs() {
		curValidLangs[lang] = true
	}
	log.Println(curValidLangs)

	resp := req("https://hosted.weblate.org/exports/stats/syncthing/gui/?format=json")

	var stats []stat
	err := json.NewDecoder(resp.Body).Decode(&stats)
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()

	names := make(map[string]string)

	var langs []string
	for _, stat := range stats {
		code := reformatLanguageCode(stat.Code)
		pct := 100 * stat.Translated / stat.Total
		if pct < 75 || !curValidLangs[code] && pct < 95 {
			log.Printf("Language %q too low completion ratio %d%%", code, pct)
		} else {
			langs = append(langs, code)
			names[code] = stat.Name

Review comment (suggestion):
This could just be `map[string]struct{}` as the value is never false (I know is already this way in the other file, just noticed it, nothing important).

Code after:
	"log"
	"net/http"
	"os"
	"regexp"
	"sort"
	"strings"
)

type stat struct {
	Code       string `json:"code"`
	Name       string `json:"name"`
	Total      int    `json:"total"`
	Translated int    `json:"translated"`
	Fuzzy      int    `json:"fuzzy"`
}

type translation map[string]string

func main() {
	log.SetFlags(log.Lshortfile)

	token := os.Getenv("WEBLATE_TOKEN")
	if token == "" {
		log.Fatal("Need environment variable WEBLATE_TOKEN")
	}

	curValidLangs := make(map[string]struct{})
	for _, lang := range loadValidLangs() {
		curValidLangs[lang] = struct{}{}
	}
	log.Println(curValidLangs)

	resp := req("https://hosted.weblate.org/exports/stats/syncthing/gui/?format=json", token)

	var stats []stat
	err := json.NewDecoder(resp.Body).Decode(&stats)
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()

	names := make(map[string]string)

	var langs []string
	for _, stat := range stats {
		code := reformatLanguageCode(stat.Code)
		pct := 100 * stat.Translated / stat.Total
		if _, valid := curValidLangs[code]; pct < 75 || !valid && pct < 95 {
			log.Printf("Language %q too low completion ratio %d%%", code, pct)
		} else {
			langs = append(langs, code)
Repository: syncthing/syncthing
File: script/weblatedl.go (Go)

Code before:
import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"regexp"
	"sort"
	"strings"
)

type stat struct {
	Code       string `json:"code"`
	Name       string `json:"name"`
	Total      int    `json:"total"`
	Translated int    `json:"translated"`
	Fuzzy      int    `json:"fuzzy"`
}

type translation map[string]string

func main() {
	log.SetFlags(log.Lshortfile)

	if t := authToken(); t == "" {
		log.Fatal("Need environment variable WEBLATE_TOKEN")
	}

	curValidLangs := map[string]bool{}
	for _, lang := range loadValidLangs() {
		curValidLangs[lang] = true
	}
	log.Println(curValidLangs)

	resp := req("https://hosted.weblate.org/exports/stats/syncthing/gui/?format=json")

	var stats []stat
	err := json.NewDecoder(resp.Body).Decode(&stats)
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()

	names := make(map[string]string)

	var langs []string
	for _, stat := range stats {
		code := reformatLanguageCode(stat.Code)
		pct := 100 * stat.Translated / stat.Total
		if pct < 75 || !curValidLangs[code] && pct < 95 {

Review comment (suggestion):
Completely nitty and optional: I'd just get the token from env here and keep the variable around, and then pass it to `req` - no function needed.

Code after:
import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"regexp"
	"sort"
	"strings"
)

type stat struct {
	Code       string `json:"code"`
	Name       string `json:"name"`
	Total      int    `json:"total"`
	Translated int    `json:"translated"`
	Fuzzy      int    `json:"fuzzy"`
}

type translation map[string]string

func main() {
	log.SetFlags(log.Lshortfile)

	token := os.Getenv("WEBLATE_TOKEN")
	if token == "" {
		log.Fatal("Need environment variable WEBLATE_TOKEN")
	}

	curValidLangs := make(map[string]struct{})
	for _, lang := range loadValidLangs() {
		curValidLangs[lang] = struct{}{}
	}
	log.Println(curValidLangs)

	resp := req("https://hosted.weblate.org/exports/stats/syncthing/gui/?format=json", token)

	var stats []stat
	err := json.NewDecoder(resp.Body).Decode(&stats)
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()

	names := make(map[string]string)

	var langs []string
	for _, stat := range stats {
		code := reformatLanguageCode(stat.Code)
		pct := 100 * stat.Translated / stat.Total
Repository: syncthing/syncthing
File: lib/config/config_test.go (Go)

Code before:
			out:    []string{"foo"},
		},
		{
			in:     []string{"foo", "bar", "baz"},
			filter: []XattrFilterEntry{{Match: "yoink", Permit: true}},
			out:    []string{},
		},
	}

	for _, tc := range cases {
		f := XattrFilter{Entries: tc.filter}
		var out []string
		for _, s := range tc.in {
			if f.Permit(s) {
				out = append(out, s)
			}
		}

		if fmt.Sprint(out) != fmt.Sprint(tc.out) {
			t.Errorf("Filter.Apply(%v, %v) == %v, expected %v", tc.in, tc.filter, out, tc.out)
		}
	}
}

// Done in various places where config is needed, but the device ID isn't known.
func TestLoadEmptyDeviceID(t *testing.T) {
	temp, err := copyToTmp(testFs, "example.xml")
	if err != nil {
		t.Fatal(err)
	}
	fd, err := testFs.Open(temp)
	if err != nil {
		t.Fatal(err)
	}
	defer fd.Close()
	cfg, _, err := ReadXML(fd, protocol.EmptyDeviceID)
	if err != nil {
		t.Fatal(err)
	}
	for _, devCfg := range cfg.Devices {
		if devCfg.DeviceID == protocol.EmptyDeviceID {
			t.Fatal("Device with empty ID")
		}
	}
	for _, folderCfg := range cfg.Folders {
		for _, devCfg := range folderCfg.Devices {
			if devCfg.DeviceID == protocol.EmptyDeviceID {
				t.Fatalf("Device with empty ID in folder %v", folderCfg.Description())
			}
		}
	}

Review comment (suggestion):
```suggestion
// Verify that opening a config with myID == protocol.EmptyDeviceID doesn't add that ID to the config.
// Done in various places where config is needed, but the device ID isn't known.
```

Code after:
			out:    []string{"foo"},
		},
		{
			in:     []string{"foo", "bar", "baz"},
			filter: []XattrFilterEntry{{Match: "yoink", Permit: true}},
			out:    []string{},
		},
	}

	for _, tc := range cases {
		f := XattrFilter{Entries: tc.filter}
		var out []string
		for _, s := range tc.in {
			if f.Permit(s) {
				out = append(out, s)
			}
		}

		if fmt.Sprint(out) != fmt.Sprint(tc.out) {
			t.Errorf("Filter.Apply(%v, %v) == %v, expected %v", tc.in, tc.filter, out, tc.out)
		}
	}
}

// Verify that opening a config with myID == protocol.EmptyDeviceID doesn't add that ID to the config.
// Done in various places where config is needed, but the device ID isn't known.
func TestLoadEmptyDeviceID(t *testing.T) {
	temp, err := copyToTmp(testFs, "example.xml")
	if err != nil {
		t.Fatal(err)
	}
	fd, err := testFs.Open(temp)
	if err != nil {
		t.Fatal(err)
	}
	defer fd.Close()
	cfg, _, err := ReadXML(fd, protocol.EmptyDeviceID)
	if err != nil {
		t.Fatal(err)
	}
	for _, devCfg := range cfg.Devices {
		if devCfg.DeviceID == protocol.EmptyDeviceID {
			t.Fatal("Device with empty ID")
		}
	}
	for _, folderCfg := range cfg.Folders {
		for _, devCfg := range folderCfg.Devices {
			if devCfg.DeviceID == protocol.EmptyDeviceID {
				t.Fatalf("Device with empty ID in folder %v", folderCfg.Description())
			}
		}
Repository: syncthing/syncthing
File: lib/model/service_map.go (Go)

Code before:
	}
	delete(s.services, k)
	delete(s.tokens, k)
	return
}

// RemoveAndWait removes the service at the given key, stopping it on the
// supervisor. If there is no service at the given key, nothing happens. The
// return value indicates whether a service was removed.
func (s *serviceMap[K, S]) RemoveAndWait(k K, timeout time.Duration) (found bool) {
	if tok, ok := s.tokens[k]; ok {
		found = true
		s.supervisor.RemoveAndWait(tok, timeout)
	}
	delete(s.services, k)
	delete(s.tokens, k)
	return found
}

// Each calls the given function for each service in the map.
func (s *serviceMap[K, S]) Each(fn func(K, S)) {
	for key, svc := range s.services {
		fn(key, svc)
	}
}

// Suture implementation

func (s *serviceMap[K, S]) Serve(ctx context.Context) error {
	return s.supervisor.Serve(ctx)
}

func (s *serviceMap[K, S]) String() string {
	var kv K
	var sv S
	return fmt.Sprintf("serviceMap[%T, %T]@%p", kv, sv, s)
}


Review comment (suggestion):
We do this over exposing the map and just looping over that at the caller, to prevent the caller from messing with the map?

(Also I want `range` over functions: https://github.com/golang/go/issues/61405)

Code after:
// indicates whether a service was removed.
func (s *serviceMap[K, S]) Remove(k K) (found bool) {
	if tok, ok := s.tokens[k]; ok {
		found = true
		s.supervisor.Remove(tok)
	}
	delete(s.services, k)
	delete(s.tokens, k)
	return
}

// RemoveAndWait removes the service at the given key, stopping it on the
// supervisor. If there is no service at the given key, nothing happens. The
// return value indicates whether a service was removed.
func (s *serviceMap[K, S]) RemoveAndWait(k K, timeout time.Duration) (found bool) {
	if tok, ok := s.tokens[k]; ok {
		found = true
		s.supervisor.RemoveAndWait(tok, timeout)
	}
	delete(s.services, k)
	delete(s.tokens, k)
	return found
}

// Each calls the given function for each service in the map.
func (s *serviceMap[K, S]) Each(fn func(K, S)) {
	for key, svc := range s.services {
		fn(key, svc)
	}
}

// Suture implementation

func (s *serviceMap[K, S]) Serve(ctx context.Context) error {
	return s.supervisor.Serve(ctx)
}

func (s *serviceMap[K, S]) String() string {
	var kv K
	var sv S
	return fmt.Sprintf("serviceMap[%T, %T]@%p", kv, sv, s)
}
Repository: syncthing/syncthing
File: lib/connections/util.go (Go)

Code before:
	addrs := make([]*url.URL, 0, len(hostPorts))
	for _, hostPort := range hostPorts {
		newUri := *uri
		newUri.Host = hostPort
		addrs = append(addrs, &newUri)
	}

	return addrs
}

func getHostPortsForAllAdapters(port int) []string {
	nets, err := osutil.GetLans()
	if err != nil {
		// Ignore failure.
		return nil
	}

	hostPorts := make([]string, 0, len(nets))

	portStr := strconv.Itoa(port)

	for _, network := range nets {
		// Only accept IPv4 link-local unicast and the private ranges defined in RFC 1918 and RFC 4193
		// IPv6 link-local addresses require an interface identifier to work correctly
		if (network.IP.To4() != nil && network.IP.IsLinkLocalUnicast()) ||
			(network.IP.IsPrivate() && network.IP.IsGlobalUnicast()) {
			hostPorts = append(hostPorts, net.JoinHostPort(network.IP.String(), portStr))
		}
	}
	return hostPorts
}

func resolve(network, hostPort string) (net.IP, int, error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
		if addr, err := net.ResolveTCPAddr(network, hostPort); err != nil {
			return net.IPv4zero, 0, err
		} else {
			return addr.IP, addr.Port, nil
		}
	case "udp", "udp4", "udp6":
		if addr, err := net.ResolveUDPAddr(network, hostPort); err != nil {
			return net.IPv4zero, 0, err
		} else {
			return addr.IP, addr.Port, nil
		}
	case "ip", "ip4", "ip6":
		if addr, err := net.ResolveIPAddr(network, hostPort); err != nil {
			return net.IPv4zero, 0, err
		} else {
			return addr.IP, 0, nil

Review comment (suggestion):
I think the `IsGlobalUnicast` is redundant here, may have been so before as well

Code after:
	addrs := make([]*url.URL, 0, len(hostPorts))
	for _, hostPort := range hostPorts {
		newUri := *uri
		newUri.Host = hostPort
		addrs = append(addrs, &newUri)
	}

	return addrs
}

func getHostPortsForAllAdapters(port int) []string {
	nets, err := osutil.GetLans()
	if err != nil {
		// Ignore failure.
		return nil
	}

	hostPorts := make([]string, 0, len(nets))

	portStr := strconv.Itoa(port)

	for _, network := range nets {
		// Only accept IPv4 link-local unicast and the private ranges defined in RFC 1918 and RFC 4193
		// IPv6 link-local addresses require an interface identifier to work correctly
		if (network.IP.To4() != nil && network.IP.IsLinkLocalUnicast()) || network.IP.IsPrivate() {
			hostPorts = append(hostPorts, net.JoinHostPort(network.IP.String(), portStr))
		}
	}
	return hostPorts
}

func resolve(network, hostPort string) (net.IP, int, error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
		if addr, err := net.ResolveTCPAddr(network, hostPort); err != nil {
			return net.IPv4zero, 0, err
		} else {
			return addr.IP, addr.Port, nil
		}
	case "udp", "udp4", "udp6":
		if addr, err := net.ResolveUDPAddr(network, hostPort); err != nil {
			return net.IPv4zero, 0, err
		} else {
			return addr.IP, addr.Port, nil
		}
	case "ip", "ip4", "ip6":
		if addr, err := net.ResolveIPAddr(network, hostPort); err != nil {
			return net.IPv4zero, 0, err
		} else {
			return addr.IP, 0, nil
		}
Repository: syncthing/syncthing
File: lib/beacon/broadcast.go (Go)

Code before:

func writeBroadcasts(ctx context.Context, inbox <-chan []byte, port int) error {
	conn, err := net.ListenUDP("udp4", nil)
	if err != nil {
		l.Debugln(err)
		return err
	}
	doneCtx, cancel := context.WithCancel(ctx)
	defer cancel()
	go func() {
		<-doneCtx.Done()
		conn.Close()
	}()

	for {
		var bs []byte
		select {
		case bs = <-inbox:
		case <-doneCtx.Done():
			return doneCtx.Err()
		}

		intfs, err := net.Interfaces()
		if err != nil {
			l.Debugln(err)
		}

		var dsts []net.IP
		for _, intf := range intfs {
			if intf.Flags&net.FlagBroadcast == 0 {
				continue
			}

			addrs, err := intf.Addrs()
			if err != nil {
				l.Debugln(err)
				continue
			}

			for _, addr := range addrs {
				if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
					baddr := bcast(iaddr)
					dsts = append(dsts, baddr.IP)
				}
			}
		}

		if len(dsts) == 0 {
			// Fall back to the general IPv4 broadcast address
			dsts = append(dsts, net.IP{0xff, 0xff, 0xff, 0xff})
		}

Review comment (suggestion):
`net.Interfaces()` will throw an error on Android. We can still carry on and use the fallback broadcast address `255.255.255.255` later on.

Code after:

func writeBroadcasts(ctx context.Context, inbox <-chan []byte, port int) error {
	conn, err := net.ListenUDP("udp4", nil)
	if err != nil {
		l.Debugln(err)
		return err
	}
	doneCtx, cancel := context.WithCancel(ctx)
	defer cancel()
	go func() {
		<-doneCtx.Done()
		conn.Close()
	}()

	for {
		var bs []byte
		select {
		case bs = <-inbox:
		case <-doneCtx.Done():
			return doneCtx.Err()
		}

		intfs, err := net.Interfaces()
		if err != nil {
			l.Debugln("Failed to list interfaces:", err)
			// net.Interfaces() is broken on Android. see https://github.com/golang/go/issues/40569
			// Use the general broadcast address 255.255.255.255 instead.
		}

		var dsts []net.IP
		for _, intf := range intfs {
			if intf.Flags&net.FlagRunning == 0 || intf.Flags&net.FlagBroadcast == 0 {
				continue
			}

			addrs, err := intf.Addrs()
			if err != nil {
				l.Debugln("Failed to list interface addresses:", err)
				// Interface discovery might work while retrieving the addresses doesn't. So log the error and carry on.
				continue
			}

			for _, addr := range addrs {
				if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
					baddr := bcast(iaddr)
					dsts = append(dsts, baddr.IP)
				}
			}
		}

		if len(dsts) == 0 {
Repository: syncthing/syncthing
File: lib/beacon/broadcast.go (Go)

Code before:
	for {
		var bs []byte
		select {
		case bs = <-inbox:
		case <-doneCtx.Done():
			return doneCtx.Err()
		}

		intfs, err := net.Interfaces()
		if err != nil {
			l.Debugln(err)
		}

		var dsts []net.IP
		for _, intf := range intfs {
			if intf.Flags&net.FlagBroadcast == 0 {
				continue
			}

			addrs, err := intf.Addrs()
			if err != nil {
				l.Debugln(err)
				continue
			}

			for _, addr := range addrs {
				if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
					baddr := bcast(iaddr)
					dsts = append(dsts, baddr.IP)
				}
			}
		}

		if len(dsts) == 0 {
			// Fall back to the general IPv4 broadcast address
			dsts = append(dsts, net.IP{0xff, 0xff, 0xff, 0xff})
		}

		l.Debugln("addresses:", dsts)

		success := 0
		for _, ip := range dsts {
			dst := &net.UDPAddr{IP: ip, Port: port}

			conn.SetWriteDeadline(time.Now().Add(time.Second))
			_, err = conn.WriteTo(bs, dst)
			conn.SetWriteDeadline(time.Time{})

			if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
				// Write timeouts should not happen. We treat it as a fatal
				// error on the socket.

Review comment (suggestion):
Interface discovery might work while retrieving the addresses doesn't. So log the error and carry on.

Code after:
	for {
		var bs []byte
		select {
		case bs = <-inbox:
		case <-doneCtx.Done():
			return doneCtx.Err()
		}

		intfs, err := net.Interfaces()
		if err != nil {
			l.Debugln("Failed to list interfaces:", err)
			// net.Interfaces() is broken on Android. see https://github.com/golang/go/issues/40569
			// Use the general broadcast address 255.255.255.255 instead.
		}

		var dsts []net.IP
		for _, intf := range intfs {
			if intf.Flags&net.FlagRunning == 0 || intf.Flags&net.FlagBroadcast == 0 {
				continue
			}

			addrs, err := intf.Addrs()
			if err != nil {
				l.Debugln("Failed to list interface addresses:", err)
				// Interface discovery might work while retrieving the addresses doesn't. So log the error and carry on.
				continue
			}

			for _, addr := range addrs {
				if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
					baddr := bcast(iaddr)
					dsts = append(dsts, baddr.IP)
				}
			}
		}

		if len(dsts) == 0 {
			// Fall back to the general IPv4 broadcast address
			dsts = append(dsts, net.IP{0xff, 0xff, 0xff, 0xff})
		}

		l.Debugln("addresses:", dsts)

		success := 0
		for _, ip := range dsts {
			dst := &net.UDPAddr{IP: ip, Port: port}

			conn.SetWriteDeadline(time.Now().Add(time.Second))
			_, err = conn.WriteTo(bs, dst)
			conn.SetWriteDeadline(time.Time{})
Repository: syncthing/syncthing
File: lib/beacon/multicast.go (Go)

Code before:
	defer cancel()
	go func() {
		<-doneCtx.Done()
		conn.Close()
	}()

	intfs, err := net.Interfaces()
	if err != nil {
		l.Debugln(err)
	}

	pconn := ipv6.NewPacketConn(conn)
	joined := 0
	for _, intf := range intfs {
		err := pconn.JoinGroup(&intf, &net.UDPAddr{IP: gaddr.IP})
		if err != nil {
			l.Debugln("IPv6 join", intf.Name, "failed:", err)
		} else {
			l.Debugln("IPv6 join", intf.Name, "success")
		}
		joined++
	}

	// Handle failed interface lookup on Android
	if len(intfs) == 0 {
		err := pconn.JoinGroup(nil, &net.UDPAddr{IP: gaddr.IP})
		if err != nil {
			l.Debugln("IPv6 join default interface failed:", err)
		} else {
			l.Debugln("IPv6 join default interface success:", err)
		}
		joined++
	}

	if joined == 0 {
		l.Debugln("no multicast interfaces available")
		return errors.New("no multicast interfaces available")
	}

	bs := make([]byte, 65536)
	for {
		select {
		case <-doneCtx.Done():
			return doneCtx.Err()
		default:
		}
		n, _, addr, err := pconn.ReadFrom(bs)
		if err != nil {
			l.Debugln(err)
			return err
		}

Review comment (suggestion):
> JoinGroup uses the system assigned multicast interface when ifi is nil

https://pkg.go.dev/golang.org/x/net/ipv6#PacketConn.JoinGroup

Code after:
	defer cancel()
	go func() {
		<-doneCtx.Done()
		conn.Close()
	}()

	intfs, err := net.Interfaces()
	if err != nil {
		l.Debugln(err)
		return err
	}

	pconn := ipv6.NewPacketConn(conn)
	joined := 0
	for _, intf := range intfs {
		err := pconn.JoinGroup(&intf, &net.UDPAddr{IP: gaddr.IP})
		if err != nil {
			l.Debugln("IPv6 join", intf.Name, "failed:", err)
		} else {
			l.Debugln("IPv6 join", intf.Name, "success")
		}
		joined++
	}

	if joined == 0 {
		l.Debugln("no multicast interfaces available")
		return errors.New("no multicast interfaces available")
	}

	bs := make([]byte, 65536)
	for {
		select {
		case <-doneCtx.Done():
			return doneCtx.Err()
		default:
		}
		n, _, addr, err := pconn.ReadFrom(bs)
		if err != nil {
			l.Debugln(err)
			return err
		}
		l.Debugf("recv %d bytes from %s", n, addr)

		c := make([]byte, n)
		copy(c, bs)
		select {
		case outbox <- recv{c, addr}:
		default:
			l.Debugln("dropping message")
		}
	}