I
I
impressive172019-11-22 23:56:50
go
impressive17, 2019-11-22 23:56:50

Why is the golang webserver not working?

Wrote a web server that should return a structure. But the server issues 404. As I understand it, helloHandler doesn't even run.

package main

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

func main(){
  handler:=http.NewServeMux()

  // C R U D
  handler.HandleFunc("/hello", helloHandler)

  s:= http.Server{
    Addr: ":8080",
    Handler: nil,
    ReadTimeout: 10 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout: 10 * time.Second,
    MaxHeaderBytes: 1 << 20,        //1*2^20 - 128kBytes
  }
  log.Fatal(s.ListenAndServe())
}

type Resp struct{
  Message string
  Error string
}



func helloHandler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  fmt.Print("WORK")
  resp := Resp {
    Message: "hello",
  }

  respJson, _ := json.Marshal(resp)

  w.WriteHeader(http.StatusOK)

  w.Write(respJson)

}

5dd84b85948ed602696706.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2019-11-23
@impressive17

Handler for the server was not specified.

s:= http.Server{
    Addr: ":8080",
    Handler: handler, //здесь
    ReadTimeout: 10 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout: 10 * time.Second,
    MaxHeaderBytes: 1 << 20,        //1*2^20 - 128kBytes
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question