ronantakizawa/codereview-bench huggingface dataset:
Repository: h2oai/wave
File: ui/src/copyable_text.tsx (TypeScript)

Code before:
    [copied, setCopied] = React.useState(false),
    onClick = async () => {
      const el = ref.current
      if (!el) return
      try {
        if (document.queryCommandSupported('copy')) {
          el.select()
          document.execCommand('copy')
          window.getSelection()?.removeAllRanges()
        }
      } catch (error) {
        await window.navigator.clipboard.writeText(value)
      }

      setCopied(true)
      timeoutRef.current = window.setTimeout(() => setCopied(false), 2000)
    }

  React.useEffect(() => () => window.clearTimeout(timeoutRef.current), [])

  return (
    <Fluent.TextField
      data-test={name}
      componentRef={ref}
      value={value}
      label={label}
      multiline={multiline}
      onRenderLabel={() =>
        <div className={css.labelContainer}>
          <Fluent.Label>{label}</Fluent.Label>
          <Fluent.PrimaryButton
            title='Copy to clipboard'
            onClick={onClick}
            iconProps={{ iconName: copied ? 'CheckMark' : 'Copy' }}
            className={clas(css.btn, copied ? css.copiedBtn : '', multiline ? css.btnMultiline : '')}
          />
        </div>
      }
      styles={{
        root: {
          ...heightStyle,
          ...styles.textFieldRoot,
          ...multiline ? styles.textFieldMultiline : undefined
        },
        wrapper: heightStyle,
        fieldGroup: heightStyle || { minHeight: height },
        field: { ...heightStyle, height, resize: multiline ? 'vertical' : 'none', },
      }}
      readOnly
    />
  )

Review comment (suggestion):
Probably not necessary in favor of `onRenderLabel`.
```suggestion
```

Code after:
        await window.navigator.clipboard.writeText(value)
      }

      setCopied(true)
      timeoutRef.current = window.setTimeout(() => setCopied(false), 2000)
    }

  React.useEffect(() => () => window.clearTimeout(timeoutRef.current), [])

  return (
    <Fluent.TextField
      data-test={name}
      componentRef={ref}
      value={value}
      multiline={multiline}
      onRenderLabel={() =>
        <div className={css.labelContainer}>
          <Fluent.Label>{label}</Fluent.Label>
          <Fluent.PrimaryButton
            title='Copy to clipboard'
            onClick={onClick}
            iconProps={{ iconName: copied ? 'CheckMark' : 'Copy' }}
            className={clas(css.btn, copied ? css.copiedBtn : '', multiline ? css.btnMultiline : '')}
          />
        </div>
      }
      styles={{
        root: {
          ...heightStyle,
          textFieldRoot: { position: 'relative', width: pc(100) },
          textFieldMultiline: multiline ? { '&:hover button': { opacity: 1 } } : undefined
        },
        wrapper: heightStyle,
        fieldGroup: heightStyle || { minHeight: height },
        field: { ...heightStyle, height, resize: multiline ? 'vertical' : 'none', },
      }}
      readOnly
    />
  )
}
Repository: h2oai/wave
File: ui/src/markup.tsx (TypeScript)

Code before:
interface State {
  /**
   * The title for this card.
   * :t "textbox"
   * :value "Untitled Content"
   **/
  title: S
  /**
   * The HTML content.
   * :t "textarea"
   * :value "<div/>"
   **/
  content: S
  /** 
   * True if title and padding should be removed. Defaults to False.
   **/
  compact?: B
}

export const
  XMarkup = ({ model: { content, name } }: { model: Markup }) => (
    <div data-test={name} dangerouslySetInnerHTML={{ __html: content }} />
  ),
  MarkupCard = ({ name, title, content, compact }: { name: S, title: S, content: S, compact?: B }) => (
    <div data-test={name} className={clas(css.card, compact ? '' : css.cardPadding)}>
      {!compact && title && <div className='wave-s12 wave-w6'>{title}</div>}
      <div className={css.body}>
        <XMarkup model={{ content }} />
      </div>
    </div>
  ),
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => <MarkupCard name={name} title={state.title} content={state.content} compact={state.compact} />
    return { render, changed }
  })

cards.register('markup', View)

