https://github.com/goproxy/goproxy.cn
func ListenHttp() error {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
// handle error
return errors.Wrap(err, "invoke net.Listen failed")
}
r := mux.NewRouter()
r.HandleFunc("/", ProductsHandler)
return http.Serve(ln, r)
}
func ProductsHandler(w http.ResponseWriter, r *http.Request) {
fmt.Print("ProductsHandler invoked")
vars := mux.Vars(r)
fmt.Print(vars)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\\n", vars["category"])
}
Understanding Unix Domain Sockets in Golang - DEV Community —> 终于搞懂了!~
const socketPath = "/tmp/test.sock"
func ListenUnixSocket() error {
socket, err := net.Listen("unix", socketPath)
if err != nil {
log.Printf("Failed to listen to socket registry")
return err
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
os.Remove(socketPath)
os.Exit(1)
}()
r := mux.NewRouter()
r.HandleFunc("/", ProductsHandler)
r.HandleFunc("/hello", HelloHandler)
srv := &http.Server{Handler: r}
err = srv.Serve(socket)
return err
}