antman1p
antman1p

Reputation: 524

How do I get GoLang's http.HandleFunc() to work without error?

I am trying to create a GoLang http.HandleFunc() that will listen for post requests and parse a json file. The Handler seems to fail as it starts and returns an error:

2017/01/24 13:35:08 listen tcp :8080: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.

I am assuming that it is throwing a fatal error.

Below is my function:

 http.HandleFunc("/", func(w http.ResponseWriter, request *http.Request) {

        //debug
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(request.URL.Path))

        var m Message

        if request.Body == nil {
            http.Error(w, "Please send a request body", 400)                
            return
        }

        err := json.NewDecoder(request.Body).Decode(&m)
        if err != nil {
            http.Error(w, err.Error(), 400)
            return
        }
 })
 log.Fatal(http.ListenAndServe(":8080", nil))

How can I get this Handler to work and not get the error?

Upvotes: 1

Views: 2904

Answers (1)

daplho
daplho

Reputation: 1135

I've remedied several of the problems with your code and made best guesses around missing information. Here is sample working code that will accept a message that has "name" and "text" fields:

package main

import (
  "encoding/json"
  "fmt"
  "html"
  "log"
  "net/http"
)

type Message struct {
  Name string `json:"name"`
  Text string `json:"text"`
}

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, request *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(request.URL.Path))

    var m Message

    if request.Body == nil {
      http.Error(w, "Please send a request body", 400)
      return
    }

    err := json.NewDecoder(request.Body).Decode(&m)
    if err != nil {
      http.Error(w, err.Error(), 400)
      return
    }

    log.Println(m)
  })

  log.Fatal(http.ListenAndServe(":8080", nil))
}

Upvotes: 1

Related Questions