Review comment (suggestion):
Let's not make `title` dependent on `compact`, might be confusing. The title should be always rendered if specified, despite looking odd.

Code after:
interface State {
  /**
   * The title for this card.
   * :t "textbox"
   * :value "Untitled Content"
   **/
  title: S
  /**
   * The HTML content.
   * :t "textarea"
   * :value "<div/>"
   **/
  content: S
  /** 
   * True if outer spacing should be removed. Defaults to False.
   **/
  compact?: B
}

export const
  XMarkup = ({ model: { content, name } }: { model: Markup }) => (
    <div data-test={name} dangerouslySetInnerHTML={{ __html: content }} />
  ),
  MarkupCard = ({ name, title, content, compact }: { name: S, title: S, content: S, compact?: B }) => (
    <div data-test={name} className={clas(css.card, compact ? '' : css.cardPadding)}>
      {title && <div className='wave-s12 wave-w6'>{title}</div>}
      <div className={css.body}>
        <XMarkup model={{ content }} />
      </div>
    </div>
  ),
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => <MarkupCard name={name} title={state.title} content={state.content} compact={state.compact} />
    return { render, changed }
  })

cards.register('markup', View)
Repository: h2oai/wave
File: ui/src/markup.tsx (TypeScript)

Code before:
  name?: S
  /** The width of the markup, e.g. '100px'. */
  width?: S
  /** True if the component should be visible. Defaults to True. */
  visible?: B
}

/**
 * Render HTML content.
 * :icon "FileHTML"
 **/
interface State {
  /**
   * The title for this card.
   * :t "textbox"
   * :value "Untitled Content"
   **/
  title: S
  /**
   * The HTML content.
   * :t "textarea"
   * :value "<div/>"
   **/
  content: S
  /** 
   * True if title and padding should be removed. Defaults to False.
   **/
  compact?: B
}

export const
  XMarkup = ({ model: { content, name } }: { model: Markup }) => (
    <div data-test={name} dangerouslySetInnerHTML={{ __html: content }} />
  ),
  MarkupCard = ({ name, title, content, compact }: { name: S, title: S, content: S, compact?: B }) => (
    <div data-test={name} className={clas(css.card, compact ? '' : css.cardPadding)}>
      {!compact && title && <div className='wave-s12 wave-w6'>{title}</div>}
      <div className={css.body}>
        <XMarkup model={{ content }} />
      </div>
    </div>
  ),
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => <MarkupCard name={name} title={state.title} content={state.content} compact={state.compact} />
    return { render, changed }
  })

cards.register('markup', View)

Review comment (suggestion):
```suggestion
   * True if outer spacing should be removed. Defaults to False.
```

Don't forget to run `make generate` after fixing this.

Code after:
  name?: S
  /** The width of the markup, e.g. '100px'. */
  width?: S
  /** True if the component should be visible. Defaults to True. */
  visible?: B
}

/**
 * Render HTML content.
 * :icon "FileHTML"
 **/
interface State {
  /**
   * The title for this card.
   * :t "textbox"
   * :value "Untitled Content"
   **/
  title: S
  /**
   * The HTML content.
   * :t "textarea"
   * :value "<div/>"
   **/
  content: S
  /** 
   * True if outer spacing should be removed. Defaults to False.
   **/
  compact?: B
}

export const
  XMarkup = ({ model: { content, name } }: { model: Markup }) => (
    <div data-test={name} dangerouslySetInnerHTML={{ __html: content }} />
  ),
  MarkupCard = ({ name, title, content, compact }: { name: S, title: S, content: S, compact?: B }) => (
    <div data-test={name} className={clas(css.card, compact ? '' : css.cardPadding)}>
      {title && <div className='wave-s12 wave-w6'>{title}</div>}
      <div className={css.body}>
        <XMarkup model={{ content }} />
      </div>
    </div>
  ),
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => <MarkupCard name={name} title={state.title} content={state.content} compact={state.compact} />
    return { render, changed }
  })

cards.register('markup', View)
Repository: h2oai/wave
File: ui/src/date_picker.tsx (TypeScript)

