-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
47 lines (39 loc) · 937 Bytes
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"github.com/gorilla/mux"
)
type Response struct {
IP string `json:"ip"`
Host string `json:"host"`
Message string `json:"message"`
}
func startHttp() error {
r := mux.NewRouter()
r.HandleFunc("/", handleGet).Methods("GET")
srv := &http.Server{
Addr: ":8080",
Handler: r,
}
// using a dedicated listener instead of ListenAndServe
// to align with the grpc server
//
// effectively a stripped down implementation of the same thing
lis, err := net.Listen("tcp", srv.Addr)
if err != nil {
return fmt.Errorf("failed to listen on port %v: %w", srv.Addr, err)
}
fmt.Printf("json http server listening at %v\n", lis.Addr())
return srv.Serve(lis)
}
func handleGet(w http.ResponseWriter, req *http.Request) {
res := Response{
IP: req.RemoteAddr,
Message: "Hello From Go!",
Host: req.Host,
}
json.NewEncoder(w).Encode(res)
}