Code before:
export const
  XDatePicker = ({ model: m }: { model: DatePicker }) => {
    const
      defaultVal = m.value || null,
      parsedVal = defaultVal ? parseDate(defaultVal) : null,
      [value, setValue] = React.useState<Date | undefined>(parsedVal ? new Date(parsedVal) : undefined),
      onSelectDate = (d: Date | null | undefined) => {
        const val = (d === null || d === undefined) ? defaultVal : formatDate(d)
        wave.args[m.name] = val
        setValue(val ? new Date(`${val}T00:00:00`) : undefined)
        if (m.trigger) wave.push()
      }

    // eslint-disable-next-line react-hooks/exhaustive-deps
    React.useEffect(() => { wave.args[m.name] = defaultVal }, [])

    return (
      <Fluent.DatePicker
        data-test={m.name}
        styles={{
          icon: { bottom: 2 },
          readOnlyTextField: { paddingRight: important('32px') },
          statusMessage: { marginTop: 0 },
          root: {
            width: m.width || 190,
            minWidth: m.width ? undefined : '100%',
          }
        }}
        label={m.label}
        value={value}
        placeholder={m.placeholder}
        disabled={m.disabled}
        onSelectDate={onSelectDate}
        minDate={parseDate(m.min || null)}
        maxDate={parseDate(m.max || null)}
      />
    )
  }

Review comment (suggestion):
Would this work as well? (Applies to the rest of the components as well).
```suggestion
            minWidth: m.width || '100%',
```

Code after:
export const
  XDatePicker = ({ model: m }: { model: DatePicker }) => {
    const
      defaultVal = m.value || null,
      parsedVal = defaultVal ? parseDate(defaultVal) : null,
      [value, setValue] = React.useState<Date | undefined>(parsedVal ? new Date(parsedVal) : undefined),
      onSelectDate = (d: Date | null | undefined) => {
        const val = (d === null || d === undefined) ? defaultVal : formatDate(d)
        wave.args[m.name] = val
        setValue(val ? new Date(`${val}T00:00:00`) : undefined)
        if (m.trigger) wave.push()
      }

    // eslint-disable-next-line react-hooks/exhaustive-deps
    React.useEffect(() => { wave.args[m.name] = defaultVal }, [])

    return (
      <Fluent.DatePicker
        data-test={m.name}
        styles={{ icon: { bottom: 2 }, readOnlyTextField: { paddingRight: important('32px') }, statusMessage: { marginTop: 0 } }}
        label={m.label}
        value={value}
        placeholder={m.placeholder}
        disabled={m.disabled}
        onSelectDate={onSelectDate}
        minDate={parseDate(m.min || null)}
        maxDate={parseDate(m.max || null)}
      />
    )
  }
Repository: h2oai/wave
File: py/examples/image_annotator_events_click.py (Python)

Code before:
@app('/demo')
async def serve(q: Q):
    if not q.client.initialized:
        q.client.initialized = True
        q.page['example'] = ui.form_card(box='1 1 5 7', items=[
            ui.image_annotator(
                name='annotator',
                title='Drag to annotate',
                image='https://images.unsplash.com/photo-1535082623926-b39352a03fb7?auto=compress&cs=tinysrgb&w=1260&h=750&q=80',
                image_height='450px',
                tags=[
                    ui.image_annotator_tag(name='v', label='Vehicle', color='$cyan'),
                    ui.image_annotator_tag(name='a', label='Animal', color='$blue'),
                ],
                items=[],
                events=['click']
            ),
        ])
        q.page['details'] = ui.markdown_card(
            box='1 8 5 2',
            title='Clicked point',
            content='Nothing is clicked.',
        )
    else:
        if q.events.annotator:
            if q.events.annotator.click:
                x, y = q.events.annotator.click.values()
                q.page['details'].content = f'You clicked on x={x}, y={y}'
    await q.page.save()


Review comment (suggestion):
```suggestion
        if q.events.annotator and q.events.annotator.click:
```

Code after:


@app('/demo')
async def serve(q: Q):
    if not q.client.initialized or q.args.back:
        q.page['example'] = ui.form_card(box='1 1 5 8', items=[
            ui.image_annotator(
                name='annotator',
                title='Click on the car and see what happens!',
                image='https://images.unsplash.com/photo-1535082623926-b39352a03fb7?auto=compress&cs=tinysrgb&w=1260&h=750&q=80',
                image_height='450px',
                allowed_shapes=['rect'],
                tags=[ui.image_annotator_tag(name='v', label='Vehicle', color='$cyan')],
                items=[],
                events=['click'],
            ),
            ui.button(name='submit', label='Submit', primary=True)
        ])
        q.client.initialized = True
    if q.args.submit:
        q.page['example'].items = [
            ui.text(f'annotator={q.args.annotator}'),
            ui.button(name='back', label='Back', primary=True),
        ]
    if q.events.annotator and q.events.annotator.click:
        x, y = q.events.annotator.click.values()
        # If the click is within the vehicle's bounding box, show the vehicle.
        if vehicle['x1'] <= x <= vehicle['x2'] and vehicle['y1'] <= y <= vehicle['y2']:
            q.page['example'].annotator.items = [
                ui.image_annotator_item(shape=ui.image_annotator_rect(x1=657, y1=273, x2=848, y2=440), tag='v')
            ]
            q.page['example'].annotator.title = 'You got it!'
        else:
            q.page['example'].annotator.title = 'You missed the car!'

    await q.page.save()
Repository: h2oai/wave
File: card.go (Go)

Code before:
			fillNameComponentMap(card.nameComponentMap, v)
		}
		ks[0] = k
		card.set(ks, v)
	}
	return card
}

func (c *Card) set(ks []string, v any) {
	switch len(ks) {
	case 0: // should not get here; outer interpreter loop will clobber this card.
		return
	case 1: // .foo = bar
		p := ks[0]
		if ib, ok := c.data[p]; ok { // TODO can optimize by duplicating all bufs in a card.bufs map
			if b, ok := ib.(Buf); ok { // avoid clobbering buffers; overwrite instead.
				b.put(v)
				return
			}
		}

		keys := strings.Split(p, ".")
		lastKey := keys[len(keys)-1]
		var x any = c.data
		// Get the object even if nested.
		for i := 0; i < len(keys)-1; i++ {
			x = get(x, keys[i])
		}

		if x, ok := x.(map[string]any); ok {
			if v == nil {
				delete(x, lastKey)
			} else {
				x[lastKey] = v
			}
		}
	default: // .foo.bar.baz = qux
		var x any = c.data

		startIdx := 0
		if _, ok := c.data[ks[0]]; !ok && c.nameComponentMap[ks[0]] != nil {
			// By-name access.
			x = c.nameComponentMap[ks[0]]
			startIdx = 1
		}
		for i := startIdx; i < len(ks)-1; i++ {
			x = get(x, ks[i])
		}

		p := ks[len(ks)-1]
		set(x, p, v)

Review comment (suggestion):
I'd rewrite this as `for ... range` for better readability:

```go
for _, key := range keys {
  x = get(x, key)
}
```

Code after:
					bufAttrs = append(bufAttrs, BufEntry{strings.TrimPrefix(k, dataPrefix), loadBuf(ns, c.B[i])})
					continue
				}
			}
		}
		if k == "items" || k == "secondary_items" || k == "buttons" {
			if card.nameComponentMap == nil {
				card.nameComponentMap = make(map[string]any)
			}
			fillNameComponentMap(card.nameComponentMap, v)
		}
		ks[0] = k
		card.set(ks, v)
	}
	for b := range bufAttrs {
		ks[0] = bufAttrs[b].k
		card.set(ks, bufAttrs[b].buf)
	}
	return card
}

func (c *Card) set(ks []string, v any) {
	switch len(ks) {
	case 0: // should not get here; outer interpreter loop will clobber this card.
		return
	case 1: // .foo = bar
		p := ks[0]
		if ib, ok := c.data[p]; ok { // TODO can optimize by duplicating all bufs in a card.bufs map
			if b, ok := ib.(Buf); ok { // avoid clobbering buffers; overwrite instead.
				b.put(v)
				return
			}
		}

		keys := strings.Split(p, ".")
		var x any = c.data
		// Get the object even if nested.
		for _, key := range keys[:len(keys)-1] {
			x = get(x, key)
		}

		if x, ok := x.(map[string]any); ok {
			lastKey := keys[len(keys)-1]
			if v == nil {
				delete(x, lastKey)
			} else {
				x[lastKey] = v
			}
		}
	default: // .foo.bar.baz = qux
		var x any = c.data
Repository: h2oai/wave
File: card.go (Go)

Code before:

		keys := strings.Split(p, ".")
		lastKey := keys[len(keys)-1]
		var x any = c.data
		// Get the object even if nested.
		for i := 0; i < len(keys)-1; i++ {
			x = get(x, keys[i])
		}

		if x, ok := x.(map[string]any); ok {
			if v == nil {
				delete(x, lastKey)
			} else {
				x[lastKey] = v
			}
		}
	default: // .foo.bar.baz = qux
		var x any = c.data

		startIdx := 0
		if _, ok := c.data[ks[0]]; !ok && c.nameComponentMap[ks[0]] != nil {
			// By-name access.
			x = c.nameComponentMap[ks[0]]
			startIdx = 1
		}
		for i := startIdx; i < len(ks)-1; i++ {
			x = get(x, ks[i])
		}

		p := ks[len(ks)-1]
		set(x, p, v)
	}
}

func set(ix any, k string, v any) {
	switch x := ix.(type) {
	case Buf:
		x.set(k, v)
	case Cur:
		x.set(k, v)
	case map[string]any:
		if v == nil {
			delete(x, k)
		} else {
			x[k] = v
		}
	case []any:
		if i, err := strconv.Atoi(k); err == nil {
			if i >= 0 && i < len(x) {
				x[i] = v
			}

Review comment (suggestion):
This can be rewritten as:

```go
for _, k := range ks[startIdx:] {
  x = get(x, k)
}
```

Code after:

func (c *Card) set(ks []string, v any) {
	switch len(ks) {
	case 0: // should not get here; outer interpreter loop will clobber this card.
		return
	case 1: // .foo = bar
		p := ks[0]
		if ib, ok := c.data[p]; ok { // TODO can optimize by duplicating all bufs in a card.bufs map
			if b, ok := ib.(Buf); ok { // avoid clobbering buffers; overwrite instead.
				b.put(v)
				return
			}
		}

		keys := strings.Split(p, ".")
		var x any = c.data
		// Get the object even if nested.
		for _, key := range keys[:len(keys)-1] {
			x = get(x, key)
		}

		if x, ok := x.(map[string]any); ok {
			lastKey := keys[len(keys)-1]
			if v == nil {
				delete(x, lastKey)
			} else {
				x[lastKey] = v
			}
		}
	default: // .foo.bar.baz = qux
		var x any = c.data

		startIdx := 0
		if _, ok := c.data[ks[0]]; !ok && c.nameComponentMap[ks[0]] != nil {
			// By-name access.
			x = c.nameComponentMap[ks[0]]
			startIdx = 1
		}
		for _, k := range ks[startIdx : len(ks)-1] {
			x = get(x, k)
		}

		p := ks[len(ks)-1]
		set(x, p, v)
	}
}

func set(ix any, k string, v any) {
	switch x := ix.(type) {
	case Buf:
		x.set(k, v)
Repository: h2oai/wave
File: card.go (Go)

Code before:
	case Buf:
		if r, ok := x.get(k); ok {
			return r
		}
	case Cur:
		return x.get(k)
	case map[string]any:
		if v, ok := x[k]; ok {
			return v
		}
	case []any:
		if i, err := strconv.Atoi(k); err == nil {
			if i >= 0 && i < len(x) {
				return x[i]
			}
		}
	}
	return nil
}

func (c *Card) dump() CardD {
	data := make(map[string]any)
	var bufs []BufD

	// Look for nested buffers within form_card.
	if v, ok := c.data["view"]; ok && v.(string) == "form" {
		fillFormCardBufs(c.data, data, &bufs, make([]string, 0))
	}

	for k, iv := range c.data {
		if v, ok := iv.(Buf); ok {
			data[dataPrefix+k] = len(bufs)
			bufs = append(bufs, v.dump())
		} else {
			data[k] = deepClone(iv)
		}
	}
	return CardD{data, bufs}
}

func deepClone(ix any) any {
	switch x := ix.(type) {
	case map[string]any:
		m := make(map[string]any)
		for k, v := range x {
			m[k] = deepClone(v)
		}
		return m
	case []any:
		s := make([]any, len(x))
		for i, v := range x {

Review comment (suggestion):
`v.(string)` might not be a string and can cause some trouble here. I'd handle it inside the `if` scope.

Code after:
			x[k] = v
		}
	case []any:
		if i, err := strconv.Atoi(k); err == nil {
			if i >= 0 && i < len(x) {
				x[i] = v
			}
		}
	}
}

func get(ix any, k string) any {
	switch x := ix.(type) {
	case Buf:
		if r, ok := x.get(k); ok {
			return r
		}
	case Cur:
		return x.get(k)
	case map[string]any:
		if v, ok := x[k]; ok {
			return v
		}
	case []any:
		if i, err := strconv.Atoi(k); err == nil {
			if i >= 0 && i < len(x) {
				return x[i]
			}
		}
	}
	return nil
}

func (c *Card) dump() CardD {
	data := make(map[string]any)
	var bufs []BufD

	// Look for nested buffers within form_card.
	if v, ok := c.data["view"]; ok {
		if v, ok := v.(string); ok && v == "form" {
			fillFormCardBufs(c.data, data, &bufs, make([]string, 0))
		}
	}

	for k, iv := range c.data {
		if v, ok := iv.(Buf); ok {
			data[dataPrefix+k] = len(bufs)
			bufs = append(bufs, v.dump())
		} else {
			data[k] = deepClone(iv)
		}
Repository: h2oai/wave
File: socket.go (Go)

Code before:
					return
				}
				sw.Write(msg)
				sw.Close()
			}
			return
		}
	}

	header := make(http.Header)
	if s.forwardedHeaders != nil {
		for k, v := range r.Header {
			if s.forwardedHeaders["*"] || s.forwardedHeaders[strings.ToLower(k)] {
				header[k] = v
			}
		}
	}
	clientID := r.URL.Query().Get("client-id")
	client, ok := s.broker.clientsByID[clientID]
	if ok {
		client.conn = conn
		client.isReconnect = true
		if client.cancel != nil {
			client.cancel()
		}
	} else {
		client = newClient(getRemoteAddr(r), s.auth, session, s.broker, conn, s.editable, s.baseURL, &header, s.pingInterval, false)
	}

	if msg, err := json.Marshal(OpsD{I: client.id}); err == nil {
		sw, err := conn.NextWriter(websocket.TextMessage)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		sw.Write(msg)
		sw.Close()
	}

	go client.flush()
	go client.listen()
}

func getRemoteAddr(r *http.Request) string {
	if addr := r.Header.Get("X-FORWARDED-FOR"); addr != "" { // forwarded via a proxy?
		return addr
	}
	return r.RemoteAddr
}


Review comment (bug):
I think it might be worth logging something here (I would say debug to start, and then maybe reduce to trace) just to see how often it's happening.

Code after:
					http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
					return
				}
				sw.Write(msg)
				sw.Close()
			}
			return
		}
	}

	header := make(http.Header)
	if s.forwardedHeaders != nil {
		for k, v := range r.Header {
			if s.forwardedHeaders["*"] || s.forwardedHeaders[strings.ToLower(k)] {
				header[k] = v
			}
		}
	}
	clientID := r.URL.Query().Get("client-id")
	client, ok := s.broker.clientsByID[clientID]
	if ok {
		client.conn = conn
		client.isReconnect = true
		if client.cancel != nil {
			client.cancel()
		}
		if s.broker.debug {
			echo(Log{"t": "socket_reconnect", "client_id": clientID, "addr": getRemoteAddr(r)})
		}
	} else {
		client = newClient(getRemoteAddr(r), s.auth, session, s.broker, conn, s.editable, s.baseURL, &header, s.pingInterval, false, s.reconnectTimeout)
	}

	if msg, err := json.Marshal(OpsD{I: client.id}); err == nil {
		sw, err := conn.NextWriter(websocket.TextMessage)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		sw.Write(msg)
		sw.Close()
	}

	go client.flush()
	go client.listen()
}

func getRemoteAddr(r *http.Request) string {
	if addr := r.Header.Get("X-FORWARDED-FOR"); addr != "" { // forwarded via a proxy?
		return addr
	}